diff --git a/.ci/travis-compile.sh b/.ci/travis-compile.sh index e09bc0f3..ba9a943e 100644 --- a/.ci/travis-compile.sh +++ b/.ci/travis-compile.sh @@ -21,7 +21,32 @@ if [[ $BUILDTYPE == "Debug" ]]; then cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix -DTEST=1 make -j2 make test + + if [[ $TRAVIS_OS_NAME == "linux" ]]; then + cd .. + clang-format -i \ + common/*.h \ + common/*.cpp \ + cockatrice/src/*.h \ + cockatrice/src/*.cpp \ + oracle/src/*.h \ + oracle/src/*.cpp \ + servatrice/src/*.h \ + servatrice/src/*.cpp + + git clean -f + git diff --quiet || ( + echo "*****************************************************"; + echo "*** This PR is not clean against our code style ***"; + echo "*** Run clang-format and fix up any differences ***"; + echo "*** Check our CONTRIBUTING.md file for details! ***"; + echo "*** Thank you ♥ ***"; + echo "*****************************************************"; + ) + git diff --exit-code + fi fi + if [[ $BUILDTYPE == "Release" ]]; then cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix make package -j2 diff --git a/.ci/travis-dependencies.sh b/.ci/travis-dependencies.sh index 39526199..3adc6a8a 100644 --- a/.ci/travis-dependencies.sh +++ b/.ci/travis-dependencies.sh @@ -3,7 +3,7 @@ if [[ $TRAVIS_OS_NAME == "osx" ]] ; then brew install ccache # enable caching on mac (PATH only set in travis-compile.sh) brew install --force qt@5.7 - brew install protobuf + brew install protobuf clang-format fi if [[ $TRAVIS_OS_NAME == "linux" ]] ; then echo Skipping... packages are installed with the Travis apt addon for sudo disabled container builds diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..a20feb82 --- /dev/null +++ b/.clang-format @@ -0,0 +1,25 @@ +IndentWidth: 4 +AccessModifierOffset: -4 +ColumnLimit: 120 +--- +Language: Cpp +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +AllowShortFunctionsOnASingleLine: None +BinPackParameters: false +AllowAllParametersOfDeclarationOnNextLine: false +IndentCaseLabels: true +PointerAlignment: Right \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index e460b012..ed45409c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,9 +26,13 @@ matrix: #install dependencies for container-based "linux" builds addons: apt: + sources: + - sourceline: 'deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-5.0 main' + key_url: 'http://llvm.org/apt/llvm-snapshot.gpg.key' packages: - bc - - cmake + - clang-format-5.0 + - cmake - libprotobuf-dev - protobuf-compiler - qt5-default @@ -39,7 +43,6 @@ addons: - libqt5svg5-dev - libqt5sql5-mysql - before_install: bash ./.ci/travis-dependencies.sh script: bash ./.ci/travis-compile.sh diff --git a/cockatrice/src/abstractcarddragitem.cpp b/cockatrice/src/abstractcarddragitem.cpp index 35476941..5f6dfd5d 100644 --- a/cockatrice/src/abstractcarddragitem.cpp +++ b/cockatrice/src/abstractcarddragitem.cpp @@ -1,15 +1,17 @@ #include "abstractcarddragitem.h" #include "carddatabase.h" #include -#include #include +#include #include static const float CARD_WIDTH_HALF = CARD_WIDTH / 2; static const float CARD_HEIGHT_HALF = CARD_HEIGHT / 2; const QColor GHOST_MASK = QColor(255, 255, 255, 50); -AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag) +AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, + const QPointF &_hotSpot, + AbstractCardDragItem *parentDrag) : QGraphicsItem(), item(_item), hotSpot(_hotSpot) { if (parentDrag) { @@ -27,7 +29,10 @@ AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, const QPoint setZValue(2000000007); } if (item->getTapped()) - setTransform(QTransform().translate(CARD_WIDTH_HALF, CARD_HEIGHT_HALF).rotate(90).translate(-CARD_WIDTH_HALF, -CARD_HEIGHT_HALF)); + setTransform(QTransform() + .translate(CARD_WIDTH_HALF, CARD_HEIGHT_HALF) + .rotate(90) + .translate(-CARD_WIDTH_HALF, -CARD_HEIGHT_HALF)); setCacheMode(DeviceCoordinateCache); } diff --git a/cockatrice/src/abstractcarddragitem.h b/cockatrice/src/abstractcarddragitem.h index d7c3a40e..39ff7115 100644 --- a/cockatrice/src/abstractcarddragitem.h +++ b/cockatrice/src/abstractcarddragitem.h @@ -7,24 +7,42 @@ class QGraphicsScene; class CardZone; class CardInfo; -class AbstractCardDragItem : public QObject, public QGraphicsItem { +class AbstractCardDragItem : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) protected: AbstractCardItem *item; QPointF hotSpot; QList childDrags; + public: - enum { Type = typeCardDrag }; - int type() const { return Type; } + 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); } + 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; } + 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); }; diff --git a/cockatrice/src/abstractcarditem.cpp b/cockatrice/src/abstractcarditem.cpp index 8b497422..e42626e0 100644 --- a/cockatrice/src/abstractcarditem.cpp +++ b/cockatrice/src/abstractcarditem.cpp @@ -1,26 +1,27 @@ -#include -#include #include +#include #include -#include +#include #include +#include #ifdef _WIN32 #include "round.h" #endif /* _WIN32 */ -#include "carddatabase.h" #include "abstractcarditem.h" +#include "carddatabase.h" +#include "gamescene.h" +#include "main.h" #include "pictureloader.h" #include "settingscache.h" -#include "main.h" -#include "gamescene.h" AbstractCardItem::AbstractCardItem(const QString &_name, Player *_owner, int _id, QGraphicsItem *parent) - : ArrowTarget(_owner, parent), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), bgColor(Qt::transparent), isHovered(false), realZValue(0) + : ArrowTarget(_owner, parent), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), + bgColor(Qt::transparent), isHovered(false), realZValue(0) { setCursor(Qt::OpenHandCursor); setFlag(ItemIsSelectable); setCacheMode(DeviceCoordinateCache); - + connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate())); cardInfoUpdated(); } @@ -44,7 +45,7 @@ void AbstractCardItem::pixmapUpdated() void AbstractCardItem::cardInfoUpdated() { info = db->getCard(name); - if(info) + if (info) connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); cacheBgColor(); @@ -59,10 +60,8 @@ void AbstractCardItem::setRealZValue(qreal _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) @@ -71,9 +70,9 @@ void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &transla const int fontSize = std::max(9, MAX_FONT_SIZE); QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); - + painter->resetTransform(); - + QTransform pixmapTransform; pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); pixmapTransform.rotate(angle); @@ -92,16 +91,14 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS QPixmap translatedPixmap; bool paintImage = true; - if(facedown || name.isEmpty()) - { + if (facedown || name.isEmpty()) { // never reveal card color, always paint the card back PictureLoader::getCardBackPixmap(translatedPixmap, translatedSize.toSize()); } else { // don't even spend time trying to load the picture if our size is too small - if(translatedSize.width() > 10) - { + if (translatedSize.width() > 10) { PictureLoader::getPixmap(translatedPixmap, info, translatedSize.toSize()); - if(translatedPixmap.isNull()) + if (translatedPixmap.isNull()) paintImage = false; } else { paintImage = false; @@ -109,7 +106,7 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS } painter->save(); - + if (paintImage) { painter->save(); transformPainter(painter, translatedSize, angle); @@ -129,7 +126,7 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS painter->drawRect(QRectF(0, 0, CARD_WIDTH - 1, CARD_HEIGHT - penWidth)); else painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 1.5)); - + if (translatedPixmap.isNull() || settingsCache->getDisplayCardNames() || facedown) { painter->save(); transformPainter(painter, translatedSize, angle); @@ -141,10 +138,12 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS 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->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(); } @@ -154,7 +153,7 @@ void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * QSizeF translatedSize = getTranslatedSize(painter); paintPicture(painter, translatedSize, tapAngle); - + painter->save(); painter->setRenderHint(QPainter::Antialiasing, false); transformPainter(painter, translatedSize, tapAngle); @@ -180,9 +179,9 @@ void AbstractCardItem::setName(const QString &_name) { if (name == _name) return; - + emit deleteCardInfoPopup(name); - if(info) + if (info) disconnect(info, nullptr, this, nullptr); name = _name; @@ -193,7 +192,7 @@ void AbstractCardItem::setHovered(bool _hovered) { if (isHovered == _hovered) return; - + if (_hovered) processHoverEvent(); isHovered = _hovered; @@ -213,16 +212,14 @@ void AbstractCardItem::setColor(const QString &_color) void AbstractCardItem::cacheBgColor() { QChar colorChar; - if (color.isEmpty()) - { - if(info) + if (color.isEmpty()) { + if (info) colorChar = info->getColorChar(); } else { colorChar = color.at(0); } - - switch(colorChar.toLower().toLatin1()) - { + + switch (colorChar.toLower().toLatin1()) { case 'b': bgColor = QColor(0, 0, 0); break; @@ -251,13 +248,16 @@ 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)); + setTransform(QTransform() + .translate((float)CARD_WIDTH / 2, (float)CARD_HEIGHT / 2) + .rotate(tapAngle) + .translate((float)-CARD_WIDTH / 2, (float)-CARD_HEIGHT / 2)); update(); } } @@ -273,8 +273,7 @@ void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if ((event->modifiers() & Qt::ControlModifier)) { setSelected(!isSelected()); - } - else if (!isSelected()) { + } else if (!isSelected()) { scene()->clearSelection(); setSelected(true); } @@ -289,7 +288,7 @@ 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(); } @@ -307,4 +306,3 @@ QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change, } else return QGraphicsItem::itemChange(change, value); } - diff --git a/cockatrice/src/abstractcarditem.h b/cockatrice/src/abstractcarditem.h index 89fb1280..c649d986 100644 --- a/cockatrice/src/abstractcarditem.h +++ b/cockatrice/src/abstractcarditem.h @@ -9,7 +9,8 @@ class Player; const int CARD_WIDTH = 72; const int CARD_HEIGHT = 102; -class AbstractCardItem : public ArrowTarget { +class AbstractCardItem : public ArrowTarget +{ Q_OBJECT protected: CardInfo *info; @@ -20,44 +21,83 @@ protected: int tapAngle; QString color; QColor bgColor; + private: bool isHovered; qreal realZValue; private slots: void pixmapUpdated(); void cardInfoUpdated(); - void callUpdate() { update(); } + void callUpdate() + { + update(); + } signals: 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; } + 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; } + 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; } + qreal getRealZValue() const + { + return realZValue; + } void setRealZValue(qreal _zValue); void setHovered(bool _hovered); - QString getColor() const { return color; } + QString getColor() const + { + return color; + } void setColor(const QString &_color); - bool getTapped() const { return tapped; } + bool getTapped() const + { + return tapped; + } void setTapped(bool _tapped, bool canAnimate = false); - bool getFaceDown() const { return facedown; } + bool getFaceDown() const + { + return facedown; + } void setFaceDown(bool _facedown); void processHoverEvent(); - void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); } + void deleteCardInfoPopup() + { + emit deleteCardInfoPopup(name); + } + protected: void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle); void mousePressEvent(QGraphicsSceneMouseEvent *event); @@ -65,5 +105,5 @@ protected: QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); void cacheBgColor(); }; - + #endif diff --git a/cockatrice/src/abstractclient.cpp b/cockatrice/src/abstractclient.cpp index a91ea784..9a700dbe 100644 --- a/cockatrice/src/abstractclient.cpp +++ b/cockatrice/src/abstractclient.cpp @@ -1,28 +1,27 @@ #include "abstractclient.h" -#include "pending_command.h" +#include "client_metatypes.h" +#include "featureset.h" +#include "get_pb_extension.h" #include "pb/commands.pb.h" -#include "pb/server_message.pb.h" +#include "pb/event_add_to_list.pb.h" +#include "pb/event_connection_closed.pb.h" +#include "pb/event_game_joined.pb.h" +#include "pb/event_list_rooms.pb.h" +#include "pb/event_notify_user.pb.h" +#include "pb/event_remove_from_list.pb.h" +#include "pb/event_replay_added.pb.h" #include "pb/event_server_identification.pb.h" #include "pb/event_server_message.pb.h" #include "pb/event_server_shutdown.pb.h" -#include "pb/event_connection_closed.pb.h" -#include "pb/event_user_message.pb.h" -#include "pb/event_notify_user.pb.h" -#include "pb/event_list_rooms.pb.h" -#include "pb/event_add_to_list.pb.h" -#include "pb/event_remove_from_list.pb.h" #include "pb/event_user_joined.pb.h" #include "pb/event_user_left.pb.h" -#include "pb/event_game_joined.pb.h" -#include "pb/event_replay_added.pb.h" -#include "get_pb_extension.h" +#include "pb/event_user_message.pb.h" +#include "pb/server_message.pb.h" +#include "pending_command.h" #include -#include "client_metatypes.h" -#include "featureset.h" -AbstractClient::AbstractClient(QObject *parent) - : QObject(parent), nextCmdId(0), status(StatusDisconnected) +AbstractClient::AbstractClient(QObject *parent) : QObject(parent), nextCmdId(0), status(StatusDisconnected) { qRegisterMetaType("QVariant"); qRegisterMetaType("CommandContainer"); @@ -44,13 +43,13 @@ AbstractClient::AbstractClient(QObject *parent) qRegisterMetaType("Event_UserMessage"); qRegisterMetaType("Event_NotifyUser"); qRegisterMetaType("ServerInfo_User"); - qRegisterMetaType >("QList"); + qRegisterMetaType>("QList"); qRegisterMetaType("Event_ReplayAdded"); - qRegisterMetaType >("missingFeatures"); + qRegisterMetaType>("missingFeatures"); FeatureSet features; features.initalizeFeatureList(clientFeatures); - + connect(this, SIGNAL(sigQueuePendingCommand(PendingCommand *)), this, SLOT(queuePendingCommand(PendingCommand *))); } @@ -64,33 +63,60 @@ void AbstractClient::processProtocolItem(const ServerMessage &item) 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::NOTIFY_USER: emit notifyUserEventReceived(event.GetExtension(Event_NotifyUser::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; + 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::NOTIFY_USER: + emit notifyUserEventReceived(event.GetExtension(Event_NotifyUser::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; } @@ -130,9 +156,9 @@ 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()); } diff --git a/cockatrice/src/abstractclient.h b/cockatrice/src/abstractclient.h index 6c8d987b..ae49de22 100644 --- a/cockatrice/src/abstractclient.h +++ b/cockatrice/src/abstractclient.h @@ -1,11 +1,11 @@ #ifndef ABSTRACTCLIENT_H #define ABSTRACTCLIENT_H -#include -#include -#include #include "pb/response.pb.h" #include "pb/serverinfo_user.pb.h" +#include +#include +#include class PendingCommand; class CommandContainer; @@ -27,7 +27,8 @@ class Event_ServerShutdown; class Event_ReplayAdded; class FeatureSet; -enum ClientStatus { +enum ClientStatus +{ StatusDisconnected, StatusDisconnecting, StatusConnecting, @@ -40,11 +41,12 @@ enum ClientStatus { StatusSubmitForgotPasswordChallenge, }; -class AbstractClient : public QObject { +class AbstractClient : public QObject +{ Q_OBJECT signals: void statusChanged(ClientStatus _status); - + // Room events void roomEventReceived(const RoomEvent &event); // Game events @@ -69,8 +71,9 @@ signals: void registerAccepted(); void registerAcceptedNeedsActivate(); void activateAccepted(); - + void sigQueuePendingCommand(PendingCommand *pend); + private: int nextCmdId; mutable QMutex clientMutex; @@ -79,23 +82,35 @@ private slots: void queuePendingCommand(PendingCommand *pend); protected slots: void processProtocolItem(const ServerMessage &item); + protected: QMap pendingCommands; QString userName, password, email, country, realName, token; int gender; void setStatus(ClientStatus _status); - int getNewCmdId() { return nextCmdId++; } + 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; } + + ClientStatus getStatus() const + { + QMutexLocker locker(&clientMutex); + return status; + } void sendCommand(const CommandContainer &cont); void sendCommand(PendingCommand *pend); - const QString getUserName() {return userName;} - + const QString getUserName() + { + return userName; + } + 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); diff --git a/cockatrice/src/abstractcounter.cpp b/cockatrice/src/abstractcounter.cpp index 67cb03da..64c19253 100644 --- a/cockatrice/src/abstractcounter.cpp +++ b/cockatrice/src/abstractcounter.cpp @@ -1,16 +1,24 @@ #include "abstractcounter.h" -#include "player.h" -#include "settingscache.h" -#include -#include -#include -#include -#include #include "pb/command_inc_counter.pb.h" #include "pb/command_set_counter.pb.h" +#include "player.h" +#include "settingscache.h" +#include +#include +#include +#include +#include -AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, bool _useNameForShortcut, QGraphicsItem *parent) - : QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), useNameForShortcut(_useNameForShortcut), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) +AbstractCounter::AbstractCounter(Player *_player, + int _id, + const QString &_name, + bool _shownInCounterArea, + int _value, + bool _useNameForShortcut, + QGraphicsItem *parent) + : QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), + useNameForShortcut(_useNameForShortcut), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), + deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) { setAcceptHoverEvents(true); @@ -37,8 +45,8 @@ AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name, } } else menu = nullptr; - - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); retranslateUi(); } @@ -93,7 +101,7 @@ void AbstractCounter::setShortcutsInactive() void AbstractCounter::refreshShortcuts() { - if(shortcutActive) + if (shortcutActive) setShortcutsActive(); } @@ -122,8 +130,8 @@ void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event) if (menu) menu->exec(event->screenPos()); event->accept(); - } - }else + } + } else event->ignore(); } @@ -152,8 +160,8 @@ void AbstractCounter::setCounter() { bool ok; dialogSemaphore = true; - int newValue = - QInputDialog::getInt(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok); + int newValue = QInputDialog::getInt(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, + -2000000000, 2000000000, 1, &ok); if (deleteAfterDialog) { deleteLater(); return; @@ -161,7 +169,7 @@ void AbstractCounter::setCounter() dialogSemaphore = false; if (!ok) return; - + Command_SetCounter cmd; cmd.set_counter_id(id); cmd.set_value(newValue); diff --git a/cockatrice/src/abstractcounter.h b/cockatrice/src/abstractcounter.h index 1e201f0c..99bcd7ca 100644 --- a/cockatrice/src/abstractcounter.h +++ b/cockatrice/src/abstractcounter.h @@ -7,7 +7,8 @@ class Player; class QMenu; class QAction; -class AbstractCounter : public QObject, public QGraphicsItem { +class AbstractCounter : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) protected: @@ -16,10 +17,11 @@ protected: QString name; int value; bool useNameForShortcut, hovered; - + void mousePressEvent(QGraphicsSceneMouseEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); + private: QAction *aSet, *aDec, *aInc; QMenu *menu; @@ -29,17 +31,39 @@ private slots: void refreshShortcuts(); void incrementCounter(); void setCounter(); + public: - AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, bool _useNameForShortcut = false, QGraphicsItem *parent = 0); + AbstractCounter(Player *_player, + int _id, + const QString &_name, + bool _shownInCounterArea, + int _value, + bool _useNameForShortcut = false, + QGraphicsItem *parent = 0); ~AbstractCounter(); - - QMenu *getMenu() const { return menu; } + + 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; } + + 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(); diff --git a/cockatrice/src/abstractgraphicsitem.cpp b/cockatrice/src/abstractgraphicsitem.cpp index 6fae46b1..af16c4af 100644 --- a/cockatrice/src/abstractgraphicsitem.cpp +++ b/cockatrice/src/abstractgraphicsitem.cpp @@ -1,7 +1,12 @@ #include "abstractgraphicsitem.h" #include -void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QColor &color, int position, int count, QPainter *painter) +void AbstractGraphicsItem::paintNumberEllipse(int number, + int fontSize, + const QColor &color, + int position, + int count, + QPainter *painter) { painter->save(); @@ -9,7 +14,7 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QC 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; @@ -18,7 +23,7 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QC painter->setPen(QColor(255, 255, 255, 0)); painter->setBrush(QBrush(QColor(color))); - + QRectF textRect; if (position == -1) textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); @@ -27,11 +32,15 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QC 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); + 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); + 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); diff --git a/cockatrice/src/abstractgraphicsitem.h b/cockatrice/src/abstractgraphicsitem.h index f838dcd3..39dcceb0 100644 --- a/cockatrice/src/abstractgraphicsitem.h +++ b/cockatrice/src/abstractgraphicsitem.h @@ -3,7 +3,8 @@ #include -enum GraphicsItemType { +enum GraphicsItemType +{ typeCard = QGraphicsItem::UserType + 1, typeCardDrag = QGraphicsItem::UserType + 2, typeZone = QGraphicsItem::UserType + 3, @@ -12,13 +13,17 @@ enum GraphicsItemType { typeOther = QGraphicsItem::UserType + 6 }; -class AbstractGraphicsItem : public QObject, public QGraphicsItem { +class AbstractGraphicsItem : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) protected: 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 a42206b8..1862aada 100644 --- a/cockatrice/src/arrowitem.cpp +++ b/cockatrice/src/arrowitem.cpp @@ -2,16 +2,16 @@ #include #include "arrowitem.h" -#include "playertarget.h" -#include "carditem.h" #include "carddatabase.h" +#include "carditem.h" #include "cardzone.h" #include "player.h" +#include "playertarget.h" #include "settingscache.h" -#include -#include -#include #include +#include +#include +#include #include "color.h" #include "pb/command_attach_card.pb.h" @@ -19,7 +19,8 @@ #include "pb/command_delete_arrow.pb.h" 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) + : QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color), + fullColor(true) { qDebug() << "ArrowItem constructor: startItem=" << static_cast(startItem); setZValue(2000000005); @@ -60,7 +61,8 @@ void ArrowItem::updatePath() if (!targetItem) return; - QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); + QPointF endPoint = targetItem->mapToScene( + QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); updatePath(endPoint); } @@ -68,13 +70,15 @@ void ArrowItem::updatePath(const QPointF &endPoint) { const double arrowWidth = 15.0; const double headWidth = 40.0; - const double headLength = headWidth / pow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++ + const double headLength = + headWidth / pow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++ const double phi = 15; if (!startItem) return; - QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); + QPointF startPoint = + startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); QLineF line(startPoint, endPoint); qreal lineLength = line.length(); @@ -92,10 +96,14 @@ void ArrowItem::updatePath(const QPointF &endPoint) 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)); + 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); @@ -229,15 +237,15 @@ void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) PlayerTarget *targetPlayer = qgraphicsitem_cast(targetItem); cmd.set_target_player_id(targetPlayer->getOwner()->getId()); } - if (startZone->getName().compare("hand") == 0) { + if (startZone->getName().compare("hand") == 0) { startCard->playCard(false); CardInfo *ci = startCard->getInfo(); if (ci && (((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || - ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && - startCard->getZone()->getName().toStdString() != "stack")))) + ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && + startCard->getZone()->getName().toStdString() != "stack")))) cmd.set_start_zone("stack"); else - cmd.set_start_zone(settingsCache->getPlayToStack() ? "stack" :"table"); + cmd.set_start_zone(settingsCache->getPlayToStack() ? "stack" : "table"); } player->sendGameCommand(cmd); } diff --git a/cockatrice/src/arrowitem.h b/cockatrice/src/arrowitem.h index 7e897d31..d5b1c512 100644 --- a/cockatrice/src/arrowitem.h +++ b/cockatrice/src/arrowitem.h @@ -9,12 +9,14 @@ class QMenu; class Player; class ArrowTarget; -class ArrowItem : public QObject, public QGraphicsItem { +class ArrowItem : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) private: QPainterPath path; QMenu *menu; + protected: Player *player; int id; @@ -22,40 +24,70 @@ protected: 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; } + 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; } + + 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 { +class ArrowDragItem : public ArrowItem +{ Q_OBJECT private: QList childArrows; + public: ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color); void addChildArrow(ArrowDragItem *childArrow); + protected: void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; -class ArrowAttachItem : public ArrowItem { +class ArrowAttachItem : public ArrowItem +{ Q_OBJECT public: ArrowAttachItem(ArrowTarget *_startItem); + protected: void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); diff --git a/cockatrice/src/arrowtarget.h b/cockatrice/src/arrowtarget.h index 31fcf157..3bf69986 100644 --- a/cockatrice/src/arrowtarget.h +++ b/cockatrice/src/arrowtarget.h @@ -7,29 +7,56 @@ class Player; class ArrowItem; -class ArrowTarget : public AbstractGraphicsItem { +class ArrowTarget : public AbstractGraphicsItem +{ Q_OBJECT protected: Player *owner; + private: bool beingPointedAt; QList arrowsFrom, arrowsTo; + public: ArrowTarget(Player *_owner, QGraphicsItem *parent = 0); ~ArrowTarget(); - - Player *getOwner() const { return owner; } - + + 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)); } + 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 468196f8..b52bee4e 100644 --- a/cockatrice/src/carddatabase.cpp +++ b/cockatrice/src/carddatabase.cpp @@ -10,12 +10,11 @@ #include const int CardDatabase::versionNeeded = 3; -const char* CardDatabase::TOKENS_SETNAME = "TK"; +const char *CardDatabase::TOKENS_SETNAME = "TK"; static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardSet *set) { - if (set == nullptr) - { + if (set == nullptr) { qDebug() << "&operator<< set is nullptr"; return xml; } @@ -30,7 +29,10 @@ static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardSet *set) return xml; } -CardSet::CardSet(const QString &_shortName, const QString &_longName, const QString &_setType, const QDate &_releaseDate) +CardSet::CardSet(const QString &_shortName, + const QString &_longName, + const QString &_setType, + const QDate &_releaseDate) : shortName(_shortName), longName(_longName), releaseDate(_releaseDate), setType(_setType) { loadSetOptions(); @@ -40,10 +42,28 @@ QString CardSet::getCorrectedShortName() const { // For Windows machines. QSet invalidFileNames; - invalidFileNames << "CON" << "PRN" << "AUX" << "NUL" << "COM1" << "COM2" << - "COM3" << "COM4" << "COM5" << "COM6" << "COM7" << "COM8" << "COM9" << - "LPT1" << "LPT2" << "LPT3" << "LPT4" << "LPT5" << "LPT6" << "LPT7" << - "LPT8" << "LPT9"; + invalidFileNames << "CON" + << "PRN" + << "AUX" + << "NUL" + << "COM1" + << "COM2" + << "COM3" + << "COM4" + << "COM5" + << "COM6" + << "COM7" + << "COM8" + << "COM9" + << "LPT1" + << "LPT2" + << "LPT3" + << "LPT4" + << "LPT5" + << "LPT6" + << "LPT7" + << "LPT8" + << "LPT9"; return invalidFileNames.contains(shortName) ? shortName + "_" : shortName; } @@ -58,34 +78,33 @@ void CardSet::loadSetOptions() void CardSet::setSortKey(unsigned int _sortKey) { sortKey = _sortKey; - settingsCache->cardDatabase().setSortKey(shortName,_sortKey); + settingsCache->cardDatabase().setSortKey(shortName, _sortKey); } void CardSet::setEnabled(bool _enabled) { enabled = _enabled; - settingsCache->cardDatabase().setEnabled(shortName,_enabled); + settingsCache->cardDatabase().setEnabled(shortName, _enabled); } void CardSet::setIsKnown(bool _isknown) { isknown = _isknown; - settingsCache->cardDatabase().setIsKnown(shortName,_isknown); + settingsCache->cardDatabase().setIsKnown(shortName, _isknown); } class SetList::KeyCompareFunctor { - public: - inline bool operator()(CardSet *a, CardSet *b) const - { - if (a == nullptr || b == nullptr) - { - qDebug() << "SetList::KeyCompareFunctor a or b is null"; - return false; - } - - return a->getSortKey() < b->getSortKey(); +public: + inline bool operator()(CardSet *a, CardSet *b) const + { + if (a == nullptr || b == nullptr) { + qDebug() << "SetList::KeyCompareFunctor a or b is null"; + return false; } + + return a->getSortKey() < b->getSortKey(); + } }; void SetList::sortByKey() @@ -96,11 +115,9 @@ void SetList::sortByKey() int SetList::getEnabledSetsNum() { int num = 0; - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if (set && set->getEnabled()) - { + if (set && set->getEnabled()) { ++num; } } @@ -110,11 +127,9 @@ int SetList::getEnabledSetsNum() int SetList::getUnknownSetsNum() { int num = 0; - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) - { + if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { ++num; } } @@ -124,11 +139,9 @@ int SetList::getUnknownSetsNum() QStringList SetList::getUnknownSetsNames() { QStringList sets = QStringList(); - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) - { + if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { sets << set->getShortName(); } } @@ -137,16 +150,12 @@ QStringList SetList::getUnknownSetsNames() void SetList::enableAllUnknown() { - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) - { + if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { set->setIsKnown(true); set->setEnabled(true); - } - else if (set && set->getIsKnownIgnored() && !set->getEnabled()) - { + } else if (set && set->getIsKnownIgnored() && !set->getEnabled()) { set->setEnabled(true); } } @@ -154,18 +163,15 @@ void SetList::enableAllUnknown() void SetList::enableAll() { - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if (set == nullptr) - { + if (set == nullptr) { qDebug() << "enabledAll has null"; continue; } - if (!set->getIsKnownIgnored()) - { + if (!set->getIsKnownIgnored()) { set->setIsKnown(true); } @@ -175,16 +181,12 @@ void SetList::enableAll() void SetList::markAllAsKnown() { - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if(set && !set->getIsKnown() && !set->getIsKnownIgnored()) - { + if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { set->setIsKnown(true); set->setEnabled(false); - } - else if (set && set->getIsKnownIgnored() && !set->getEnabled()) - { + } else if (set && set->getIsKnownIgnored() && !set->getEnabled()) { set->setEnabled(true); } } @@ -195,22 +197,17 @@ void SetList::guessSortKeys() // sort by release date DESC; invalid dates to the bottom. QDate distantFuture(2050, 1, 1); int aHundredYears = 36500; - for (int i = 0; i < size(); ++i) - { + for (int i = 0; i < size(); ++i) { CardSet *set = at(i); - if (set == nullptr) - { + if (set == nullptr) { qDebug() << "guessSortKeys set is null"; continue; } QDate date = set->getReleaseDate(); - if (date.isNull()) - { + if (date.isNull()) { set->setSortKey(static_cast(aHundredYears)); - } - else - { + } else { set->setSortKey(static_cast(date.daysTo(distantFuture))); } } @@ -234,34 +231,17 @@ CardInfo::CardInfo(const QString &_name, const QStringMap &_customPicURLs, MuidMap _muIds, QStringMap _collectorNumbers, - QStringMap _rarities - ) - : name(_name), - isToken(_isToken), - sets(_sets), - manacost(_manacost), - cmc(_cmc), - cardtype(_cardtype), - powtough(_powtough), - text(_text), - colors(_colors), - relatedCards(_relatedCards), - reverseRelatedCards(_reverseRelatedCards), - setsNames(), - upsideDownArt(_upsideDownArt), - loyalty(_loyalty), - customPicURLs(_customPicURLs), - muIds(std::move(_muIds)), - collectorNumbers(std::move(_collectorNumbers)), - rarities(std::move(_rarities)), - cipt(_cipt), - tableRow(_tableRow) + QStringMap _rarities) + : name(_name), isToken(_isToken), sets(_sets), manacost(_manacost), cmc(_cmc), cardtype(_cardtype), + powtough(_powtough), text(_text), colors(_colors), relatedCards(_relatedCards), + reverseRelatedCards(_reverseRelatedCards), setsNames(), upsideDownArt(_upsideDownArt), loyalty(_loyalty), + customPicURLs(_customPicURLs), muIds(std::move(_muIds)), collectorNumbers(std::move(_collectorNumbers)), + rarities(std::move(_rarities)), cipt(_cipt), tableRow(_tableRow) { pixmapCacheKey = QLatin1String("card_") + name; simpleName = CardInfo::simplifyName(name); - for (int i = 0; i < sets.size(); i++) - { + for (int i = 0; i < sets.size(); i++) { sets[i]->append(this); } @@ -282,18 +262,15 @@ QString CardInfo::getMainCardType() const */ int pos; - if ((pos = result.indexOf('-')) != -1) - { + if ((pos = result.indexOf('-')) != -1) { result.remove(pos, result.length()); } - if ((pos = result.indexOf("—")) != -1) - { + if ((pos = result.indexOf("—")) != -1) { result.remove(pos, result.length()); } - if ((pos = result.indexOf("//")) != -1) - { + if ((pos = result.indexOf("//")) != -1) { result.remove(pos, result.length()); } @@ -303,8 +280,7 @@ QString CardInfo::getMainCardType() const Instant */ - if ((pos = result.lastIndexOf(' ')) != -1) - { + if ((pos = result.lastIndexOf(' ')) != -1) { result = result.mid(pos + 1); } /* @@ -324,8 +300,7 @@ QString CardInfo::getCorrectedName() const void CardInfo::addToSet(CardSet *set) { - if (set == nullptr) - { + if (set == nullptr) { qDebug() << "addToSet(nullptr)"; return; } @@ -340,15 +315,12 @@ void CardInfo::refreshCachedSetNames() { // update the cached list of set names QStringList setList; - for (int i = 0; i < sets.size(); i++) - { - if (sets[i]->getEnabled()) - { + for (int i = 0; i < sets.size(); i++) { + if (sets[i]->getEnabled()) { setList << sets[i]->getShortName(); } } setsNames = setList.join(", "); - } QString CardInfo::simplifyName(const QString &name) @@ -374,8 +346,7 @@ QString CardInfo::simplifyName(const QString &name) const QChar CardInfo::getColorChar() const { - switch(colors.size()) - { + switch (colors.size()) { case 0: return QChar(); case 1: @@ -387,8 +358,7 @@ const QChar CardInfo::getColorChar() const static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfo *info) { - if (info == nullptr) - { + if (info == nullptr) { qDebug() << "operator<< info is nullptr"; return xml; } @@ -399,23 +369,20 @@ static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfo *info) const SetList &sets = info->getSets(); QString tmpString; QString tmpSet; - for (int i = 0; i < sets.size(); i++) - { + for (int i = 0; i < sets.size(); i++) { xml.writeStartElement("set"); - tmpSet=sets[i]->getShortName(); + tmpSet = sets[i]->getShortName(); xml.writeAttribute("rarity", info->getRarity(tmpSet)); xml.writeAttribute("muId", QString::number(info->getMuId(tmpSet))); tmpString = info->getCollectorNumber(tmpSet); - if (!tmpString.isEmpty()) - { + if (!tmpString.isEmpty()) { xml.writeAttribute("num", info->getCollectorNumber(tmpSet)); } tmpString = info->getCustomPicURL(tmpSet); - if (!tmpString.isEmpty()) - { + if (!tmpString.isEmpty()) { xml.writeAttribute("picURL", tmpString); } @@ -423,69 +390,50 @@ static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfo *info) xml.writeEndElement(); } const QStringList &colors = info->getColors(); - for (int i = 0; i < colors.size(); i++) - { + for (int i = 0; i < colors.size(); i++) { xml.writeTextElement("color", colors[i]); } const QList related = info->getRelatedCards(); - for (auto i : related) - { + for (auto i : related) { xml.writeStartElement("related"); - if (i->getDoesAttach()) - { + if (i->getDoesAttach()) { xml.writeAttribute("attach", "attach"); } - if (i->getIsCreateAllExclusion()) - { + if (i->getIsCreateAllExclusion()) { xml.writeAttribute("exclude", "exclude"); } - if (i->getIsVariable()) - { - if (1 == i->getDefaultCount()) - { + if (i->getIsVariable()) { + if (1 == i->getDefaultCount()) { xml.writeAttribute("count", "x"); - } - else - { + } else { xml.writeAttribute("count", "x=" + QString::number(i->getDefaultCount())); } - } - else if (1 != i->getDefaultCount()) - { + } else if (1 != i->getDefaultCount()) { xml.writeAttribute("count", QString::number(i->getDefaultCount())); } xml.writeCharacters(i->getName()); xml.writeEndElement(); } const QList reverseRelated = info->getReverseRelatedCards(); - for (auto i : reverseRelated) - { + for (auto i : reverseRelated) { xml.writeStartElement("reverse-related"); - if (i->getDoesAttach()) - { + if (i->getDoesAttach()) { xml.writeAttribute("attach", "attach"); } - if (i->getIsCreateAllExclusion()) - { + if (i->getIsCreateAllExclusion()) { xml.writeAttribute("exclude", "exclude"); } - if (i->getIsVariable()) - { - if (1 == i->getDefaultCount()) - { + if (i->getIsVariable()) { + if (1 == i->getDefaultCount()) { xml.writeAttribute("count", "x"); - } - else - { + } else { xml.writeAttribute("count", "x=" + QString::number(i->getDefaultCount())); } - } - else if (1 != i->getDefaultCount()) - { + } else if (1 != i->getDefaultCount()) { xml.writeAttribute("count", QString::number(i->getDefaultCount())); } xml.writeCharacters(i->getName()); @@ -494,26 +442,21 @@ static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfo *info) xml.writeTextElement("manacost", info->getManaCost()); xml.writeTextElement("cmc", info->getCmc()); xml.writeTextElement("type", info->getCardType()); - if (!info->getPowTough().isEmpty()) - { + 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") - { + if (info->getMainCardType() == "Planeswalker") { xml.writeTextElement("loyalty", QString::number(info->getLoyalty())); } - if (info->getCipt()) - { + if (info->getCipt()) { xml.writeTextElement("cipt", "1"); } - if (info->getIsToken()) - { + if (info->getIsToken()) { xml.writeTextElement("token", "1"); } - if (info->getUpsideDownArt()) - { + if (info->getUpsideDownArt()) { xml.writeTextElement("upsidedown", "1"); } @@ -537,11 +480,9 @@ void CardDatabase::clear() clearDatabaseMutex->lock(); QHashIterator i(cards); - while (i.hasNext()) - { + while (i.hasNext()) { i.next(); - if (i.value()) - { + if (i.value()) { removeCard(i.value()); i.value()->deleteLater(); } @@ -552,8 +493,7 @@ void CardDatabase::clear() simpleNameCards.clear(); QHashIterator setIt(sets); - while (setIt.hasNext()) - { + while (setIt.hasNext()) { setIt.next(); delete setIt.value(); } @@ -566,8 +506,7 @@ void CardDatabase::clear() void CardDatabase::addCard(CardInfo *card) { - if (card == nullptr) - { + if (card == nullptr) { qDebug() << "addCard(nullptr)"; return; } @@ -581,19 +520,18 @@ void CardDatabase::addCard(CardInfo *card) void CardDatabase::removeCard(CardInfo *card) { - if (card == nullptr) - { + if (card == nullptr) { qDebug() << "removeCard(nullptr)"; return; } - foreach(CardRelation * cardRelation, card->getRelatedCards()) + foreach (CardRelation *cardRelation, card->getRelatedCards()) cardRelation->deleteLater(); - foreach(CardRelation * cardRelation, card->getReverseRelatedCards()) + foreach (CardRelation *cardRelation, card->getReverseRelatedCards()) cardRelation->deleteLater(); - foreach(CardRelation * cardRelation, card->getReverseRelatedCards2Me()) + foreach (CardRelation *cardRelation, card->getReverseRelatedCards2Me()) cardRelation->deleteLater(); removeCardMutex->lock(); @@ -611,7 +549,7 @@ CardInfo *CardDatabase::getCard(const QString &cardName) const QList CardDatabase::getCards(const QStringList &cardNames) const { QList cardInfos; - foreach(QString cardName, cardNames) + foreach (QString cardName, cardNames) cardInfos.append(getCardFromMap(cards, cardName)); return cardInfos; @@ -624,12 +562,9 @@ CardInfo *CardDatabase::getCardBySimpleName(const QString &cardName) const CardSet *CardDatabase::getSet(const QString &setName) { - if (sets.contains(setName)) - { + if (sets.contains(setName)) { return sets.value(setName); - } - else - { + } else { CardSet *newSet = new CardSet(setName); sets.insert(setName, newSet); return newSet; @@ -640,8 +575,7 @@ SetList CardDatabase::getSetList() const { SetList result; QHashIterator i(sets); - while (i.hasNext()) - { + while (i.hasNext()) { i.next(); result << i.value(); } @@ -650,42 +584,28 @@ SetList CardDatabase::getSetList() const void CardDatabase::loadSetsFromXml(QXmlStreamReader &xml) { - while (!xml.atEnd()) - { - if (xml.readNext() == QXmlStreamReader::EndElement) - { + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) { break; } - if (xml.name() == "set") - { + if (xml.name() == "set") { QString shortName, longName, setType; QDate releaseDate; - while (!xml.atEnd()) - { - if (xml.readNext() == QXmlStreamReader::EndElement) - { + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) { break; } - if (xml.name() == "name") - { + if (xml.name() == "name") { shortName = xml.readElementText(); - } - else if (xml.name() == "longname") - { + } else if (xml.name() == "longname") { longName = xml.readElementText(); - } - else if (xml.name() == "settype") - { + } else if (xml.name() == "settype") { setType = xml.readElementText(); - } - else if (xml.name() == "releasedate") - { + } else if (xml.name() == "releasedate") { releaseDate = QDate::fromString(xml.readElementText(), Qt::ISODate); - } - else if (xml.name() != "") - { + } else if (xml.name() != "") { qDebug() << "[XMLReader] Unknown set property" << xml.name() << ", trying to continue anyway"; xml.skipCurrentElement(); } @@ -701,15 +621,12 @@ void CardDatabase::loadSetsFromXml(QXmlStreamReader &xml) void CardDatabase::loadCardsFromXml(QXmlStreamReader &xml) { - while (!xml.atEnd()) - { - if (xml.readNext() == QXmlStreamReader::EndElement) - { + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) { break; } - if (xml.name() == "card") - { + if (xml.name() == "card") { QString name, manacost, cmc, type, pt, text; QStringList colors; QList relatedCards, reverseRelatedCards; @@ -722,152 +639,106 @@ void CardDatabase::loadCardsFromXml(QXmlStreamReader &xml) bool cipt = false; bool isToken = false; bool upsideDown = false; - while (!xml.atEnd()) - { - if (xml.readNext() == QXmlStreamReader::EndElement) - { + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) { break; } - if (xml.name() == "name") - { + if (xml.name() == "name") { name = xml.readElementText(); - } - else if (xml.name() == "manacost") - { + } else if (xml.name() == "manacost") { manacost = xml.readElementText(); - } - else if (xml.name() == "cmc") - { + } else if (xml.name() == "cmc") { cmc = xml.readElementText(); - } - else if (xml.name() == "type") - { + } else if (xml.name() == "type") { type = xml.readElementText(); - } - else if (xml.name() == "pt") - { + } else if (xml.name() == "pt") { pt = xml.readElementText(); - } - else if (xml.name() == "text") - { + } else if (xml.name() == "text") { text = xml.readElementText(); - } - else if (xml.name() == "set") - { + } else if (xml.name() == "set") { QXmlStreamAttributes attrs = xml.attributes(); QString setName = xml.readElementText(); sets.append(getSet(setName)); - if (attrs.hasAttribute("muId")) - { + if (attrs.hasAttribute("muId")) { muids[setName] = attrs.value("muId").toString().toInt(); } - if (attrs.hasAttribute("picURL")) - { + if (attrs.hasAttribute("picURL")) { customPicURLs[setName] = attrs.value("picURL").toString(); } - if (attrs.hasAttribute("num")) - { + if (attrs.hasAttribute("num")) { collectorNumbers[setName] = attrs.value("num").toString(); } - if (attrs.hasAttribute("rarity")) - { + if (attrs.hasAttribute("rarity")) { rarities[setName] = attrs.value("rarity").toString(); } - } - else if (xml.name() == "color") - { + } else if (xml.name() == "color") { colors << xml.readElementText(); - } - else if (xml.name() == "related" || xml.name() == "reverse-related") - { + } else if (xml.name() == "related" || xml.name() == "reverse-related") { bool attach = false; bool exclude = false; bool variable = false; int count = 1; QXmlStreamAttributes attrs = xml.attributes(); QString cardName = xml.readElementText(); - if (attrs.hasAttribute("count")) - { - if (attrs.value("count").toString().indexOf("x=") == 0) - { + if (attrs.hasAttribute("count")) { + if (attrs.value("count").toString().indexOf("x=") == 0) { variable = true; count = attrs.value("count").toString().remove(0, 2).toInt(); - } - else if (attrs.value("count").toString().indexOf("x") == 0) - { + } else if (attrs.value("count").toString().indexOf("x") == 0) { variable = true; - } - else - { + } else { count = attrs.value("count").toString().toInt(); } - if (count < 1) - { + if (count < 1) { count = 1; } } - if (attrs.hasAttribute("attach")) - { + if (attrs.hasAttribute("attach")) { attach = true; } - if (attrs.hasAttribute("exclude")) - { + if (attrs.hasAttribute("exclude")) { exclude = true; } auto *relation = new CardRelation(cardName, attach, exclude, variable, count); - if (xml.name() == "reverse-related") - { + if (xml.name() == "reverse-related") { reverseRelatedCards << relation; - } - else - { + } else { relatedCards << relation; } - } - else if (xml.name() == "tablerow") - { + } else if (xml.name() == "tablerow") { tableRow = xml.readElementText().toInt(); - } - else if (xml.name() == "cipt") - { + } else if (xml.name() == "cipt") { cipt = (xml.readElementText() == "1"); - } - else if (xml.name() == "upsidedown") - { + } else if (xml.name() == "upsidedown") { upsideDown = (xml.readElementText() == "1"); - } - else if (xml.name() == "loyalty") - { + } else if (xml.name() == "loyalty") { loyalty = xml.readElementText().toInt(); - } - else if (xml.name() == "token") - { + } else if (xml.name() == "token") { isToken = static_cast(xml.readElementText().toInt()); - } - else if (xml.name() != "") - { + } else if (xml.name() != "") { qDebug() << "[XMLReader] Unknown card property" << xml.name() << ", trying to continue anyway"; xml.skipCurrentElement(); } } - addCard(new CardInfo(name, isToken, manacost, cmc, type, pt, text, colors, relatedCards, reverseRelatedCards, upsideDown, loyalty, cipt, tableRow, sets, customPicURLs, muids, collectorNumbers, rarities)); + addCard(new CardInfo(name, isToken, manacost, cmc, type, pt, text, colors, relatedCards, + reverseRelatedCards, upsideDown, loyalty, cipt, tableRow, sets, customPicURLs, muids, + collectorNumbers, rarities)); } } } CardInfo *CardDatabase::getCardFromMap(const CardNameMap &cardMap, const QString &cardName) const { - if (cardMap.contains(cardName)) - { + if (cardMap.contains(cardName)) { return cardMap.value(cardName); } @@ -878,45 +749,33 @@ LoadStatus CardDatabase::loadFromFile(const QString &fileName) { QFile file(fileName); file.open(QIODevice::ReadOnly); - if (!file.isOpen()) - { + if (!file.isOpen()) { return FileError; } QXmlStreamReader xml(&file); - while (!xml.atEnd()) - { - if (xml.readNext() == QXmlStreamReader::StartElement) - { - if (xml.name() != "cockatrice_carddatabase") - { + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::StartElement) { + if (xml.name() != "cockatrice_carddatabase") { return Invalid; } int version = xml.attributes().value("version").toString().toInt(); - if (version < versionNeeded) - { + if (version < versionNeeded) { qDebug() << "[XMLReader] Version too old: " << version; return VersionTooOld; } - while (!xml.atEnd()) - { - if (xml.readNext() == QXmlStreamReader::EndElement) - { + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) { break; } - if (xml.name() == "sets") - { + if (xml.name() == "sets") { loadSetsFromXml(xml); - } - else if (xml.name() == "cards") - { + } else if (xml.name() == "cards") { loadCardsFromXml(xml); - } - else if (xml.name() != "") - { + } else if (xml.name() != "") { qDebug() << "[XMLReader] Unknown item" << xml.name() << ", trying to continue anyway"; xml.skipCurrentElement(); } @@ -924,8 +783,7 @@ LoadStatus CardDatabase::loadFromFile(const QString &fileName) } } - if (cards.isEmpty()) - { + if (cards.isEmpty()) { return NoCards; } @@ -935,8 +793,7 @@ LoadStatus CardDatabase::loadFromFile(const QString &fileName) bool CardDatabase::saveToFile(const QString &fileName, bool tokens) { QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) - { + if (!file.open(QIODevice::WriteOnly)) { return false; } @@ -947,12 +804,10 @@ bool CardDatabase::saveToFile(const QString &fileName, bool tokens) xml.writeStartElement("cockatrice_carddatabase"); xml.writeAttribute("version", QString::number(versionNeeded)); - if (! tokens) - { + if (!tokens) { xml.writeStartElement("sets"); QHashIterator setIterator(sets); - while (setIterator.hasNext()) - { + while (setIterator.hasNext()) { xml << setIterator.next().value(); } @@ -961,11 +816,9 @@ bool CardDatabase::saveToFile(const QString &fileName, bool tokens) xml.writeStartElement("cards"); QHashIterator cardIterator(cards); - while (cardIterator.hasNext()) - { + while (cardIterator.hasNext()) { CardInfo *card = cardIterator.next().value(); - if (tokens == card->getIsToken()) - { + if (tokens == card->getIsToken()) { xml << card; } } @@ -980,14 +833,14 @@ bool CardDatabase::saveToFile(const QString &fileName, bool tokens) LoadStatus CardDatabase::loadCardDatabase(const QString &path) { LoadStatus tempLoadStatus = NotLoaded; - if (!path.isEmpty()) - { + if (!path.isEmpty()) { loadFromFileMutex->lock(); tempLoadStatus = loadFromFile(path); loadFromFileMutex->unlock(); } - qDebug() << "[CardDatabase] loadCardDatabase(): Path =" << path << "Status =" << tempLoadStatus << "Cards =" << cards.size() << "Sets=" << sets.size(); + qDebug() << "[CardDatabase] loadCardDatabase(): Path =" << path << "Status =" << tempLoadStatus + << "Cards =" << cards.size() << "Sets=" << sets.size(); return tempLoadStatus; } @@ -1001,13 +854,13 @@ LoadStatus CardDatabase::loadCardDatabases() clear(); // remove old db loadStatus = loadCardDatabase(settingsCache->getCardDatabasePath()); // load main card database - loadCardDatabase(settingsCache->getTokenDatabasePath()); // load tokens database - loadCardDatabase(settingsCache->getSpoilerCardDatabasePath()); // load spoilers database + loadCardDatabase(settingsCache->getTokenDatabasePath()); // load tokens database + loadCardDatabase(settingsCache->getSpoilerCardDatabasePath()); // load spoilers database // load custom card databases QDir dir(settingsCache->getCustomCardDatabasePath()); - foreach(QString fileName, dir.entryList(QStringList("*.xml"), QDir::Files | QDir::Readable, QDir::Name | QDir::IgnoreCase)) - { + foreach (QString fileName, + dir.entryList(QStringList("*.xml"), QDir::Files | QDir::Readable, QDir::Name | QDir::IgnoreCase)) { loadCardDatabase(dir.absoluteFilePath(fileName)); } @@ -1016,8 +869,7 @@ LoadStatus CardDatabase::loadCardDatabases() // reorder sets (TODO: refactor, this smells) SetList allSets; QHashIterator setsIterator(sets); - while (setsIterator.hasNext()) - { + while (setsIterator.hasNext()) { allSets.append(setsIterator.next().value()); } allSets.sortByKey(); @@ -1025,13 +877,10 @@ LoadStatus CardDatabase::loadCardDatabases() // resolve the reverse-related tags refreshCachedReverseRelatedCards(); - if (loadStatus == Ok) - { + if (loadStatus == Ok) { checkUnknownSets(); // update deck editors, etc qDebug() << "CardDatabase::loadCardDatabases success"; - } - else - { + } else { qDebug() << "CardDatabase::loadCardDatabases failed"; emit cardDatabaseLoadingFailed(); // bring up the settings dialog } @@ -1042,38 +891,30 @@ LoadStatus CardDatabase::loadCardDatabases() void CardDatabase::refreshCachedReverseRelatedCards() { - foreach(CardInfo * card, cards) + foreach (CardInfo *card, cards) card->resetReverseRelatedCards2Me(); - foreach(CardInfo * card, cards) - { - if (card->getReverseRelatedCards().isEmpty()) - { + foreach (CardInfo *card, cards) { + if (card->getReverseRelatedCards().isEmpty()) { continue; } QString relatedCardName; - if (card->getPowTough().size() > 0) - { + if (card->getPowTough().size() > 0) { relatedCardName = card->getPowTough() + " " + card->getName(); // "n/n name" - } - else - { + } else { relatedCardName = card->getName(); // "name" } - foreach(CardRelation * cardRelation, card->getReverseRelatedCards()) - { - const QString & targetCard = cardRelation->getName(); - if (!cards.contains(targetCard)) - { + foreach (CardRelation *cardRelation, card->getReverseRelatedCards()) { + const QString &targetCard = cardRelation->getName(); + if (!cards.contains(targetCard)) { continue; } auto *newCardRelation = new CardRelation(relatedCardName, cardRelation->getDoesAttach(), - cardRelation->getIsCreateAllExclusion(), - cardRelation->getIsVariable(), - cardRelation->getDefaultCount()); + cardRelation->getIsCreateAllExclusion(), + cardRelation->getIsVariable(), cardRelation->getDefaultCount()); cards.value(targetCard)->addReverseRelatedCards2Me(newCardRelation); } } @@ -1083,17 +924,12 @@ QStringList CardDatabase::getAllColors() const { QSet colors; QHashIterator cardIterator(cards); - while (cardIterator.hasNext()) - { + while (cardIterator.hasNext()) { const QStringList &cardColors = cardIterator.next().value()->getColors(); - if (cardColors.isEmpty()) - { + if (cardColors.isEmpty()) { colors.insert("X"); - } - else - { - for (int i = 0; i < cardColors.size(); ++i) - { + } else { + for (int i = 0; i < cardColors.size(); ++i) { colors.insert(cardColors[i]); } } @@ -1105,8 +941,7 @@ QStringList CardDatabase::getAllMainCardTypes() const { QSet types; QHashIterator cardIterator(cards); - while (cardIterator.hasNext()) - { + while (cardIterator.hasNext()) { types.insert(cardIterator.next().value()->getMainCardType()); } return types.toList(); @@ -1116,22 +951,16 @@ void CardDatabase::checkUnknownSets() { SetList sets = getSetList(); - if (sets.getEnabledSetsNum()) - { + if (sets.getEnabledSetsNum()) { // if some sets are first found on thus run, ask the user int numUnknownSets = sets.getUnknownSetsNum(); QStringList unknownSetNames = sets.getUnknownSetsNames(); - if (numUnknownSets > 0) - { + if (numUnknownSets > 0) { emit cardDatabaseNewSetsFound(numUnknownSets, unknownSetNames); - } - else - { + } else { sets.markAllAsKnown(); } - } - else - { + } else { // No set enabled. Probably this is the first time running trice sets.guessSortKeys(); sets.sortByKey(); @@ -1157,7 +986,7 @@ void CardDatabase::markAllSetsAsKnown() void CardDatabase::notifyEnabledSetsChanged() { // refresh the list of cached set names - foreach(CardInfo * card, cards) + foreach (CardInfo *card, cards) card->refreshCachedSetNames(); // inform the carddatabasemodels that they need to re-check their list of cards @@ -1169,8 +998,7 @@ bool CardDatabase::saveCustomTokensToFile() CardSet *customTokensSet = getSet(CardDatabase::TOKENS_SETNAME); QString fileName = settingsCache->getCustomCardDatabasePath() + "/" + CardDatabase::TOKENS_SETNAME + ".xml"; QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) - { + if (!file.open(QIODevice::WriteOnly)) { return false; } @@ -1183,11 +1011,9 @@ bool CardDatabase::saveCustomTokensToFile() xml.writeStartElement("cards"); QHashIterator cardIterator(cards); - while (cardIterator.hasNext()) - { + while (cardIterator.hasNext()) { CardInfo *card = cardIterator.next().value(); - if (card->getSets().contains(customTokensSet)) - { + if (card->getSets().contains(customTokensSet)) { xml << card; } } @@ -1199,20 +1025,19 @@ bool CardDatabase::saveCustomTokensToFile() return true; } -CardRelation::CardRelation(const QString &_name, bool _doesAttach, bool _isCreateAllExclusion, bool _isVariableCount, int _defaultCount) : - name(_name), - doesAttach(_doesAttach), - isCreateAllExclusion(_isCreateAllExclusion), - isVariableCount(_isVariableCount), - defaultCount(_defaultCount) +CardRelation::CardRelation(const QString &_name, + bool _doesAttach, + bool _isCreateAllExclusion, + bool _isVariableCount, + int _defaultCount) + : name(_name), doesAttach(_doesAttach), isCreateAllExclusion(_isCreateAllExclusion), + isVariableCount(_isVariableCount), defaultCount(_defaultCount) { - } void CardInfo::resetReverseRelatedCards2Me() { - foreach(CardRelation * cardRelation, this->getReverseRelatedCards2Me()) - { + foreach (CardRelation *cardRelation, this->getReverseRelatedCards2Me()) { cardRelation->deleteLater(); } reverseRelatedCardsToMe = QList(); diff --git a/cockatrice/src/carddatabase.h b/cockatrice/src/carddatabase.h index a76bb598..43b48f66 100644 --- a/cockatrice/src/carddatabase.h +++ b/cockatrice/src/carddatabase.h @@ -1,14 +1,14 @@ #ifndef CARDDATABASE_H #define CARDDATABASE_H -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include class CardDatabase; class CardInfo; @@ -21,174 +21,324 @@ typedef QMap MuidMap; class CardSet : public QList { - private: - QString shortName, longName; - unsigned int sortKey; - QDate releaseDate; - QString setType; - bool enabled, isknown; +private: + QString shortName, longName; + unsigned int sortKey; + QDate releaseDate; + QString setType; + bool enabled, isknown; - public: - explicit CardSet(const QString &_shortName = QString(), const QString &_longName = QString(), const QString &_setType = QString(), const QDate &_releaseDate = QDate()); - QString getCorrectedShortName() const; - QString getShortName() const { return shortName; } - QString getLongName() const { return longName; } - QString getSetType() const { return setType; } - QDate getReleaseDate() const { return releaseDate; } - void setLongName(QString & _longName) { longName = _longName; } - void setSetType(QString & _setType) { setType = _setType; } - void setReleaseDate(QDate & _releaseDate) { releaseDate = _releaseDate; } +public: + explicit CardSet(const QString &_shortName = QString(), + const QString &_longName = QString(), + const QString &_setType = QString(), + const QDate &_releaseDate = QDate()); + QString getCorrectedShortName() const; + QString getShortName() const + { + return shortName; + } + QString getLongName() const + { + return longName; + } + QString getSetType() const + { + return setType; + } + QDate getReleaseDate() const + { + return releaseDate; + } + void setLongName(QString &_longName) + { + longName = _longName; + } + void setSetType(QString &_setType) + { + setType = _setType; + } + void setReleaseDate(QDate &_releaseDate) + { + releaseDate = _releaseDate; + } - void loadSetOptions(); - int getSortKey() const { return sortKey; } - void setSortKey(unsigned int _sortKey); - bool getEnabled() const { return enabled; } - void setEnabled(bool _enabled); - bool getIsKnown() const { return isknown; } - void setIsKnown(bool _isknown); + void loadSetOptions(); + int getSortKey() const + { + return sortKey; + } + void setSortKey(unsigned int _sortKey); + bool getEnabled() const + { + return enabled; + } + void setEnabled(bool _enabled); + bool getIsKnown() const + { + return isknown; + } + void setIsKnown(bool _isknown); - //Determine incomplete sets. - bool getIsKnownIgnored() const { return longName.length() + setType.length() + releaseDate.toString().length() == 0 ; } + // Determine incomplete sets. + bool getIsKnownIgnored() const + { + return longName.length() + setType.length() + releaseDate.toString().length() == 0; + } }; class SetList : public QList { - private: - class KeyCompareFunctor; +private: + class KeyCompareFunctor; - public: - void sortByKey(); - void guessSortKeys(); - void enableAllUnknown(); - void enableAll(); - void markAllAsKnown(); - int getEnabledSetsNum(); - int getUnknownSetsNum(); - QStringList getUnknownSetsNames(); +public: + void sortByKey(); + void guessSortKeys(); + void enableAllUnknown(); + void enableAll(); + void markAllAsKnown(); + int getEnabledSetsNum(); + int getUnknownSetsNum(); + QStringList getUnknownSetsNames(); }; class CardInfo : public QObject { Q_OBJECT - private: - QString name; +private: + QString name; - /* - * The name without punctuation or capitalization, for better card tag name - * recognition. - */ - QString simpleName; + /* + * The name without punctuation or capitalization, for better card tag name + * recognition. + */ + QString simpleName; - bool isToken; - SetList sets; - QString manacost; - QString cmc; - QString cardtype; - QString powtough; - QString text; - QStringList colors; + bool isToken; + SetList sets; + QString manacost; + QString cmc; + QString cardtype; + QString powtough; + QString text; + QStringList colors; - // the cards i'm related to - QList relatedCards; + // the cards i'm related to + QList relatedCards; - // the card i'm reverse-related to - QList reverseRelatedCards; + // the card i'm reverse-related to + QList reverseRelatedCards; - // the cards thare are reverse-related to me - QList reverseRelatedCardsToMe; + // the cards thare are reverse-related to me + QList reverseRelatedCardsToMe; - QString setsNames; + QString setsNames; - bool upsideDownArt; - int loyalty; - QStringMap customPicURLs; - MuidMap muIds; - QStringMap collectorNumbers; - QStringMap rarities; - bool cipt; - int tableRow; - QString pixmapCacheKey; + bool upsideDownArt; + int loyalty; + QStringMap customPicURLs; + MuidMap muIds; + QStringMap collectorNumbers; + QStringMap rarities; + bool cipt; + int tableRow; + QString pixmapCacheKey; - public: - explicit CardInfo(const QString &_name = QString(), - bool _isToken = false, - const QString &_manacost = QString(), - const QString &_cmc = QString(), - const QString &_cardtype = QString(), - const QString &_powtough = QString(), - const QString &_text = QString(), - const QStringList &_colors = QStringList(), - const QList &_relatedCards = QList(), - const QList &_reverseRelatedCards = QList(), - bool _upsideDownArt = false, - int _loyalty = 0, - bool _cipt = false, - int _tableRow = 0, - const SetList &_sets = SetList(), - const QStringMap &_customPicURLs = QStringMap(), - MuidMap muids = MuidMap(), - QStringMap _collectorNumbers = QStringMap(), - QStringMap _rarities = QStringMap() - ); - ~CardInfo() override; +public: + explicit CardInfo(const QString &_name = QString(), + bool _isToken = false, + const QString &_manacost = QString(), + const QString &_cmc = QString(), + const QString &_cardtype = QString(), + const QString &_powtough = QString(), + const QString &_text = QString(), + const QStringList &_colors = QStringList(), + const QList &_relatedCards = QList(), + const QList &_reverseRelatedCards = QList(), + bool _upsideDownArt = false, + int _loyalty = 0, + bool _cipt = false, + int _tableRow = 0, + const SetList &_sets = SetList(), + const QStringMap &_customPicURLs = QStringMap(), + MuidMap muids = MuidMap(), + QStringMap _collectorNumbers = QStringMap(), + QStringMap _rarities = QStringMap()); + ~CardInfo() override; - inline const QString &getName() const { return name; } - inline const QString &getSetsNames() const { return setsNames; } - const QString &getSimpleName() const { return simpleName; } - bool getIsToken() const { return isToken; } - const SetList &getSets() const { return sets; } - inline const QString &getManaCost() const { return manacost; } - inline const QString &getCmc() const { return cmc; } - inline const QString &getCardType() const { return cardtype; } - inline const QString &getPowTough() const { return powtough; } - const QString &getText() const { return text; } - const QString &getPixmapCacheKey() const { return pixmapCacheKey; } - const int &getLoyalty() const { return loyalty; } - bool getCipt() const { return cipt; } - //void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); } - //void setCmc(const QString &_cmc) { cmc = _cmc; 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 QChar getColorChar() const; - const QStringList &getColors() const { return colors; } - const QList &getRelatedCards() const { return relatedCards; } - const QList &getReverseRelatedCards() const { return reverseRelatedCards; } - const QList &getReverseRelatedCards2Me() const { return reverseRelatedCardsToMe; } - void resetReverseRelatedCards2Me(); - void addReverseRelatedCards2Me(CardRelation * cardRelation) { reverseRelatedCardsToMe.append(cardRelation); } - bool getUpsideDownArt() const { return upsideDownArt; } - QString getCustomPicURL(const QString &set) const { return customPicURLs.value(set); } - int getMuId(const QString &set) const { return muIds.value(set); } - QString getCollectorNumber(const QString &set) const { return collectorNumbers.value(set); } - QString getRarity(const QString &set) const { return rarities.value(set); } - QStringMap getRarities() const { return rarities; } - 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 setCustomPicURL(const QString &_set, const QString &_customPicURL) { customPicURLs.insert(_set, _customPicURL); } - void setMuId(const QString &_set, const int &_muId) { muIds.insert(_set, _muId); } - void setSetNumber(const QString &_set, const QString &_setNumber) { collectorNumbers.insert(_set, _setNumber); } - void setRarity(const QString &_set, const QString &_setNumber) { rarities.insert(_set, _setNumber); } - void addToSet(CardSet *set); - void emitPixmapUpdated() { emit pixmapUpdated(); } - void refreshCachedSetNames(); + inline const QString &getName() const + { + return name; + } + inline const QString &getSetsNames() const + { + return setsNames; + } + const QString &getSimpleName() const + { + return simpleName; + } + bool getIsToken() const + { + return isToken; + } + const SetList &getSets() const + { + return sets; + } + inline const QString &getManaCost() const + { + return manacost; + } + inline const QString &getCmc() const + { + return cmc; + } + inline const QString &getCardType() const + { + return cardtype; + } + inline const QString &getPowTough() const + { + return powtough; + } + const QString &getText() const + { + return text; + } + const QString &getPixmapCacheKey() const + { + return pixmapCacheKey; + } + const int &getLoyalty() const + { + return loyalty; + } + bool getCipt() const + { + return cipt; + } + // void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); } + // void setCmc(const QString &_cmc) { cmc = _cmc; 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 QChar getColorChar() const; + const QStringList &getColors() const + { + return colors; + } + const QList &getRelatedCards() const + { + return relatedCards; + } + const QList &getReverseRelatedCards() const + { + return reverseRelatedCards; + } + const QList &getReverseRelatedCards2Me() const + { + return reverseRelatedCardsToMe; + } + void resetReverseRelatedCards2Me(); + void addReverseRelatedCards2Me(CardRelation *cardRelation) + { + reverseRelatedCardsToMe.append(cardRelation); + } + bool getUpsideDownArt() const + { + return upsideDownArt; + } + QString getCustomPicURL(const QString &set) const + { + return customPicURLs.value(set); + } + int getMuId(const QString &set) const + { + return muIds.value(set); + } + QString getCollectorNumber(const QString &set) const + { + return collectorNumbers.value(set); + } + QString getRarity(const QString &set) const + { + return rarities.value(set); + } + QStringMap getRarities() const + { + return rarities; + } + 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 setCustomPicURL(const QString &_set, const QString &_customPicURL) { customPicURLs.insert(_set, + // _customPicURL); } + void setMuId(const QString &_set, const int &_muId) + { + muIds.insert(_set, _muId); + } + void setSetNumber(const QString &_set, const QString &_setNumber) + { + collectorNumbers.insert(_set, _setNumber); + } + void setRarity(const QString &_set, const QString &_setNumber) + { + rarities.insert(_set, _setNumber); + } + void addToSet(CardSet *set); + void emitPixmapUpdated() + { + emit pixmapUpdated(); + } + void refreshCachedSetNames(); - /** - * Simplify a name to have no punctuation and lowercase all letters, for - * less strict name-matching. - */ - static QString simplifyName(const QString &name); + /** + * Simplify a name to have no punctuation and lowercase all letters, for + * less strict name-matching. + */ + static QString simplifyName(const QString &name); - signals: - void pixmapUpdated(); - void cardInfoChanged(CardInfo *card); +signals: + void pixmapUpdated(); + void cardInfoChanged(CardInfo *card); }; -enum LoadStatus { Ok, VersionTooOld, Invalid, NotLoaded, FileError, NoCards }; +enum LoadStatus +{ + Ok, + VersionTooOld, + Invalid, + NotLoaded, + FileError, + NoCards +}; typedef QHash CardNameMap; typedef QHash SetNameMap; @@ -196,103 +346,126 @@ typedef QHash SetNameMap; class CardDatabase : public QObject { Q_OBJECT - protected: - /* - * The cards, indexed by name. - */ - CardNameMap cards; +protected: + /* + * The cards, indexed by name. + */ + CardNameMap cards; - /** - * The cards, indexed by their simple name. - */ - CardNameMap simpleNameCards; + /** + * The cards, indexed by their simple name. + */ + CardNameMap simpleNameCards; - /* - * The sets, indexed by short name. - */ - SetNameMap sets; + /* + * The sets, indexed by short name. + */ + SetNameMap sets; - LoadStatus loadStatus; - private: - static const int versionNeeded; - void loadCardsFromXml(QXmlStreamReader &xml); - void loadSetsFromXml(QXmlStreamReader &xml); + LoadStatus loadStatus; - CardInfo *getCardFromMap(const CardNameMap &cardMap, const QString &cardName) const; - void checkUnknownSets(); - void refreshCachedReverseRelatedCards(); +private: + static const int versionNeeded; + void loadCardsFromXml(QXmlStreamReader &xml); + void loadSetsFromXml(QXmlStreamReader &xml); - QBasicMutex *reloadDatabaseMutex = new QBasicMutex(), - *clearDatabaseMutex = new QBasicMutex(), - *loadFromFileMutex = new QBasicMutex(), - *addCardMutex = new QBasicMutex(), + CardInfo *getCardFromMap(const CardNameMap &cardMap, const QString &cardName) const; + void checkUnknownSets(); + void refreshCachedReverseRelatedCards(); + + QBasicMutex *reloadDatabaseMutex = new QBasicMutex(), *clearDatabaseMutex = new QBasicMutex(), + *loadFromFileMutex = new QBasicMutex(), *addCardMutex = new QBasicMutex(), *removeCardMutex = new QBasicMutex(); - public: - static const char* TOKENS_SETNAME; +public: + static const char *TOKENS_SETNAME; - explicit CardDatabase(QObject *parent = nullptr); - ~CardDatabase() override; - void clear(); - void addCard(CardInfo *card); - void removeCard(CardInfo *card); - CardInfo *getCard(const QString &cardName) const; - QList getCards(const QStringList &cardNames) const; + explicit CardDatabase(QObject *parent = nullptr); + ~CardDatabase() override; + void clear(); + void addCard(CardInfo *card); + void removeCard(CardInfo *card); + CardInfo *getCard(const QString &cardName) const; + QList getCards(const QStringList &cardNames) const; - /* - * Get a card by its simple name. The name will be simplified in this - * function, so you don't need to simplify it beforehand. - */ - CardInfo *getCardBySimpleName(const QString &cardName) const; + /* + * Get a card by its simple name. The name will be simplified in this + * function, so you don't need to simplify it beforehand. + */ + CardInfo *getCardBySimpleName(const QString &cardName) const; - CardSet *getSet(const QString &setName); - QList getCardList() const { return cards.values(); } - SetList getSetList() const; - LoadStatus loadFromFile(const QString &fileName); - bool saveToFile(const QString &fileName, bool tokens = false); - bool saveCustomTokensToFile(); - QStringList getAllColors() const; - QStringList getAllMainCardTypes() const; - LoadStatus getLoadStatus() const { return loadStatus; } - void enableAllUnknownSets(); - void markAllSetsAsKnown(); - void notifyEnabledSetsChanged(); + CardSet *getSet(const QString &setName); + QList getCardList() const + { + return cards.values(); + } + SetList getSetList() const; + LoadStatus loadFromFile(const QString &fileName); + bool saveToFile(const QString &fileName, bool tokens = false); + bool saveCustomTokensToFile(); + QStringList getAllColors() const; + QStringList getAllMainCardTypes() const; + LoadStatus getLoadStatus() const + { + return loadStatus; + } + void enableAllUnknownSets(); + void markAllSetsAsKnown(); + void notifyEnabledSetsChanged(); - public slots: - LoadStatus loadCardDatabases(); - private slots: - LoadStatus loadCardDatabase(const QString &path); - signals: - void cardDatabaseLoadingFailed(); - void cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknownSetsNames); - void cardDatabaseAllNewSetsEnabled(); - void cardDatabaseEnabledSetsChanged(); - void cardAdded(CardInfo *card); - void cardRemoved(CardInfo *card); +public slots: + LoadStatus loadCardDatabases(); +private slots: + LoadStatus loadCardDatabase(const QString &path); +signals: + void cardDatabaseLoadingFailed(); + void cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknownSetsNames); + void cardDatabaseAllNewSetsEnabled(); + void cardDatabaseEnabledSetsChanged(); + void cardAdded(CardInfo *card); + void cardRemoved(CardInfo *card); }; class CardRelation : public QObject { Q_OBJECT - private: - QString name; - bool doesAttach; - bool isCreateAllExclusion; - bool isVariableCount; - int defaultCount; - public: - explicit CardRelation(const QString &_name = QString(), - bool _doesAttach = false, - bool _isCreateAllExclusion = false, - bool _isVariableCount = false, - int _defaultCount = 1 - ); +private: + QString name; + bool doesAttach; + bool isCreateAllExclusion; + bool isVariableCount; + int defaultCount; - inline const QString &getName() const { return name; } - bool getDoesAttach() const { return doesAttach; } - bool getCanCreateAnother() const { return !doesAttach; } - bool getIsCreateAllExclusion() const { return isCreateAllExclusion; } - bool getIsVariable() const { return isVariableCount; } - int getDefaultCount() const { return defaultCount; } +public: + explicit CardRelation(const QString &_name = QString(), + bool _doesAttach = false, + bool _isCreateAllExclusion = false, + bool _isVariableCount = false, + int _defaultCount = 1); + + inline const QString &getName() const + { + return name; + } + bool getDoesAttach() const + { + return doesAttach; + } + bool getCanCreateAnother() const + { + return !doesAttach; + } + bool getIsCreateAllExclusion() const + { + return isCreateAllExclusion; + } + bool getIsVariable() const + { + return isVariableCount; + } + int getDefaultCount() const + { + return defaultCount; + } }; #endif \ No newline at end of file diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index d4ef90f5..ed66397a 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -17,35 +17,39 @@ CardDatabaseModel::~CardDatabaseModel() { } -int CardDatabaseModel::rowCount(const QModelIndex &/*parent*/) const +int CardDatabaseModel::rowCount(const QModelIndex & /*parent*/) const { return cardList.size(); } -int CardDatabaseModel::columnCount(const QModelIndex &/*parent*/) const +int CardDatabaseModel::columnCount(const QModelIndex & /*parent*/) const { return CARDDBMODEL_COLUMNS; } QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || - index.row() >= cardList.size() || - index.column() >= CARDDBMODEL_COLUMNS || + if (!index.isValid() || index.row() >= cardList.size() || index.column() >= CARDDBMODEL_COLUMNS || (role != Qt::DisplayRole && role != SortRole)) return QVariant(); CardInfo *card = cardList.at(index.row()); - switch (index.column()){ - case NameColumn: return card->getName(); - case SetListColumn: return card->getSetsNames(); - case ManaCostColumn: return role == SortRole ? - QString("%1%2").arg(card->getCmc(), 4, QChar('0')).arg(card->getManaCost()) : - card->getManaCost(); - case CardTypeColumn: return card->getCardType(); - case PTColumn: return card->getPowTough(); - case ColorColumn: return card->getColors().join(""); - default: return QVariant(); + switch (index.column()) { + case NameColumn: + return card->getName(); + case SetListColumn: + return card->getSetsNames(); + case ManaCostColumn: + return role == SortRole ? QString("%1%2").arg(card->getCmc(), 4, QChar('0')).arg(card->getManaCost()) + : card->getManaCost(); + case CardTypeColumn: + return card->getCardType(); + case PTColumn: + return card->getPowTough(); + case ColorColumn: + return card->getColors().join(""); + default: + return QVariant(); } } @@ -56,13 +60,20 @@ QVariant CardDatabaseModel::headerData(int section, Qt::Orientation orientation, if (orientation != Qt::Horizontal) return QVariant(); switch (section) { - case NameColumn: return QString(tr("Name")); - case SetListColumn: return QString(tr("Sets")); - case ManaCostColumn: return QString(tr("Mana cost")); - case CardTypeColumn: return QString(tr("Card type")); - case PTColumn: return QString(tr("P/T")); - case ColorColumn: return QString(tr("Color(s)")); - default: return QVariant(); + case NameColumn: + return QString(tr("Name")); + case SetListColumn: + return QString(tr("Sets")); + case ManaCostColumn: + return QString(tr("Mana cost")); + case CardTypeColumn: + return QString(tr("Card type")); + case PTColumn: + return QString(tr("P/T")); + case ColorColumn: + return QString(tr("Color(s)")); + default: + return QVariant(); } } @@ -71,18 +82,17 @@ void CardDatabaseModel::cardInfoChanged(CardInfo *card) const int row = cardList.indexOf(card); if (row == -1) return; - + emit dataChanged(index(row, 0), index(row, CARDDBMODEL_COLUMNS - 1)); } bool CardDatabaseModel::checkCardHasAtLeastOneEnabledSet(CardInfo *card) { - if(!showOnlyCardsFromEnabledSets) + if (!showOnlyCardsFromEnabledSets) return true; - foreach(CardSet * set, card->getSets()) - { - if(set->getEnabled()) + foreach (CardSet *set, card->getSets()) { + if (set->getEnabled()) return true; } @@ -92,24 +102,21 @@ bool CardDatabaseModel::checkCardHasAtLeastOneEnabledSet(CardInfo *card) void CardDatabaseModel::cardDatabaseEnabledSetsChanged() { // remove all the cards no more present in at least one enabled set - foreach(CardInfo * card, cardList) - { - if(!checkCardHasAtLeastOneEnabledSet(card)) + foreach (CardInfo *card, cardList) { + if (!checkCardHasAtLeastOneEnabledSet(card)) cardRemoved(card); } // re-check all the card currently not shown, maybe their part of a newly-enabled set - foreach(CardInfo * card, db->getCardList()) - { - if(!cardList.contains(card)) + foreach (CardInfo *card, db->getCardList()) { + if (!cardList.contains(card)) cardAdded(card); } } void CardDatabaseModel::cardAdded(CardInfo *card) { - if(checkCardHasAtLeastOneEnabledSet(card)) - { + if (checkCardHasAtLeastOneEnabledSet(card)) { // add the card if it's present in at least one enabled set beginInsertRows(QModelIndex(), cardList.size(), cardList.size()); cardList.append(card); @@ -123,16 +130,14 @@ void CardDatabaseModel::cardRemoved(CardInfo *card) const int row = cardList.indexOf(card); if (row == -1) return; - + beginRemoveRows(QModelIndex(), row, row); disconnect(card, 0, this, 0); cardList.removeAt(row); endRemoveRows(); } -CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) - : QSortFilterProxyModel(parent), - isToken(ShowAll) +CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) : QSortFilterProxyModel(parent), isToken(ShowAll) { filterTree = NULL; setFilterCaseSensitivity(Qt::CaseInsensitive); @@ -141,17 +146,17 @@ CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) loadedRowCount = 0; } -bool CardDatabaseDisplayModel::canFetchMore(const QModelIndex & index) const +bool CardDatabaseDisplayModel::canFetchMore(const QModelIndex &index) const { return loadedRowCount < sourceModel()->rowCount(index); } -void CardDatabaseDisplayModel::fetchMore(const QModelIndex & index) +void CardDatabaseDisplayModel::fetchMore(const QModelIndex &index) { int remainder = sourceModel()->rowCount(index) - loadedRowCount; int itemsToFetch = qMin(100, remainder); - beginInsertRows(QModelIndex(), loadedRowCount, loadedRowCount+itemsToFetch-1); + beginInsertRows(QModelIndex(), loadedRowCount, loadedRowCount + itemsToFetch - 1); loadedRowCount += itemsToFetch; endInsertRows(); @@ -162,13 +167,13 @@ int CardDatabaseDisplayModel::rowCount(const QModelIndex &parent) const return qMin(QSortFilterProxyModel::rowCount(parent), loadedRowCount); } -bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { +bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelIndex &right) const +{ QString leftString = sourceModel()->data(left, CardDatabaseModel::SortRole).toString(); QString rightString = sourceModel()->data(right, CardDatabaseModel::SortRole).toString(); - if (!cardName.isEmpty() && left.column() == CardDatabaseModel::NameColumn) - { + if (!cardName.isEmpty() && left.column() == CardDatabaseModel::NameColumn) { bool isLeftType = leftString.startsWith(cardName, Qt::CaseInsensitive); bool isRightType = rightString.startsWith(cardName, Qt::CaseInsensitive); @@ -180,20 +185,18 @@ bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelInd // same checks for the right string if (isRightType && (!isLeftType || rightString.size() == cardName.size())) return false; - } - else if (right.column() == CardDatabaseModel::PTColumn && left.column() == CardDatabaseModel::PTColumn) { + } else if (right.column() == CardDatabaseModel::PTColumn && left.column() == CardDatabaseModel::PTColumn) { QStringList leftList = leftString.split("/"); QStringList rightList = rightString.split("/"); if (leftList.size() == 2 && rightList.size() == 2) { - //cool, have both P/T in list now + // cool, have both P/T in list now int lessThanNum = lessThanNumerically(leftList.at(0), rightList.at(0)); if (lessThanNum != 0) { return lessThanNum < 0; - } - else { - //power equal, check toughness + } else { + // power equal, check toughness return lessThanNumerically(leftList.at(1), rightList.at(1)) < 0; } } @@ -201,7 +204,8 @@ bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelInd return QString::localeAwareCompare(leftString, rightString) < 0; } -int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QString&right) { +int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QString &right) +{ if (left == right) { return 0; } @@ -213,15 +217,13 @@ int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QSt if (okLeft && okRight) { if (leftNum < rightNum) { return -1; - } - else if(leftNum > rightNum){ + } else if (leftNum > rightNum) { return 1; - } - else { + } else { return 0; } } - //try and parsing again, for weird ones like "1+*" + // try and parsing again, for weird ones like "1+*" QString leftAfterNum = ""; QString rightAfterNum = ""; if (!okLeft) { @@ -249,42 +251,39 @@ int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QSt } } if (okLeft && okRight) { - + if (leftNum != rightNum) { - //both parsed as numbers, but different number + // both parsed as numbers, but different number if (leftNum < rightNum) { return -1; - } - else { + } else { return 1; } - } - else { - //both parsed, same number, but at least one has something else - //so compare the part after the number - prefer nothing + } else { + // both parsed, same number, but at least one has something else + // so compare the part after the number - prefer nothing return QString::localeAwareCompare(leftAfterNum, rightAfterNum); } - } - else if (okLeft) { + } else if (okLeft) { return -1; - } - else if (okRight) { + } else if (okRight) { return 1; } - //couldn't parse it, just return String comparison + // couldn't parse it, just return String comparison return QString::localeAwareCompare(left, right); } 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; return rowMatchesCardName(info); } -bool CardDatabaseDisplayModel::rowMatchesCardName(CardInfo const *info) const { +bool CardDatabaseDisplayModel::rowMatchesCardName(CardInfo const *info) const +{ if (!cardName.isEmpty() && !info->getName().contains(cardName, Qt::CaseInsensitive)) return false; @@ -323,10 +322,8 @@ void CardDatabaseDisplayModel::filterTreeChanged() invalidate(); } -TokenDisplayModel::TokenDisplayModel(QObject *parent) - : CardDatabaseDisplayModel(parent) +TokenDisplayModel::TokenDisplayModel(QObject *parent) : CardDatabaseDisplayModel(parent) { - } bool TokenDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const diff --git a/cockatrice/src/carddatabasemodel.h b/cockatrice/src/carddatabasemodel.h index 8b257d4f..a12e221f 100644 --- a/cockatrice/src/carddatabasemodel.h +++ b/cockatrice/src/carddatabasemodel.h @@ -1,27 +1,46 @@ #ifndef CARDDATABASEMODEL_H #define CARDDATABASEMODEL_H +#include "carddatabase.h" #include -#include #include #include -#include "carddatabase.h" +#include class FilterTree; -class CardDatabaseModel : public QAbstractListModel { +class CardDatabaseModel : public QAbstractListModel +{ Q_OBJECT public: - enum Columns { NameColumn, SetListColumn, ManaCostColumn, PTColumn, CardTypeColumn, ColorColumn }; - enum Role { SortRole=Qt::UserRole }; + enum Columns + { + NameColumn, + SetListColumn, + ManaCostColumn, + PTColumn, + CardTypeColumn, + ColorColumn + }; + enum Role + { + SortRole = Qt::UserRole + }; CardDatabaseModel(CardDatabase *_db, bool _showOnlyCardsFromEnabledSets, QObject *parent = 0); ~CardDatabaseModel(); int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - CardDatabase *getDatabase() const { return db; } - CardInfo *getCard(int index) const { return cardList[index]; } + CardDatabase *getDatabase() const + { + return db; + } + CardInfo *getCard(int index) const + { + return cardList[index]; + } + private: QList cardList; CardDatabase *db; @@ -35,10 +54,17 @@ private slots: void cardDatabaseEnabledSetsChanged(); }; -class CardDatabaseDisplayModel : public QSortFilterProxyModel { +class CardDatabaseDisplayModel : public QSortFilterProxyModel +{ Q_OBJECT public: - enum FilterBool { ShowTrue, ShowFalse, ShowAll }; + enum FilterBool + { + ShowTrue, + ShowFalse, + ShowAll + }; + private: FilterBool isToken; QString cardNameBeginning, cardName, cardText; @@ -46,22 +72,55 @@ private: QSet cardNameSet, cardTypes, cardColors; FilterTree *filterTree; int loadedRowCount; + public: CardDatabaseDisplayModel(QObject *parent = 0); void setFilterTree(FilterTree *filterTree); - void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } - void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } - void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } - void setCardNameSet(const QSet &_cardNameSet) { cardNameSet = _cardNameSet; invalidate(); } - void setSearchTerm(const QString &_searchTerm) { searchTerm = _searchTerm; } - void setCardText(const QString &_cardText) { cardText = _cardText; invalidate(); } - void setCardTypes(const QSet &_cardTypes) { cardTypes = _cardTypes; invalidate(); } - void setCardColors(const QSet &_cardColors) { cardColors = _cardColors; invalidate(); } + void setIsToken(FilterBool _isToken) + { + isToken = _isToken; + invalidate(); + } + void setCardNameBeginning(const QString &_beginning) + { + cardNameBeginning = _beginning; + invalidate(); + } + void setCardName(const QString &_cardName) + { + cardName = _cardName; + invalidate(); + } + void setCardNameSet(const QSet &_cardNameSet) + { + cardNameSet = _cardNameSet; + invalidate(); + } + void setSearchTerm(const QString &_searchTerm) + { + searchTerm = _searchTerm; + } + void setCardText(const QString &_cardText) + { + cardText = _cardText; + invalidate(); + } + void setCardTypes(const QSet &_cardTypes) + { + cardTypes = _cardTypes; + invalidate(); + } + void setCardColors(const QSet &_cardColors) + { + cardColors = _cardColors; + invalidate(); + } void clearFilterAll(); int rowCount(const QModelIndex &parent = QModelIndex()) const; + protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const; - static int lessThanNumerically(const QString &left, const QString&right); + static int lessThanNumerically(const QString &left, const QString &right); bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; bool rowMatchesCardName(CardInfo const *info) const; bool canFetchMore(const QModelIndex &parent) const; @@ -70,11 +129,13 @@ private slots: void filterTreeChanged(); }; -class TokenDisplayModel : public CardDatabaseDisplayModel { +class TokenDisplayModel : public CardDatabaseDisplayModel +{ Q_OBJECT public: TokenDisplayModel(QObject *parent = 0); int rowCount(const QModelIndex &parent = QModelIndex()) const; + protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; diff --git a/cockatrice/src/carddragitem.cpp b/cockatrice/src/carddragitem.cpp index 0ebab9a4..c92924bd 100644 --- a/cockatrice/src/carddragitem.cpp +++ b/cockatrice/src/carddragitem.cpp @@ -1,14 +1,18 @@ #include "carddragitem.h" #include "carditem.h" #include "cardzone.h" +#include "gamescene.h" #include "tablezone.h" #include "zoneviewzone.h" -#include "gamescene.h" -#include #include +#include #include -CardDragItem::CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag) +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) { } @@ -16,14 +20,16 @@ CardDragItem::CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bo 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)); } 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; @@ -42,18 +48,18 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos) 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) @@ -85,7 +91,7 @@ void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) } } - if(currentZone) + if (currentZone) currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint()); event->accept(); diff --git a/cockatrice/src/carddragitem.h b/cockatrice/src/carddragitem.h index ea81998f..2c7b2b8c 100644 --- a/cockatrice/src/carddragitem.h +++ b/cockatrice/src/carddragitem.h @@ -5,19 +5,32 @@ class CardItem; -class CardDragItem : public AbstractCardDragItem { +class CardDragItem : public AbstractCardDragItem +{ Q_OBJECT private: 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; } + 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); }; diff --git a/cockatrice/src/cardfilter.h b/cockatrice/src/cardfilter.h index 17dbadb4..bc4c2489 100644 --- a/cockatrice/src/cardfilter.h +++ b/cockatrice/src/cardfilter.h @@ -3,9 +3,11 @@ #include -class CardFilter { +class CardFilter +{ public: - enum Type { + enum Type + { TypeAnd = 0, TypeOr, TypeAndNot, @@ -15,7 +17,8 @@ public: /* if you add an atribute here you also need to * add its string representation in attrName */ - enum Attr { + enum Attr + { AttrCmc = 0, AttrColor, AttrManaCost, @@ -35,11 +38,20 @@ private: enum Attr a; public: - CardFilter(QString term, Type type, Attr attr) : trm(term), t(type), a(attr) {}; + CardFilter(QString term, Type type, Attr attr) : trm(term), t(type), a(attr){}; - Type type() const { return t; } - const QString &term() const { return trm; } - Attr attr() const { return a; } + Type type() const + { + return t; + } + const QString &term() const + { + return trm; + } + Attr attr() const + { + return a; + } static const char *typeName(Type t); static const char *attrName(Attr a); diff --git a/cockatrice/src/cardframe.cpp b/cockatrice/src/cardframe.cpp index 3421457f..3e3373a2 100644 --- a/cockatrice/src/cardframe.cpp +++ b/cockatrice/src/cardframe.cpp @@ -1,10 +1,10 @@ #include "cardframe.h" -#include "carditem.h" #include "carddatabase.h" -#include "main.h" #include "cardinfopicture.h" #include "cardinfotext.h" +#include "carditem.h" +#include "main.h" #include "settingscache.h" #include @@ -68,11 +68,10 @@ void CardFrame::retranslateUi() void CardFrame::setViewMode(int mode) { - if(currentIndex() != mode) + if (currentIndex() != mode) setCurrentIndex(mode); - switch (mode) - { + switch (mode) { case ImageOnlyView: case TextOnlyView: tab1Layout->addWidget(pic); @@ -91,15 +90,13 @@ void CardFrame::setViewMode(int mode) void CardFrame::setCard(CardInfo *card) { - if (info) - { + if (info) { disconnect(info, nullptr, this, nullptr); } info = card; - if (info) - { + if (info) { connect(info, SIGNAL(destroyed()), this, SLOT(clear())); } @@ -114,13 +111,12 @@ void CardFrame::setCard(const QString &cardName) void CardFrame::setCard(AbstractCardItem *card) { - if (card) - { + if (card) { setCard(card->getInfo()); } } void CardFrame::clear() { - setCard((CardInfo*) nullptr); + setCard((CardInfo *)nullptr); } diff --git a/cockatrice/src/cardframe.h b/cockatrice/src/cardframe.h index 97a0b3a8..63a849ee 100644 --- a/cockatrice/src/cardframe.h +++ b/cockatrice/src/cardframe.h @@ -13,26 +13,31 @@ class QSplitter; class CardFrame : public QTabWidget { Q_OBJECT - private: - CardInfo *info; - CardInfoPicture *pic; - CardInfoText *text; - bool cardTextOnly; - QWidget *tab1, *tab2, *tab3; - QVBoxLayout *tab1Layout, *tab2Layout, *tab3Layout; - QSplitter *splitter; +private: + CardInfo *info; + CardInfoPicture *pic; + CardInfoText *text; + bool cardTextOnly; + QWidget *tab1, *tab2, *tab3; + QVBoxLayout *tab1Layout, *tab2Layout, *tab3Layout; + QSplitter *splitter; - public: - enum ViewMode { ImageOnlyView, TextOnlyView, ImageAndTextView }; - explicit CardFrame(const QString &cardName = QString(), QWidget *parent = nullptr); - void retranslateUi(); +public: + enum ViewMode + { + ImageOnlyView, + TextOnlyView, + ImageAndTextView + }; + explicit CardFrame(const QString &cardName = QString(), QWidget *parent = nullptr); + void retranslateUi(); - public slots: - void setCard(CardInfo *card); - void setCard(const QString &cardName); - void setCard(AbstractCardItem *card); - void clear(); - void setViewMode(int mode); +public slots: + void setCard(CardInfo *card); + void setCard(const QString &cardName); + void setCard(AbstractCardItem *card); + void clear(); + void setViewMode(int mode); }; #endif diff --git a/cockatrice/src/cardinfopicture.cpp b/cockatrice/src/cardinfopicture.cpp index 44b2dd9c..be06903e 100644 --- a/cockatrice/src/cardinfopicture.cpp +++ b/cockatrice/src/cardinfopicture.cpp @@ -1,33 +1,28 @@ #include "cardinfopicture.h" -#include #include #include +#include -#include "carditem.h" #include "carddatabase.h" -#include "pictureloader.h" +#include "carditem.h" #include "main.h" +#include "pictureloader.h" -CardInfoPicture::CardInfoPicture(QWidget *parent) - : QWidget(parent), - info(nullptr), - pixmapDirty(true) +CardInfoPicture::CardInfoPicture(QWidget *parent) : QWidget(parent), info(nullptr), pixmapDirty(true) { setMinimumHeight(100); } void CardInfoPicture::setCard(CardInfo *card) { - if (info) - { + if (info) { disconnect(info, nullptr, this, nullptr); } info = card; - if (info) - { + if (info) { connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); } @@ -47,7 +42,7 @@ void CardInfoPicture::updatePixmap() void CardInfoPicture::loadPixmap() { - if(info) + if (info) PictureLoader::getPixmap(resizedPixmap, info, size()); else PictureLoader::getCardBackPixmap(resizedPixmap, size()); @@ -58,7 +53,7 @@ void CardInfoPicture::paintEvent(QPaintEvent *) if (width() == 0 || height() == 0) return; - if(pixmapDirty) + if (pixmapDirty) loadPixmap(); QPainter painter(this); diff --git a/cockatrice/src/cardinfopicture.h b/cockatrice/src/cardinfopicture.h index 50cf3e84..9544b26d 100644 --- a/cockatrice/src/cardinfopicture.h +++ b/cockatrice/src/cardinfopicture.h @@ -6,7 +6,8 @@ class AbstractCardItem; class CardInfo; -class CardInfoPicture : public QWidget { +class CardInfoPicture : public QWidget +{ Q_OBJECT private: @@ -16,10 +17,11 @@ private: public: CardInfoPicture(QWidget *parent = 0); + protected: void resizeEvent(QResizeEvent *event); - void paintEvent(QPaintEvent *); - void loadPixmap(); + void paintEvent(QPaintEvent *); + void loadPixmap(); public slots: void setCard(CardInfo *card); void updatePixmap(); diff --git a/cockatrice/src/cardinfotext.cpp b/cockatrice/src/cardinfotext.cpp index fd06c5c2..46b4c6d6 100644 --- a/cockatrice/src/cardinfotext.cpp +++ b/cockatrice/src/cardinfotext.cpp @@ -1,14 +1,13 @@ #include "cardinfotext.h" +#include "carddatabase.h" +#include "carditem.h" +#include "main.h" +#include #include #include -#include -#include "carditem.h" -#include "carddatabase.h" -#include "main.h" -CardInfoText::CardInfoText(QWidget *parent) - : QFrame(parent), info(nullptr) +CardInfoText::CardInfoText(QWidget *parent) : QFrame(parent), info(nullptr) { nameLabel1 = new QLabel; nameLabel2 = new QLabel; @@ -59,8 +58,7 @@ CardInfoText::CardInfoText(QWidget *parent) void CardInfoText::setCard(CardInfo *card) { - if (card) - { + if (card) { nameLabel2->setText(card->getName()); manacostLabel2->setText(card->getManaCost()); colorLabel2->setText(card->getColors().join("")); @@ -68,9 +66,7 @@ void CardInfoText::setCard(CardInfo *card) powtoughLabel2->setText(card->getPowTough()); loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); textLabel->setText(card->getText()); - } - else - { + } else { nameLabel2->setText(""); manacostLabel2->setText(""); colorLabel2->setText(""); diff --git a/cockatrice/src/cardinfotext.h b/cockatrice/src/cardinfotext.h index 2c7da466..0a9f5dc5 100644 --- a/cockatrice/src/cardinfotext.h +++ b/cockatrice/src/cardinfotext.h @@ -7,7 +7,8 @@ class QLabel; class QTextEdit; class CardInfo; -class CardInfoText : public QFrame { +class CardInfoText : public QFrame +{ Q_OBJECT private: diff --git a/cockatrice/src/cardinfowidget.cpp b/cockatrice/src/cardinfowidget.cpp index e85f48ef..c5c09b89 100644 --- a/cockatrice/src/cardinfowidget.cpp +++ b/cockatrice/src/cardinfowidget.cpp @@ -1,16 +1,14 @@ -#include -#include #include "cardinfowidget.h" -#include "carditem.h" #include "carddatabase.h" #include "cardinfopicture.h" #include "cardinfotext.h" +#include "carditem.h" #include "main.h" +#include +#include CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::WindowFlags flags) - : QFrame(parent, flags) - , aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH) - , info(nullptr) + : QFrame(parent, flags), aspectRatio((qreal)CARD_HEIGHT / (qreal)CARD_WIDTH), info(nullptr) { setContentsMargins(3, 3, 3, 3); pic = new CardInfoPicture(); @@ -18,7 +16,7 @@ CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::Win text = new CardInfoText(); text->setObjectName("text"); - QVBoxLayout * layout = new QVBoxLayout(); + QVBoxLayout *layout = new QVBoxLayout(); layout->setObjectName("layout"); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); @@ -33,7 +31,7 @@ CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::Win pic->setFixedWidth(pixmapWidth); pic->setFixedHeight(pixmapHeight); setFixedWidth(pixmapWidth + 150); - + setCard(cardName); // ensure our parent gets a valid size to position us correctly @@ -45,7 +43,7 @@ void CardInfoWidget::setCard(CardInfo *card) if (info) disconnect(info, nullptr, this, nullptr); info = card; - if(info) + if (info) connect(info, SIGNAL(destroyed()), this, SLOT(clear())); text->setCard(info); @@ -64,5 +62,5 @@ void CardInfoWidget::setCard(AbstractCardItem *card) void CardInfoWidget::clear() { - setCard((CardInfo *) nullptr); + setCard((CardInfo *)nullptr); } diff --git a/cockatrice/src/cardinfowidget.h b/cockatrice/src/cardinfowidget.h index 52ab62d3..d99af573 100644 --- a/cockatrice/src/cardinfowidget.h +++ b/cockatrice/src/cardinfowidget.h @@ -1,16 +1,17 @@ #ifndef CARDINFOWIDGET_H #define CARDINFOWIDGET_H +#include #include #include -#include class CardInfo; class CardInfoPicture; class CardInfoText; class AbstractCardItem; -class CardInfoWidget : public QFrame { +class CardInfoWidget : public QFrame +{ Q_OBJECT private: @@ -18,6 +19,7 @@ private: CardInfo *info; CardInfoPicture *pic; CardInfoText *text; + public: CardInfoWidget(const QString &cardName, QWidget *parent = 0, Qt::WindowFlags f = 0); diff --git a/cockatrice/src/carditem.cpp b/cockatrice/src/carditem.cpp index f62fa730..5fabb4bb 100644 --- a/cockatrice/src/carditem.cpp +++ b/cockatrice/src/carditem.cpp @@ -1,31 +1,31 @@ -#include -#include -#include -#include -#include "gamescene.h" #include "carditem.h" -#include "carddragitem.h" -#include "carddatabase.h" -#include "cardzone.h" -#include "zoneviewzone.h" -#include "tablezone.h" -#include "player.h" #include "arrowitem.h" +#include "carddatabase.h" +#include "carddragitem.h" +#include "cardzone.h" +#include "gamescene.h" #include "main.h" +#include "pb/serverinfo_card.pb.h" +#include "player.h" #include "settingscache.h" #include "tab_game.h" -#include "pb/serverinfo_card.pb.h" - +#include "tablezone.h" +#include "zoneviewzone.h" +#include +#include +#include +#include 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); } @@ -33,14 +33,14 @@ CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _reve CardItem::~CardItem() { prepareDelete(); - + if (scene()) static_cast(scene())->unregisterAnimationItem(this); - + delete cardMenu; delete ptMenu; delete moveMenu; - + deleteDragItem(); } @@ -53,12 +53,12 @@ void CardItem::prepareDelete() } 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; @@ -87,69 +87,65 @@ void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, { painter->save(); AbstractCardItem::paint(painter, option, widget); - + int i = 0; QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - { + 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()) - { + + if (!pt.isEmpty()) { painter->save(); transformPainter(painter, translatedSize, tapAngle); - if(info) - { + if (info) { QStringList ptSplit = pt.split("/"); QStringList ptDbSplit = info->getPowTough().split("/"); - + if (getFaceDown() || ptDbSplit.at(0) != ptSplit.at(0) || ptDbSplit.at(1) != ptSplit.at(1)) painter->setPen(QColor(255, 150, 0)); else painter->setPen(Qt::white); - } - else - { + } else { painter->setPen(Qt::white); } painter->setBackground(Qt::black); painter->setBackgroundMode(Qt::OpaqueMode); - - painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 10 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt); + + painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 10 * scaleFactor, + translatedSize.height() - 8 * scaleFactor), + Qt::AlignRight | Qt::AlignBottom, pt); painter->restore(); } - if (!annotation.isEmpty()) - { + 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->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, + translatedSize.height() - 8 * scaleFactor), + Qt::AlignCenter | Qt::TextWrapAnywhere, annotation); painter->restore(); } - if (getBeingPointedAt()) - { + if (getBeingPointedAt()) { painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); painter->restore(); } - if (doesntUntap) - { + if (doesntUntap) { painter->save(); painter->setRenderHint(QPainter::Antialiasing, false); @@ -203,7 +199,7 @@ void CardItem::setAttachedTo(CardItem *_attachedTo) { if (attachedTo) attachedTo->removeAttachedCard(this); - + gridPoint.setX(-1); attachedTo = _attachedTo; if (attachedTo) { @@ -216,7 +212,7 @@ void CardItem::setAttachedTo(CardItem *_attachedTo) if (zone) zone->reorganizeCards(); - + emit updateCardMenu(this); } @@ -244,7 +240,7 @@ void CardItem::processCardInfo(const ServerInfo_Card &info) 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()); @@ -271,7 +267,7 @@ CardDragItem *CardItem::createDragItem(int _id, const QPointF &_pos, const QPoin void CardItem::deleteDragItem() { - if(dragItem) + if (dragItem) dragItem->deleteLater(); dragItem = NULL; } @@ -280,12 +276,12 @@ 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()); @@ -293,7 +289,7 @@ void CardItem::drawArrow(const QColor &arrowColor) continue; if (c->getZone() != zone) continue; - + ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor); scene()->addItem(childArrow); arrow->addChildArrow(childArrow); @@ -303,9 +299,10 @@ void CardItem::drawArrow(const QColor &arrowColor) void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (event->buttons().testFlag(Qt::RightButton)) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < + 2 * QApplication::startDragDistance()) return; - + QColor arrowColor = Qt::red; if (event->modifiers().testFlag(Qt::ControlModifier)) arrowColor = Qt::yellow; @@ -313,10 +310,11 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) 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()) + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < + 2 * QApplication::startDragDistance()) return; if (zone->getIsView()) { const ZoneViewZone *const view = static_cast(zone); @@ -324,12 +322,12 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) 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++) { @@ -399,7 +397,6 @@ void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) event->accept(); } - bool CardItem::animationEvent() { int rotation = ROTATION_DEGREES_PER_FRAME; @@ -408,7 +405,10 @@ bool CardItem::animationEvent() tapAngle += rotation; - setTransform(QTransform().translate(CARD_WIDTH_HALF, CARD_HEIGHT_HALF).rotate(tapAngle).translate(-CARD_WIDTH_HALF, -CARD_HEIGHT_HALF)); + setTransform(QTransform() + .translate(CARD_WIDTH_HALF, CARD_HEIGHT_HALF) + .rotate(tapAngle) + .translate(-CARD_WIDTH_HALF, -CARD_HEIGHT_HALF)); setHovered(false); update(); diff --git a/cockatrice/src/carditem.h b/cockatrice/src/carditem.h index 524c1695..700d205b 100644 --- a/cockatrice/src/carditem.h +++ b/cockatrice/src/carditem.h @@ -16,7 +16,8 @@ const float CARD_WIDTH_HALF = CARD_WIDTH / 2; const float CARD_HEIGHT_HALF = CARD_HEIGHT / 2; const int ROTATION_DEGREES_PER_FRAME = 10; -class CardItem : public AbstractCardItem { +class CardItem : public AbstractCardItem +{ Q_OBJECT private: CardZone *zone; @@ -31,56 +32,131 @@ private: CardDragItem *dragItem; CardItem *attachedTo; QList attachedCards; - + QMenu *cardMenu, *ptMenu, *moveMenu; void prepareDelete(); public slots: 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); + 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; } + 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; } + 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; } + const QMap &getCounters() const + { + return counters; + } void setCounter(int _id, int _value); - QString getAnnotation() const { return annotation; } + QString getAnnotation() const + { + return annotation; + } void setAnnotation(const QString &_annotation); - bool getDoesntUntap() const { return doesntUntap; } + bool getDoesntUntap() const + { + return doesntUntap; + } void setDoesntUntap(bool _doesntUntap); - QString getPT() const { return pt; } + 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; } + 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 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; } - + 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); diff --git a/cockatrice/src/cardlist.cpp b/cockatrice/src/cardlist.cpp index d034bccf..11c2a262 100644 --- a/cockatrice/src/cardlist.cpp +++ b/cockatrice/src/cardlist.cpp @@ -1,9 +1,8 @@ #include "cardlist.h" -#include "carditem.h" #include "carddatabase.h" +#include "carditem.h" -CardList::CardList(bool _contentsKnown) - : QList(), contentsKnown(_contentsKnown) +CardList::CardList(bool _contentsKnown) : QList(), contentsKnown(_contentsKnown) { } @@ -32,9 +31,11 @@ CardItem *CardList::findCard(const int id, const bool remove, int *position) return 0; } -class CardList::compareFunctor { +class CardList::compareFunctor +{ private: int flags; + public: compareFunctor(int _flags) : flags(_flags) { diff --git a/cockatrice/src/cardlist.h b/cockatrice/src/cardlist.h index d148ca6d..1835ca96 100644 --- a/cockatrice/src/cardlist.h +++ b/cockatrice/src/cardlist.h @@ -5,16 +5,26 @@ class CardItem; -class CardList : public QList { +class CardList : public QList +{ private: class compareFunctor; + protected: bool contentsKnown; + public: - enum SortFlags { SortByName = 1, SortByType = 2 }; + 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; } + bool getContentsKnown() const + { + return contentsKnown; + } void sort(int flags = SortByName); }; diff --git a/cockatrice/src/cardzone.cpp b/cockatrice/src/cardzone.cpp index e21ec287..80f8d8ed 100644 --- a/cockatrice/src/cardzone.cpp +++ b/cockatrice/src/cardzone.cpp @@ -1,16 +1,23 @@ -#include -#include -#include -#include #include "cardzone.h" #include "carditem.h" -#include "player.h" -#include "zoneviewzone.h" #include "pb/command_move_card.pb.h" #include "pb/serverinfo_user.pb.h" +#include "player.h" +#include "zoneviewzone.h" +#include +#include +#include +#include -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) +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) { if (!isView) player->addZone(this); @@ -31,10 +38,9 @@ void CardZone::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. + 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 (auto attachedCard : attachedCards) attachedCard->setParentItem(attachedCard->getZone()); @@ -49,61 +55,37 @@ QString CardZone::getTranslatedName(bool theirOwn, GrammaticalCase gc) const { QString ownerName = player->getName(); if (name == "hand") - return (theirOwn - ? tr("their hand", "nominative") - : tr("%1's hand", "nominative").arg(ownerName) - ); + return (theirOwn ? tr("their hand", "nominative") : tr("%1's hand", "nominative").arg(ownerName)); else if (name == "deck") switch (gc) { - case CaseLookAtZone: - return (theirOwn - ? tr("their library", "look at zone") - : tr("%1's library", "look at zone").arg(ownerName) - ); - case CaseTopCardsOfZone: - return (theirOwn - ? tr("of their library", "top cards of zone,") - : tr("of %1's library", "top cards of zone").arg(ownerName) - ); - case CaseRevealZone: - return (theirOwn - ? tr("their library", "reveal zone") - : tr("%1's library", "reveal zone").arg(ownerName) - ); - case CaseShuffleZone: - return (theirOwn - ? tr("their library", "shuffle") - : tr("%1's library", "shuffle").arg(ownerName) - ); - default: - return (theirOwn - ? tr("their library", "nominative") - : tr("%1's library", "nominative").arg(ownerName) - ); + case CaseLookAtZone: + return (theirOwn ? tr("their library", "look at zone") + : tr("%1's library", "look at zone").arg(ownerName)); + case CaseTopCardsOfZone: + return (theirOwn ? tr("of their library", "top cards of zone,") + : tr("of %1's library", "top cards of zone").arg(ownerName)); + case CaseRevealZone: + return (theirOwn ? tr("their library", "reveal zone") + : tr("%1's library", "reveal zone").arg(ownerName)); + case CaseShuffleZone: + return (theirOwn ? tr("their library", "shuffle") : tr("%1's library", "shuffle").arg(ownerName)); + default: + return (theirOwn ? tr("their library", "nominative") : tr("%1's library", "nominative").arg(ownerName)); } else if (name == "grave") - return (theirOwn - ? tr("their graveyard", "nominative") - : tr("%1's graveyard", "nominative").arg(ownerName) - ); + return (theirOwn ? tr("their graveyard", "nominative") : tr("%1's graveyard", "nominative").arg(ownerName)); else if (name == "rfg") - return (theirOwn - ? tr("their exile", "nominative") - : tr("%1's exile", "nominative").arg(ownerName) - ); + return (theirOwn ? tr("their exile", "nominative") : tr("%1's exile", "nominative").arg(ownerName)); else if (name == "sb") switch (gc) { - case CaseLookAtZone: - return (theirOwn - ? tr("their sideboard", "look at zone") - : tr("%1's sideboard", "look at zone").arg(ownerName) - ); - case CaseNominative: - return (theirOwn - ? tr("their sideboard", "nominative") - : tr("%1's sideboard", "nominative").arg(ownerName) - ); - default: break; + case CaseLookAtZone: + return (theirOwn ? tr("their sideboard", "look at zone") + : tr("%1's sideboard", "look at zone").arg(ownerName)); + case CaseNominative: + return (theirOwn ? tr("their sideboard", "nominative") + : tr("%1's sideboard", "nominative").arg(ownerName)); + default: + break; } return QString(); } diff --git a/cockatrice/src/cardzone.h b/cockatrice/src/cardzone.h index 513b229a..0a80ebf6 100644 --- a/cockatrice/src/cardzone.h +++ b/cockatrice/src/cardzone.h @@ -1,10 +1,10 @@ #ifndef CARDZONE_H #define CARDZONE_H -#include -#include "cardlist.h" #include "abstractgraphicsitem.h" +#include "cardlist.h" #include "translation.h" +#include class Player; class ZoneViewZone; @@ -13,7 +13,8 @@ class QAction; class QPainter; class CardDragItem; -class CardZone : public AbstractGraphicsItem { +class CardZone : public AbstractGraphicsItem +{ Q_OBJECT protected: Player *player; @@ -34,36 +35,90 @@ signals: public slots: 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); + 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; } + 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 theirOwn, GrammaticalCase gc) const; - Player *getPlayer() const { return player; } - bool contentsKnown() const { return cards.getContentsKnown(); } - const CardList &getCards() const { return cards; } + 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; } + 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; } + bool getIsView() const + { + return isView; + } + bool getAlwaysRevealTopCard() const + { + return alwaysRevealTopCard; + } + void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) + { + alwaysRevealTopCard = _alwaysRevealTopCard; + } }; #endif diff --git a/cockatrice/src/chatview/userlistProxy.h b/cockatrice/src/chatview/userlistProxy.h index febb7952..015b9dee 100644 --- a/cockatrice/src/chatview/userlistProxy.h +++ b/cockatrice/src/chatview/userlistProxy.h @@ -1,6 +1,7 @@ #ifndef COCKATRICE_USERLISTPROXY_H #define COCKATRICE_USERLISTPROXY_H +class QString; class ServerInfo_User; /** diff --git a/cockatrice/src/counter_general.cpp b/cockatrice/src/counter_general.cpp index 72748b73..164837c2 100644 --- a/cockatrice/src/counter_general.cpp +++ b/cockatrice/src/counter_general.cpp @@ -2,7 +2,14 @@ #include "pixmapgenerator.h" #include -GeneralCounter::GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, bool useNameForShortcut, QGraphicsItem *parent) +GeneralCounter::GeneralCounter(Player *_player, + int _id, + const QString &_name, + const QColor &_color, + int _radius, + int _value, + bool useNameForShortcut, + QGraphicsItem *parent) : AbstractCounter(_player, _id, _name, true, _value, useNameForShortcut, parent), color(_color), radius(_radius) { setCacheMode(DeviceCoordinateCache); @@ -19,14 +26,14 @@ void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * / 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.setPixelSize(qMax((int)(radius * scaleFactor), 10)); f.setWeight(QFont::Bold); painter->setPen(Qt::black); painter->setFont(f); diff --git a/cockatrice/src/counter_general.h b/cockatrice/src/counter_general.h index aaf6a8e6..5e14b18f 100644 --- a/cockatrice/src/counter_general.h +++ b/cockatrice/src/counter_general.h @@ -3,13 +3,22 @@ #include "abstractcounter.h" -class GeneralCounter : public AbstractCounter { +class GeneralCounter : public AbstractCounter +{ Q_OBJECT private: QColor color; int radius; + public: - GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, bool useNameForShortcut = false, QGraphicsItem *parent = 0); + GeneralCounter(Player *_player, + int _id, + const QString &_name, + const QColor &_color, + int _radius, + int _value, + bool useNameForShortcut = false, + QGraphicsItem *parent = 0); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; diff --git a/cockatrice/src/deck_loader.cpp b/cockatrice/src/deck_loader.cpp index 56086825..0f47db8a 100644 --- a/cockatrice/src/deck_loader.cpp +++ b/cockatrice/src/deck_loader.cpp @@ -1,53 +1,50 @@ -#include -#include -#include #include "deck_loader.h" -#include "decklist.h" #include "carddatabase.h" +#include "decklist.h" #include "main.h" +#include +#include +#include -const QStringList DeckLoader::fileNameFilters = QStringList() - << QObject::tr("Common deck formats (*.cod *.dec *.txt *.mwDeck)") - << QObject::tr("All files (*.*)"); +const QStringList DeckLoader::fileNameFilters = + QStringList() << QObject::tr("Common deck formats (*.cod *.dec *.txt *.mwDeck)") << QObject::tr("All files (*.*)"); DeckLoader::DeckLoader() : DeckList(), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1) { - } -DeckLoader::DeckLoader(const QString &nativeString) : DeckList(nativeString), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1) +DeckLoader::DeckLoader(const QString &nativeString) + : DeckList(nativeString), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1) { - } -DeckLoader::DeckLoader(const DeckList &other) : DeckList(other), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1) +DeckLoader::DeckLoader(const DeckList &other) + : DeckList(other), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1) { - } -DeckLoader::DeckLoader(const DeckLoader &other) : DeckList(other), lastFileName(other.lastFileName), lastFileFormat(other.lastFileFormat), lastRemoteDeckId(other.lastRemoteDeckId) +DeckLoader::DeckLoader(const DeckLoader &other) + : 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)) - { + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return false; } bool result = false; - switch (fmt) - { - case PlainTextFormat: result = loadFromFile_Plain(&file); break; - case CockatriceFormat: - { + switch (fmt) { + case PlainTextFormat: + result = loadFromFile_Plain(&file); + break; + case CockatriceFormat: { result = loadFromFile_Native(&file); qDebug() << "Loaded from" << fileName << "-" << result; - if (!result) - { + if (!result) { qDebug() << "Retying as plain format"; file.seek(0); result = loadFromFile_Plain(&file); @@ -60,8 +57,7 @@ bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt) break; } - if (result) - { + if (result) { lastFileName = fileName; lastFileFormat = fmt; @@ -75,8 +71,7 @@ bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt) bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) { bool result = loadFromString_Native(nativeString); - if (result) - { + if (result) { lastFileName = QString(); lastFileFormat = CockatriceFormat; lastRemoteDeckId = remoteDeckId; @@ -89,98 +84,96 @@ bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) { QFile file(fileName); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) - { + 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; + switch (fmt) { + case PlainTextFormat: + result = saveToFile_Plain(&file); + break; + case CockatriceFormat: + result = saveToFile_Native(&file); + break; } - if (result) - { + if (result) { lastFileName = fileName; lastFileFormat = fmt; } return result; } -//This struct is here to support the forEachCard function call, defined in decklist. It -//requires a function to be called for each card, and passes an inner node and a card for -//each card in the decklist. +// This struct is here to support the forEachCard function call, defined in decklist. It +// requires a function to be called for each card, and passes an inner node and a card for +// each card in the decklist. struct FormatDeckListForExport { - //Create refrences for the strings that will be passed in. + // Create refrences for the strings that will be passed in. QString &mainBoardCards; QString &sideBoardCards; - //create main operator for struct, allowing the foreachcard to work. - FormatDeckListForExport(QString &_mainBoardCards, QString &_sideBoardCards) : mainBoardCards(_mainBoardCards), sideBoardCards(_sideBoardCards){}; + // create main operator for struct, allowing the foreachcard to work. + FormatDeckListForExport(QString &_mainBoardCards, QString &_sideBoardCards) + : mainBoardCards(_mainBoardCards), sideBoardCards(_sideBoardCards){}; void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const { - //Get the card name - CardInfo * dbCard = db->getCard(card->getName()); - if (!dbCard || dbCard->getIsToken()) - { - //If it's a token, we don't care about the card. + // Get the card name + CardInfo *dbCard = db->getCard(card->getName()); + if (!dbCard || dbCard->getIsToken()) { + // If it's a token, we don't care about the card. return; } - //Check if it's a sideboard card. - if (node->getName() == DECK_ZONE_SIDE) + // Check if it's a sideboard card. + if (node->getName() == DECK_ZONE_SIDE) { + // Get the number of cards and add the card name + sideBoardCards += QString::number(card->getNumber()); + // Add a space between card num and name + sideBoardCards += "%20"; + // Add card name + sideBoardCards += card->getName(); + // Add a return at the end of the card + sideBoardCards += "%0A"; + } else // If it's a mainboard card, do the same thing, but for the mainboard card string { - //Get the number of cards and add the card name - sideBoardCards+=QString::number(card->getNumber()); - //Add a space between card num and name - sideBoardCards+="%20"; - //Add card name - sideBoardCards+=card->getName(); - //Add a return at the end of the card - sideBoardCards+="%0A"; - } - else //If it's a mainboard card, do the same thing, but for the mainboard card string - { - mainBoardCards+=QString::number(card->getNumber()); - mainBoardCards+="%20"; - mainBoardCards+=card->getName(); - mainBoardCards+="%0A"; + mainBoardCards += QString::number(card->getNumber()); + mainBoardCards += "%20"; + mainBoardCards += card->getName(); + mainBoardCards += "%0A"; } } }; -//Export deck to decklist function, called to format the deck in a way to be sent to a server +// Export deck to decklist function, called to format the deck in a way to be sent to a server QString DeckLoader::exportDeckToDecklist() { - //Add the base url + // Add the base url QString deckString = "https://www.decklist.org/?"; - //Create two strings to pass to function + // Create two strings to pass to function QString mainBoardCards, sideBoardCards; - //Set up the struct to call. + // Set up the struct to call. FormatDeckListForExport formatDeckListForExport(mainBoardCards, sideBoardCards); - //call our struct function for each card in the deck + // call our struct function for each card in the deck forEachCard(formatDeckListForExport); - //Remove the extra return at the end of the last cards + // Remove the extra return at the end of the last cards mainBoardCards.chop(3); sideBoardCards.chop(3); - //if after we've called it for each card, and the strings are empty, we know that - //there were no non-token cards in the deck, so show an error message. - if((QString::compare(mainBoardCards, "", Qt::CaseInsensitive) == 0) && - (QString::compare(sideBoardCards, "", Qt::CaseInsensitive) == 0)) { + // if after we've called it for each card, and the strings are empty, we know that + // there were no non-token cards in the deck, so show an error message. + if ((QString::compare(mainBoardCards, "", Qt::CaseInsensitive) == 0) && + (QString::compare(sideBoardCards, "", Qt::CaseInsensitive) == 0)) { return ""; } - //return a string with the url for decklist export - deckString+="deckmain="+mainBoardCards+"&deckside="+sideBoardCards; + // return a string with the url for decklist export + deckString += "deckmain=" + mainBoardCards + "&deckside=" + sideBoardCards; return deckString; } DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) { - if (fileName.endsWith(".cod", Qt::CaseInsensitive)) - { + if (fileName.endsWith(".cod", Qt::CaseInsensitive)) { return CockatriceFormat; } return PlainTextFormat; @@ -188,14 +181,12 @@ DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments) { - if (addComments) - { + if (addComments) { saveToStream_DeckHeader(out); } // loop zones - for (int i = 0; i < getRoot()->size(); i++) - { + for (int i = 0; i < getRoot()->size(); i++) { const auto *zoneNode = dynamic_cast(getRoot()->at(i)); saveToStream_DeckZone(out, zoneNode, addComments); @@ -209,16 +200,13 @@ bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments) void DeckLoader::saveToStream_DeckHeader(QTextStream &out) { - if (!getName().isEmpty()) - { + if (!getName().isEmpty()) { out << "// " << getName() << "\n\n"; } - if (!getComments().isEmpty()) - { + if (!getComments().isEmpty()) { QStringList commentRows = getComments().split(QRegExp("\n|\r\n|\r")); - foreach(QString row, commentRows) - { + foreach (QString row, commentRows) { out << "// " << row << "\n"; } out << "\n"; @@ -227,13 +215,12 @@ void DeckLoader::saveToStream_DeckHeader(QTextStream &out) void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments) { - // group cards by card type and count the subtotals - QMultiMap cardsByType; + // group cards by card type and count the subtotals + QMultiMap cardsByType; QMap cardTotalByType; int cardTotal = 0; - for (int j = 0; j < zoneNode->size(); j++) - { + for (int j = 0; j < zoneNode->size(); j++) { auto *card = dynamic_cast(zoneNode->at(j)); CardInfo *info = db->getCard(card->getName()); @@ -241,51 +228,45 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode cardsByType.insert(cardType, card); - if (cardTotalByType.contains(cardType)) - { + if (cardTotalByType.contains(cardType)) { cardTotalByType[cardType] += card->getNumber(); - } - else - { + } else { cardTotalByType[cardType] = card->getNumber(); } cardTotal += card->getNumber(); } - if (addComments) - { + if (addComments) { out << "// " << cardTotal << " " << zoneNode->getVisibleName() << "\n"; } // print cards to stream - foreach(QString cardType, cardsByType.uniqueKeys()) - { - if (addComments) - { + foreach (QString cardType, cardsByType.uniqueKeys()) { + if (addComments) { out << "// " << cardTotalByType[cardType] << " " << cardType << "\n"; } - QList cards = cardsByType.values(cardType); + QList cards = cardsByType.values(cardType); saveToStream_DeckZoneCards(out, zoneNode, cards, addComments); - if (addComments) - { + if (addComments) { out << "\n"; } } } -void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out, const InnerDecklistNode *zoneNode, QList cards, bool addComments) +void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out, + const InnerDecklistNode *zoneNode, + QList cards, + bool addComments) { // QMultiMap sorts values in reverse order - for (int i = cards.size() - 1; i >= 0; --i) - { - DecklistCardNode* card = cards[i]; + for (int i = cards.size() - 1; i >= 0; --i) { + DecklistCardNode *card = cards[i]; - if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) - { + if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) { out << "SB: "; } @@ -297,8 +278,7 @@ QString DeckLoader::getCardZoneFromName(QString cardName, QString currentZoneNam { CardInfo *card = db->getCard(cardName); - if (card && card->getIsToken()) - { + if (card && card->getIsToken()) { return DECK_ZONE_TOKENS; } @@ -307,11 +287,9 @@ QString DeckLoader::getCardZoneFromName(QString cardName, QString currentZoneNam QString DeckLoader::getCompleteCardName(const QString cardName) const { - if (db) - { + if (db) { CardInfo *temp = db->getCardBySimpleName(cardName); - if (temp) - { + if (temp) { return temp->getName(); } } diff --git a/cockatrice/src/deck_loader.h b/cockatrice/src/deck_loader.h index 97557fac..ac8926f2 100644 --- a/cockatrice/src/deck_loader.h +++ b/cockatrice/src/deck_loader.h @@ -6,43 +6,59 @@ class DeckLoader : public DeckList { Q_OBJECT - signals: - void deckLoaded(); +signals: + void deckLoaded(); - public: - enum FileFormat { PlainTextFormat, CockatriceFormat }; - static const QStringList fileNameFilters; +public: + enum FileFormat + { + PlainTextFormat, + CockatriceFormat + }; + static const QStringList fileNameFilters; - private: - QString lastFileName; - FileFormat lastFileFormat; - int lastRemoteDeckId; +private: + 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; } +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 getFormatFromName(const QString &fileName); + 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); - QString exportDeckToDecklist(); + bool loadFromFile(const QString &fileName, FileFormat fmt); + bool loadFromRemote(const QString &nativeString, int remoteDeckId); + bool saveToFile(const QString &fileName, FileFormat fmt); + QString exportDeckToDecklist(); - // overload - bool saveToStream_Plain(QTextStream &out, bool addComments = true); + // overload + bool saveToStream_Plain(QTextStream &out, bool addComments = true); - protected: - void saveToStream_DeckHeader(QTextStream &out); - void saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments = true); - void saveToStream_DeckZoneCards(QTextStream &out, const InnerDecklistNode *zoneNode, QList cards, bool addComments = true); - virtual QString getCardZoneFromName(QString cardName, QString currentZoneName); - virtual QString getCompleteCardName(const QString cardName) const; +protected: + void saveToStream_DeckHeader(QTextStream &out); + void saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments = true); + void saveToStream_DeckZoneCards(QTextStream &out, + const InnerDecklistNode *zoneNode, + QList cards, + bool addComments = true); + virtual QString getCardZoneFromName(QString cardName, QString currentZoneName); + virtual QString getCompleteCardName(const QString cardName) const; }; #endif diff --git a/cockatrice/src/decklistmodel.cpp b/cockatrice/src/decklistmodel.cpp index ef8b89cb..cb3fe244 100644 --- a/cockatrice/src/decklistmodel.cpp +++ b/cockatrice/src/decklistmodel.cpp @@ -1,17 +1,17 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "main.h" #include "decklistmodel.h" #include "carddatabase.h" -#include "settingscache.h" #include "deck_loader.h" +#include "main.h" +#include "settingscache.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include DeckListModel::DeckListModel(QObject *parent) : QAbstractItemModel(parent), lastKnownColumn(1), lastKnownOrder(Qt::AscendingOrder) @@ -35,18 +35,15 @@ void DeckListModel::rebuildTree() InnerDecklistNode *listRoot = deckList->getRoot(); - for (int i = 0; i < listRoot->size(); i++) - { + for (int i = 0; i < listRoot->size(); i++) { auto *currentZone = dynamic_cast(listRoot->at(i)); auto *node = new InnerDecklistNode(currentZone->getName(), root); - for (int j = 0; j < currentZone->size(); j++) - { + for (int j = 0; j < currentZone->size(); j++) { auto *currentCard = dynamic_cast(currentZone->at(j)); // TODO: better sanity checking - if (currentCard == nullptr) - { + if (currentCard == nullptr) { continue; } @@ -55,8 +52,7 @@ void DeckListModel::rebuildTree() auto *cardTypeNode = dynamic_cast(node->findChild(cardType)); - if (!cardTypeNode) - { + if (!cardTypeNode) { cardTypeNode = new InnerDecklistNode(cardType, node); } @@ -69,54 +65,44 @@ void DeckListModel::rebuildTree() int DeckListModel::rowCount(const QModelIndex &parent) const { - //debugIndexInfo("rowCount", parent); + // debugIndexInfo("rowCount", parent); auto *node = getNode(parent); - if (node) - { + if (node) { return node->size(); - } - else - { + } else { return 0; } } -int DeckListModel::columnCount(const QModelIndex &/*parent*/) const +int DeckListModel::columnCount(const QModelIndex & /*parent*/) const { return 2; } QVariant DeckListModel::data(const QModelIndex &index, int role) const { - //debugIndexInfo("data", index); - if (!index.isValid()) - { + // debugIndexInfo("data", index); + if (!index.isValid()) { return QVariant(); } - if (index.column() >= columnCount()) - { + if (index.column() >= columnCount()) { return QVariant(); } auto *temp = static_cast(index.internalPointer()); auto *card = dynamic_cast(temp); - if (card == nullptr) - { + if (card == nullptr) { auto *node = dynamic_cast(temp); - switch (role) - { - case Qt::FontRole: - { + switch (role) { + case Qt::FontRole: { QFont f; f.setBold(true); return f; } case Qt::DisplayRole: - case Qt::EditRole: - { - switch (index.column()) - { + case Qt::EditRole: { + switch (index.column()) { case 0: return node->recursiveCount(true); case 1: @@ -125,40 +111,35 @@ QVariant DeckListModel::data(const QModelIndex &index, int role) const return QVariant(); } } - case Qt::BackgroundRole: - { + case Qt::BackgroundRole: { int color = 90 + 60 * node->depth(); return QBrush(QColor(color, 255, color)); } - case Qt::ForegroundRole: - { - return QBrush(QColor(0 ,0 ,0)); + case Qt::ForegroundRole: { + return QBrush(QColor(0, 0, 0)); } - default: return QVariant(); + default: + return QVariant(); } - } - else - { - switch (role) - { + } else { + switch (role) { case Qt::DisplayRole: - case Qt::EditRole: - { - switch (index.column()) - { - case 0: return card->getNumber(); - case 1: return card->getName(); - default: return QVariant(); + case Qt::EditRole: { + switch (index.column()) { + case 0: + return card->getNumber(); + case 1: + return card->getName(); + default: + return QVariant(); } } - case Qt::BackgroundRole: - { + case Qt::BackgroundRole: { int color = 255 - (index.row() % 2) * 30; return QBrush(QColor(color, color, color)); } - case Qt::ForegroundRole: - { - return QBrush(QColor(0 ,0 ,0)); + case Qt::ForegroundRole: { + return QBrush(QColor(0, 0, 0)); } default: return QVariant(); @@ -168,41 +149,38 @@ QVariant DeckListModel::data(const QModelIndex &index, int role) const QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - { + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) { return QVariant(); } - if (section >= columnCount()) - { + if (section >= columnCount()) { return QVariant(); } - switch (section) - { - case 0: return tr("Number"); - case 1: return tr("Card"); - default: return QVariant(); + switch (section) { + case 0: + return tr("Number"); + case 1: + return tr("Card"); + default: + return QVariant(); } } QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const { - //debugIndexInfo("index", parent); - if (!hasIndex(row, column, parent)) - { + // debugIndexInfo("index", parent); + if (!hasIndex(row, column, parent)) { return {}; } auto *parentNode = getNode(parent); return row >= parentNode->size() ? QModelIndex() : createIndex(row, column, parentNode->at(row)); - } QModelIndex DeckListModel::parent(const QModelIndex &ind) const { - if (!ind.isValid()) - { + if (!ind.isValid()) { return {}; } @@ -211,8 +189,7 @@ QModelIndex DeckListModel::parent(const QModelIndex &ind) const Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - { + if (!index.isValid()) { return nullptr; } @@ -224,8 +201,7 @@ Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const void DeckListModel::emitRecursiveUpdates(const QModelIndex &index) { - if (!index.isValid()) - { + if (!index.isValid()) { return; } @@ -236,16 +212,19 @@ void DeckListModel::emitRecursiveUpdates(const QModelIndex &index) bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role) { auto *node = getNode(index); - if (!node || (role != Qt::EditRole)) - { + if (!node || (role != Qt::EditRole)) { return false; } - switch (index.column()) - { - case 0: node->setNumber(value.toInt()); break; - case 1: node->setName(value.toString()); break; - default: return false; + switch (index.column()) { + case 0: + node->setNumber(value.toInt()); + break; + case 1: + node->setName(value.toString()); + break; + default: + return false; } emitRecursiveUpdates(index); @@ -256,34 +235,27 @@ bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent) { auto *node = getNode(parent); - if (!node) - { + if (!node) { return false; } - if (row + count > node->size()) - { + if (row + count > node->size()) { return false; } beginRemoveRows(parent, row, row + count - 1); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { AbstractDecklistNode *toDelete = node->takeAt(row); - if (auto *temp = dynamic_cast(toDelete)) - { + if (auto *temp = dynamic_cast(toDelete)) { deckList->deleteNode(temp->getDataNode()); } delete toDelete; } endRemoveRows(); - if (node->empty() && (node != root)) - { + if (node->empty() && (node != root)) { removeRows(parent.row(), 1, parent.parent()); - } - else - { + } else { emitRecursiveUpdates(parent); } @@ -293,8 +265,7 @@ bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent) InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent) { auto *newNode = dynamic_cast(parent->findChild(name)); - if (!newNode) - { + if (!newNode) { beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); newNode = new InnerDecklistNode(name, parent); endInsertRows(); @@ -309,21 +280,18 @@ DecklistModelCardNode *DeckListModel::findCardNode(const QString &cardName, cons QString cardType; zoneNode = dynamic_cast(root->findChild(zoneName)); - if (!zoneNode) - { + if (!zoneNode) { return nullptr; } info = db->getCard(cardName); - if (!info) - { + if (!info) { return nullptr; } cardType = info->getMainCardType(); typeNode = dynamic_cast(zoneNode->findChild(cardType)); - if (!typeNode) - { + if (!typeNode) { return nullptr; } @@ -335,8 +303,7 @@ QModelIndex DeckListModel::findCard(const QString &cardName, const QString &zone DecklistModelCardNode *cardNode; cardNode = findCardNode(cardName, zoneName); - if (!cardNode) - { + if (!cardNode) { return {}; } @@ -346,38 +313,16 @@ QModelIndex DeckListModel::findCard(const QString &cardName, const QString &zone QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway) { CardInfo *info = db->getCard(cardName); - if (info == nullptr) - { - if (abAddAnyway) - { + if (info == nullptr) { + if (abAddAnyway) { // We need to keep this card added no matter what // This is usually called from tab_deck_editor // So we'll create a new CardInfo with the name // and default values for all fields - info = new CardInfo( - cardName, - false, - nullptr, - nullptr, - "unknown", - nullptr, - nullptr, - QStringList(), - QList(), - QList(), - false, - 0, - false, - 0, - SetList(), - QStringMap(), - MuidMap(), - QStringMap(), - QStringMap() - ); - } - else - { + info = new CardInfo(cardName, false, nullptr, nullptr, "unknown", nullptr, nullptr, QStringList(), + QList(), QList(), false, 0, false, 0, SetList(), + QStringMap(), MuidMap(), QStringMap(), QStringMap()); + } else { return {}; } } @@ -389,15 +334,12 @@ QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneN QModelIndex parentIndex = nodeToIndex(cardTypeNode); auto *cardNode = dynamic_cast(cardTypeNode->findChild(cardName)); - if (!cardNode) - { + if (!cardNode) { DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); endInsertRows(); - } - else - { + } else { cardNode->setNumber(cardNode->getNumber() + 1); deckList->updateDeckHash(); } @@ -408,8 +350,7 @@ QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneN QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const { - if (node == nullptr || node == root) - { + if (node == nullptr || node == root) { return {}; } @@ -420,17 +361,15 @@ void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order) { // Sort children of node and save the information needed to // update the list of persistent indexes. - QVector > sortResult = node->sort(order); + QVector> sortResult = node->sort(order); QModelIndexList from, to; int columns = columnCount(); - for (int i = sortResult.size() - 1; i >= 0; --i) - { + for (int i = sortResult.size() - 1; i >= 0; --i) { const int fromRow = sortResult[i].first; const int toRow = sortResult[i].second; AbstractDecklistNode *temp = node->at(toRow); - for (int j = 0; j < columns; ++j) - { + for (int j = 0; j < columns; ++j) { from << createIndex(fromRow, j, temp); to << createIndex(toRow, j, temp); } @@ -438,11 +377,9 @@ void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order) changePersistentIndexList(from, to); // Recursion - for (int i = node->size() - 1; i >= 0; --i) - { + for (int i = node->size() - 1; i >= 0; --i) { auto *subNode = dynamic_cast(node->at(i)); - if (subNode) - { + if (subNode) { sortHelper(subNode, order); } } @@ -455,8 +392,7 @@ void DeckListModel::sort(int column, Qt::SortOrder order) emit layoutAboutToBeChanged(); DeckSortMethod sortMethod; - switch(column) - { + switch (column) { case 0: sortMethod = ByNumber; break; @@ -490,8 +426,7 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no { const int totalColumns = 2; - if (node->height() == 1) - { + if (node->height() == 1) { QTextBlockFormat blockFormat; QTextCharFormat charFormat; charFormat.setFontPointSize(11); @@ -502,9 +437,8 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no tableFormat.setCellPadding(0); tableFormat.setCellSpacing(0); tableFormat.setBorder(0); - QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); - for (int i = 0; i < node->size(); i++) - { + QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); + for (int i = 0; i < node->size(); i++) { auto *card = dynamic_cast(node->at(i)); QTextCharFormat cellCharFormat; @@ -519,11 +453,8 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no cell.setFormat(cellCharFormat); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(card->getName()); - } - } - else if (node->height() == 2) - { + } else if (node->height() == 2) { QTextBlockFormat blockFormat; QTextCharFormat charFormat; charFormat.setFontPointSize(14); @@ -536,15 +467,13 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no tableFormat.setCellSpacing(0); tableFormat.setBorder(0); QVector constraints; - for (int i = 0; i < totalColumns; i++) - { + for (int i = 0; i < totalColumns; i++) { constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); } tableFormat.setColumnWidthConstraints(constraints); QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); - for (int i = 0; i < node->size(); i++) - { + for (int i = 0; i < node->size(); i++) { QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); printDeckListNode(&cellCursor, dynamic_cast(node->at(i))); } @@ -576,10 +505,9 @@ void DeckListModel::printDeckList(QPrinter *printer) cursor.insertText(deckList->getComments()); cursor.insertBlock(headerBlockFormat, headerCharFormat); - for (int i = 0; i < root->size(); i++) - { + for (int i = 0; i < root->size(); i++) { cursor.insertHtml("
"); - //cursor.insertHtml("
"); + // cursor.insertHtml("
"); cursor.insertBlock(headerBlockFormat, headerCharFormat); printDeckListNode(&cursor, dynamic_cast(root->at(i))); diff --git a/cockatrice/src/decklistmodel.h b/cockatrice/src/decklistmodel.h index 898b4a51..5e4f4dd3 100644 --- a/cockatrice/src/decklistmodel.h +++ b/cockatrice/src/decklistmodel.h @@ -1,9 +1,9 @@ #ifndef DECKLISTMODEL_H #define DECKLISTMODEL_H +#include "decklist.h" #include #include -#include "decklist.h" class DeckLoader; class CardDatabase; @@ -11,19 +11,40 @@ class QProgressDialog; class QPrinter; class QTextCursor; -class DecklistModelCardNode : public AbstractDecklistCardNode { +class DecklistModelCardNode : public AbstractDecklistCardNode +{ private: DecklistCardNode *dataNode; + public: - DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } - int getNumber() const { return dataNode->getNumber(); } - void setNumber(int _number) { dataNode->setNumber(_number); } - QString getName() const { return dataNode->getName(); } - void setName(const QString &_name) { dataNode->setName(_name); } - DecklistCardNode *getDataNode() const { return dataNode; } + DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) + : AbstractDecklistCardNode(_parent), dataNode(_dataNode) + { + } + int getNumber() const + { + return dataNode->getNumber(); + } + void setNumber(int _number) + { + dataNode->setNumber(_number); + } + QString getName() const + { + return dataNode->getName(); + } + void setName(const QString &_name) + { + dataNode->setName(_name); + } + DecklistCardNode *getDataNode() const + { + return dataNode; + } }; -class DeckListModel : public QAbstractItemModel { +class DeckListModel : public QAbstractItemModel +{ Q_OBJECT private slots: void rebuildTree(); @@ -31,11 +52,12 @@ public slots: void printDeckList(QPrinter *printer); signals: void deckHashChanged(); + public: DeckListModel(QObject *parent = 0); ~DeckListModel(); int rowCount(const QModelIndex &parent) const; - int columnCount(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) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; @@ -47,8 +69,12 @@ public: QModelIndex addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway = false); void sort(int column, Qt::SortOrder order); void cleanList(); - DeckLoader *getDeckList() const { return deckList; } + DeckLoader *getDeckList() const + { + return deckList; + } void setDeckList(DeckLoader *_deck); + private: DeckLoader *deckList; InnerDecklistNode *root; @@ -62,7 +88,7 @@ private: void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node); - template T getNode(const QModelIndex &index) const + template T getNode(const QModelIndex &index) const { if (!index.isValid()) return dynamic_cast(root); diff --git a/cockatrice/src/deckstats_interface.cpp b/cockatrice/src/deckstats_interface.cpp index 1a4ee815..1e038210 100644 --- a/cockatrice/src/deckstats_interface.cpp +++ b/cockatrice/src/deckstats_interface.cpp @@ -1,17 +1,15 @@ #include "deckstats_interface.h" #include "decklist.h" -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include #include -DeckStatsInterface::DeckStatsInterface( - CardDatabase &_cardDatabase, - QObject *parent -) : QObject(parent), cardDatabase(_cardDatabase) +DeckStatsInterface::DeckStatsInterface(CardDatabase &_cardDatabase, QObject *parent) + : QObject(parent), cardDatabase(_cardDatabase) { manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); @@ -25,7 +23,7 @@ void DeckStatsInterface::queryFinished(QNetworkReply *reply) deleteLater(); return; } - + QString data(reply->readAll()); reply->deleteLater(); @@ -35,10 +33,10 @@ void DeckStatsInterface::queryFinished(QNetworkReply *reply) deleteLater(); return; } - + QString deckUrl = rx.cap(1); QDesktopServices::openUrl(deckUrl); - + deleteLater(); } @@ -59,41 +57,33 @@ void DeckStatsInterface::analyzeDeck(DeckList *deck) { QByteArray data; getAnalyzeRequestData(deck, &data); - + QNetworkRequest request(QUrl("https://deckstats.net/index.php")); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - + manager->post(request, data); } -struct CopyIfNotAToken { +struct CopyIfNotAToken +{ CardDatabase &cardDatabase; DeckList &destination; - CopyIfNotAToken( - CardDatabase &_cardDatabase, - DeckList &_destination - ) : cardDatabase(_cardDatabase), destination(_destination) {}; + CopyIfNotAToken(CardDatabase &_cardDatabase, DeckList &_destination) + : cardDatabase(_cardDatabase), destination(_destination){}; - void operator()( - const InnerDecklistNode *node, - const DecklistCardNode *card - ) const { - CardInfo * dbCard = cardDatabase.getCard(card->getName()); + void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const + { + CardInfo *dbCard = cardDatabase.getCard(card->getName()); if (dbCard && !dbCard->getIsToken()) { - DecklistCardNode *addedCard = destination.addCard( - card->getName(), - node->getName() - ); + DecklistCardNode *addedCard = destination.addCard(card->getName(), node->getName()); addedCard->setNumber(card->getNumber()); } } }; -void DeckStatsInterface::copyDeckWithoutTokens( - const DeckList &source, - DeckList &destination -) { +void DeckStatsInterface::copyDeckWithoutTokens(const DeckList &source, DeckList &destination) +{ CopyIfNotAToken copyIfNotAToken(cardDatabase, destination); source.forEachCard(copyIfNotAToken); } diff --git a/cockatrice/src/deckstats_interface.h b/cockatrice/src/deckstats_interface.h index c3a59c9b..03fa9f7f 100644 --- a/cockatrice/src/deckstats_interface.h +++ b/cockatrice/src/deckstats_interface.h @@ -10,7 +10,8 @@ class QNetworkAccessManager; class QNetworkReply; class DeckList; -class DeckStatsInterface : public QObject { +class DeckStatsInterface : public QObject +{ Q_OBJECT private: QNetworkAccessManager *manager; @@ -22,11 +23,12 @@ private: * closest non-token card instead. So we construct a new deck which has no * tokens. */ - void copyDeckWithoutTokens(const DeckList &source, DeckList& destination); + void copyDeckWithoutTokens(const DeckList &source, DeckList &destination); private slots: void queryFinished(QNetworkReply *reply); void getAnalyzeRequestData(DeckList *deck, QByteArray *data); + public: DeckStatsInterface(CardDatabase &_cardDatabase, QObject *parent = 0); void analyzeDeck(DeckList *deck); diff --git a/cockatrice/src/deckview.cpp b/cockatrice/src/deckview.cpp index 2a5acccc..fb6b264d 100644 --- a/cockatrice/src/deckview.cpp +++ b/cockatrice/src/deckview.cpp @@ -1,15 +1,17 @@ +#include "deckview.h" +#include "carddatabase.h" +#include "decklist.h" +#include "main.h" +#include "settingscache.h" +#include "thememanager.h" #include #include #include #include -#include "deckview.h" -#include "decklist.h" -#include "carddatabase.h" -#include "settingscache.h" -#include "thememanager.h" -#include "main.h" -DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag) +DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, + const QPointF &_hotSpot, + AbstractCardDragItem *parentDrag) : AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0) { } @@ -25,7 +27,7 @@ void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos) if (!cursorZone) return; currentZone = cursorZone; - + QPointF newPos = cursorScenePos; if (newPos != pos()) { for (int i = 0; i < childDrags.size(); i++) @@ -56,10 +58,10 @@ void DeckViewCardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) c->handleDrop(currentZone); sc->removeItem(c); } - + sc->updateContents(); } - + event->accept(); } @@ -77,7 +79,7 @@ DeckViewCard::~DeckViewCard() void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { AbstractCardItem::paint(painter, option, widget); - + painter->save(); QPen pen; pen.setWidth(3); @@ -90,18 +92,19 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < + 2 * QApplication::startDragDistance()) return; - + 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++) { @@ -122,8 +125,7 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event) if (static_cast(scene())->getLocked()) return; - if (event->button() == Qt::LeftButton) - { + if (event->button() == Qt::LeftButton) { QList result; QList sel = scene()->selectedItems(); @@ -156,8 +158,7 @@ void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event) processHoverEvent(); } -DeckViewCardContainer::DeckViewCardContainer(const QString &_name) - : QGraphicsItem(), name(_name), width(0), height(0) +DeckViewCardContainer::DeckViewCardContainer(const QString &_name) : QGraphicsItem(), name(_name), width(0), height(0) { setCacheMode(DeviceCoordinateCache); } @@ -170,19 +171,20 @@ QRectF DeckViewCardContainer::boundingRect() const void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { qreal totalTextWidth = getCardTypeTextWidth(); - + painter->fillRect(boundingRect(), themeManager->getTableBgBrush()); 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())); - + 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(); @@ -212,12 +214,12 @@ void DeckViewCardContainer::addCard(DeckViewCard *card) void DeckViewCardContainer::removeCard(DeckViewCard *card) { cards.removeAt(cards.indexOf(card)); - cardsByType.remove(card->getInfo() ? card->getInfo()->getMainCardType(): "", card); + cardsByType.remove(card->getInfo() ? card->getInfo()->getMainCardType() : "", card); } -QList > DeckViewCardContainer::getRowsAndCols() const +QList> DeckViewCardContainer::getRowsAndCols() const { - QList > result; + QList> result; QList cardTypeList = cardsByType.uniqueKeys(); for (int i = 0; i < cardTypeList.size(); ++i) result.append(QPair(1, cardsByType.count(cardTypeList[i]))); @@ -231,7 +233,7 @@ int DeckViewCardContainer::getCardTypeTextWidth() const f.setPixelSize(16); f.setWeight(QFont::Bold); QFontMetrics fm(f); - + int maxCardTypeWidth = 0; QMapIterator i(cardsByType); while (i.hasNext()) { @@ -239,56 +241,56 @@ int DeckViewCardContainer::getCardTypeTextWidth() const if (cardTypeWidth > maxCardTypeWidth) maxCardTypeWidth = cardTypeWidth; } - + return maxCardTypeWidth + 15; } -QSizeF DeckViewCardContainer::calculateBoundingRect(const QList > &rowsAndCols) const +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); } -bool DeckViewCardContainer::sortCardsByName(DeckViewCard * c1, DeckViewCard * c2) +bool DeckViewCardContainer::sortCardsByName(DeckViewCard *c1, DeckViewCard *c2) { if (c1 && c2) - return c1->getName() < c2->getName(); + return c1->getName() < c2->getName(); return false; } -void DeckViewCardContainer::rearrangeItems(const QList > &rowsAndCols) +void DeckViewCardContainer::rearrangeItems(const QList> &rowsAndCols) { currentRowsAndCols = rowsAndCols; - + int totalCols = 0, totalRows = 0; qreal yUntilNow = separatorY + paddingY; - qreal x = (qreal) getCardTypeTextWidth(); + 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]); - qSort( row.begin(), row.end(), DeckViewCardContainer::sortCardsByName); + qSort(row.begin(), row.end(), DeckViewCardContainer::sortCardsByName); 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(); @@ -302,8 +304,7 @@ void DeckViewCardContainer::setWidth(qreal _width) update(); } -DeckViewScene::DeckViewScene(QObject *parent) - : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) +DeckViewScene::DeckViewScene(QObject *parent) : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) { } @@ -325,7 +326,7 @@ void DeckViewScene::setDeck(const DeckList &_deck) { if (deck) delete deck; - + deck = new DeckList(_deck); rebuildTree(); applySideboardPlan(deck->getCurrentSideboardPlan()); @@ -335,21 +336,21 @@ void DeckViewScene::setDeck(const DeckList &_deck) 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) @@ -372,7 +373,7 @@ void DeckViewScene::applySideboardPlan(const QList &plan) 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) @@ -382,7 +383,7 @@ void DeckViewScene::applySideboardPlan(const QList &plan) } if (!card) continue; - + start->removeCard(card); target->addCard(card); card->setParentItem(target); @@ -393,19 +394,19 @@ void DeckViewScene::rearrangeItems() { const int spacing = CARD_HEIGHT / 3; QList contList = cardContainers.values(); - + // Initialize space requirements - QList > > rowsAndColsList; - QList > cardCountList; + QList>> rowsAndColsList; + QList> cardCountList; for (int i = 0; i < contList.size(); ++i) { - QList > rowsAndCols = contList[i]->getRowsAndCols(); + 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 @@ -417,11 +418,11 @@ void DeckViewScene::rearrangeItems() 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) @@ -431,13 +432,14 @@ void DeckViewScene::rearrangeItems() 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))); + 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]; @@ -445,11 +447,11 @@ void DeckViewScene::rearrangeItems() 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)); } @@ -484,14 +486,13 @@ void DeckViewScene::resetSideboardPlan() rearrangeItems(); } -DeckView::DeckView(QWidget *parent) - : QGraphicsView(parent) +DeckView::DeckView(QWidget *parent) : QGraphicsView(parent) { deckViewScene = new DeckViewScene(this); - + setBackgroundBrush(QBrush(QColor(0, 0, 0))); setDragMode(RubberBandDrag); - setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/); + setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing /* | QPainter::SmoothPixmapTransform*/); setScene(deckViewScene); connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); @@ -502,7 +503,7 @@ DeckView::DeckView(QWidget *parent) void DeckView::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); - deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height()); + deckViewScene->setOptimalAspectRatio((qreal)width() / (qreal)height()); deckViewScene->rearrangeItems(); } diff --git a/cockatrice/src/deckview.h b/cockatrice/src/deckview.h index 18a90fc6..8e81c9c0 100644 --- a/cockatrice/src/deckview.h +++ b/cockatrice/src/deckview.h @@ -1,12 +1,12 @@ #ifndef DECKVIEW_H #define DECKVIEW_H +#include "abstractcarddragitem.h" #include #include #include #include #include -#include "abstractcarddragitem.h" #include "pb/move_card_to_zone.pb.h" @@ -17,65 +17,90 @@ class DeckViewCardContainer; class DeckViewCardDragItem; class MoveCardToZone; -class DeckViewCard : public AbstractCardItem { +class DeckViewCard : public AbstractCardItem +{ private: 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; } + const QString &getOriginZone() const + { + return originZone; + } + protected: void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event); }; -class DeckViewCardDragItem : public AbstractCardDragItem { +class DeckViewCardDragItem : public AbstractCardDragItem +{ private: DeckViewCardContainer *currentZone; void handleDrop(DeckViewCardContainer *target); + public: DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); void updatePosition(const QPointF &cursorScenePos); + protected: void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; -class DeckViewCardContainer : public QGraphicsItem { +class DeckViewCardContainer : public QGraphicsItem +{ private: static const int separatorY = 20; static const int paddingY = 10; - static bool sortCardsByName(DeckViewCard * c1, DeckViewCard * c2); - + static bool sortCardsByName(DeckViewCard *c1, DeckViewCard *c2); + QString name; QList cards; QMultiMap cardsByType; - QList > currentRowsAndCols; + QList> currentRowsAndCols; qreal width, height; int getCardTypeTextWidth() const; + public: - enum { Type = typeDeckViewCardContainer }; - int type() const { return Type; } + 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; } + 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 { +class DeckViewScene : public QGraphicsScene +{ Q_OBJECT signals: void newCardAdded(AbstractCardItem *card); void sideboardPlanChanged(); + private: bool locked; DeckList *deck; @@ -83,13 +108,23 @@ private: qreal optimalAspectRatio; void clearContents(); void rebuildTree(); + public: DeckViewScene(QObject *parent = 0); ~DeckViewScene(); - void setLocked(bool _locked) { locked = _locked; } - bool getLocked() const { return locked; } + void setLocked(bool _locked) + { + locked = _locked; + } + bool getLocked() const + { + return locked; + } void setDeck(const DeckList &_deck); - void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } + void setOptimalAspectRatio(qreal _optimalAspectRatio) + { + optimalAspectRatio = _optimalAspectRatio; + } void rearrangeItems(); void updateContents(); QList getSideboardPlan() const; @@ -97,10 +132,12 @@ public: void applySideboardPlan(const QList &plan); }; -class DeckView : public QGraphicsView { +class DeckView : public QGraphicsView +{ Q_OBJECT private: DeckViewScene *deckViewScene; + protected: void resizeEvent(QResizeEvent *event); public slots: @@ -108,11 +145,18 @@ public slots: signals: 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 setLocked(bool _locked) + { + deckViewScene->setLocked(_locked); + } + QList getSideboardPlan() const + { + return deckViewScene->getSideboardPlan(); + } void mouseDoubleClickEvent(QMouseEvent *event); void resetSideboardPlan(); }; diff --git a/cockatrice/src/dlg_connect.cpp b/cockatrice/src/dlg_connect.cpp index 4077d2f0..06c0ac9c 100644 --- a/cockatrice/src/dlg_connect.cpp +++ b/cockatrice/src/dlg_connect.cpp @@ -1,17 +1,17 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "dlg_connect.h" #include "settingscache.h" #include "userconnection_information.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #define PUBLIC_SERVERS_URL "https://github.com/Cockatrice/Cockatrice/wiki/Public-Servers" @@ -24,7 +24,7 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) rebuildComboBoxList(); newHostButton = new QRadioButton(tr("New Host"), this); - + saveLabel = new QLabel(tr("Name:")); saveEdit = new QLineEdit(settingsCache->servers().getSaveName()); saveLabel->setBuddy(saveEdit); @@ -45,14 +45,15 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) passwordEdit = new QLineEdit(settingsCache->servers().getPassword()); passwordLabel->setBuddy(passwordEdit); passwordEdit->setEchoMode(QLineEdit::Password); - + savePasswordCheckBox = new QCheckBox(tr("&Save password")); savePasswordCheckBox->setChecked(settingsCache->servers().getSavePassword()); autoConnectCheckBox = new QCheckBox(tr("A&uto connect")); autoConnectCheckBox->setToolTip(tr("Automatically connect to the most recent login when Cockatrice opens")); - publicServersLabel = new QLabel(QString("(%2)").arg(PUBLIC_SERVERS_URL).arg(tr("Public Servers"))); + publicServersLabel = + new QLabel(QString("(%2)").arg(PUBLIC_SERVERS_URL).arg(tr("Public Servers"))); publicServersLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); publicServersLabel->setWordWrap(true); publicServersLabel->setTextFormat(Qt::RichText); @@ -60,13 +61,10 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) publicServersLabel->setOpenExternalLinks(true); publicServersLabel->setAlignment(Qt::AlignCenter); - if (savePasswordCheckBox->isChecked()) - { + if (savePasswordCheckBox->isChecked()) { autoConnectCheckBox->setChecked(static_cast(settingsCache->servers().getAutoConnect())); autoConnectCheckBox->setEnabled(true); - } - else - { + } else { settingsCache->servers().setAutoConnect(0); autoConnectCheckBox->setChecked(false); autoConnectCheckBox->setEnabled(false); @@ -140,7 +138,8 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) previousHostButton->setChecked(true); - connect(previousHosts, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(updateDisplayInfo(const QString &))); + connect(previousHosts, SIGNAL(currentIndexChanged(const QString &)), this, + SLOT(updateDisplayInfo(const QString &))); playernameEdit->setFocus(); } @@ -148,24 +147,13 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) void DlgConnect::actSaveConfig() { bool updateSuccess = settingsCache->servers().updateExistingServer( - saveEdit->text().trimmed(), - hostEdit->text().trimmed(), - portEdit->text().trimmed(), - playernameEdit->text().trimmed(), - passwordEdit->text(), - savePasswordCheckBox->isChecked() - ); + saveEdit->text().trimmed(), hostEdit->text().trimmed(), portEdit->text().trimmed(), + playernameEdit->text().trimmed(), passwordEdit->text(), savePasswordCheckBox->isChecked()); - if (! updateSuccess) - { - settingsCache->servers().addNewServer( - saveEdit->text().trimmed(), - hostEdit->text().trimmed(), - portEdit->text().trimmed(), - playernameEdit->text().trimmed(), - passwordEdit->text(), - savePasswordCheckBox->isChecked() - ); + if (!updateSuccess) { + settingsCache->servers().addNewServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(), + portEdit->text().trimmed(), playernameEdit->text().trimmed(), + passwordEdit->text(), savePasswordCheckBox->isChecked()); } rebuildComboBoxList(); @@ -178,8 +166,7 @@ void DlgConnect::rebuildComboBoxList() UserConnection_Information uci; savedHostList = uci.getServerInfo(); - if (savedHostList.size() == 1) - { + if (savedHostList.size() == 1) { settingsCache->servers().addNewServer("Woogerworks", "cockatrice.woogerworks.com", "4747", "", "", false); settingsCache->servers().addNewServer("Chickatrice", "chickatrice.net", "4747", "", "", false); settingsCache->servers().addNewServer("cockatric.es", "cockatric.es", "4747", "", "", false); @@ -188,28 +175,23 @@ void DlgConnect::rebuildComboBoxList() savedHostList = uci.getServerInfo(); int i = 0; - for (UserConnection_Information tmp : savedHostList) - { + for (UserConnection_Information tmp : savedHostList) { QString saveName = tmp.getSaveName(); - if (saveName.size()) - { + if (saveName.size()) { previousHosts->addItem(saveName); - - if (settingsCache->servers().getPrevioushostName() == saveName) - { + + if (settingsCache->servers().getPrevioushostName() == saveName) { previousHosts->setCurrentIndex(i); } - + i++; } } } - void DlgConnect::previousHostSelected(bool state) { - if (state) - { + if (state) { saveEdit->setDisabled(true); previousHosts->setDisabled(false); } @@ -217,8 +199,7 @@ void DlgConnect::previousHostSelected(bool state) void DlgConnect::updateDisplayInfo(const QString &saveName) { - if (saveEdit == nullptr) - { + if (saveEdit == nullptr) { return; } @@ -226,23 +207,21 @@ void DlgConnect::updateDisplayInfo(const QString &saveName) QStringList data = uci.getServerInfo(saveName); bool savePasswordStatus = (data.at(5) == "1"); - + saveEdit->setText(data.at(0)); hostEdit->setText(data.at(1)); portEdit->setText(data.at(2)); playernameEdit->setText(data.at(3)); savePasswordCheckBox->setChecked(savePasswordStatus); - if (savePasswordStatus) - { + if (savePasswordStatus) { passwordEdit->setText(data.at(4)); } } void DlgConnect::newHostSelected(bool state) { - if (state) - { + if (state) { previousHosts->setDisabled(true); hostEdit->clear(); portEdit->clear(); @@ -252,23 +231,17 @@ void DlgConnect::newHostSelected(bool state) saveEdit->clear(); saveEdit->setPlaceholderText("New Menu Name"); saveEdit->setDisabled(false); - } - else - { + } else { rebuildComboBoxList(); } } - void DlgConnect::passwordSaved(int state) { Q_UNUSED(state); - if (savePasswordCheckBox->isChecked()) - { - autoConnectCheckBox->setEnabled(true); - } - else - { + if (savePasswordCheckBox->isChecked()) { + autoConnectCheckBox->setEnabled(true); + } else { autoConnectCheckBox->setChecked(false); autoConnectCheckBox->setEnabled(false); } @@ -276,40 +249,25 @@ void DlgConnect::passwordSaved(int state) void DlgConnect::actOk() { - if (newHostButton->isChecked()) - { - if (saveEdit->text().isEmpty()) - { + if (newHostButton->isChecked()) { + if (saveEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Connection Warning"), tr("You need to name your new connection profile.")); return; } - settingsCache->servers().addNewServer( - saveEdit->text().trimmed(), - hostEdit->text().trimmed(), - portEdit->text().trimmed(), - playernameEdit->text().trimmed(), - passwordEdit->text(), - savePasswordCheckBox->isChecked() - ); - } - else - { - settingsCache->servers().updateExistingServer( - saveEdit->text().trimmed(), - hostEdit->text().trimmed(), - portEdit->text().trimmed(), - playernameEdit->text().trimmed(), - passwordEdit->text(), - savePasswordCheckBox->isChecked() - ); + settingsCache->servers().addNewServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(), + portEdit->text().trimmed(), playernameEdit->text().trimmed(), + passwordEdit->text(), savePasswordCheckBox->isChecked()); + } else { + settingsCache->servers().updateExistingServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(), + portEdit->text().trimmed(), playernameEdit->text().trimmed(), + passwordEdit->text(), savePasswordCheckBox->isChecked()); } settingsCache->servers().setPrevioushostName(saveEdit->text()); settingsCache->servers().setAutoConnect(autoConnectCheckBox->isChecked()); - if (playernameEdit->text().isEmpty()) - { + if (playernameEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Connect Warning"), tr("The player name can't be empty.")); return; } @@ -317,7 +275,6 @@ void DlgConnect::actOk() accept(); } - QString DlgConnect::getHost() const { return hostEdit->text().trimmed(); @@ -332,12 +289,10 @@ void DlgConnect::actCancel() bool DeleteHighlightedItemWhenShiftDelPressedEventFilter::eventFilter(QObject *obj, QEvent *event) { - if (event->type() == QEvent::KeyPress) - { + if (event->type() == QEvent::KeyPress) { auto *keyEvent = dynamic_cast(event); - if (keyEvent->key() == Qt::Key_Delete) - { + if (keyEvent->key() == Qt::Key_Delete) { auto *combobox = reinterpret_cast(obj); combobox->removeItem(combobox->currentIndex()); return true; diff --git a/cockatrice/src/dlg_connect.h b/cockatrice/src/dlg_connect.h index 76a7b086..885df027 100644 --- a/cockatrice/src/dlg_connect.h +++ b/cockatrice/src/dlg_connect.h @@ -18,17 +18,27 @@ protected: bool eventFilter(QObject *obj, QEvent *event); }; - -class DlgConnect : public QDialog { +class DlgConnect : public QDialog +{ Q_OBJECT -signals : +signals: void sigStartForgotPasswordRequest(); + public: DlgConnect(QWidget *parent = 0); QString getHost() const; - int getPort() const { return portEdit->text().toInt(); } - QString getPlayerName() const { return playernameEdit->text(); } - QString getPassword() const { return passwordEdit->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 actCancel(); @@ -39,6 +49,7 @@ private slots: void actForgotPassword(); void updateDisplayInfo(const QString &saveName); void rebuildComboBoxList(); + private: QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *saveLabel, *publicServersLabel; QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *saveEdit; diff --git a/cockatrice/src/dlg_create_token.cpp b/cockatrice/src/dlg_create_token.cpp index 22120908..378a2aac 100644 --- a/cockatrice/src/dlg_create_token.cpp +++ b/cockatrice/src/dlg_create_token.cpp @@ -1,23 +1,23 @@ +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include +#include +#include +#include "carddatabasemodel.h" +#include "cardinfopicture.h" #include "decklist.h" #include "dlg_create_token.h" -#include "carddatabasemodel.h" #include "main.h" #include "settingscache.h" -#include "cardinfopicture.h" DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent) : QDialog(parent), predefinedTokens(_predefinedTokens) @@ -49,7 +49,7 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa 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); @@ -63,14 +63,14 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa 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, false, this); cardDatabaseDisplayModel = new TokenDisplayModel(this); cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); - + 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")); @@ -91,28 +91,26 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa chooseTokenView->header()->restoreState(deckHeaderState); chooseTokenView->header()->setStretchLastSection(false); - chooseTokenView->header()->hideSection(1); // Sets - chooseTokenView->header()->hideSection(2); // Mana Cost + chooseTokenView->header()->hideSection(1); // Sets + chooseTokenView->header()->hideSection(2); // Mana Cost chooseTokenView->header()->setSectionResizeMode(5, QHeaderView::ResizeToContents); // Color(s) - connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); + connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, + SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); connect(chooseTokenView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(actOk())); - - if (predefinedTokens.isEmpty()) - { + + if (predefinedTokens.isEmpty()) { chooseTokenFromAllRadioButton->setChecked(true); chooseTokenFromDeckRadioButton->setDisabled(true); // No tokens in deck = no need for option - } - else - { + } 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); @@ -125,7 +123,7 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(actReject())); - + QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(hbox); mainLayout->addWidget(buttonBox); @@ -147,14 +145,13 @@ void DlgCreateToken::tokenSelectionChanged(const QModelIndex ¤t, const QMo { const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : 0; - - if(cardInfo) - { + + if (cardInfo) { updateSearchFieldWithoutUpdatingFilter(cardInfo->getName()); const QChar cardColor = cardInfo->getColorChar(); colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); ptEdit->setText(cardInfo->getPowTough()); - if(settingsCache->getAnnotateTokens()) + if (settingsCache->getAnnotateTokens()) annotationEdit->setText(cardInfo->getText()); } else { nameEdit->setText(""); @@ -166,7 +163,8 @@ void DlgCreateToken::tokenSelectionChanged(const QModelIndex ¤t, const QMo pic->setCard(cardInfo); } -void DlgCreateToken::updateSearchFieldWithoutUpdatingFilter(const QString &newValue) const { +void DlgCreateToken::updateSearchFieldWithoutUpdatingFilter(const QString &newValue) const +{ nameEdit->blockSignals(true); nameEdit->setText(newValue); nameEdit->blockSignals(false); diff --git a/cockatrice/src/dlg_create_token.h b/cockatrice/src/dlg_create_token.h index d7d314e9..824139dc 100644 --- a/cockatrice/src/dlg_create_token.h +++ b/cockatrice/src/dlg_create_token.h @@ -17,7 +17,8 @@ class CardDatabaseModel; class TokenDisplayModel; class CardInfoPicture; -class DlgCreateToken : public QDialog { +class DlgCreateToken : public QDialog +{ Q_OBJECT public: DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0); @@ -26,6 +27,7 @@ public: QString getPT() const; QString getAnnotation() const; bool getDestroy() const; + protected: void closeEvent(QCloseEvent *event); private slots: @@ -35,6 +37,7 @@ private slots: void actChooseTokenFromDeck(bool checked); void actOk(); void actReject(); + private: CardDatabaseModel *cardDatabaseModel; TokenDisplayModel *cardDatabaseDisplayModel; diff --git a/cockatrice/src/dlg_creategame.cpp b/cockatrice/src/dlg_creategame.cpp index 371a135d..c7ccaccd 100644 --- a/cockatrice/src/dlg_creategame.cpp +++ b/cockatrice/src/dlg_creategame.cpp @@ -1,23 +1,24 @@ +#include "dlg_creategame.h" +#include "settingscache.h" +#include "tab_room.h" +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include #include +#include #include -#include "dlg_creategame.h" -#include "tab_room.h" -#include "settingscache.h" -#include "pending_command.h" #include "pb/serverinfo_game.pb.h" +#include "pending_command.h" -void DlgCreateGame::sharedCtor() { +void DlgCreateGame::sharedCtor() +{ rememberGameSettings = new QCheckBox(tr("Re&member settings")); descriptionLabel = new QLabel(tr("&Description:")); descriptionEdit = new QLineEdit; @@ -106,7 +107,8 @@ void DlgCreateGame::sharedCtor() { } DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent) - : QDialog(parent), room(_room), gameTypes(_gameTypes) { + : QDialog(parent), room(_room), gameTypes(_gameTypes) +{ sharedCtor(); rememberGameSettings->setChecked(settingsCache->getRememberGameSettings()); @@ -139,7 +141,8 @@ DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap &_gameType } DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap &_gameTypes, QWidget *parent) - : QDialog(parent), room(0), gameTypes(_gameTypes) { + : QDialog(parent), room(0), gameTypes(_gameTypes) +{ sharedCtor(); rememberGameSettings->setEnabled(false); @@ -180,7 +183,8 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMapsetText(""); maxPlayersEdit->setValue(2); @@ -205,8 +209,8 @@ void DlgCreateGame::actReset() { descriptionEdit->setFocus(); } - -void DlgCreateGame::actOK() { +void DlgCreateGame::actOK() +{ Command_CreateGame cmd; cmd.set_description(descriptionEdit->text().simplified().toStdString()); cmd.set_password(passwordEdit->text().toStdString()); @@ -247,7 +251,8 @@ void DlgCreateGame::actOK() { buttonBox->setEnabled(false); } -void DlgCreateGame::checkResponse(const Response &response) { +void DlgCreateGame::checkResponse(const Response &response) +{ buttonBox->setEnabled(true); if (response.response_code() == Response::RespOk) @@ -258,9 +263,9 @@ void DlgCreateGame::checkResponse(const Response &response) { } } -void DlgCreateGame::spectatorsAllowedChanged(int state) { +void DlgCreateGame::spectatorsAllowedChanged(int 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 b3eae315..e555b7cb 100644 --- a/cockatrice/src/dlg_creategame.h +++ b/cockatrice/src/dlg_creategame.h @@ -17,7 +17,8 @@ class TabRoom; class Response; class ServerInfo_Game; -class DlgCreateGame : public QDialog { +class DlgCreateGame : public QDialog +{ Q_OBJECT public: DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent = 0); @@ -27,6 +28,7 @@ private slots: void actReset(); void checkResponse(const Response &response); void spectatorsAllowedChanged(int state); + private: TabRoom *room; QMap gameTypes; @@ -37,11 +39,12 @@ private: QLineEdit *descriptionEdit, *passwordEdit; QSpinBox *maxPlayersEdit; QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox; - QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox; + QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, + *spectatorsSeeEverythingCheckBox; QDialogButtonBox *buttonBox; QPushButton *clearButton; QCheckBox *rememberGameSettings; - + void sharedCtor(); }; diff --git a/cockatrice/src/dlg_edit_avatar.cpp b/cockatrice/src/dlg_edit_avatar.cpp index 3c5fe1fa..06228459 100644 --- a/cockatrice/src/dlg_edit_avatar.cpp +++ b/cockatrice/src/dlg_edit_avatar.cpp @@ -10,27 +10,27 @@ #include "dlg_edit_avatar.h" -DlgEditAvatar::DlgEditAvatar(QWidget *parent) - : QDialog(parent) +DlgEditAvatar::DlgEditAvatar(QWidget *parent) : QDialog(parent) { imageLabel = new QLabel(tr("No image chosen.")); imageLabel->setFixedSize(400, 200); imageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); imageLabel->setStyleSheet("border: 1px solid #000"); - textLabel = new QLabel(tr("To change your avatar, choose a new image.\nTo remove your current avatar, confirm without choosing a new image.")); + textLabel = new QLabel(tr("To change your avatar, choose a new image.\nTo remove your current avatar, confirm " + "without choosing a new image.")); browseButton = new QPushButton(tr("Browse...")); connect(browseButton, SIGNAL(clicked()), this, SLOT(actBrowse())); - + QGridLayout *grid = new QGridLayout; grid->addWidget(imageLabel, 0, 0, 1, 2); grid->addWidget(textLabel, 1, 0); grid->addWidget(browseButton, 1, 1); - + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(actCancel())); - + QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(grid); mainLayout->addWidget(buttonBox); @@ -42,7 +42,7 @@ DlgEditAvatar::DlgEditAvatar(QWidget *parent) } void DlgEditAvatar::actOk() -{ +{ accept(); } @@ -53,9 +53,9 @@ void DlgEditAvatar::actCancel() void DlgEditAvatar::actBrowse() { - QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)")); - if(fileName.isEmpty()) - { + QString fileName = + QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)")); + if (fileName.isEmpty()) { imageLabel->setText(tr("No image chosen.")); return; } @@ -64,8 +64,7 @@ void DlgEditAvatar::actBrowse() QImageReader imgReader; imgReader.setDecideFormatFromContent(true); imgReader.setFileName(fileName); - if(!imgReader.read(&image)) - { + if (!imgReader.read(&image)) { qDebug() << "Avatar image loading failed for file:" << fileName; imageLabel->setText(tr("Invalid image chosen.")); return; @@ -76,11 +75,11 @@ void DlgEditAvatar::actBrowse() QByteArray DlgEditAvatar::getImage() { const QPixmap *pix = imageLabel->pixmap(); - if(!pix || pix->isNull()) + if (!pix || pix->isNull()) return QByteArray(); QImage image = pix->toImage(); - if(image.isNull()) + if (image.isNull()) return QByteArray(); QByteArray ba; diff --git a/cockatrice/src/dlg_edit_avatar.h b/cockatrice/src/dlg_edit_avatar.h index 0c34f0bb..cd72af50 100644 --- a/cockatrice/src/dlg_edit_avatar.h +++ b/cockatrice/src/dlg_edit_avatar.h @@ -1,15 +1,16 @@ #ifndef DLG_EDITAVATAR_H #define DLG_EDITAVATAR_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgEditAvatar : public QDialog { +class DlgEditAvatar : public QDialog +{ Q_OBJECT public: DlgEditAvatar(QWidget *parent = 0); @@ -18,6 +19,7 @@ private slots: void actOk(); void actCancel(); void actBrowse(); + private: QLabel *textLabel, *imageLabel; QPushButton *browseButton; diff --git a/cockatrice/src/dlg_edit_password.cpp b/cockatrice/src/dlg_edit_password.cpp index 7637e208..b642b136 100644 --- a/cockatrice/src/dlg_edit_password.cpp +++ b/cockatrice/src/dlg_edit_password.cpp @@ -4,17 +4,16 @@ #include #include -#include "settingscache.h" #include "dlg_edit_password.h" +#include "settingscache.h" -DlgEditPassword::DlgEditPassword(QWidget *parent) - : QDialog(parent) +DlgEditPassword::DlgEditPassword(QWidget *parent) : QDialog(parent) { oldPasswordLabel = new QLabel(tr("Old password:")); oldPasswordEdit = new QLineEdit(); - if(settingsCache->servers().getSavePassword()) + if (settingsCache->servers().getSavePassword()) oldPasswordEdit->setText(settingsCache->servers().getPassword()); oldPasswordLabel->setBuddy(oldPasswordEdit); @@ -29,7 +28,7 @@ DlgEditPassword::DlgEditPassword(QWidget *parent) newPasswordEdit2 = new QLineEdit(); newPasswordLabel2->setBuddy(newPasswordLabel2); newPasswordEdit2->setEchoMode(QLineEdit::Password); - + QGridLayout *grid = new QGridLayout; grid->addWidget(oldPasswordLabel, 0, 0); grid->addWidget(oldPasswordEdit, 0, 1); @@ -37,11 +36,11 @@ DlgEditPassword::DlgEditPassword(QWidget *parent) grid->addWidget(newPasswordEdit, 1, 1); grid->addWidget(newPasswordLabel2, 2, 0); grid->addWidget(newPasswordEdit2, 2, 1); - + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(actCancel())); - + QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(grid); mainLayout->addWidget(buttonBox); @@ -54,8 +53,7 @@ DlgEditPassword::DlgEditPassword(QWidget *parent) void DlgEditPassword::actOk() { - if(newPasswordEdit->text() != newPasswordEdit2->text()) - { + if (newPasswordEdit->text() != newPasswordEdit2->text()) { QMessageBox::warning(this, tr("Error"), tr("The new passwords don't match.")); return; } diff --git a/cockatrice/src/dlg_edit_password.h b/cockatrice/src/dlg_edit_password.h index ba1bd202..23009639 100644 --- a/cockatrice/src/dlg_edit_password.h +++ b/cockatrice/src/dlg_edit_password.h @@ -1,23 +1,31 @@ #ifndef DLG_EDITPASSWORD_H #define DLG_EDITPASSWORD_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgEditPassword : public QDialog { +class DlgEditPassword : public QDialog +{ Q_OBJECT public: DlgEditPassword(QWidget *parent = 0); - QString getOldPassword() const { return oldPasswordEdit->text(); } - QString getNewPassword() const { return newPasswordEdit->text(); } + QString getOldPassword() const + { + return oldPasswordEdit->text(); + } + QString getNewPassword() const + { + return newPasswordEdit->text(); + } private slots: void actOk(); void actCancel(); + private: QLabel *oldPasswordLabel, *newPasswordLabel, *newPasswordLabel2; QLineEdit *oldPasswordEdit, *newPasswordEdit, *newPasswordEdit2; diff --git a/cockatrice/src/dlg_edit_tokens.cpp b/cockatrice/src/dlg_edit_tokens.cpp index a68fb3fd..7db03bb7 100644 --- a/cockatrice/src/dlg_edit_tokens.cpp +++ b/cockatrice/src/dlg_edit_tokens.cpp @@ -2,29 +2,28 @@ #include "carddatabase.h" #include "carddatabasemodel.h" #include "main.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include #include +#include +#include #include +#include +#include +#include -DlgEditTokens::DlgEditTokens(QWidget *parent) - : QDialog(parent), currentCard(0) +DlgEditTokens::DlgEditTokens(QWidget *parent) : QDialog(parent), currentCard(0) { 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"), QChar('w')); @@ -36,17 +35,17 @@ DlgEditTokens::DlgEditTokens(QWidget *parent) colorEdit->addItem(tr("colorless"), QChar()); 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); @@ -56,7 +55,7 @@ DlgEditTokens::DlgEditTokens(QWidget *parent) 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); @@ -65,7 +64,7 @@ DlgEditTokens::DlgEditTokens(QWidget *parent) cardDatabaseDisplayModel = new TokenDisplayModel(this); cardDatabaseDisplayModel->setSourceModel(databaseModel); cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); - + chooseTokenView = new QTreeView; chooseTokenView->setModel(cardDatabaseDisplayModel); chooseTokenView->setUniformRowHeights(true); @@ -80,31 +79,32 @@ DlgEditTokens::DlgEditTokens(QWidget *parent) chooseTokenView->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents); chooseTokenView->header()->setSectionResizeMode(4, QHeaderView::ResizeToContents); - connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); - + connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, + SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); + QAction *aAddToken = new QAction(tr("Add token"), this); aAddToken->setIcon(QPixmap("theme:icons/increment")); connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken())); QAction *aRemoveToken = new QAction(tr("Remove token"), this); aRemoveToken->setIcon(QPixmap("theme:icons/decrement")); 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); @@ -118,8 +118,7 @@ void DlgEditTokens::tokenSelectionChanged(const QModelIndex ¤t, const QMod const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); currentCard = current.row() >= 0 ? databaseModel->getCard(realIndex.row()) : 0; - if(currentCard) - { + if (currentCard) { nameEdit->setText(currentCard->getName()); const QChar cardColor = currentCard->getColorChar(); colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); @@ -139,16 +138,17 @@ void DlgEditTokens::actAddToken() bool askAgain = true; do { name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:")); - if(name.isEmpty()) + if (name.isEmpty()) return; if (databaseModel->getDatabase()->getCard(name)) { - QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.\nMake sure to enable the 'Token' set in the \"Manage sets\" dialog to display them correctly.")); + QMessageBox::critical(this, tr("Error"), + tr("The chosen name conflicts with an existing card or token.\nMake sure to enable " + "the 'Token' set in the \"Manage sets\" dialog to display them correctly.")); } else { askAgain = false; } } while (askAgain); - - + CardInfo *card = new CardInfo(name, true); card->addToSet(databaseModel->getDatabase()->getSet(CardDatabase::TOKENS_SETNAME)); card->setCardType("Token"); diff --git a/cockatrice/src/dlg_edit_tokens.h b/cockatrice/src/dlg_edit_tokens.h index 2fbb6886..7717f922 100644 --- a/cockatrice/src/dlg_edit_tokens.h +++ b/cockatrice/src/dlg_edit_tokens.h @@ -12,16 +12,18 @@ class QLineEdit; class QTreeView; class CardInfo; -class DlgEditTokens : public QDialog { +class DlgEditTokens : public QDialog +{ 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(); + private: CardInfo *currentCard; CardDatabaseModel *databaseModel; @@ -31,6 +33,7 @@ private: QComboBox *colorEdit; QLineEdit *nameEdit, *ptEdit, *annotationEdit; QTreeView *chooseTokenView; + public: DlgEditTokens(QWidget *parent = 0); }; diff --git a/cockatrice/src/dlg_edit_user.cpp b/cockatrice/src/dlg_edit_user.cpp index 2c319b63..7b93ee90 100644 --- a/cockatrice/src/dlg_edit_user.cpp +++ b/cockatrice/src/dlg_edit_user.cpp @@ -1,14 +1,13 @@ -#include +#include +#include #include #include -#include -#include +#include #include "dlg_edit_user.h" #include "settingscache.h" -DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QString realName) - : QDialog(parent) +DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QString realName) : QDialog(parent) { emailLabel = new QLabel(tr("Email:")); emailEdit = new QLineEdit(); @@ -23,8 +22,7 @@ DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QStrin QStringList countries = settingsCache->getCountries(); int i = 1; - foreach(QString c, countries) - { + foreach (QString c, countries) { countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c); if (c == country) countryEdit->setCurrentIndex(i); diff --git a/cockatrice/src/dlg_edit_user.h b/cockatrice/src/dlg_edit_user.h index 3504a2c9..2bd1f56f 100644 --- a/cockatrice/src/dlg_edit_user.h +++ b/cockatrice/src/dlg_edit_user.h @@ -1,25 +1,42 @@ #ifndef DLG_EDITUSER_H #define DLG_EDITUSER_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgEditUser : public QDialog { +class DlgEditUser : public QDialog +{ Q_OBJECT public: - DlgEditUser(QWidget *parent = 0, QString email = QString(), QString country = QString(), QString realName = QString()); - QString getEmail() const { return emailEdit->text(); } - int getGender() const { return -1; } //This will return GenderUnknown for protocol purposes. - QString getCountry() const { return countryEdit->currentIndex() == 0 ? "" : countryEdit->currentText(); } - QString getRealName() const { return realnameEdit->text(); } + DlgEditUser(QWidget *parent = 0, + QString email = QString(), + QString country = QString(), + QString realName = QString()); + QString getEmail() const + { + return emailEdit->text(); + } + int getGender() const + { + return -1; + } // This will return GenderUnknown for protocol purposes. + QString getCountry() const + { + return countryEdit->currentIndex() == 0 ? "" : countryEdit->currentText(); + } + QString getRealName() const + { + return realnameEdit->text(); + } private slots: void actOk(); void actCancel(); + private: QLabel *emailLabel, *countryLabel, *realnameLabel; QLineEdit *emailEdit, *realnameEdit; diff --git a/cockatrice/src/dlg_filter_games.cpp b/cockatrice/src/dlg_filter_games.cpp index 6aeba14b..a968d582 100644 --- a/cockatrice/src/dlg_filter_games.cpp +++ b/cockatrice/src/dlg_filter_games.cpp @@ -1,20 +1,20 @@ #include "dlg_filter_games.h" #include -#include -#include -#include -#include +#include +#include +#include #include #include +#include +#include +#include +#include #include -#include -#include -#include -DlgFilterGames::DlgFilterGames(const QMap &_allGameTypes, const GamesProxyModel *_gamesProxyModel, QWidget *parent) - : QDialog(parent), - allGameTypes(_allGameTypes), - gamesProxyModel(_gamesProxyModel) +DlgFilterGames::DlgFilterGames(const QMap &_allGameTypes, + const GamesProxyModel *_gamesProxyModel, + QWidget *parent) + : QDialog(parent), allGameTypes(_allGameTypes), gamesProxyModel(_gamesProxyModel) { showBuddiesOnlyGames = new QCheckBox(tr("Show '&buddies only' games")); showBuddiesOnlyGames->setChecked(gamesProxyModel->getShowBuddiesOnlyGames()); @@ -84,7 +84,6 @@ DlgFilterGames::DlgFilterGames(const QMap &_allGameTypes, const Ga QGroupBox *restrictionsGroupBox = new QGroupBox(tr("Restrictions")); restrictionsGroupBox->setLayout(restrictionsLayout); - QGridLayout *leftGrid = new QGridLayout; leftGrid->addWidget(gameNameFilterLabel, 0, 0); leftGrid->addWidget(gameNameFilterEdit, 0, 1); @@ -93,7 +92,6 @@ DlgFilterGames::DlgFilterGames(const QMap &_allGameTypes, const Ga leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2); leftGrid->addWidget(restrictionsGroupBox, 3, 0, 1, 2); - QVBoxLayout *leftColumn = new QVBoxLayout; leftColumn->addLayout(leftGrid); leftColumn->addStretch(); @@ -117,7 +115,8 @@ DlgFilterGames::DlgFilterGames(const QMap &_allGameTypes, const Ga setWindowTitle(tr("Filter games")); } -void DlgFilterGames::actOk() { +void DlgFilterGames::actOk() +{ accept(); } @@ -205,5 +204,6 @@ int DlgFilterGames::getMaxPlayersFilterMax() const void DlgFilterGames::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax) { maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin); - maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax); + maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() + : _maxPlayersFilterMax); } diff --git a/cockatrice/src/dlg_filter_games.h b/cockatrice/src/dlg_filter_games.h index 5b7ca6be..e9667e4e 100644 --- a/cockatrice/src/dlg_filter_games.h +++ b/cockatrice/src/dlg_filter_games.h @@ -1,17 +1,18 @@ #ifndef DLG_FILTER_GAMES_H #define DLG_FILTER_GAMES_H -#include -#include -#include -#include #include "gamesmodel.h" +#include +#include +#include +#include class QCheckBox; class QLineEdit; class QSpinBox; -class DlgFilterGames : public QDialog { +class DlgFilterGames : public QDialog +{ Q_OBJECT private: QCheckBox *showBuddiesOnlyGames; @@ -28,8 +29,11 @@ private: private slots: void actOk(); + public: - DlgFilterGames(const QMap &_allGameTypes, const GamesProxyModel *_gamesProxyModel, QWidget *parent = 0); + DlgFilterGames(const QMap &_allGameTypes, + const GamesProxyModel *_gamesProxyModel, + QWidget *parent = 0); bool getUnavailableGamesVisible() const; void setUnavailableGamesVisible(bool _unavailableGamesVisible); diff --git a/cockatrice/src/dlg_forgotpasswordchallenge.cpp b/cockatrice/src/dlg_forgotpasswordchallenge.cpp index 9423f8e8..0f7c4ede 100644 --- a/cockatrice/src/dlg_forgotpasswordchallenge.cpp +++ b/cockatrice/src/dlg_forgotpasswordchallenge.cpp @@ -1,32 +1,36 @@ -#include #include +#include +#include #include #include -#include +#include #include -#include #include "dlg_forgotpasswordchallenge.h" #include "settingscache.h" -DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) - : QDialog(parent) +DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) : QDialog(parent) { - QString lastfphost; QString lastfpport; QString lastfpplayername; + QString lastfphost; + QString lastfpport; + QString lastfpplayername; lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com"); lastfpport = settingsCache->servers().getPort("4747"); lastfpplayername = settingsCache->servers().getPlayerName("Player"); - if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) { + if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && + !settingsCache->servers().getFPPlayerName().isEmpty()) { lastfphost = settingsCache->servers().getFPHostname(); lastfpport = settingsCache->servers().getFPPort(); lastfpplayername = settingsCache->servers().getFPPlayerName(); } - if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() && settingsCache->servers().getFPPlayerName().isEmpty()) - { - QMessageBox::warning(this, tr("Forgot Password Challenge Warning"), tr("Oops, looks like something has gone wrong. Please restart the forgot password process by using the forgot password button on the connection screen.")); + if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() && + settingsCache->servers().getFPPlayerName().isEmpty()) { + QMessageBox::warning(this, tr("Forgot Password Challenge Warning"), + tr("Oops, looks like something has gone wrong. Please restart the forgot password " + "process by using the forgot password button on the connection screen.")); actCancel(); } @@ -46,7 +50,8 @@ DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) emailEdit = new QLineEdit(); emailLabel->setBuddy(emailLabel); - if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) { + if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && + !settingsCache->servers().getFPPlayerName().isEmpty()) { hostLabel->hide(); hostEdit->hide(); portLabel->hide(); @@ -81,8 +86,7 @@ DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) void DlgForgotPasswordChallenge::actOk() { - if (emailEdit->text().isEmpty()) - { + if (emailEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Forgot Password Challenge Warning"), tr("The email address can't be empty.")); return; } diff --git a/cockatrice/src/dlg_forgotpasswordchallenge.h b/cockatrice/src/dlg_forgotpasswordchallenge.h index 3f7ce9b4..f8503aa5 100644 --- a/cockatrice/src/dlg_forgotpasswordchallenge.h +++ b/cockatrice/src/dlg_forgotpasswordchallenge.h @@ -1,25 +1,39 @@ #ifndef DLG_FORGOTPASSWORDCHALLENGE_H #define DLG_FORGOTPASSWORDCHALLENGE_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgForgotPasswordChallenge : public QDialog { +class DlgForgotPasswordChallenge : public QDialog +{ Q_OBJECT public: DlgForgotPasswordChallenge(QWidget *parent = 0); - QString getHost() const { return hostEdit->text(); } - int getPort() const { return portEdit->text().toInt(); } - QString getPlayerName() const { return playernameEdit->text(); } - QString getEmail() const { return emailEdit->text(); } + QString getHost() const + { + return hostEdit->text(); + } + int getPort() const + { + return portEdit->text().toInt(); + } + QString getPlayerName() const + { + return playernameEdit->text(); + } + QString getEmail() const + { + return emailEdit->text(); + } private slots: void actOk(); void actCancel(); + private: QLabel *hostLabel, *portLabel, *playernameLabel, *emailLabel; QLineEdit *hostEdit, *portEdit, *playernameEdit, *emailEdit; diff --git a/cockatrice/src/dlg_forgotpasswordrequest.cpp b/cockatrice/src/dlg_forgotpasswordrequest.cpp index e5965866..ec1b74c7 100644 --- a/cockatrice/src/dlg_forgotpasswordrequest.cpp +++ b/cockatrice/src/dlg_forgotpasswordrequest.cpp @@ -1,24 +1,26 @@ -#include #include +#include +#include #include #include -#include +#include #include -#include #include "dlg_forgotpasswordrequest.h" #include "settingscache.h" -DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent) - : QDialog(parent) +DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent) : QDialog(parent) { - QString lastfphost; QString lastfpport; QString lastfpplayername; + QString lastfphost; + QString lastfpport; + QString lastfpplayername; lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com"); lastfpport = settingsCache->servers().getPort("4747"); lastfpplayername = settingsCache->servers().getPlayerName("Player"); - if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) { + if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && + !settingsCache->servers().getFPPlayerName().isEmpty()) { lastfphost = settingsCache->servers().getFPHostname(); lastfpport = settingsCache->servers().getFPPort(); lastfpplayername = settingsCache->servers().getFPPlayerName(); @@ -60,8 +62,7 @@ DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent) void DlgForgotPasswordRequest::actOk() { - if(playernameEdit->text().isEmpty()) - { + if (playernameEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Forgot Password Request Warning"), tr("The player name can't be empty.")); return; } diff --git a/cockatrice/src/dlg_forgotpasswordrequest.h b/cockatrice/src/dlg_forgotpasswordrequest.h index 9cdf2cc2..d7da9e09 100644 --- a/cockatrice/src/dlg_forgotpasswordrequest.h +++ b/cockatrice/src/dlg_forgotpasswordrequest.h @@ -1,24 +1,35 @@ #ifndef DLG_FORGOTPASSWORDREQUEST_H #define DLG_FORGOTPASSWORDREQUEST_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgForgotPasswordRequest : public QDialog { +class DlgForgotPasswordRequest : public QDialog +{ Q_OBJECT public: DlgForgotPasswordRequest(QWidget *parent = 0); - QString getHost() const { return hostEdit->text(); } - int getPort() const { return portEdit->text().toInt(); } - QString getPlayerName() const { return playernameEdit->text(); } + QString getHost() const + { + return hostEdit->text(); + } + int getPort() const + { + return portEdit->text().toInt(); + } + QString getPlayerName() const + { + return playernameEdit->text(); + } private slots: void actOk(); void actCancel(); + private: QLabel *hostLabel, *portLabel, *playernameLabel; QLineEdit *hostEdit, *portEdit, *playernameEdit; diff --git a/cockatrice/src/dlg_forgotpasswordreset.cpp b/cockatrice/src/dlg_forgotpasswordreset.cpp index 1d3d4c7e..7530bc2a 100644 --- a/cockatrice/src/dlg_forgotpasswordreset.cpp +++ b/cockatrice/src/dlg_forgotpasswordreset.cpp @@ -1,32 +1,36 @@ -#include #include +#include +#include #include #include -#include +#include #include -#include #include "dlg_forgotpasswordreset.h" #include "settingscache.h" -DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) - : QDialog(parent) +DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) : QDialog(parent) { - QString lastfphost; QString lastfpport; QString lastfpplayername; + QString lastfphost; + QString lastfpport; + QString lastfpplayername; lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com"); lastfpport = settingsCache->servers().getPort("4747"); lastfpplayername = settingsCache->servers().getPlayerName("Player"); - if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) { + if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && + !settingsCache->servers().getFPPlayerName().isEmpty()) { lastfphost = settingsCache->servers().getFPHostname(); lastfpport = settingsCache->servers().getFPPort(); lastfpplayername = settingsCache->servers().getFPPlayerName(); } - if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() && settingsCache->servers().getFPPlayerName().isEmpty()) - { - QMessageBox::warning(this, tr("Forgot Password Reset Warning"), tr("Opps, looks like something has gone wrong. Please re-start the forgot password process by using the forgot password button on the connection screen.")); + if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() && + settingsCache->servers().getFPPlayerName().isEmpty()) { + QMessageBox::warning(this, tr("Forgot Password Reset Warning"), + tr("Opps, looks like something has gone wrong. Please re-start the forgot password " + "process by using the forgot password button on the connection screen.")); actCancel(); } @@ -56,7 +60,8 @@ DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) newpasswordverifyLabel->setBuddy(newpasswordEdit); newpasswordverifyEdit->setEchoMode(QLineEdit::Password); - if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) { + if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && + !settingsCache->servers().getFPPlayerName().isEmpty()) { hostLabel->hide(); hostEdit->hide(); portLabel->hide(); @@ -95,26 +100,22 @@ DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) void DlgForgotPasswordReset::actOk() { - if(playernameEdit->text().isEmpty()) - { + if (playernameEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The player name can't be empty.")); return; } - if (tokenEdit->text().isEmpty()) - { + if (tokenEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The token can't be empty.")); return; } - if (newpasswordEdit->text().isEmpty()) - { + if (newpasswordEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The new password can't be empty.")); return; } - if (newpasswordEdit->text() != newpasswordverifyEdit->text()) - { + if (newpasswordEdit->text() != newpasswordverifyEdit->text()) { QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The passwords do not match.")); return; } diff --git a/cockatrice/src/dlg_forgotpasswordreset.h b/cockatrice/src/dlg_forgotpasswordreset.h index 0832b15d..41c593a1 100644 --- a/cockatrice/src/dlg_forgotpasswordreset.h +++ b/cockatrice/src/dlg_forgotpasswordreset.h @@ -1,26 +1,43 @@ #ifndef DLG_FORGOTPASSWORDRESET_H #define DLG_FORGOTPASSWORDRESET_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgForgotPasswordReset : public QDialog { +class DlgForgotPasswordReset : public QDialog +{ Q_OBJECT public: DlgForgotPasswordReset(QWidget *parent = 0); - QString getHost() const { return hostEdit->text(); } - int getPort() const { return portEdit->text().toInt(); } - QString getPlayerName() const { return playernameEdit->text(); } - QString getToken() const { return tokenEdit->text(); } - QString getPassword() const { return newpasswordEdit->text(); } + QString getHost() const + { + return hostEdit->text(); + } + int getPort() const + { + return portEdit->text().toInt(); + } + QString getPlayerName() const + { + return playernameEdit->text(); + } + QString getToken() const + { + return tokenEdit->text(); + } + QString getPassword() const + { + return newpasswordEdit->text(); + } private slots: void actOk(); void actCancel(); + private: QLabel *hostLabel, *portLabel, *playernameLabel, *tokenLabel, *newpasswordLabel, *newpasswordverifyLabel; QLineEdit *hostEdit, *portEdit, *playernameEdit, *tokenEdit, *newpasswordEdit, *newpasswordverifyEdit; diff --git a/cockatrice/src/dlg_load_deck_from_clipboard.cpp b/cockatrice/src/dlg_load_deck_from_clipboard.cpp index 12b15931..8d39ea41 100644 --- a/cockatrice/src/dlg_load_deck_from_clipboard.cpp +++ b/cockatrice/src/dlg_load_deck_from_clipboard.cpp @@ -1,27 +1,27 @@ -#include -#include -#include -#include -#include -#include -#include -#include #include "dlg_load_deck_from_clipboard.h" #include "deck_loader.h" #include "settingscache.h" +#include +#include +#include +#include +#include +#include +#include +#include DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) : QDialog(parent), deckList(nullptr) { contentsEdit = new QPlainTextEdit; - + refreshButton = new QPushButton(tr("&Refresh")); 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())); - + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(contentsEdit); mainLayout->addWidget(buttonBox); @@ -30,9 +30,9 @@ DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) : QDialog(pa setWindowTitle(tr("Load deck from clipboard")); resize(500, 500); - + actRefresh(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); } @@ -50,28 +50,20 @@ void DlgLoadDeckFromClipboard::actOK() { QString buffer = contentsEdit->toPlainText(); QTextStream stream(&buffer); - + auto *deckLoader = new DeckLoader; - if (buffer.contains("")) - { - if (deckLoader->loadFromString_Native(buffer)) - { + if (buffer.contains("")) { + if (deckLoader->loadFromString_Native(buffer)) { deckList = deckLoader; accept(); - } - else - { + } else { QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); delete deckLoader; } - } - else if (deckLoader->loadFromStream_Plain(stream)) - { + } else if (deckLoader->loadFromStream_Plain(stream)) { deckList = deckLoader; accept(); - } - else - { + } else { QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); delete deckLoader; } diff --git a/cockatrice/src/dlg_load_deck_from_clipboard.h b/cockatrice/src/dlg_load_deck_from_clipboard.h index 63fb68d1..7a9833b4 100644 --- a/cockatrice/src/dlg_load_deck_from_clipboard.h +++ b/cockatrice/src/dlg_load_deck_from_clipboard.h @@ -10,19 +10,22 @@ class QPushButton; class DlgLoadDeckFromClipboard : public QDialog { Q_OBJECT - private slots: - void actOK(); - void actRefresh(); - void refreshShortcuts(); +private slots: + void actOK(); + void actRefresh(); + void refreshShortcuts(); - private: - DeckLoader *deckList; - QPlainTextEdit *contentsEdit; - QPushButton *refreshButton; +private: + DeckLoader *deckList; + QPlainTextEdit *contentsEdit; + QPushButton *refreshButton; - public: - explicit DlgLoadDeckFromClipboard(QWidget *parent = nullptr); - DeckLoader *getDeckList() const { return deckList; } +public: + explicit DlgLoadDeckFromClipboard(QWidget *parent = nullptr); + DeckLoader *getDeckList() const + { + return deckList; + } }; #endif diff --git a/cockatrice/src/dlg_load_remote_deck.cpp b/cockatrice/src/dlg_load_remote_deck.cpp index 09b820ac..cd2c889d 100644 --- a/cockatrice/src/dlg_load_remote_deck.cpp +++ b/cockatrice/src/dlg_load_remote_deck.cpp @@ -1,16 +1,15 @@ -#include -#include -#include -#include -#include "remotedecklist_treewidget.h" #include "dlg_load_remote_deck.h" #include "main.h" +#include "remotedecklist_treewidget.h" +#include +#include +#include +#include -DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) - : QDialog(parent), client(_client) +DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) : 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())); @@ -26,15 +25,19 @@ DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) 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 5fd78258..8979d00a 100644 --- a/cockatrice/src/dlg_load_remote_deck.h +++ b/cockatrice/src/dlg_load_remote_deck.h @@ -9,7 +9,8 @@ class AbstractClient; class QPushButton; class QDialogButtonBox; -class DlgLoadRemoteDeck: public QDialog { +class DlgLoadRemoteDeck : public QDialog +{ Q_OBJECT private: AbstractClient *client; @@ -17,6 +18,7 @@ private: QDialogButtonBox *buttonBox; private slots: void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous); + public: DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0); int getDeckId() const; diff --git a/cockatrice/src/dlg_register.cpp b/cockatrice/src/dlg_register.cpp index 65f68190..606adfd7 100644 --- a/cockatrice/src/dlg_register.cpp +++ b/cockatrice/src/dlg_register.cpp @@ -1,17 +1,16 @@ -#include #include +#include +#include #include #include -#include +#include #include -#include #include "dlg_register.h" -#include "settingscache.h" #include "pb/serverinfo_user.pb.h" +#include "settingscache.h" -DlgRegister::DlgRegister(QWidget *parent) - : QDialog(parent) +DlgRegister::DlgRegister(QWidget *parent) : QDialog(parent) { hostLabel = new QLabel(tr("&Host:")); hostEdit = new QLineEdit(settingsCache->servers().getHostname("cockatrice.woogerworks.com")); @@ -298,7 +297,7 @@ DlgRegister::DlgRegister(QWidget *parent) countryEdit->addItem(QPixmap("theme:countries/zw"), "zw"); countryEdit->setCurrentIndex(0); QStringList countries = settingsCache->getCountries(); - foreach(QString c, countries) + foreach (QString c, countries) countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c); realnameLabel = new QLabel(tr("Real name:")); @@ -341,18 +340,15 @@ DlgRegister::DlgRegister(QWidget *parent) void DlgRegister::actOk() { - if (passwordEdit->text() != passwordConfirmationEdit->text()) - { - QMessageBox::critical(this, tr("Registration Warning"), tr("Your passwords do not match, please try again.")); - return; - } - else if (emailConfirmationEdit->text() != emailEdit->text()) - { - QMessageBox::critical(this, tr("Registration Warning"), tr("Your email addresses do not match, please try again.")); + if (passwordEdit->text() != passwordConfirmationEdit->text()) { + QMessageBox::critical(this, tr("Registration Warning"), tr("Your passwords do not match, please try again.")); + return; + } else if (emailConfirmationEdit->text() != emailEdit->text()) { + QMessageBox::critical(this, tr("Registration Warning"), + tr("Your email addresses do not match, please try again.")); return; } - if(playernameEdit->text().isEmpty()) - { + if (playernameEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Registration Warning"), tr("The player name can't be empty.")); return; } diff --git a/cockatrice/src/dlg_register.h b/cockatrice/src/dlg_register.h index 83717106..287a5856 100644 --- a/cockatrice/src/dlg_register.h +++ b/cockatrice/src/dlg_register.h @@ -1,32 +1,60 @@ #ifndef DLG_REGISTER_H #define DLG_REGISTER_H +#include #include #include -#include class QLabel; class QPushButton; class QCheckBox; -class DlgRegister : public QDialog { +class DlgRegister : public QDialog +{ Q_OBJECT public: DlgRegister(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(); } - QString getEmail() const { return emailEdit->text(); } - int getGender() const { return -1; } //This will return GenderUnknown for the protocol. - QString getCountry() const { return countryEdit->currentIndex() == 0 ? "" : countryEdit->currentText(); } - QString getRealName() const { return realnameEdit->text(); } + 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(); + } + QString getEmail() const + { + return emailEdit->text(); + } + int getGender() const + { + return -1; + } // This will return GenderUnknown for the protocol. + QString getCountry() const + { + return countryEdit->currentIndex() == 0 ? "" : countryEdit->currentText(); + } + QString getRealName() const + { + return realnameEdit->text(); + } private slots: void actOk(); void actCancel(); + private: - QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *passwordConfirmationLabel, *emailLabel, *emailConfirmationLabel, *countryLabel, *realnameLabel; - QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *passwordConfirmationEdit, *emailEdit, *emailConfirmationEdit, *realnameEdit; + QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *passwordConfirmationLabel, *emailLabel, + *emailConfirmationLabel, *countryLabel, *realnameLabel; + QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *passwordConfirmationEdit, *emailEdit, + *emailConfirmationEdit, *realnameEdit; QComboBox *countryEdit; }; diff --git a/cockatrice/src/dlg_settings.cpp b/cockatrice/src/dlg_settings.cpp index 814b6dae..80a93746 100644 --- a/cockatrice/src/dlg_settings.cpp +++ b/cockatrice/src/dlg_settings.cpp @@ -1,36 +1,35 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "dlg_settings.h" +#include "carddatabase.h" +#include "main.h" +#include "releasechannel.h" +#include "sequenceEdit/shortcutstab.h" +#include "settingscache.h" +#include "soundengine.h" +#include "spoilerbackgroundupdater.h" +#include "thememanager.h" #include #include -#include -#include -#include -#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include "carddatabase.h" -#include "dlg_settings.h" -#include "main.h" -#include "settingscache.h" -#include "thememanager.h" -#include "releasechannel.h" -#include "soundengine.h" -#include "sequenceEdit/shortcutstab.h" -#include "spoilerbackgroundupdater.h" +#include +#include +#include #define WIKI_CUSTOM_PIC_URL "https://github.com/Cockatrice/Cockatrice/wiki/Custom-Picture-Download-URLs" @@ -41,16 +40,16 @@ GeneralSettingsPage::GeneralSettingsPage() 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 == QCoreApplication::translate("i18n", DEFAULT_LANG_NAME))) + if ((qmFiles[i] == setLanguage) || + (setLanguage.isEmpty() && langName == QCoreApplication::translate("i18n", DEFAULT_LANG_NAME))) languageBox.setCurrentIndex(i); } picDownloadCheckBox.setChecked(settingsCache->getPicDownload()); // updates - QList channels = settingsCache->getUpdateReleaseChannels(); - foreach(ReleaseChannel* chan, channels) - { + QList channels = settingsCache->getUpdateReleaseChannels(); + foreach (ReleaseChannel *chan, channels) { updateReleaseChannelBox.insertItem(chan->getIndex(), tr(chan->getName().toUtf8())); } updateReleaseChannelBox.setCurrentIndex(settingsCache->getUpdateReleaseChannel()->getIndex()); @@ -72,7 +71,8 @@ GeneralSettingsPage::GeneralSettingsPage() connect(&languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int))); connect(&picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int))); connect(&pixmapCacheEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setPixmapCacheSize(int))); - connect(&updateReleaseChannelBox, SIGNAL(currentIndexChanged(int)), settingsCache, SLOT(setUpdateReleaseChannel(int))); + connect(&updateReleaseChannelBox, SIGNAL(currentIndexChanged(int)), settingsCache, + SLOT(setUpdateReleaseChannel(int))); connect(&updateNotificationCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotifyAboutUpdate(int))); connect(&picDownloadCheckBox, SIGNAL(clicked(bool)), this, SLOT(setEnabledStatus(bool))); connect(defaultUrlEdit, SIGNAL(textChanged(QString)), settingsCache, SLOT(setPicUrl(QString))); @@ -131,8 +131,7 @@ GeneralSettingsPage::GeneralSettingsPage() QPushButton *tokenDatabasePathButton = new QPushButton("..."); connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked())); - if (settingsCache->getIsPortableBuild()) - { + if (settingsCache->getIsPortableBuild()) { deckPathEdit->setEnabled(false); replaysPathEdit->setEnabled(false); picsPathEdit->setEnabled(false); @@ -182,7 +181,7 @@ QStringList GeneralSettingsPage::findQmFiles() QString GeneralSettingsPage::languageName(const QString &qmFile) { - if(qmFile == DEFAULT_LANG_CODE) + if (qmFile == DEFAULT_LANG_CODE) return DEFAULT_LANG_NAME; QTranslator translator; @@ -240,11 +239,11 @@ void GeneralSettingsPage::clearDownloadedPicsButtonClicked() QString picsPath = settingsCache->getPicsPath() + "/downloadedPics/"; QStringList dirs = QDir(picsPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot); bool outerSuccessRemove = true; - for (int i = 0; i < dirs.length(); i ++) { + for (int i = 0; i < dirs.length(); i++) { QString currentPath = picsPath + dirs.at(i) + "/"; QStringList files = QDir(currentPath).entryList(QDir::Files); bool innerSuccessRemove = true; - for (int j = 0; j < files.length(); j ++) + for (int j = 0; j < files.length(); j++) if (!QDir(currentPath).remove(files.at(j))) { qDebug() << "Failed to remove " + currentPath.toUtf8() + files.at(j).toUtf8(); outerSuccessRemove = false; @@ -290,8 +289,7 @@ void GeneralSettingsPage::retranslateUi() languageLabel.setText(tr("Language:")); picDownloadCheckBox.setText(tr("Download card pictures on the fly")); - if(settingsCache->getIsPortableBuild()) - { + if (settingsCache->getIsPortableBuild()) { pathsGroupBox->setTitle(tr("Paths (editing disabled in portable mode)")); } else { pathsGroupBox->setTitle(tr("Paths")); @@ -305,7 +303,8 @@ void GeneralSettingsPage::retranslateUi() pixmapCacheLabel.setText(tr("Picture cache size:")); defaultUrlLabel.setText(tr("Primary download URL:")); fallbackUrlLabel.setText(tr("Fallback download URL:")); - urlLinkLabel.setText(QString("%2").arg(WIKI_CUSTOM_PIC_URL).arg(tr("How to set a custom picture url"))); + urlLinkLabel.setText( + QString("%2").arg(WIKI_CUSTOM_PIC_URL).arg(tr("How to set a custom picture url"))); clearDownloadedPicsButton.setText(tr("Reset/clear downloaded pictures")); updateReleaseChannelLabel.setText(tr("Update channel")); updateNotificationCheckBox.setText(tr("Notify if a feature supported by the server is missing in my client")); @@ -368,11 +367,13 @@ AppearanceSettingsPage::AppearanceSettingsPage() handGroupBox->setLayout(handGrid); invertVerticalCoordinateCheckBox.setChecked(settingsCache->getInvertVerticalCoordinate()); - connect(&invertVerticalCoordinateCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setInvertVerticalCoordinate(int))); + connect(&invertVerticalCoordinateCheckBox, SIGNAL(stateChanged(int)), settingsCache, + SLOT(setInvertVerticalCoordinate(int))); minPlayersForMultiColumnLayoutEdit.setMinimum(2); minPlayersForMultiColumnLayoutEdit.setValue(settingsCache->getMinPlayersForMultiColumnLayout()); - connect(&minPlayersForMultiColumnLayoutEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMinPlayersForMultiColumnLayout(int))); + connect(&minPlayersForMultiColumnLayoutEdit, SIGNAL(valueChanged(int)), settingsCache, + SLOT(setMinPlayersForMultiColumnLayout(int))); minPlayersForMultiColumnLayoutLabel.setBuddy(&minPlayersForMultiColumnLayoutEdit); connect(&maxFontSizeForCardsEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMaxFontSize(int))); @@ -403,7 +404,7 @@ AppearanceSettingsPage::AppearanceSettingsPage() void AppearanceSettingsPage::themeBoxChanged(int index) { QStringList themeDirs = themeManager->getAvailableThemes().keys(); - if(index >= 0 && index < themeDirs.count()) + if (index >= 0 && index < themeDirs.count()) settingsCache->setThemeName(themeDirs.at(index)); } @@ -429,12 +430,14 @@ void AppearanceSettingsPage::retranslateUi() UserInterfaceSettingsPage::UserInterfaceSettingsPage() { notificationsEnabledCheckBox.setChecked(settingsCache->getNotificationsEnabled()); - connect(¬ificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotificationsEnabled(int))); + connect(¬ificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, + SLOT(setNotificationsEnabled(int))); connect(¬ificationsEnabledCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setSpecNotificationEnabled(int))); specNotificationsEnabledCheckBox.setChecked(settingsCache->getSpectatorNotificationsEnabled()); specNotificationsEnabledCheckBox.setEnabled(settingsCache->getNotificationsEnabled()); - connect(&specNotificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setSpectatorNotificationsEnabled(int))); + connect(&specNotificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, + SLOT(setSpectatorNotificationsEnabled(int))); doubleClickToPlayCheckBox.setChecked(settingsCache->getDoubleClickToPlay()); connect(&doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int))); @@ -471,7 +474,8 @@ UserInterfaceSettingsPage::UserInterfaceSettingsPage() setLayout(mainLayout); } -void UserInterfaceSettingsPage::setSpecNotificationEnabled(int i) { +void UserInterfaceSettingsPage::setSpecNotificationEnabled(int i) +{ specNotificationsEnabledCheckBox.setEnabled(i != 0); } @@ -557,8 +561,7 @@ QString DeckEditorSettingsPage::getLastUpdateTime() QDir fileDir(fi.path()); QFile file(fileName); - if (file.exists()) - { + if (file.exists()) { return fi.lastModified().toString("MMM d, hh:mm"); } @@ -568,8 +571,7 @@ QString DeckEditorSettingsPage::getLastUpdateTime() void DeckEditorSettingsPage::spoilerPathButtonClicked() { QString lsPath = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (lsPath.isEmpty()) - { + if (lsPath.isEmpty()) { return; } @@ -586,8 +588,7 @@ void DeckEditorSettingsPage::setSpoilersEnabled(bool anInput) updateNowButton->setEnabled(anInput); infoOnSpoilersLabel.setEnabled(anInput); - if (! anInput) - { + if (!anInput) { SpoilerBackgroundUpdater::deleteSpoilerFile(); } } @@ -598,12 +599,10 @@ void DeckEditorSettingsPage::retranslateUi() mcDownloadSpoilersCheckBox.setText(tr("Download Spoilers Automatically")); mcSpoilerSaveLabel.setText(tr("Spoiler Location:")); mcGeneralMessageLabel.setText(tr("Hey, something's here finally!")); - infoOnSpoilersLabel.setText( - tr("Last Updated") + ": " + getLastUpdateTime() + "\n\n" + - tr("Spoilers download automatically on launch") + "\n" + - tr("Press the button to manually update without relaunching") + "\n\n" + - tr("Do not close settings until manual update complete") - ); + infoOnSpoilersLabel.setText(tr("Last Updated") + ": " + getLastUpdateTime() + "\n\n" + + tr("Spoilers download automatically on launch") + "\n" + + tr("Press the button to manually update without relaunching") + "\n\n" + + tr("Do not close settings until manual update complete")); } MessagesSettingsPage::MessagesSettingsPage() @@ -612,12 +611,14 @@ MessagesSettingsPage::MessagesSettingsPage() connect(&chatMentionCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setChatMention(int))); chatMentionCompleterCheckbox.setChecked(settingsCache->getChatMentionCompleter()); - connect(&chatMentionCompleterCheckbox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setChatMentionCompleter(int))); + connect(&chatMentionCompleterCheckbox, SIGNAL(stateChanged(int)), settingsCache, + SLOT(setChatMentionCompleter(int))); ignoreUnregUsersMainChat.setChecked(settingsCache->getIgnoreUnregisteredUsers()); ignoreUnregUserMessages.setChecked(settingsCache->getIgnoreUnregisteredUserMessages()); connect(&ignoreUnregUsersMainChat, SIGNAL(stateChanged(int)), settingsCache, SLOT(setIgnoreUnregisteredUsers(int))); - connect(&ignoreUnregUserMessages, SIGNAL(stateChanged(int)), settingsCache, SLOT(setIgnoreUnregisteredUserMessages(int))); + connect(&ignoreUnregUserMessages, SIGNAL(stateChanged(int)), settingsCache, + SLOT(setIgnoreUnregisteredUserMessages(int))); invertMentionForeground.setChecked(settingsCache->getChatMentionForeground()); connect(&invertMentionForeground, SIGNAL(stateChanged(int)), this, SLOT(updateTextColor(int))); @@ -743,13 +744,13 @@ void MessagesSettingsPage::updateTextHighlightColor(int value) void MessagesSettingsPage::updateMentionPreview() { mentionColor->setStyleSheet("QLineEdit{background:#" + settingsCache->getChatMentionColor() + - ";color: " + (settingsCache->getChatMentionForeground() ? "white" : "black") + ";}"); + ";color: " + (settingsCache->getChatMentionForeground() ? "white" : "black") + ";}"); } void MessagesSettingsPage::updateHighlightPreview() { - highlightColor->setStyleSheet("QLineEdit{background:#" + settingsCache->getChatHighlightColor() + - ";color: " + (settingsCache->getChatHighlightForeground() ? "white" : "black") + ";}"); + highlightColor->setStyleSheet("QLineEdit{background:#" + settingsCache->getChatHighlightColor() + ";color: " + + (settingsCache->getChatHighlightForeground() ? "white" : "black") + ";}"); } void MessagesSettingsPage::storeSettings() @@ -796,7 +797,6 @@ void MessagesSettingsPage::retranslateUi() customAlertStringLabel.setText(tr("Separate words with a space, alphanumeric characters only")); } - SoundSettingsPage::SoundSettingsPage() { soundEnabledCheckBox.setChecked(settingsCache->getSoundEnabled()); @@ -851,7 +851,7 @@ SoundSettingsPage::SoundSettingsPage() void SoundSettingsPage::themeBoxChanged(int index) { QStringList themeDirs = soundEngine->getAvailableThemes().keys(); - if(index >= 0 && index < themeDirs.count()) + if (index >= 0 && index < themeDirs.count()) settingsCache->setSoundThemeName(themeDirs.at(index)); } @@ -952,7 +952,8 @@ void DlgSettings::createIcons() shortcutsButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); shortcutsButton->setIcon(QPixmap("theme:config/shorcuts")); - connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(changePage(QListWidgetItem *, QListWidgetItem *))); + connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, + SLOT(changePage(QListWidgetItem *, QListWidgetItem *))); } void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous) @@ -965,7 +966,7 @@ void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous void DlgSettings::setTab(int index) { - if (index <= contentsWidget->count()-1 && index >= 0) { + if (index <= contentsWidget->count() - 1 && index >= 0) { changePage(contentsWidget->item(index), contentsWidget->currentItem()); contentsWidget->setCurrentRow(index); } @@ -990,75 +991,69 @@ void DlgSettings::closeEvent(QCloseEvent *event) QString loadErrorMessage = tr("Unknown Error loading card database"); LoadStatus loadStatus = db->getLoadStatus(); qDebug() << "Card Database load status: " << loadStatus; - switch(loadStatus) - { + switch (loadStatus) { case Ok: showLoadError = false; break; case Invalid: - loadErrorMessage = - tr("Your card database is invalid.\n\n" - "Cockatrice may not function correctly with an invalid database\n\n" - "You may need to rerun oracle to update your card database.\n\n" - "Would you like to change your database location setting?"); + loadErrorMessage = tr("Your card database is invalid.\n\n" + "Cockatrice may not function correctly with an invalid database\n\n" + "You may need to rerun oracle to update your card database.\n\n" + "Would you like to change your database location setting?"); break; case VersionTooOld: - loadErrorMessage = - tr("Your card database version is too old.\n\n" - "This can cause problems loading card information or images\n\n" - "Usually this can be fixed by rerunning oracle to to update your card database.\n\n" - "Would you like to change your database location setting?"); + loadErrorMessage = tr("Your card database version is too old.\n\n" + "This can cause problems loading card information or images\n\n" + "Usually this can be fixed by rerunning oracle to to update your card database.\n\n" + "Would you like to change your database location setting?"); break; case NotLoaded: - loadErrorMessage = - tr("Your card database did not finish loading\n\n" - "Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues with your cards.xml attached\n\n" - "Would you like to change your database location setting?"); + loadErrorMessage = tr("Your card database did not finish loading\n\n" + "Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues with your " + "cards.xml attached\n\n" + "Would you like to change your database location setting?"); break; case FileError: - loadErrorMessage = - tr("File Error loading your card database.\n\n" - "Would you like to change your database location setting?"); + loadErrorMessage = tr("File Error loading your card database.\n\n" + "Would you like to change your database location setting?"); break; case NoCards: - loadErrorMessage = - tr("Your card database was loaded but contains no cards.\n\n" - "Would you like to change your database location setting?"); + loadErrorMessage = tr("Your card database was loaded but contains no cards.\n\n" + "Would you like to change your database location setting?"); break; default: - loadErrorMessage = - tr("Unknown card database load status\n\n" - "Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues\n\n" - "Would you like to change your database location setting?"); + loadErrorMessage = tr("Unknown card database load status\n\n" + "Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues\n\n" + "Would you like to change your database location setting?"); break; } - if (showLoadError) - { + if (showLoadError) { if (QMessageBox::critical(this, tr("Error"), loadErrorMessage, QMessageBox::Yes | QMessageBox::No) == - QMessageBox::Yes) - { + QMessageBox::Yes) { event->ignore(); return; } } - if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) - { + if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) { // TODO: Prompt to create it - 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) - { + 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 (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) { // TODO: Prompt to create it - 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) - { + 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; } diff --git a/cockatrice/src/dlg_settings.h b/cockatrice/src/dlg_settings.h index c437efd2..75da474b 100644 --- a/cockatrice/src/dlg_settings.h +++ b/cockatrice/src/dlg_settings.h @@ -1,8 +1,8 @@ #ifndef DLG_SETTINGS_H #define DLG_SETTINGS_H -#include #include +#include #include #include #include @@ -28,225 +28,226 @@ class QSpinBox; class AbstractSettingsPage : public QWidget { - public: - virtual void retranslateUi() = 0; +public: + virtual void retranslateUi() = 0; }; class GeneralSettingsPage : public AbstractSettingsPage { Q_OBJECT - public: - GeneralSettingsPage(); - void retranslateUi() override; +public: + GeneralSettingsPage(); + void retranslateUi() override; - private slots: - void deckPathButtonClicked(); - void replaysPathButtonClicked(); - void picsPathButtonClicked(); - void clearDownloadedPicsButtonClicked(); - void cardDatabasePathButtonClicked(); - void tokenDatabasePathButtonClicked(); - void languageBoxChanged(int index); - void setEnabledStatus(bool); - void defaultUrlRestoreButtonClicked(); - void fallbackUrlRestoreButtonClicked(); +private slots: + void deckPathButtonClicked(); + void replaysPathButtonClicked(); + void picsPathButtonClicked(); + void clearDownloadedPicsButtonClicked(); + void cardDatabasePathButtonClicked(); + void tokenDatabasePathButtonClicked(); + void languageBoxChanged(int index); + void setEnabledStatus(bool); + void defaultUrlRestoreButtonClicked(); + void fallbackUrlRestoreButtonClicked(); - private: - QStringList findQmFiles(); - QString languageName(const QString &qmFile); - QLineEdit *deckPathEdit; - QLineEdit *replaysPathEdit; - QLineEdit *picsPathEdit; - QLineEdit *cardDatabasePathEdit; - QLineEdit *tokenDatabasePathEdit; - QLineEdit *defaultUrlEdit; - QLineEdit *fallbackUrlEdit; - QSpinBox pixmapCacheEdit; - QGroupBox *personalGroupBox; - QGroupBox *pathsGroupBox; - QComboBox languageBox; - QCheckBox picDownloadCheckBox; - QCheckBox updateNotificationCheckBox; - QComboBox updateReleaseChannelBox; - QLabel languageLabel; - QLabel pixmapCacheLabel; - QLabel deckPathLabel; - QLabel replaysPathLabel; - QLabel picsPathLabel; - QLabel cardDatabasePathLabel; - QLabel tokenDatabasePathLabel; - QLabel defaultUrlLabel; - QLabel fallbackUrlLabel; - QLabel urlLinkLabel; - QLabel updateReleaseChannelLabel; - QPushButton clearDownloadedPicsButton; - QPushButton defaultUrlRestoreButton; - QPushButton fallbackUrlRestoreButton; +private: + QStringList findQmFiles(); + QString languageName(const QString &qmFile); + QLineEdit *deckPathEdit; + QLineEdit *replaysPathEdit; + QLineEdit *picsPathEdit; + QLineEdit *cardDatabasePathEdit; + QLineEdit *tokenDatabasePathEdit; + QLineEdit *defaultUrlEdit; + QLineEdit *fallbackUrlEdit; + QSpinBox pixmapCacheEdit; + QGroupBox *personalGroupBox; + QGroupBox *pathsGroupBox; + QComboBox languageBox; + QCheckBox picDownloadCheckBox; + QCheckBox updateNotificationCheckBox; + QComboBox updateReleaseChannelBox; + QLabel languageLabel; + QLabel pixmapCacheLabel; + QLabel deckPathLabel; + QLabel replaysPathLabel; + QLabel picsPathLabel; + QLabel cardDatabasePathLabel; + QLabel tokenDatabasePathLabel; + QLabel defaultUrlLabel; + QLabel fallbackUrlLabel; + QLabel urlLinkLabel; + QLabel updateReleaseChannelLabel; + QPushButton clearDownloadedPicsButton; + QPushButton defaultUrlRestoreButton; + QPushButton fallbackUrlRestoreButton; }; class AppearanceSettingsPage : public AbstractSettingsPage { Q_OBJECT - private slots: - void themeBoxChanged(int index); +private slots: + void themeBoxChanged(int index); - private: - QLabel themeLabel; - QComboBox themeBox; - QLabel minPlayersForMultiColumnLayoutLabel; - QLabel maxFontSizeForCardsLabel; - QCheckBox displayCardNamesCheckBox; - QCheckBox cardScalingCheckBox; - QCheckBox horizontalHandCheckBox; - QCheckBox leftJustifiedHandCheckBox; - QCheckBox invertVerticalCoordinateCheckBox; - QGroupBox *themeGroupBox; - QGroupBox *cardsGroupBox; - QGroupBox *handGroupBox; - QGroupBox *tableGroupBox; - QSpinBox minPlayersForMultiColumnLayoutEdit; - QSpinBox maxFontSizeForCardsEdit; +private: + QLabel themeLabel; + QComboBox themeBox; + QLabel minPlayersForMultiColumnLayoutLabel; + QLabel maxFontSizeForCardsLabel; + QCheckBox displayCardNamesCheckBox; + QCheckBox cardScalingCheckBox; + QCheckBox horizontalHandCheckBox; + QCheckBox leftJustifiedHandCheckBox; + QCheckBox invertVerticalCoordinateCheckBox; + QGroupBox *themeGroupBox; + QGroupBox *cardsGroupBox; + QGroupBox *handGroupBox; + QGroupBox *tableGroupBox; + QSpinBox minPlayersForMultiColumnLayoutEdit; + QSpinBox maxFontSizeForCardsEdit; - public: - AppearanceSettingsPage(); - void retranslateUi() override; +public: + AppearanceSettingsPage(); + void retranslateUi() override; }; class UserInterfaceSettingsPage : public AbstractSettingsPage { Q_OBJECT - private slots: - void setSpecNotificationEnabled(int); +private slots: + void setSpecNotificationEnabled(int); - private: - QCheckBox notificationsEnabledCheckBox; - QCheckBox specNotificationsEnabledCheckBox; - QCheckBox doubleClickToPlayCheckBox; - QCheckBox playToStackCheckBox; - QCheckBox annotateTokensCheckBox; - QCheckBox tapAnimationCheckBox; - QGroupBox *generalGroupBox; - QGroupBox *animationGroupBox; +private: + QCheckBox notificationsEnabledCheckBox; + QCheckBox specNotificationsEnabledCheckBox; + QCheckBox doubleClickToPlayCheckBox; + QCheckBox playToStackCheckBox; + QCheckBox annotateTokensCheckBox; + QCheckBox tapAnimationCheckBox; + QGroupBox *generalGroupBox; + QGroupBox *animationGroupBox; - public: - UserInterfaceSettingsPage(); - void retranslateUi() override; +public: + UserInterfaceSettingsPage(); + void retranslateUi() override; }; class DeckEditorSettingsPage : public AbstractSettingsPage { Q_OBJECT - public: - DeckEditorSettingsPage(); - void retranslateUi() override; - QString getLastUpdateTime(); +public: + DeckEditorSettingsPage(); + void retranslateUi() override; + QString getLastUpdateTime(); - private slots: - void setSpoilersEnabled(bool); - void spoilerPathButtonClicked(); - void updateSpoilers(); - void unlockSettings(); +private slots: + void setSpoilersEnabled(bool); + void spoilerPathButtonClicked(); + void updateSpoilers(); + void unlockSettings(); - private: - QCheckBox mcDownloadSpoilersCheckBox; - QLabel msDownloadSpoilersLabel; - QGroupBox *mpGeneralGroupBox; - QGroupBox *mpSpoilerGroupBox; - QLineEdit *mpSpoilerSavePathLineEdit; - QLabel mcSpoilerSaveLabel; - QLabel mcGeneralMessageLabel; - QLabel infoOnSpoilersLabel; - QPushButton *mpSpoilerPathButton; - QPushButton *updateNowButton; +private: + QCheckBox mcDownloadSpoilersCheckBox; + QLabel msDownloadSpoilersLabel; + QGroupBox *mpGeneralGroupBox; + QGroupBox *mpSpoilerGroupBox; + QLineEdit *mpSpoilerSavePathLineEdit; + QLabel mcSpoilerSaveLabel; + QLabel mcGeneralMessageLabel; + QLabel infoOnSpoilersLabel; + QPushButton *mpSpoilerPathButton; + QPushButton *updateNowButton; }; class MessagesSettingsPage : public AbstractSettingsPage { Q_OBJECT - public: - MessagesSettingsPage(); - void retranslateUi() override; +public: + MessagesSettingsPage(); + void retranslateUi() override; - private slots: - void actAdd(); - void actRemove(); - void updateColor(const QString &value); - void updateHighlightColor(const QString &value); - void updateTextColor(int value); - void updateTextHighlightColor(int value); +private slots: + void actAdd(); + void actRemove(); + void updateColor(const QString &value); + void updateHighlightColor(const QString &value); + void updateTextColor(int value); + void updateTextHighlightColor(int value); - private: - QListWidget *messageList; - QAction *aAdd; - QAction *aRemove; - QCheckBox chatMentionCheckBox; - QCheckBox chatMentionCompleterCheckbox; - QCheckBox invertMentionForeground; - QCheckBox invertHighlightForeground; - QCheckBox ignoreUnregUsersMainChat; - QCheckBox ignoreUnregUserMessages; - QCheckBox messagePopups; - QCheckBox mentionPopups; - QCheckBox roomHistory; - QGroupBox *chatGroupBox; - QGroupBox *highlightGroupBox; - QGroupBox *messageShortcuts; - QLineEdit *mentionColor; - QLineEdit *highlightColor; - QLineEdit *customAlertString; - QLabel hexLabel; - QLabel hexHighlightLabel; - QLabel customAlertStringLabel; +private: + QListWidget *messageList; + QAction *aAdd; + QAction *aRemove; + QCheckBox chatMentionCheckBox; + QCheckBox chatMentionCompleterCheckbox; + QCheckBox invertMentionForeground; + QCheckBox invertHighlightForeground; + QCheckBox ignoreUnregUsersMainChat; + QCheckBox ignoreUnregUserMessages; + QCheckBox messagePopups; + QCheckBox mentionPopups; + QCheckBox roomHistory; + QGroupBox *chatGroupBox; + QGroupBox *highlightGroupBox; + QGroupBox *messageShortcuts; + QLineEdit *mentionColor; + QLineEdit *highlightColor; + QLineEdit *customAlertString; + QLabel hexLabel; + QLabel hexHighlightLabel; + QLabel customAlertStringLabel; - void storeSettings(); - void updateMentionPreview(); - void updateHighlightPreview(); + void storeSettings(); + void updateMentionPreview(); + void updateHighlightPreview(); }; class SoundSettingsPage : public AbstractSettingsPage { Q_OBJECT - public: - SoundSettingsPage(); - void retranslateUi() override; +public: + SoundSettingsPage(); + void retranslateUi() override; - private: - QLabel themeLabel; - QComboBox themeBox; - QGroupBox *soundGroupBox; - QPushButton soundTestButton; - QCheckBox soundEnabledCheckBox; - QLabel masterVolumeLabel; - QSlider *masterVolumeSlider; - QSpinBox *masterVolumeSpinBox; +private: + QLabel themeLabel; + QComboBox themeBox; + QGroupBox *soundGroupBox; + QPushButton soundTestButton; + QCheckBox soundEnabledCheckBox; + QLabel masterVolumeLabel; + QSlider *masterVolumeSlider; + QSpinBox *masterVolumeSpinBox; - private slots: - void masterVolumeChanged(int value); - void themeBoxChanged(int index); +private slots: + void masterVolumeChanged(int value); + void themeBoxChanged(int index); }; class DlgSettings : public QDialog { Q_OBJECT - public: - explicit DlgSettings(QWidget *parent = nullptr); - void setTab(int index); +public: + explicit DlgSettings(QWidget *parent = nullptr); + void setTab(int index); - private slots: - void changePage(QListWidgetItem *current, QListWidgetItem *previous); - void updateLanguage(); +private slots: + void changePage(QListWidgetItem *current, QListWidgetItem *previous); + void updateLanguage(); - private: - QListWidget *contentsWidget; - QStackedWidget *pagesWidget; - QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton, *soundButton; - QListWidgetItem *shortcutsButton; - void createIcons(); - void retranslateUi(); +private: + QListWidget *contentsWidget; + QStackedWidget *pagesWidget; + QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton, + *soundButton; + QListWidgetItem *shortcutsButton; + void createIcons(); + void retranslateUi(); - protected: - void changeEvent(QEvent *event) override; - void closeEvent(QCloseEvent *event) override; +protected: + void changeEvent(QEvent *event) override; + void closeEvent(QCloseEvent *event) override; }; #endif \ No newline at end of file diff --git a/cockatrice/src/dlg_update.cpp b/cockatrice/src/dlg_update.cpp index 8a7212e3..e0d1feb4 100644 --- a/cockatrice/src/dlg_update.cpp +++ b/cockatrice/src/dlg_update.cpp @@ -1,13 +1,13 @@ -#include -#include #include #include +#include #include +#include -#include +#include #include #include -#include +#include #include #include "dlg_update.h" @@ -15,13 +15,17 @@ #include "settingscache.h" #include "window_main.h" -DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) { +DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) +{ - //Handle layout + // Handle layout statusLabel = new QLabel(this); statusLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); statusLabel->setWordWrap(true); - descriptionLabel = new QLabel(tr("Current release channel") + QString(": %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8())), this); + descriptionLabel = + new QLabel(tr("Current release channel") + + QString(": %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8())), + this); progress = new QProgressBar(this); buttonBox = new QDialogButtonBox(this); @@ -33,7 +37,7 @@ DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) { gotoDownload = new QPushButton(tr("Open Download Page"), this); addStopDownloadAndRemoveOthers(false); // Add all buttons to box - enableUpdateButton(false); //Unless we know there's an update available, you can't install + enableUpdateButton(false); // Unless we know there's an update available, you can't install buttonBox->addButton(ok, QDialogButtonBox::AcceptRole); connect(gotoDownload, SIGNAL(clicked()), this, SLOT(gotoDownloadPage())); @@ -49,160 +53,180 @@ DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) { setLayout(parentLayout); - //Check for SSL (this probably isn't necessary) + // Check for SSL (this probably isn't necessary) if (!QSslSocket::supportsSsl()) { enableUpdateButton(false); QMessageBox::critical(this, tr("Error"), - tr("Cockatrice was not built with SSL support, therefore you cannot download updates automatically! \nPlease visit the download page to update manually.")); + tr("Cockatrice was not built with SSL support, therefore you cannot download updates " + "automatically! \nPlease visit the download page to update manually.")); } - //Initialize the checker and downloader class + // Initialize the checker and downloader class uDownloader = new UpdateDownloader(this); connect(uDownloader, SIGNAL(downloadSuccessful(QUrl)), this, SLOT(downloadSuccessful(QUrl))); connect(uDownloader, SIGNAL(progressMade(qint64, qint64)), this, SLOT(downloadProgressMade(qint64, qint64))); connect(uDownloader, SIGNAL(error(QString)), this, SLOT(downloadError(QString))); - ReleaseChannel * channel = settingsCache->getUpdateReleaseChannel(); - connect(channel, SIGNAL(finishedCheck(bool, bool, Release *)), this, SLOT(finishedUpdateCheck(bool, bool, Release *))); + ReleaseChannel *channel = settingsCache->getUpdateReleaseChannel(); + connect(channel, SIGNAL(finishedCheck(bool, bool, Release *)), this, + SLOT(finishedUpdateCheck(bool, bool, Release *))); connect(channel, SIGNAL(error(QString)), this, SLOT(updateCheckError(QString))); - //Check for updates + // Check for updates beginUpdateCheck(); } -void DlgUpdate::closeDialog() { +void DlgUpdate::closeDialog() +{ accept(); } - -void DlgUpdate::gotoDownloadPage() { +void DlgUpdate::gotoDownloadPage() +{ QDesktopServices::openUrl(settingsCache->getUpdateReleaseChannel()->getManualDownloadUrl()); } -void DlgUpdate::downloadUpdate() { +void DlgUpdate::downloadUpdate() +{ setLabel(tr("Downloading update...")); addStopDownloadAndRemoveOthers(true); // Will remove all other buttons uDownloader->beginDownload(updateUrl); } -void DlgUpdate::cancelDownload() { +void DlgUpdate::cancelDownload() +{ emit uDownloader->stopDownload(); setLabel("Download canceled"); addStopDownloadAndRemoveOthers(false); downloadProgressMade(0, 1); } -void DlgUpdate::beginUpdateCheck() { +void DlgUpdate::beginUpdateCheck() +{ progress->setMinimum(0); progress->setMaximum(0); setLabel(tr("Checking for updates...")); settingsCache->getUpdateReleaseChannel()->checkForUpdates(); } -void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Release *release) { +void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Release *release) +{ QString publishDate, versionName; - //Update the UI to say we've finished + // Update the UI to say we've finished progress->setMaximum(100); setLabel(tr("Finished checking for updates")); - //If there are no available builds, then they can't auto update. + // If there are no available builds, then they can't auto update. enableUpdateButton(isCompatible); - //Give the user the appropriate message + // Give the user the appropriate message if (!needToUpdate) { - //If there's no need to update, tell them that. However we still allow them to run the - //downloader themselves if there's a compatible build - QMessageBox::information(this, tr("No Update Available"), - tr("Cockatrice is up to date!") + "

" - + tr("You are already running the latest version available in the chosen release channel.") + "
" - + "" + tr("Current version") + QString(": %1
").arg(VERSION_STRING) - + "" + tr("Selected release channel") + QString(": %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8()))); + // If there's no need to update, tell them that. However we still allow them to run the + // downloader themselves if there's a compatible build + QMessageBox::information( + this, tr("No Update Available"), + tr("Cockatrice is up to date!") + "

" + + tr("You are already running the latest version available in the chosen release channel.") + "
" + + "" + tr("Current version") + QString(": %1
").arg(VERSION_STRING) + "" + + tr("Selected release channel") + + QString(": %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8()))); return; } publishDate = release->getPublishDate().toString(Qt::DefaultLocaleLongDate); if (isCompatible) { - //If there is an update, save its URL and work out its name + // If there is an update, save its URL and work out its name updateUrl = release->getDownloadUrl(); int reply; - reply = QMessageBox::question(this, tr("Update Available"), - tr("A new version of Cockatrice is available!") + "

" - + "" + tr("New version") + QString(": %1
").arg(release->getName()) - + "" + tr("Released") + QString(": %1 (").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + ")

" - + tr("Do you want to update now?"), + reply = QMessageBox::question( + this, tr("Update Available"), + tr("A new version of Cockatrice is available!") + "

" + "" + tr("New version") + + QString(": %1
").arg(release->getName()) + "" + tr("Released") + + QString(": %1 (").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + + ")

" + tr("Do you want to update now?"), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) downloadUpdate(); } else { - QMessageBox::information(this, tr("Update Available"), - tr("A new version of Cockatrice is available!") + "

" - + "" + tr("New version") + QString(": %1
").arg(release->getName()) - + "" + tr("Released") + QString(": %1 (").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + ")

" - + tr("Unfortunately there are no download packages available for your operating system. \nYou may have to build from source yourself.") + "

" - + tr("Please check the download page manually and visit the wiki for instructions on compiling.")); + QMessageBox::information( + this, tr("Update Available"), + tr("A new version of Cockatrice is available!") + "

" + "" + tr("New version") + + QString(": %1
").arg(release->getName()) + "" + tr("Released") + + QString(": %1 (").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + + ")

" + + tr("Unfortunately there are no download packages available for your operating system. \nYou may have " + "to build from source yourself.") + + "

" + + tr("Please check the download page manually and visit the wiki for instructions on compiling.")); } } -void DlgUpdate::enableUpdateButton(bool enable) { +void DlgUpdate::enableUpdateButton(bool enable) +{ manualDownload->setEnabled(enable); } -void DlgUpdate::addStopDownloadAndRemoveOthers(bool enable) { +void DlgUpdate::addStopDownloadAndRemoveOthers(bool enable) +{ if (enable) { buttonBox->addButton(stopDownload, QDialogButtonBox::ActionRole); buttonBox->removeButton(manualDownload); buttonBox->removeButton(gotoDownload); - } - else { + } else { buttonBox->removeButton(stopDownload); buttonBox->addButton(manualDownload, QDialogButtonBox::ActionRole); buttonBox->addButton(gotoDownload, QDialogButtonBox::ActionRole); } } -void DlgUpdate::enableOkButton(bool enable) { +void DlgUpdate::enableOkButton(bool enable) +{ ok->setEnabled(enable); } -void DlgUpdate::setLabel(QString newText) { +void DlgUpdate::setLabel(QString newText) +{ statusLabel->setText(newText); } -void DlgUpdate::updateCheckError(QString errorString) { +void DlgUpdate::updateCheckError(QString errorString) +{ setLabel(tr("Error")); QMessageBox::critical(this, tr("Update Error"), - tr("An error occurred while checking for updates:") + QString(" ") + errorString); + tr("An error occurred while checking for updates:") + QString(" ") + errorString); } -void DlgUpdate::downloadError(QString errorString) { +void DlgUpdate::downloadError(QString errorString) +{ setLabel(tr("Error")); enableUpdateButton(true); QMessageBox::critical(this, tr("Update Error"), - tr("An error occurred while downloading an update:") + QString(" ") + errorString); + tr("An error occurred while downloading an update:") + QString(" ") + errorString); } -void DlgUpdate::downloadSuccessful(QUrl filepath) { +void DlgUpdate::downloadSuccessful(QUrl filepath) +{ setLabel(tr("Installing...")); - //Try to open the installer. If it opens, quit Cockatrice - if (QDesktopServices::openUrl(filepath)) - { + // Try to open the installer. If it opens, quit Cockatrice + if (QDesktopServices::openUrl(filepath)) { QMetaObject::invokeMethod(static_cast(parent()), "close", Qt::QueuedConnection); qDebug() << "Opened downloaded update file successfully - closing Cockatrice"; close(); } else { setLabel(tr("Error")); QMessageBox::critical(this, tr("Update Error"), - tr("Cockatrice is unable to open the installer.") + "

" - + tr("Try to update manually by closing Cockatrice and running the installer.") + "
" - + tr("Download location") + QString(": %1").arg(filepath.toLocalFile())); + tr("Cockatrice is unable to open the installer.") + "

" + + tr("Try to update manually by closing Cockatrice and running the installer.") + + "
" + tr("Download location") + QString(": %1").arg(filepath.toLocalFile())); } } -void DlgUpdate::downloadProgressMade(qint64 bytesRead, qint64 totalBytes) { +void DlgUpdate::downloadProgressMade(qint64 bytesRead, qint64 totalBytes) +{ progress->setMaximum(totalBytes); progress->setValue(bytesRead); } diff --git a/cockatrice/src/dlg_update.h b/cockatrice/src/dlg_update.h index ddf24752..b4cb8344 100644 --- a/cockatrice/src/dlg_update.h +++ b/cockatrice/src/dlg_update.h @@ -1,15 +1,16 @@ #ifndef DLG_UPDATE_H #define DLG_UPDATE_H -#include -#include #include +#include +#include #include "update_downloader.h" class Release; -class DlgUpdate : public QDialog { -Q_OBJECT +class DlgUpdate : public QDialog +{ + Q_OBJECT public: DlgUpdate(QWidget *parent); @@ -23,6 +24,7 @@ private slots: void downloadProgressMade(qint64 bytesRead, qint64 totalBytes); void downloadError(QString errorString); void closeDialog(); + private: QUrl updateUrl; void enableUpdateButton(bool enable); diff --git a/cockatrice/src/dlg_viewlog.cpp b/cockatrice/src/dlg_viewlog.cpp index 84d3ae4c..91a07787 100644 --- a/cockatrice/src/dlg_viewlog.cpp +++ b/cockatrice/src/dlg_viewlog.cpp @@ -2,16 +2,15 @@ #include "logger.h" #include "settingscache.h" -#include #include +#include DlgViewLog::DlgViewLog(QWidget *parent) : QDialog(parent) { - logArea = new QPlainTextEdit; logArea->setReadOnly(true); - + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(logArea); @@ -27,7 +26,7 @@ DlgViewLog::DlgViewLog(QWidget *parent) : QDialog(parent) resize(800, 500); loadInitialLogBuffer(); - connect(&Logger::getInstance(), SIGNAL(logEntryAdded(QString)), this, SLOT(logEntryAdded(QString))); + connect(&Logger::getInstance(), SIGNAL(logEntryAdded(QString)), this, SLOT(logEntryAdded(QString))); } void DlgViewLog::actCheckBoxChanged(bool abNewValue) @@ -38,7 +37,7 @@ void DlgViewLog::actCheckBoxChanged(bool abNewValue) void DlgViewLog::loadInitialLogBuffer() { QList logBuffer = Logger::getInstance().getLogBuffer(); - foreach(QString message, logBuffer) + foreach (QString message, logBuffer) logEntryAdded(message); } @@ -49,8 +48,7 @@ void DlgViewLog::logEntryAdded(QString message) void DlgViewLog::closeEvent(QCloseEvent * /* event */) { - if (coClearLog->isChecked()) - { + if (coClearLog->isChecked()) { logArea->clear(); } diff --git a/cockatrice/src/dlg_viewlog.h b/cockatrice/src/dlg_viewlog.h index 06ec1a6f..3845f006 100644 --- a/cockatrice/src/dlg_viewlog.h +++ b/cockatrice/src/dlg_viewlog.h @@ -1,18 +1,21 @@ #ifndef DLG_VIEWLOG_H #define DLG_VIEWLOG_H -#include #include +#include class QPlainTextEdit; class QCloseEvent; -class DlgViewLog : public QDialog { -Q_OBJECT +class DlgViewLog : public QDialog +{ + Q_OBJECT public: explicit DlgViewLog(QWidget *parent); + protected: void closeEvent(QCloseEvent *event) override; + private: QPlainTextEdit *logArea; QCheckBox *coClearLog; diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp index 32c1cf09..7c4b9930 100644 --- a/cockatrice/src/filterbuilder.cpp +++ b/cockatrice/src/filterbuilder.cpp @@ -1,30 +1,23 @@ #include "filterbuilder.h" -#include #include -#include +#include #include +#include #include "cardfilter.h" -FilterBuilder::FilterBuilder(QWidget *parent) - : QWidget(parent) +FilterBuilder::FilterBuilder(QWidget *parent) : QWidget(parent) { filterCombo = new QComboBox; filterCombo->setObjectName("filterCombo"); for (int i = 0; i < CardFilter::AttrEnd; i++) - filterCombo->addItem( - tr(CardFilter::attrName(static_cast(i))), - QVariant(i) - ); + filterCombo->addItem(tr(CardFilter::attrName(static_cast(i))), QVariant(i)); typeCombo = new QComboBox; typeCombo->setObjectName("typeCombo"); for (int i = 0; i < CardFilter::TypeEnd; i++) - typeCombo->addItem( - tr(CardFilter::typeName(static_cast(i))), - QVariant(i) - ); + typeCombo->addItem(tr(CardFilter::typeName(static_cast(i))), QVariant(i)); QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString()); ok->setObjectName("ok"); @@ -65,7 +58,7 @@ void FilterBuilder::destroyFilter() delete fltr; } -static int comboCurrentIntData(const QComboBox *combo) +static int comboCurrentIntData(const QComboBox *combo) { return combo->itemData(combo->currentIndex()).toInt(); } @@ -79,9 +72,8 @@ void FilterBuilder::emit_add() return; destroyFilter(); - fltr = new CardFilter(txt, - static_cast(comboCurrentIntData(typeCombo)), - static_cast(comboCurrentIntData(filterCombo))); + fltr = new CardFilter(txt, static_cast(comboCurrentIntData(typeCombo)), + static_cast(comboCurrentIntData(filterCombo))); emit add(fltr); edit->clear(); } diff --git a/cockatrice/src/filterbuilder.h b/cockatrice/src/filterbuilder.h index 3a5c2178..2b6ed3b6 100644 --- a/cockatrice/src/filterbuilder.h +++ b/cockatrice/src/filterbuilder.h @@ -8,7 +8,8 @@ class QComboBox; class QLineEdit; class CardFilter; -class FilterBuilder : public QWidget { +class FilterBuilder : public QWidget +{ Q_OBJECT private: @@ -29,6 +30,7 @@ signals: public slots: private slots: void emit_add(); + protected: }; diff --git a/cockatrice/src/filtertree.cpp b/cockatrice/src/filtertree.cpp index 249e35f0..0149d7d9 100644 --- a/cockatrice/src/filtertree.cpp +++ b/cockatrice/src/filtertree.cpp @@ -1,17 +1,15 @@ #include "filtertree.h" -#include "cardfilter.h" #include "carddatabase.h" +#include "cardfilter.h" #include -template -FilterTreeNode *FilterTreeBranch::nodeAt(int i) const +template FilterTreeNode *FilterTreeBranch::nodeAt(int i) const { return (childNodes.size() > i) ? childNodes.at(i) : nullptr; } -template -void FilterTreeBranch::deleteAt(int i) +template void FilterTreeBranch::deleteAt(int i) { preRemoveChild(this, i); delete childNodes.takeAt(i); @@ -19,19 +17,16 @@ void FilterTreeBranch::deleteAt(int i) nodeChanged(); } -template -int FilterTreeBranch::childIndex(const FilterTreeNode *node) const +template int FilterTreeBranch::childIndex(const FilterTreeNode *node) const { auto *unconst = const_cast(node); auto downcasted = dynamic_cast(unconst); return (downcasted) ? childNodes.indexOf(downcasted) : -1; } -template -FilterTreeBranch::~FilterTreeBranch() +template FilterTreeBranch::~FilterTreeBranch() { - while (!childNodes.isEmpty()) - { + while (!childNodes.isEmpty()) { delete childNodes.takeFirst(); } } @@ -40,10 +35,8 @@ const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const { QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - { - if ((*i)->type == type) - { + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) { + if ((*i)->type == type) { return *i; } } @@ -56,17 +49,14 @@ FilterItemList *LogicMap::typeList(CardFilter::Type type) QList::iterator i; int count = 0; - for (i = childNodes.begin(); i != childNodes.end(); i++) - { - if ((*i)->type == type) - { + for (i = childNodes.begin(); i != childNodes.end(); i++) { + if ((*i)->type == type) { break; } count++; } - if (i == childNodes.end()) - { + if (i == childNodes.end()) { preInsertChild(this, count); i = childNodes.insert(i, new FilterItemList(type, this)); postInsertChild(this, count); @@ -83,10 +73,8 @@ FilterTreeNode *LogicMap::parent() const int FilterItemList::termIndex(const QString &term) const { - for (int i = 0; i < childNodes.count(); i++) - { - if ((childNodes.at(i))->term == term) - { + for (int i = 0; i < childNodes.count(); i++) { + if ((childNodes.at(i))->term == term) { return i; } } @@ -97,8 +85,7 @@ int FilterItemList::termIndex(const QString &term) const FilterTreeNode *FilterItemList::termNode(const QString &term) { int i = termIndex(term); - if (i < 0) - { + if (i < 0) { FilterItem *fi = new FilterItem(term, this); int count = childNodes.count(); @@ -115,15 +102,12 @@ FilterTreeNode *FilterItemList::termNode(const QString &term) bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const { - for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - { - if (! (*i)->isEnabled()) - { + for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) { + if (!(*i)->isEnabled()) { continue; } - if (! (*i)->acceptCardAttr(info, attr)) - { + if (!(*i)->acceptCardAttr(info, attr)) { return false; } } @@ -141,20 +125,16 @@ bool FilterItemList::testTypeOr(const CardInfo *info, CardFilter::Attr attr) con { bool noChildEnabledChild = true; - for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - { - if (! (*i)->isEnabled()) - { + for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) { + if (!(*i)->isEnabled()) { continue; } - if (noChildEnabledChild) - { + if (noChildEnabledChild) { noChildEnabledChild = false; } - if ((*i)->acceptCardAttr(info, attr)) - { + if ((*i)->acceptCardAttr(info, attr)) { return true; } } @@ -198,8 +178,7 @@ bool FilterItem::acceptColor(const CardInfo *info) const converted_term.replace(QString(" "), QString(""), Qt::CaseInsensitive); // Colorless card filter - if (converted_term.toLower() == "c" && info->getColors().length() < 1) - { + if (converted_term.toLower() == "c" && info->getColors().length() < 1) { return true; } @@ -208,12 +187,9 @@ bool FilterItem::acceptColor(const CardInfo *info) const * then we should match all of them to the card's colors */ int match_count = 0; - for (auto &it : converted_term) - { - for (auto i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) - { - if ((*i).contains(it, Qt::CaseInsensitive)) - { + for (auto &it : converted_term) { + for (auto i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) { + if ((*i).contains(it, Qt::CaseInsensitive)) { match_count++; } } @@ -230,11 +206,9 @@ bool FilterItem::acceptText(const CardInfo *info) const bool FilterItem::acceptSet(const CardInfo *info) const { bool status = false; - for (auto i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) - { - if ((*i)->getShortName().compare(term, Qt::CaseInsensitive) == 0 - || (*i)->getLongName().compare(term, Qt::CaseInsensitive) == 0) - { + for (auto i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) { + if ((*i)->getShortName().compare(term, Qt::CaseInsensitive) == 0 || + (*i)->getLongName().compare(term, Qt::CaseInsensitive) == 0) { status = true; break; } @@ -264,13 +238,13 @@ bool FilterItem::acceptCmc(const CardInfo *info) const bool FilterItem::acceptPower(const CardInfo *info) const { int slash = info->getPowTough().indexOf("/"); - return (slash != -1) ? (info->getPowTough().mid(0,slash) == term) : false; + return (slash != -1) ? (info->getPowTough().mid(0, slash) == term) : false; } bool FilterItem::acceptToughness(const CardInfo *info) const { int slash = info->getPowTough().indexOf("/"); - return (slash != -1) ? (info->getPowTough().mid(slash+1) == term) : false; + return (slash != -1) ? (info->getPowTough().mid(slash + 1) == term) : false; } bool FilterItem::acceptRarity(const CardInfo *info) const @@ -286,25 +260,36 @@ bool FilterItem::acceptRarity(const CardInfo *info) const * Will also need to replace just "mythic" */ converted_term.replace("mythic", "mythic rare", Qt::CaseInsensitive); - for (int i = 0; converted_term.length() <= 3 && i <= 6; i++) - { - switch (i) - { - case 0: converted_term.replace("mr", "mythic rare", Qt::CaseInsensitive); break; - case 1: converted_term.replace("m r", "mythic rare", Qt::CaseInsensitive); break; - case 2: converted_term.replace("m", "mythic rare", Qt::CaseInsensitive); break; - case 3: converted_term.replace("c", "common", Qt::CaseInsensitive); break; - case 4: converted_term.replace("u", "uncommon", Qt::CaseInsensitive); break; - case 5: converted_term.replace("r", "rare", Qt::CaseInsensitive); break; - case 6: converted_term.replace("s", "special", Qt::CaseInsensitive); break; - default: break; + for (int i = 0; converted_term.length() <= 3 && i <= 6; i++) { + switch (i) { + case 0: + converted_term.replace("mr", "mythic rare", Qt::CaseInsensitive); + break; + case 1: + converted_term.replace("m r", "mythic rare", Qt::CaseInsensitive); + break; + case 2: + converted_term.replace("m", "mythic rare", Qt::CaseInsensitive); + break; + case 3: + converted_term.replace("c", "common", Qt::CaseInsensitive); + break; + case 4: + converted_term.replace("u", "uncommon", Qt::CaseInsensitive); + break; + case 5: + converted_term.replace("r", "rare", Qt::CaseInsensitive); + break; + case 6: + converted_term.replace("s", "special", Qt::CaseInsensitive); + break; + default: + break; } } - foreach (QString rareLevel, info->getRarities()) - { - if (rareLevel.compare(converted_term, Qt::CaseInsensitive) == 0) - { + foreach (QString rareLevel, info->getRarities()) { + if (rareLevel.compare(converted_term, Qt::CaseInsensitive) == 0) { return true; } } @@ -313,19 +298,29 @@ bool FilterItem::acceptRarity(const CardInfo *info) const bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const { - switch (attr) - { - case CardFilter::AttrName: return acceptName(info); - case CardFilter::AttrType: return acceptType(info); - case CardFilter::AttrColor: return acceptColor(info); - case CardFilter::AttrText: return acceptText(info); - case CardFilter::AttrSet: return acceptSet(info); - case CardFilter::AttrManaCost: return acceptManaCost(info); - case CardFilter::AttrCmc: return acceptCmc(info); - case CardFilter::AttrRarity: return acceptRarity(info); - case CardFilter::AttrPow: return acceptPower(info); - case CardFilter::AttrTough: return acceptToughness(info); - default: return true; /* ignore this attribute */ + switch (attr) { + case CardFilter::AttrName: + return acceptName(info); + case CardFilter::AttrType: + return acceptType(info); + case CardFilter::AttrColor: + return acceptColor(info); + case CardFilter::AttrText: + return acceptText(info); + case CardFilter::AttrSet: + return acceptSet(info); + case CardFilter::AttrManaCost: + return acceptManaCost(info); + case CardFilter::AttrCmc: + return acceptCmc(info); + case CardFilter::AttrRarity: + return acceptRarity(info); + case CardFilter::AttrPow: + return acceptPower(info); + case CardFilter::AttrTough: + return acceptToughness(info); + default: + return true; /* ignore this attribute */ } } @@ -341,17 +336,14 @@ LogicMap *FilterTree::attrLogicMap(CardFilter::Attr attr) QList::iterator i; int count = 0; - for (i = childNodes.begin(); i != childNodes.end(); i++) - { - if ((*i)->attr == attr) - { + for (i = childNodes.begin(); i != childNodes.end(); i++) { + if ((*i)->attr == attr) { break; } count++; } - if (i == childNodes.end()) - { + if (i == childNodes.end()) { preInsertChild(this, count); i = childNodes.insert(i, new LogicMap(attr, this)); postInsertChild(this, count); @@ -397,32 +389,27 @@ bool FilterTree::testAttr(const CardInfo *info, const LogicMap *lm) const bool status = true; fil = lm->findTypeList(CardFilter::TypeAnd); - if (fil && fil->isEnabled() && !fil->testTypeAnd(info, lm->attr)) - { + if (fil && fil->isEnabled() && !fil->testTypeAnd(info, lm->attr)) { return false; } fil = lm->findTypeList(CardFilter::TypeAndNot); - if (fil && fil->isEnabled() && !fil->testTypeAndNot(info, lm->attr)) - { + if (fil && fil->isEnabled() && !fil->testTypeAndNot(info, lm->attr)) { return false; } fil = lm->findTypeList(CardFilter::TypeOr); - if (fil && fil->isEnabled()) - { + if (fil && fil->isEnabled()) { status = false; // if this is true we can return because it is OR'd with the OrNot list - if (fil->testTypeOr(info, lm->attr)) - { + if (fil->testTypeOr(info, lm->attr)) { return true; } } fil = lm->findTypeList(CardFilter::TypeOrNot); - if (fil && fil->isEnabled() && fil->testTypeOrNot(info, lm->attr)) - { + if (fil && fil->isEnabled() && fil->testTypeOrNot(info, lm->attr)) { return true; } @@ -431,10 +418,8 @@ bool FilterTree::testAttr(const CardInfo *info, const LogicMap *lm) const bool FilterTree::acceptsCard(const CardInfo *info) const { - for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - { - if ((*i)->isEnabled() && !testAttr(info, *i)) - { + for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) { + if ((*i)->isEnabled() && !testAttr(info, *i)) { return false; } } @@ -444,8 +429,7 @@ bool FilterTree::acceptsCard(const CardInfo *info) const void FilterTree::clear() { - while (childCount() > 0) - { + while (childCount() > 0) { deleteAt(0); } } \ No newline at end of file diff --git a/cockatrice/src/filtertree.h b/cockatrice/src/filtertree.h index f03c4316..30021669 100644 --- a/cockatrice/src/filtertree.h +++ b/cockatrice/src/filtertree.h @@ -9,55 +9,111 @@ class CardInfo; -class FilterTreeNode { +class FilterTreeNode +{ private: bool enabled; + public: - FilterTreeNode() : enabled(true) {} - virtual bool isEnabled() const { return enabled; } - virtual void enable() { enabled = true; nodeChanged(); } - virtual void disable() { enabled = false; nodeChanged(); } - virtual FilterTreeNode *parent() const { return NULL; } - virtual FilterTreeNode *nodeAt(int /* i */) const { return NULL; } - virtual void deleteAt(int /* i */) {} - virtual int childCount() const { return 0; } - virtual int childIndex(const FilterTreeNode * /* node */) const { return -1; } - virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; } - virtual QString text() const { return QString(textCStr()); } - virtual bool isLeaf() const { return false; } - virtual const char *textCStr() const { return ""; } - virtual void nodeChanged() const { - if (parent() != NULL) parent()->nodeChanged(); + FilterTreeNode() : enabled(true) + { } - virtual void preInsertChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->preInsertChild(p, i); + virtual bool isEnabled() const + { + return enabled; } - virtual void postInsertChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->postInsertChild(p, i); + virtual void enable() + { + enabled = true; + nodeChanged(); } - virtual void preRemoveChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->preRemoveChild(p, i); + virtual void disable() + { + enabled = false; + nodeChanged(); } - virtual void postRemoveChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->postRemoveChild(p, i); + virtual FilterTreeNode *parent() const + { + return NULL; + } + virtual FilterTreeNode *nodeAt(int /* i */) const + { + return NULL; + } + virtual void deleteAt(int /* i */) + { + } + virtual int childCount() const + { + return 0; + } + virtual int childIndex(const FilterTreeNode * /* node */) const + { + return -1; + } + virtual int index() const + { + return (parent() != NULL) ? parent()->childIndex(this) : -1; + } + virtual QString text() const + { + return QString(textCStr()); + } + virtual bool isLeaf() const + { + return false; + } + virtual const char *textCStr() const + { + return ""; + } + virtual void nodeChanged() const + { + if (parent() != NULL) + parent()->nodeChanged(); + } + virtual void preInsertChild(const FilterTreeNode *p, int i) const + { + if (parent() != NULL) + parent()->preInsertChild(p, i); + } + virtual void postInsertChild(const FilterTreeNode *p, int i) const + { + if (parent() != NULL) + parent()->postInsertChild(p, i); + } + virtual void preRemoveChild(const FilterTreeNode *p, int i) const + { + if (parent() != NULL) + parent()->preRemoveChild(p, i); + } + virtual void postRemoveChild(const FilterTreeNode *p, int i) const + { + if (parent() != NULL) + parent()->postRemoveChild(p, i); } }; -template -class FilterTreeBranch : public FilterTreeNode { +template class FilterTreeBranch : public FilterTreeNode +{ protected: QList childNodes; + public: virtual ~FilterTreeBranch(); FilterTreeNode *nodeAt(int i) const; void deleteAt(int i); - int childCount() const { return childNodes.size(); } + int childCount() const + { + return childNodes.size(); + } int childIndex(const FilterTreeNode *node) const; }; class FilterItemList; class FilterTree; -class LogicMap : public FilterTreeBranch { +class LogicMap : public FilterTreeBranch +{ private: FilterTree *const p; @@ -65,28 +121,44 @@ private: public: const CardFilter::Attr attr; - LogicMap(CardFilter::Attr a, FilterTree *parent) - : p(parent), attr(a) {} + LogicMap(CardFilter::Attr a, FilterTree *parent) : p(parent), attr(a) + { + } const FilterItemList *findTypeList(CardFilter::Type type) const; FilterItemList *typeList(CardFilter::Type type); FilterTreeNode *parent() const; - const char* textCStr() const { return CardFilter::attrName(attr); } + const char *textCStr() const + { + return CardFilter::attrName(attr); + } }; class FilterItem; -class FilterItemList : public FilterTreeBranch { +class FilterItemList : public FilterTreeBranch +{ private: LogicMap *const p; + public: const CardFilter::Type type; - FilterItemList(CardFilter::Type t, LogicMap *parent) - : p(parent), type(t) {} - CardFilter::Attr attr() const { return p->attr; } - FilterTreeNode *parent() const { return p; } + FilterItemList(CardFilter::Type t, LogicMap *parent) : p(parent), type(t) + { + } + CardFilter::Attr attr() const + { + return p->attr; + } + FilterTreeNode *parent() const + { + return p; + } int termIndex(const QString &term) const; FilterTreeNode *termNode(const QString &term); - const char *textCStr() const { return CardFilter::typeName(type); } + const char *textCStr() const + { + return CardFilter::typeName(type); + } bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const; bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const; @@ -94,22 +166,43 @@ public: bool testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const; }; -class FilterItem : public FilterTreeNode { +class FilterItem : public FilterTreeNode +{ private: FilterItemList *const p; + public: const QString term; - FilterItem(QString trm, FilterItemList *parent) - : p(parent), term(trm) {} - virtual ~FilterItem() {}; + FilterItem(QString trm, FilterItemList *parent) : p(parent), term(trm) + { + } + virtual ~FilterItem(){}; - CardFilter::Attr attr() const { return p->attr(); } - CardFilter::Type type() const { return p->type; } - FilterTreeNode *parent() const { return p; } - QString text() const { return term; } - const char *textCStr() const { return term.toStdString().c_str(); } - bool isLeaf() const { return true; } + CardFilter::Attr attr() const + { + return p->attr(); + } + CardFilter::Type type() const + { + return p->type; + } + FilterTreeNode *parent() const + { + return p; + } + QString text() const + { + return term; + } + const char *textCStr() const + { + return term.toStdString().c_str(); + } + bool isLeaf() const + { + return true; + } bool acceptName(const CardInfo *info) const; bool acceptType(const CardInfo *info) const; @@ -124,7 +217,8 @@ public: bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const; }; -class FilterTree : public QObject, public FilterTreeBranch { +class FilterTree : public QObject, public FilterTreeBranch +{ Q_OBJECT signals: @@ -136,30 +230,47 @@ signals: private: LogicMap *attrLogicMap(CardFilter::Attr attr); - FilterItemList *attrTypeList(CardFilter::Attr attr, - CardFilter::Type type); + FilterItemList *attrTypeList(CardFilter::Attr attr, CardFilter::Type type); bool testAttr(const CardInfo *info, const LogicMap *lm) const; - void nodeChanged() const { emit changed(); } - void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } - void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } - void preRemoveChild(const FilterTreeNode *p, int i) const { emit preRemoveRow(p, i); } - void postRemoveChild(const FilterTreeNode *p, int i) const { emit postRemoveRow(p, i); } + void nodeChanged() const + { + emit changed(); + } + void preInsertChild(const FilterTreeNode *p, int i) const + { + emit preInsertRow(p, i); + } + void postInsertChild(const FilterTreeNode *p, int i) const + { + emit postInsertRow(p, i); + } + void preRemoveChild(const FilterTreeNode *p, int i) const + { + emit preRemoveRow(p, i); + } + void postRemoveChild(const FilterTreeNode *p, int i) const + { + emit postRemoveRow(p, i); + } public: FilterTree(); ~FilterTree(); - int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, - const QString &term); + int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, const QString &term); int findTermIndex(const CardFilter *f); - FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, - const QString &term); + FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, const QString &term); FilterTreeNode *termNode(const CardFilter *f); - FilterTreeNode *attrTypeNode(CardFilter::Attr attr, - CardFilter::Type type); - const char *textCStr() const { return "root"; } - int index() const { return 0; } + FilterTreeNode *attrTypeNode(CardFilter::Attr attr, CardFilter::Type type); + const char *textCStr() const + { + return "root"; + } + int index() const + { + return 0; + } bool acceptsCard(const CardInfo *info) const; void clear(); diff --git a/cockatrice/src/filtertreemodel.cpp b/cockatrice/src/filtertreemodel.cpp index 5fed7766..f37ea38e 100644 --- a/cockatrice/src/filtertreemodel.cpp +++ b/cockatrice/src/filtertreemodel.cpp @@ -1,24 +1,19 @@ -#include #include "filtertreemodel.h" -#include "filtertree.h" #include "cardfilter.h" +#include "filtertree.h" +#include -FilterTreeModel::FilterTreeModel(QObject *parent) - : QAbstractItemModel(parent) +FilterTreeModel::FilterTreeModel(QObject *parent) : QAbstractItemModel(parent) { fTree = new FilterTree; - connect(fTree, - SIGNAL(preInsertRow(const FilterTreeNode *, int)), - this, SLOT(proxyBeginInsertRow(const FilterTreeNode *, int))); - connect(fTree, - SIGNAL(postInsertRow(const FilterTreeNode *, int)), - this, SLOT(proxyEndInsertRow(const FilterTreeNode *, int))); - connect(fTree, - SIGNAL(preRemoveRow(const FilterTreeNode *, int)), - this, SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int))); - connect(fTree, - SIGNAL(postRemoveRow(const FilterTreeNode *, int)), - this, SLOT(proxyEndRemoveRow(const FilterTreeNode *, int))); + connect(fTree, SIGNAL(preInsertRow(const FilterTreeNode *, int)), this, + SLOT(proxyBeginInsertRow(const FilterTreeNode *, int))); + connect(fTree, SIGNAL(postInsertRow(const FilterTreeNode *, int)), this, + SLOT(proxyEndInsertRow(const FilterTreeNode *, int))); + connect(fTree, SIGNAL(preRemoveRow(const FilterTreeNode *, int)), this, + SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int))); + connect(fTree, SIGNAL(postRemoveRow(const FilterTreeNode *, int)), this, + SLOT(proxyEndRemoveRow(const FilterTreeNode *, int))); } FilterTreeModel::~FilterTreeModel() @@ -26,13 +21,13 @@ FilterTreeModel::~FilterTreeModel() delete fTree; } -void FilterTreeModel::proxyBeginInsertRow(const FilterTreeNode *node, int i) +void FilterTreeModel::proxyBeginInsertRow(const FilterTreeNode *node, int i) { int idx; idx = node->index(); if (idx >= 0) - beginInsertRows(createIndex(idx, 0, (void *) node), i, i); + beginInsertRows(createIndex(idx, 0, (void *)node), i, i); } void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int) @@ -44,13 +39,13 @@ void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int) endInsertRows(); } -void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i) +void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i) { int idx; idx = node->index(); if (idx >= 0) - beginRemoveRows(createIndex(idx, 0, (void *) node), i, i); + beginRemoveRows(createIndex(idx, 0, (void *)node), i, i); } void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int) @@ -102,7 +97,7 @@ int FilterTreeModel::rowCount(const QModelIndex &parent) const return result; } -int FilterTreeModel::columnCount(const QModelIndex &/*parent*/) const +int FilterTreeModel::columnCount(const QModelIndex & /*parent*/) const { return 1; } @@ -133,7 +128,7 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const case Qt::ToolTipRole: case Qt::StatusTipRole: case Qt::WhatsThisRole: - if(!node->isLeaf()) + if (!node->isLeaf()) return tr(node->textCStr()); else return node->text(); @@ -149,8 +144,7 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const return QVariant(); } -bool FilterTreeModel::setData(const QModelIndex &index, - const QVariant &value, int role) +bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) { FilterTreeNode *node; @@ -158,7 +152,7 @@ bool FilterTreeModel::setData(const QModelIndex &index, return false; if (index.column() >= columnCount()) return false; - if (role != Qt::CheckStateRole ) + if (role != Qt::CheckStateRole) return false; node = indexToNode(index); @@ -208,8 +202,7 @@ QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int return createIndex(row, column, child); } -QModelIndex FilterTreeModel::index(int row, int column, - const QModelIndex &parent) const +QModelIndex FilterTreeModel::index(int row, int column, const QModelIndex &parent) const { const FilterTreeNode *node; @@ -249,12 +242,12 @@ QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const return QModelIndex(); } -bool FilterTreeModel::removeRows(int row, int count, const QModelIndex & parent) +bool FilterTreeModel::removeRows(int row, int count, const QModelIndex &parent) { FilterTreeNode *node; int i, last; - last = row+count-1; + last = row + count - 1; if (!parent.isValid() || count < 1 || row < 0) return false; diff --git a/cockatrice/src/filtertreemodel.h b/cockatrice/src/filtertreemodel.h index ac90db57..a70c8036 100644 --- a/cockatrice/src/filtertreemodel.h +++ b/cockatrice/src/filtertreemodel.h @@ -7,7 +7,8 @@ class FilterTree; class CardFilter; class FilterTreeNode; -class FilterTreeModel : public QAbstractItemModel { +class FilterTreeModel : public QAbstractItemModel +{ Q_OBJECT private: FilterTree *fTree; @@ -28,17 +29,18 @@ private: public: FilterTreeModel(QObject *parent = 0); ~FilterTreeModel(); - FilterTree *filterTree() const { return fTree; } + FilterTree *filterTree() const + { + return fTree; + } int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; + int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, - int role = Qt::EditRole); + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); Qt::ItemFlags flags(const QModelIndex &index) const; QModelIndex parent(const QModelIndex &ind) const; - QModelIndex index(int row, int column, - const QModelIndex &parent) const; - bool removeRows(int row, int count, const QModelIndex & parent); + QModelIndex index(int row, int column, const QModelIndex &parent) const; + bool removeRows(int row, int count, const QModelIndex &parent); }; #endif diff --git a/cockatrice/src/gamescene.cpp b/cockatrice/src/gamescene.cpp index 23057db3..1f3c8d69 100644 --- a/cockatrice/src/gamescene.cpp +++ b/cockatrice/src/gamescene.cpp @@ -1,28 +1,25 @@ #include "gamescene.h" +#include "carditem.h" +#include "phasestoolbar.h" #include "player.h" +#include "settingscache.h" #include "zoneviewwidget.h" #include "zoneviewzone.h" -#include "phasestoolbar.h" -#include "settingscache.h" -#include "carditem.h" -#include #include -#include -#include #include -#include #include +#include +#include +#include +#include GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent) - : QGraphicsScene(parent), - phasesToolbar(_phasesToolbar), - viewSize(QSize()), - playerRotation(0) + : QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()), playerRotation(0) { animationTimer = new QBasicTimer; addItem(phasesToolbar); connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange())); - + rearrange(); } @@ -93,7 +90,7 @@ void GameScene::rearrange() const int playersCount = playersPlaying.size(); const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2; - const int rows = ceil((qreal) playersCount / columns); + const int rows = ceil((qreal)playersCount / columns); qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; QList columnWidth; @@ -150,29 +147,32 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb } ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false); - zoneViews.append(item); - connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); + zoneViews.append(item); + connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); addItem(item); - if (zoneName=="grave") + if (zoneName == "grave") item->setPos(360, 100); - else if (zoneName=="rfg") + else if (zoneName == "rfg") item->setPos(380, 120); else item->setPos(340, 80); } -void GameScene::addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission) +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); - connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); + connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); addItem(item); item->setPos(600, 80); } void GameScene::removeZoneView(ZoneViewWidget *item) { - zoneViews.removeAt(zoneViews.indexOf(item)); + zoneViews.removeAt(zoneViews.indexOf(item)); removeItem(item); } @@ -201,8 +201,8 @@ QTransform GameScene::getViewportTransform() const void GameScene::processViewSizeChange(const QSize &newSize) { viewSize = newSize; - - qreal newRatio = ((qreal) newSize.width()) / newSize.height(); + + qreal newRatio = ((qreal)newSize.width()) / newSize.height(); qreal minWidth = 0; QList minWidthByColumn; for (int col = 0; col < playersByColumn.size(); ++col) { @@ -215,7 +215,7 @@ void GameScene::processViewSizeChange(const QSize &newSize) minWidth += minWidthByColumn[col]; } minWidth += phasesToolbar->getWidth(); - + qreal minRatio = minWidth / sceneRect().height(); qreal newWidth; if (minRatio > newRatio) { @@ -230,7 +230,7 @@ void GameScene::processViewSizeChange(const QSize &newSize) qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); qreal newx = phasesToolbar->getWidth(); for (int col = 0; col < playersByColumn.size(); ++col) { - for (int row = 0; row < playersByColumn[col].size(); ++row){ + for (int row = 0; row < playersByColumn[col].size(); ++row) { playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn); playersByColumn[col][row]->setPos(newx, playersByColumn[col][row]->y()); } @@ -240,14 +240,15 @@ void GameScene::processViewSizeChange(const QSize &newSize) void GameScene::updateHover(const QPointF &scenePos) { - QList itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); - + 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; @@ -260,7 +261,7 @@ void GameScene::updateHover(const QPointF &scenePos) continue; } else if (card->getZone() != zone) continue; - + if (card->getRealZValue() > maxZ) { maxZ = card->getRealZValue(); maxZCard = card; @@ -278,7 +279,7 @@ bool GameScene::event(QEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseMove) updateHover(static_cast(event)->scenePos()); - + return QGraphicsScene::event(event); } diff --git a/cockatrice/src/gamescene.h b/cockatrice/src/gamescene.h index 6ac014cd..c5016e1d 100644 --- a/cockatrice/src/gamescene.h +++ b/cockatrice/src/gamescene.h @@ -15,14 +15,15 @@ class ServerInfo_Card; class PhasesToolbar; class QBasicTimer; -class GameScene : public QGraphicsScene { +class GameScene : public QGraphicsScene +{ Q_OBJECT private: static const int playerAreaSpacing = 5; - + PhasesToolbar *phasesToolbar; QList players; - QList > playersByColumn; + QList> playersByColumn; QList zoneViews; QSize viewSize; QPointer hoveredCard; @@ -30,6 +31,7 @@ private: QSet cardsToAnimate; int playerRotation; void updateHover(const QPointF &scenePos); + public: GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0); ~GameScene(); @@ -37,16 +39,19 @@ public: 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 addRevealedZoneView(Player *player, + CardZone *zone, + const QList &cardList, + bool withWritePermission); void removeZoneView(ZoneViewWidget *item); void addPlayer(Player *player); void removePlayer(Player *player); @@ -54,6 +59,7 @@ public slots: void closeMostRecentZoneView(); void adjustPlayerRotation(int rotationAdjustment); void rearrange(); + protected: bool event(QEvent *event); void timerEvent(QTimerEvent *event); diff --git a/cockatrice/src/gameselector.cpp b/cockatrice/src/gameselector.cpp index 0a745f5e..1651f271 100644 --- a/cockatrice/src/gameselector.cpp +++ b/cockatrice/src/gameselector.cpp @@ -1,30 +1,36 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "tab_supervisor.h" +#include "gameselector.h" #include "dlg_creategame.h" #include "dlg_filter_games.h" -#include "gameselector.h" #include "gamesmodel.h" -#include "tab_room.h" -#include "pending_command.h" +#include "pb/response.pb.h" #include "pb/room_commands.pb.h" #include "pb/serverinfo_game.pb.h" -#include "pb/response.pb.h" +#include "pending_command.h" +#include "tab_room.h" +#include "tab_supervisor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include -GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, const bool restoresettings, const bool showfilters, QWidget *parent) +GameSelector::GameSelector(AbstractClient *_client, + const TabSupervisor *_tabSupervisor, + TabRoom *_room, + const QMap &_rooms, + const QMap &_gameTypes, + const bool restoresettings, + const bool showfilters, + QWidget *parent) : QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room) { gameListView = new QTreeView; gameListModel = new GamesModel(_rooms, _gameTypes, this); - if(showfilters) - { + if (showfilters) { gameListProxyModel = new GamesProxyModel(this, tabSupervisor->isOwnUserRegistered()); gameListProxyModel->setSourceModel(gameListModel); gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); @@ -53,7 +59,7 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId()); if (showfilters && restoresettings) - gameListProxyModel->loadFilterParameters(gameTypeMap); + gameListProxyModel->loadFilterParameters(gameTypeMap); gameListView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); @@ -74,8 +80,7 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup spectateButton = new QPushButton; QHBoxLayout *buttonLayout = new QHBoxLayout; - if(showfilters) - { + if (showfilters) { buttonLayout->addWidget(filterButton); buttonLayout->addWidget(clearFilterButton); } @@ -93,12 +98,13 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup retranslateUi(); setLayout(mainLayout); - setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5); + 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(gameListView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(actSelectedGameChanged(const QModelIndex &, const QModelIndex &))); + connect(gameListView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, + SLOT(actSelectedGameChanged(const QModelIndex &, const QModelIndex &))); connect(gameListView, SIGNAL(activated(const QModelIndex &)), this, SLOT(actJoin())); } @@ -147,15 +153,31 @@ void GameSelector::checkResponse(const Response &response) joinButton->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: ; + 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:; } if (response.response_code() != Response::RespSpectatorsNotAllowed) @@ -225,5 +247,5 @@ void GameSelector::actSelectedGameChanged(const QModelIndex ¤t, const QMod bool overrideRestrictions = !tabSupervisor->getAdminLocked(); spectateButton->setEnabled(game.spectators_allowed() || overrideRestrictions); - joinButton->setEnabled( game.player_count() < game.max_players() || overrideRestrictions); + joinButton->setEnabled(game.player_count() < game.max_players() || overrideRestrictions); } diff --git a/cockatrice/src/gameselector.h b/cockatrice/src/gameselector.h index 69d22dc3..2fc0e335 100644 --- a/cockatrice/src/gameselector.h +++ b/cockatrice/src/gameselector.h @@ -1,8 +1,8 @@ #ifndef GAMESELECTOR_H #define GAMESELECTOR_H -#include #include "gametypemap.h" +#include class QTreeView; class GamesModel; @@ -15,7 +15,8 @@ class TabRoom; class ServerInfo_Game; class Response; -class GameSelector : public QGroupBox { +class GameSelector : public QGroupBox +{ Q_OBJECT private slots: void actSetFilter(); @@ -26,6 +27,7 @@ private slots: void checkResponse(const Response &response); signals: void gameJoined(int gameId); + private: AbstractClient *client; const TabSupervisor *tabSupervisor; @@ -36,8 +38,16 @@ private: GamesProxyModel *gameListProxyModel; QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton; GameTypeMap gameTypeMap; + public: - GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, const bool restoresettings, const bool showfilters, QWidget *parent = 0); + GameSelector(AbstractClient *_client, + const TabSupervisor *_tabSupervisor, + TabRoom *_room, + const QMap &_rooms, + const QMap &_gameTypes, + const bool restoresettings, + const bool showfilters, + QWidget *parent = 0); void retranslateUi(); void processGameInfo(const ServerInfo_Game &info); }; diff --git a/cockatrice/src/gamesmodel.cpp b/cockatrice/src/gamesmodel.cpp index 1f3d222c..81a112a1 100644 --- a/cockatrice/src/gamesmodel.cpp +++ b/cockatrice/src/gamesmodel.cpp @@ -3,14 +3,25 @@ #include "pixmapgenerator.h" #include "settingscache.h" +#include #include #include #include -#include -enum GameListColumn {ROOM, CREATED, DESCRIPTION, CREATOR, GAME_TYPE, RESTRICTIONS, PLAYERS, SPECTATORS}; +enum GameListColumn +{ + ROOM, + CREATED, + DESCRIPTION, + CREATOR, + GAME_TYPE, + RESTRICTIONS, + PLAYERS, + SPECTATORS +}; -const QString GamesModel::getGameCreatedString(const int secs) const { +const QString GamesModel::getGameCreatedString(const int secs) const +{ QString ret; if (secs < SECS_PER_MIN * 2) // for first min we display "New" @@ -48,7 +59,7 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const const ServerInfo_Game &g = gameList[index.row()]; switch (index.column()) { - case ROOM: + case ROOM: return rooms.value(g.room_id()); case CREATED: { QDateTime then; @@ -56,113 +67,119 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const int secs = then.secsTo(QDateTime::currentDateTime()); switch (role) { - case Qt::DisplayRole: return getGameCreatedString(secs); - case SORT_ROLE: return QVariant(secs); - case Qt::TextAlignmentRole: return Qt::AlignCenter; - default: return QVariant(); + case Qt::DisplayRole: + return getGameCreatedString(secs); + case SORT_ROLE: + return QVariant(secs); + case Qt::TextAlignmentRole: + return Qt::AlignCenter; + default: + return QVariant(); } } - case DESCRIPTION: - switch(role) { - case SORT_ROLE: - case Qt::DisplayRole: - return QString::fromStdString(g.description()); - case Qt::TextAlignmentRole: - return Qt::AlignLeft; - default: - return QVariant(); - } + case DESCRIPTION: + switch (role) { + case SORT_ROLE: + case Qt::DisplayRole: + return QString::fromStdString(g.description()); + case Qt::TextAlignmentRole: + return Qt::AlignLeft; + default: + return QVariant(); + } case CREATOR: { - switch(role) { - case SORT_ROLE: - case Qt::DisplayRole: - return QString::fromStdString(g.creator_info().name()); - case Qt::DecorationRole: { - QPixmap avatarPixmap = UserLevelPixmapGenerator::generatePixmap(13, (UserLevelFlags)g.creator_info().user_level(), false, QString::fromStdString(g.creator_info().privlevel())); + switch (role) { + case SORT_ROLE: + case Qt::DisplayRole: + return QString::fromStdString(g.creator_info().name()); + case Qt::DecorationRole: { + QPixmap avatarPixmap = UserLevelPixmapGenerator::generatePixmap( + 13, (UserLevelFlags)g.creator_info().user_level(), false, + QString::fromStdString(g.creator_info().privlevel())); return QIcon(avatarPixmap); } - default: - return QVariant(); + default: + return QVariant(); } } case GAME_TYPE: switch (role) { - case SORT_ROLE: - case Qt::DisplayRole: { - 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 SORT_ROLE: + case Qt::DisplayRole: { + 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 Qt::TextAlignmentRole: - return Qt::AlignLeft; - default: - return QVariant(); - } - case RESTRICTIONS: - switch(role) { - case SORT_ROLE: - case Qt::DisplayRole: { - QStringList result; - if (g.with_password()) - result.append(tr("password")); - if (g.only_buddies()) - result.append(tr("buddies only")); - if (g.only_registered()) - result.append(tr("reg. users only")); - return result.join(", "); + case Qt::TextAlignmentRole: + return Qt::AlignLeft; + default: + return QVariant(); } - case Qt::DecorationRole:{ - return g.with_password() ? QIcon(LockPixmapGenerator::generatePixmap(13)) : QVariant(); - case Qt::TextAlignmentRole: - return Qt::AlignLeft; - default: - return QVariant(); + case RESTRICTIONS: + switch (role) { + case SORT_ROLE: + case Qt::DisplayRole: { + QStringList result; + if (g.with_password()) + result.append(tr("password")); + if (g.only_buddies()) + result.append(tr("buddies only")); + if (g.only_registered()) + result.append(tr("reg. users only")); + return result.join(", "); + } + case Qt::DecorationRole: { + return g.with_password() ? QIcon(LockPixmapGenerator::generatePixmap(13)) : QVariant(); + case Qt::TextAlignmentRole: + return Qt::AlignLeft; + default: + return QVariant(); + } } + case PLAYERS: + switch (role) { + case SORT_ROLE: + case Qt::DisplayRole: + return QString("%1/%2").arg(g.player_count()).arg(g.max_players()); + case Qt::TextAlignmentRole: + return Qt::AlignCenter; + default: + return QVariant(); } - case PLAYERS: - switch(role) { - case SORT_ROLE: - case Qt::DisplayRole: - return QString("%1/%2").arg(g.player_count()).arg(g.max_players()); - case Qt::TextAlignmentRole: - return Qt::AlignCenter; - default: - return QVariant(); - } - - case SPECTATORS: - switch(role) { - case SORT_ROLE: - case Qt::DisplayRole: { - if (g.spectators_allowed()) { - QString result; - result.append(QString::number(g.spectators_count())); - if (g.spectators_can_chat() && g.spectators_omniscient()) - { - result.append(" (").append(tr("can chat")).append(" & ").append(tr("see hands")).append(")"); + case SPECTATORS: + switch (role) { + case SORT_ROLE: + case Qt::DisplayRole: { + if (g.spectators_allowed()) { + QString result; + result.append(QString::number(g.spectators_count())); + + if (g.spectators_can_chat() && g.spectators_omniscient()) { + result.append(" (") + .append(tr("can chat")) + .append(" & ") + .append(tr("see hands")) + .append(")"); + } else if (g.spectators_can_chat()) { + result.append(" (").append(tr("can chat")).append(")"); + } else if (g.spectators_omniscient()) { + result.append(" (").append(tr("can see hands")).append(")"); + } + + return result; } - else if (g.spectators_can_chat()) - { - result.append(" (").append(tr("can chat")).append(")"); - } - else if (g.spectators_omniscient()) - { - result.append(" (").append(tr("can see hands")).append(")"); - } - - return result; + return QVariant(tr("not allowed")); } - return QVariant(tr("not allowed")); + case Qt::TextAlignmentRole: + return Qt::AlignLeft; + default: + return QVariant(); } - case Qt::TextAlignmentRole: - return Qt::AlignLeft; - default: - return QVariant(); - } - default: return QVariant(); + default: + return QVariant(); } } @@ -171,29 +188,36 @@ QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, in if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole)) return QVariant(); switch (section) { - case ROOM: return tr("Room"); - case CREATED: { - switch(role) { - case Qt::DisplayRole: - return tr("Age"); - case Qt::TextAlignmentRole: - return Qt::AlignCenter; + case ROOM: + return tr("Room"); + case CREATED: { + switch (role) { + case Qt::DisplayRole: + return tr("Age"); + case Qt::TextAlignmentRole: + return Qt::AlignCenter; + } } - } - case DESCRIPTION: return tr("Description"); - case CREATOR: return tr("Creator"); - case GAME_TYPE: return tr("Type"); - case RESTRICTIONS: return tr("Restrictions"); - case PLAYERS: { - switch(role) { - case Qt::DisplayRole: - return tr("Players"); - case Qt::TextAlignmentRole: - return Qt::AlignCenter; + case DESCRIPTION: + return tr("Description"); + case CREATOR: + return tr("Creator"); + case GAME_TYPE: + return tr("Type"); + case RESTRICTIONS: + return tr("Restrictions"); + case PLAYERS: { + switch (role) { + case Qt::DisplayRole: + return tr("Players"); + case Qt::TextAlignmentRole: + return Qt::AlignCenter; + } } - } - case SPECTATORS: return tr("Spectators"); - default: return QVariant(); + case SPECTATORS: + return tr("Spectators"); + default: + return QVariant(); } } @@ -213,7 +237,7 @@ void GamesModel::updateGameList(const ServerInfo_Game &game) endRemoveRows(); } else { gameList[i].MergeFrom(game); - emit dataChanged(index(i, 0), index(i, NUM_COLS-1)); + emit dataChanged(index(i, 0), index(i, NUM_COLS - 1)); } return; } @@ -226,19 +250,15 @@ void GamesModel::updateGameList(const ServerInfo_Game &game) } GamesProxyModel::GamesProxyModel(QObject *parent, bool _ownUserIsRegistered) - : QSortFilterProxyModel(parent), - ownUserIsRegistered(_ownUserIsRegistered), - showBuddiesOnlyGames(false), - unavailableGamesVisible(false), - showPasswordProtectedGames(true), - maxPlayersFilterMin(-1), - maxPlayersFilterMax(-1) + : QSortFilterProxyModel(parent), ownUserIsRegistered(_ownUserIsRegistered), showBuddiesOnlyGames(false), + unavailableGamesVisible(false), showPasswordProtectedGames(true), maxPlayersFilterMin(-1), maxPlayersFilterMax(-1) { setSortRole(GamesModel::SORT_ROLE); setDynamicSortFilter(true); } -void GamesProxyModel::setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames) { +void GamesProxyModel::setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames) +{ showBuddiesOnlyGames = _showBuddiesOnlyGames; invalidateFilter(); } @@ -306,7 +326,7 @@ void GamesProxyModel::loadFilterParameters(const QMap &allGameType QMapIterator gameTypesIterator(allGameTypes); while (gameTypesIterator.hasNext()) { gameTypesIterator.next(); - if (settingsCache->gameFilters().isGameTypeEnabled(gameTypesIterator.value())){ + if (settingsCache->gameFilters().isGameTypeEnabled(gameTypesIterator.value())) { gameTypeFilter.insert(gameTypesIterator.key()); } } @@ -320,19 +340,19 @@ void GamesProxyModel::saveFilterParameters(const QMap &allGameType settingsCache->gameFilters().setUnavailableGamesVisible(unavailableGamesVisible); settingsCache->gameFilters().setShowPasswordProtectedGames(showPasswordProtectedGames); settingsCache->gameFilters().setGameNameFilter(gameNameFilter); - + QMapIterator gameTypeIterator(allGameTypes); while (gameTypeIterator.hasNext()) { gameTypeIterator.next(); bool enabled = gameTypeFilter.contains(gameTypeIterator.key()); - settingsCache->gameFilters().setGameTypeEnabled(gameTypeIterator.value(),enabled); + settingsCache->gameFilters().setGameTypeEnabled(gameTypeIterator.value(), enabled); } settingsCache->gameFilters().setMinPlayers(maxPlayersFilterMin); settingsCache->gameFilters().setMaxPlayers(maxPlayersFilterMax); } -bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourceParent*/) const +bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { GamesModel *model = qobject_cast(sourceModel()); if (!model) diff --git a/cockatrice/src/gamesmodel.h b/cockatrice/src/gamesmodel.h index ef01e9ed..68351170 100644 --- a/cockatrice/src/gamesmodel.h +++ b/cockatrice/src/gamesmodel.h @@ -1,30 +1,38 @@ #ifndef GAMESMODEL_H #define GAMESMODEL_H -#include -#include -#include -#include #include "gametypemap.h" #include "pb/serverinfo_game.pb.h" +#include +#include +#include +#include -class GamesModel : public QAbstractTableModel { -Q_OBJECT +class GamesModel : public QAbstractTableModel +{ + Q_OBJECT private: QList gameList; QMap rooms; QMap gameTypes; static const int NUM_COLS = 8; - static const int SECS_PER_MIN = 60; + static const int SECS_PER_MIN = 60; static const int SECS_PER_TEN_MIN = 600; static const int SECS_PER_HOUR = 3600; + public: - static const int SORT_ROLE = Qt::UserRole+1; + static const int SORT_ROLE = Qt::UserRole + 1; 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 NUM_COLS; } + int rowCount(const QModelIndex &parent = QModelIndex()) const + { + return parent.isValid() ? 0 : gameList.size(); + } + int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const + { + return NUM_COLS; + } QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; const QString getGameCreatedString(const int secs) const; @@ -35,15 +43,25 @@ public: */ void updateGameList(const ServerInfo_Game &game); - int roomColIndex() { return 0; } - int startTimeColIndex() { return 1; } + int roomColIndex() + { + return 0; + } + int startTimeColIndex() + { + return 1; + } - const QMap &getGameTypes() { return gameTypes; } + const QMap &getGameTypes() + { + return gameTypes; + } }; class ServerInfo_User; -class GamesProxyModel : public QSortFilterProxyModel { +class GamesProxyModel : public QSortFilterProxyModel +{ Q_OBJECT private: bool ownUserIsRegistered; @@ -54,28 +72,54 @@ private: QSet gameTypeFilter; int maxPlayersFilterMin, maxPlayersFilterMax; - static const int DEFAULT_MAX_PLAYERS_MAX = 99; + static const int DEFAULT_MAX_PLAYERS_MAX = 99; + public: GamesProxyModel(QObject *parent = 0, bool _ownUserIsRegistered = false); - bool getShowBuddiesOnlyGames() const {return showBuddiesOnlyGames; } + bool getShowBuddiesOnlyGames() const + { + return showBuddiesOnlyGames; + } void setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames); - bool getUnavailableGamesVisible() const { return unavailableGamesVisible; } + bool getUnavailableGamesVisible() const + { + return unavailableGamesVisible; + } void setUnavailableGamesVisible(bool _unavailableGamesVisible); - bool getShowPasswordProtectedGames() const { return showPasswordProtectedGames; } + bool getShowPasswordProtectedGames() const + { + return showPasswordProtectedGames; + } void setShowPasswordProtectedGames(bool _showPasswordProtectedGames); - QString getGameNameFilter() const { return gameNameFilter; } + QString getGameNameFilter() const + { + return gameNameFilter; + } void setGameNameFilter(const QString &_gameNameFilter); - QString getCreatorNameFilter() const { return creatorNameFilter; } + QString getCreatorNameFilter() const + { + return creatorNameFilter; + } void setCreatorNameFilter(const QString &_creatorNameFilter); - QSet getGameTypeFilter() const { return gameTypeFilter; } + QSet getGameTypeFilter() const + { + return gameTypeFilter; + } void setGameTypeFilter(const QSet &_gameTypeFilter); - int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; } - int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; } + int getMaxPlayersFilterMin() const + { + return maxPlayersFilterMin; + } + int getMaxPlayersFilterMax() const + { + return maxPlayersFilterMax; + } void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); void resetFilterParameters(); void loadFilterParameters(const QMap &allGameTypes); void saveFilterParameters(const QMap &allGameTypes); + protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; diff --git a/cockatrice/src/gameview.cpp b/cockatrice/src/gameview.cpp index 2c5c6163..b96e5f5b 100644 --- a/cockatrice/src/gameview.cpp +++ b/cockatrice/src/gameview.cpp @@ -1,12 +1,11 @@ #include "gameview.h" #include "gamescene.h" #include "settingscache.h" -#include #include +#include #include -GameView::GameView(QGraphicsScene *scene, QWidget *parent) - : QGraphicsView(scene, parent), rubberBand(0) +GameView::GameView(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent), rubberBand(0) { setBackgroundBrush(QBrush(QColor(0, 0, 0))); setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing); @@ -14,7 +13,7 @@ GameView::GameView(QGraphicsScene *scene, QWidget *parent) 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())); @@ -23,7 +22,7 @@ GameView::GameView(QGraphicsScene *scene, QWidget *parent) connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView())); addAction(aCloseMostRecentZoneView); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); rubberBand = new QRubberBand(QRubberBand::Rectangle, this); } @@ -35,7 +34,7 @@ void GameView::resizeEvent(QResizeEvent *event) GameScene *s = dynamic_cast(scene()); if (s) s->processViewSizeChange(event->size()); - + updateSceneRect(scene()->sceneRect()); } diff --git a/cockatrice/src/gameview.h b/cockatrice/src/gameview.h index c5fdfe30..a3bae139 100644 --- a/cockatrice/src/gameview.h +++ b/cockatrice/src/gameview.h @@ -5,12 +5,14 @@ class QRubberBand; -class GameView : public QGraphicsView { +class GameView : public QGraphicsView +{ Q_OBJECT private: QAction *aCloseMostRecentZoneView; QRubberBand *rubberBand; QPointF selectionOrigin; + protected: void resizeEvent(QResizeEvent *event); private slots: @@ -20,6 +22,7 @@ private slots: void refreshShortcuts(); public slots: void updateSceneRect(const QRectF &rect); + public: GameView(QGraphicsScene *scene, QWidget *parent = 0); }; diff --git a/cockatrice/src/handcounter.cpp b/cockatrice/src/handcounter.cpp index 8b58b6a1..2ba13b40 100644 --- a/cockatrice/src/handcounter.cpp +++ b/cockatrice/src/handcounter.cpp @@ -1,11 +1,10 @@ -#include -#include -#include #include "handcounter.h" #include "cardzone.h" +#include +#include +#include -HandCounter::HandCounter(QGraphicsItem *parent) - : AbstractGraphicsItem(parent), number(0) +HandCounter::HandCounter(QGraphicsItem *parent) : AbstractGraphicsItem(parent), number(0) { setCacheMode(DeviceCoordinateCache); } @@ -37,7 +36,7 @@ void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*op painter->resetTransform(); painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect()); painter->restore(); - + paintNumberEllipse(number, 24, Qt::white, -1, -1, painter); } diff --git a/cockatrice/src/handcounter.h b/cockatrice/src/handcounter.h index af1cf3e4..b4e8b5a7 100644 --- a/cockatrice/src/handcounter.h +++ b/cockatrice/src/handcounter.h @@ -1,25 +1,34 @@ #ifndef HANDCOUNTER_H #define HANDCOUNTER_H -#include #include "abstractgraphicsitem.h" +#include class QPainter; class QPixmap; -class HandCounter : public AbstractGraphicsItem { +class HandCounter : public AbstractGraphicsItem +{ Q_OBJECT private: int number; + protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); public slots: void updateNumber(); signals: void showContextMenu(const QPoint &screenPos); + public: - enum { Type = typeOther }; - int type() const { return Type; } + enum + { + Type = typeOther + }; + int type() const + { + return Type; + } HandCounter(QGraphicsItem *parent = 0); ~HandCounter(); QRectF boundingRect() const; diff --git a/cockatrice/src/handzone.cpp b/cockatrice/src/handzone.cpp index a5b97548..e7d4e589 100644 --- a/cockatrice/src/handzone.cpp +++ b/cockatrice/src/handzone.cpp @@ -1,10 +1,10 @@ -#include #include "handzone.h" -#include "settingscache.h" -#include "thememanager.h" -#include "player.h" #include "carddragitem.h" #include "carditem.h" +#include "player.h" +#include "settingscache.h" +#include "thememanager.h" +#include #include "pb/command_move_card.pb.h" @@ -37,7 +37,7 @@ void HandZone::addCardImpl(CardItem *card, int x, int /*y*/) card->update(); } -void HandZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint & dropPoint) +void HandZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint) { QPoint point = dropPoint + scenePos().toPoint(); int x = -1; @@ -50,7 +50,7 @@ void HandZone::handleDropEvent(const QList &dragItems, CardZone if (point.y() < static_cast(cards.at(x))->scenePos().y()) break; } - + Command_MoveCard cmd; cmd.set_start_player_id(startZone->getPlayer()->getId()); cmd.set_start_zone(startZone->getName().toStdString()); @@ -58,10 +58,10 @@ void HandZone::handleDropEvent(const QList &dragItems, CardZone 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); } @@ -86,17 +86,19 @@ void HandZone::reorganizeCards() bool leftJustified = settingsCache->getLeftJustified(); qreal cardWidth = cards.at(0)->boundingRect().width(); const int xPadding = leftJustified ? cardWidth * 1.4 : 5; - qreal totalWidth = leftJustified? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding; - + qreal totalWidth = + leftJustified ? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding; + 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); + c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5); else { - qreal xPosition = leftJustified ? xPadding + ((qreal) i) * cardWidth : - xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2; + qreal xPosition = + leftJustified ? xPadding + ((qreal)i) * cardWidth + : xPadding + ((qreal)i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2; c->setPos(xPosition, 5); } c->setRealZValue(i); @@ -109,16 +111,16 @@ void HandZone::reorganizeCards() 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)); + c->setPos(x, ((qreal)i) * (totalHeight - cardHeight) / (cardCount - 1)); else - c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setPos(x, ((qreal)i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); c->setRealZValue(i); } } diff --git a/cockatrice/src/handzone.h b/cockatrice/src/handzone.h index 47fb5075..0e69970a 100644 --- a/cockatrice/src/handzone.h +++ b/cockatrice/src/handzone.h @@ -3,7 +3,8 @@ #include "selectzone.h" -class HandZone : public SelectZone { +class HandZone : public SelectZone +{ Q_OBJECT private: qreal width, zoneHeight; @@ -11,6 +12,7 @@ private slots: void updateBg(); public slots: void updateOrientation(); + public: HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0); void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); @@ -18,9 +20,9 @@ public: void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void reorganizeCards(); void setWidth(qreal _width); + protected: void addCardImpl(CardItem *card, int x, int y); }; #endif - diff --git a/cockatrice/src/keysignals.cpp b/cockatrice/src/keysignals.cpp index bbd94dbb..cfd42219 100644 --- a/cockatrice/src/keysignals.cpp +++ b/cockatrice/src/keysignals.cpp @@ -1,68 +1,64 @@ #include "keysignals.h" #include -bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event) { +bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event) +{ QKeyEvent *kevent; - if(event->type() != QEvent::KeyPress) + if (event->type() != QEvent::KeyPress) return false; kevent = static_cast(event); - switch(kevent->key()) { - case Qt::Key_Return: - case Qt::Key_Enter: - if (kevent->modifiers().testFlag(Qt::AltModifier) - && kevent->modifiers().testFlag(Qt::ControlModifier) ) - emit onCtrlAltEnter(); - else if (kevent->modifiers() & Qt::ControlModifier) - emit onCtrlEnter(); - else - emit onEnter(); + switch (kevent->key()) { + case Qt::Key_Return: + case Qt::Key_Enter: + if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) + emit onCtrlAltEnter(); + else if (kevent->modifiers() & Qt::ControlModifier) + emit onCtrlEnter(); + else + emit onEnter(); - break; - case Qt::Key_Right: - emit onRight(); + break; + case Qt::Key_Right: + emit onRight(); - break; - case Qt::Key_Left: - emit onLeft(); + break; + case Qt::Key_Left: + emit onLeft(); - break; - case Qt::Key_Delete: - case Qt::Key_Backspace: - emit onDelete(); + break; + case Qt::Key_Delete: + case Qt::Key_Backspace: + emit onDelete(); - break; - case Qt::Key_Minus: - if (kevent->modifiers().testFlag(Qt::AltModifier) - && kevent->modifiers().testFlag(Qt::ControlModifier) ) - emit onCtrlAltMinus(); + break; + case Qt::Key_Minus: + if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) + emit onCtrlAltMinus(); - break; - case Qt::Key_Equal: - if (kevent->modifiers().testFlag(Qt::AltModifier) - && kevent->modifiers().testFlag(Qt::ControlModifier) ) - emit onCtrlAltEqual(); + break; + case Qt::Key_Equal: + if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) + emit onCtrlAltEqual(); - break; - case Qt::Key_BracketLeft: - if (kevent->modifiers().testFlag(Qt::AltModifier) - && kevent->modifiers().testFlag(Qt::ControlModifier) ) - emit onCtrlAltLBracket(); + break; + case Qt::Key_BracketLeft: + if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) + emit onCtrlAltLBracket(); - break; - case Qt::Key_BracketRight: - if (kevent->modifiers().testFlag(Qt::AltModifier) - && kevent->modifiers().testFlag(Qt::ControlModifier) ) - emit onCtrlAltRBracket(); + break; + case Qt::Key_BracketRight: + if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) + emit onCtrlAltRBracket(); - break; - case Qt::Key_S: - emit onS(); + break; + case Qt::Key_S: + emit onS(); - break; - default: - return false; + break; + default: + return false; } return false; diff --git a/cockatrice/src/keysignals.h b/cockatrice/src/keysignals.h index 94c9dd39..8ae79d3c 100644 --- a/cockatrice/src/keysignals.h +++ b/cockatrice/src/keysignals.h @@ -1,10 +1,11 @@ #ifndef KEYSIGNALS_H #define KEYSIGNALS_H -#include #include +#include -class KeySignals : public QObject { +class KeySignals : public QObject +{ Q_OBJECT signals: diff --git a/cockatrice/src/lineeditcompleter.cpp b/cockatrice/src/lineeditcompleter.cpp index 76d05c25..b84e9d14 100644 --- a/cockatrice/src/lineeditcompleter.cpp +++ b/cockatrice/src/lineeditcompleter.cpp @@ -1,77 +1,76 @@ -#include -#include -#include -#include -#include +#include "lineeditcompleter.h" #include +#include +#include +#include +#include #include #include -#include -#include -#include "lineeditcompleter.h" +#include +#include -LineEditCompleter::LineEditCompleter(QWidget *parent) -: QLineEdit(parent) +LineEditCompleter::LineEditCompleter(QWidget *parent) : QLineEdit(parent) { } -void LineEditCompleter::focusOutEvent(QFocusEvent * e){ +void LineEditCompleter::focusOutEvent(QFocusEvent *e) +{ QLineEdit::focusOutEvent(e); - if (c->popup()->isVisible()){ - //Remove Popup + if (c->popup()->isVisible()) { + // Remove Popup c->popup()->hide(); - //Truncate the line to last space or whole string + // Truncate the line to last space or whole string QString textValue = text(); int lastIndex = textValue.length(); int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; int leftShift = qMin(lastIndex, lastWordStartIndex); setText(textValue.left(leftShift)); - //Insert highlighted line from popup + // Insert highlighted line from popup insert(c->completionModel()->index(c->popup()->currentIndex().row(), 0).data().toString() + " "); - //Set focus back to the textbox since tab was pressed + // Set focus back to the textbox since tab was pressed setFocus(); } } -void LineEditCompleter::keyPressEvent(QKeyEvent * event) +void LineEditCompleter::keyPressEvent(QKeyEvent *event) { - switch (event->key()){ - case Qt::Key_Return: - case Qt::Key_Enter: - case Qt::Key_Escape: - if (c->popup()->isVisible()){ - event->ignore(); - //Remove Popup - c->popup()->hide(); - //Truncate the line to last space or whole string - QString textValue = text(); - int lastIndexof = qMax(0, textValue.lastIndexOf(" ")); - QString finalString = textValue.left(lastIndexof); - //Add a space if there's a word - if (finalString != "") - finalString += " "; - setText(finalString); - return; - } - break; - case Qt::Key_Space: - if (c->popup()->isVisible()){ - event->ignore(); - //Remove Popup - c->popup()->hide(); - //Truncate the line to last space or whole string - QString textValue = text(); - int lastIndex = textValue.length(); - int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; - int leftShift = qMin(lastIndex, lastWordStartIndex); - setText(textValue.left(leftShift)); - //Insert highlighted line from popup - insert(c->completionModel()->index(c->popup()->currentIndex().row(), 0).data().toString() + " "); - return; - } - break; - default: - break; + switch (event->key()) { + case Qt::Key_Return: + case Qt::Key_Enter: + case Qt::Key_Escape: + if (c->popup()->isVisible()) { + event->ignore(); + // Remove Popup + c->popup()->hide(); + // Truncate the line to last space or whole string + QString textValue = text(); + int lastIndexof = qMax(0, textValue.lastIndexOf(" ")); + QString finalString = textValue.left(lastIndexof); + // Add a space if there's a word + if (finalString != "") + finalString += " "; + setText(finalString); + return; + } + break; + case Qt::Key_Space: + if (c->popup()->isVisible()) { + event->ignore(); + // Remove Popup + c->popup()->hide(); + // Truncate the line to last space or whole string + QString textValue = text(); + int lastIndex = textValue.length(); + int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; + int leftShift = qMin(lastIndex, lastWordStartIndex); + setText(textValue.left(leftShift)); + // Insert highlighted line from popup + insert(c->completionModel()->index(c->popup()->currentIndex().row(), 0).data().toString() + " "); + return; + } + break; + default: + break; } QLineEdit::keyPressEvent(event); @@ -82,20 +81,20 @@ void LineEditCompleter::keyPressEvent(QKeyEvent * event) return; } - //Set new completion prefix + // Set new completion prefix c->setCompletionPrefix(cursorWord(text())); - if (c->completionPrefix().length() < 1){ + if (c->completionPrefix().length() < 1) { c->popup()->hide(); return; } - //Draw completion box + // Draw completion box QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); - //Select first item in the completion popup - QItemSelectionModel* sm = new QItemSelectionModel(c->completionModel()); + // Select first item in the completion popup + QItemSelectionModel *sm = new QItemSelectionModel(c->completionModel()); c->popup()->setSelectionModel(sm); sm->select(c->completionModel()->index(0, 0), QItemSelectionModel::ClearAndSelect); sm->setCurrentIndex(c->completionModel()->index(0, 0), QItemSelectionModel::NoUpdate); @@ -104,17 +103,17 @@ void LineEditCompleter::keyPressEvent(QKeyEvent * event) QString LineEditCompleter::cursorWord(const QString &line) const { return line.mid(line.left(cursorPosition()).lastIndexOf(" ") + 1, - cursorPosition() - line.left(cursorPosition()).lastIndexOf(" ") - 1); + cursorPosition() - line.left(cursorPosition()).lastIndexOf(" ") - 1); } void LineEditCompleter::insertCompletion(QString arg) { QString s_arg = arg + " "; setText(text().replace(text().left(cursorPosition()).lastIndexOf(" ") + 1, - cursorPosition() - text().left(cursorPosition()).lastIndexOf(" ") - 1, s_arg)); + cursorPosition() - text().left(cursorPosition()).lastIndexOf(" ") - 1, s_arg)); } -void LineEditCompleter::setCompleter(QCompleter* completer) +void LineEditCompleter::setCompleter(QCompleter *completer) { c = completer; c->setWidget(this); @@ -127,7 +126,7 @@ void LineEditCompleter::setCompletionList(QStringList completionList) return; QStringListModel *model; - model = (QStringListModel*)(c->model()); + model = (QStringListModel *)(c->model()); if (model == NULL) model = new QStringListModel(); model->setStringList(completionList); diff --git a/cockatrice/src/lineeditcompleter.h b/cockatrice/src/lineeditcompleter.h index 673a78d2..cd020b68 100644 --- a/cockatrice/src/lineeditcompleter.h +++ b/cockatrice/src/lineeditcompleter.h @@ -1,25 +1,27 @@ #ifndef LINEEDITCOMPLETER_H #define LINEEDITCOMPLETER_H -#include -#include #include +#include +#include #include class LineEditCompleter : public QLineEdit { Q_OBJECT private: - QString cursorWord(const QString& line) const; - QCompleter* c; + QString cursorWord(const QString &line) const; + QCompleter *c; private slots: void insertCompletion(QString); + protected: - void keyPressEvent(QKeyEvent * event); - void focusOutEvent(QFocusEvent * e); + void keyPressEvent(QKeyEvent *event); + void focusOutEvent(QFocusEvent *e); + public: explicit LineEditCompleter(QWidget *parent = 0); - void setCompleter(QCompleter*); + void setCompleter(QCompleter *); void setCompletionList(QStringList); }; diff --git a/cockatrice/src/localclient.cpp b/cockatrice/src/localclient.cpp index 8dd15cd6..1f34c89f 100644 --- a/cockatrice/src/localclient.cpp +++ b/cockatrice/src/localclient.cpp @@ -3,16 +3,19 @@ #include "pb/session_commands.pb.h" -LocalClient::LocalClient(LocalServerInterface *_lsi, const QString &_playerName, const QString &_clientId, QObject *parent) +LocalClient::LocalClient(LocalServerInterface *_lsi, + const QString &_playerName, + const QString &_clientId, + QObject *parent) : AbstractClient(parent), lsi(_lsi) { connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &))); - + Command_Login loginCmd; loginCmd.set_user_name(_playerName.toStdString()); loginCmd.set_clientid(_clientId.toStdString()); sendCommand(prepareSessionCommand(loginCmd)); - + Command_JoinRoom joinCmd; joinCmd.set_room_id(0); sendCommand(prepareSessionCommand(joinCmd)); diff --git a/cockatrice/src/localclient.h b/cockatrice/src/localclient.h index c0769a60..b546695f 100644 --- a/cockatrice/src/localclient.h +++ b/cockatrice/src/localclient.h @@ -5,14 +5,16 @@ class LocalServerInterface; -class LocalClient : public AbstractClient { +class LocalClient : public AbstractClient +{ Q_OBJECT private: LocalServerInterface *lsi; + public: LocalClient(LocalServerInterface *_lsi, const QString &_playerName, const QString &_clientId, QObject *parent = 0); ~LocalClient(); - + void sendCommandContainer(const CommandContainer &cont); private slots: void itemFromServer(const ServerMessage &item); diff --git a/cockatrice/src/localserver.cpp b/cockatrice/src/localserver.cpp index 22fcfc1c..7cd5bf6c 100644 --- a/cockatrice/src/localserver.cpp +++ b/cockatrice/src/localserver.cpp @@ -2,8 +2,7 @@ #include "localserverinterface.h" #include "server_room.h" -LocalServer::LocalServer(QObject *parent) - : Server(parent) +LocalServer::LocalServer(QObject *parent) : Server(parent) { setDatabaseInterface(new LocalServer_DatabaseInterface(this)); addRoom(new Server_Room(0, 0, QString(), QString(), QString(), QString(), false, QString(), QStringList(), this)); @@ -37,7 +36,12 @@ ServerInfo_User LocalServer_DatabaseInterface::getUserData(const QString &name, return result; } -AuthenticationResult LocalServer_DatabaseInterface::checkUserPassword(Server_ProtocolHandler * /* handler */, const QString & /* user */, const QString & /* password */, const QString & /* clientId */, QString & /* reasonStr */, int & /* secondsLeft */) +AuthenticationResult LocalServer_DatabaseInterface::checkUserPassword(Server_ProtocolHandler * /* handler */, + const QString & /* user */, + const QString & /* password */, + const QString & /* clientId */, + QString & /* reasonStr */, + int & /* secondsLeft */) { return UnknownUser; } diff --git a/cockatrice/src/localserver.h b/cockatrice/src/localserver.h index abefb376..bf7b5a79 100644 --- a/cockatrice/src/localserver.h +++ b/cockatrice/src/localserver.h @@ -12,22 +12,39 @@ class LocalServer : public Server public: LocalServer(QObject *parent = 0); ~LocalServer(); - + LocalServerInterface *newConnection(); }; -class LocalServer_DatabaseInterface : public Server_DatabaseInterface { +class LocalServer_DatabaseInterface : public Server_DatabaseInterface +{ Q_OBJECT private: LocalServer *localServer; + protected: 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, const QString &clientId, QString &reasonStr, int &secondsLeft); - int getNextGameId() { return localServer->getNextLocalGameId(); } - int getNextReplayId() { return -1; } - int getActiveUserCount(QString /* connectionType */) { return 0; } + AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, + const QString &user, + const QString &password, + const QString &clientId, + QString &reasonStr, + int &secondsLeft); + int getNextGameId() + { + return localServer->getNextLocalGameId(); + } + int getNextReplayId() + { + return -1; + } + int getActiveUserCount(QString /* connectionType */) + { + return 0; + } }; #endif diff --git a/cockatrice/src/localserverinterface.h b/cockatrice/src/localserverinterface.h index 1d0edb65..46c82d68 100644 --- a/cockatrice/src/localserverinterface.h +++ b/cockatrice/src/localserverinterface.h @@ -11,9 +11,15 @@ class LocalServerInterface : public Server_ProtocolHandler public: LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface); ~LocalServerInterface(); - - QString getAddress() const { return QString(); } - QString getConnectionType() const { return "local"; }; + + QString getAddress() const + { + return QString(); + } + QString getConnectionType() const + { + return "local"; + }; void transmitProtocolItem(const ServerMessage &item); signals: void itemToClient(const ServerMessage &item); diff --git a/cockatrice/src/logger.cpp b/cockatrice/src/logger.cpp index d1380530..1ca0d526 100644 --- a/cockatrice/src/logger.cpp +++ b/cockatrice/src/logger.cpp @@ -7,7 +7,7 @@ #define LOGGER_FILENAME "qdebug.txt" #if QT_VERSION >= 0x050400 - #include +#include #endif Logger::Logger() : logToFileEnabled(false) @@ -26,12 +26,9 @@ Logger::~Logger() void Logger::logToFile(bool enabled) { - if (enabled) - { + if (enabled) { openLogfileSession(); - } - else - { + } else { closeLogfileSession(); } } @@ -43,8 +40,7 @@ QString Logger::getClientVersion() void Logger::openLogfileSession() { - if (logToFileEnabled) - { + if (logToFileEnabled) { return; } @@ -77,8 +73,7 @@ void Logger::internalLog(const QString message) QMutexLocker locker(&mutex); logBuffer.append(message); - if (logBuffer.size() > LOGGER_MAX_ENTRIES) - { + if (logBuffer.size() > LOGGER_MAX_ENTRIES) { logBuffer.removeAt(1); } @@ -93,8 +88,7 @@ QString Logger::getSystemArchitecture() { QString result; - if (!getClientOperatingSystem().isEmpty()) - { + if (!getClientOperatingSystem().isEmpty()) { result.append(tr("Client Operating System") + ": " + getClientOperatingSystem() + "\n"); } @@ -106,9 +100,9 @@ QString Logger::getSystemArchitecture() QString Logger::getClientOperatingSystem() { - #if QT_VERSION >= 0x050400 - return QSysInfo::prettyProductName(); - #endif +#if QT_VERSION >= 0x050400 + return QSysInfo::prettyProductName(); +#endif return {}; } diff --git a/cockatrice/src/logger.h b/cockatrice/src/logger.h index d2c5a3b3..8a257738 100644 --- a/cockatrice/src/logger.h +++ b/cockatrice/src/logger.h @@ -1,61 +1,64 @@ #ifndef LOGGER_H #define LOGGER_H -#include #include -#include -#include #include +#include +#include +#include #if defined(Q_PROCESSOR_X86_32) - #define BUILD_ARCHITECTURE "32-bit" +#define BUILD_ARCHITECTURE "32-bit" #elif defined(Q_PROCESSOR_X86_64) - #define BUILD_ARCHITECTURE "64-bit" +#define BUILD_ARCHITECTURE "64-bit" #elif defined(Q_PROCESSOR_ARM) - #define BUILD_ARCHITECTURE "ARM" +#define BUILD_ARCHITECTURE "ARM" #else - #define BUILD_ARCHITECTURE "unknown" +#define BUILD_ARCHITECTURE "unknown" #endif class Logger : public QObject { Q_OBJECT - public: - static Logger& getInstance() - { - static Logger instance; - return instance; - } +public: + static Logger &getInstance() + { + static Logger instance; + return instance; + } - void logToFile(bool enabled); - void log(QtMsgType type, const QMessageLogContext &ctx, const QString message); - QString getClientVersion(); - QString getClientOperatingSystem(); - QString getSystemArchitecture(); - QList getLogBuffer() { return logBuffer; } + void logToFile(bool enabled); + void log(QtMsgType type, const QMessageLogContext &ctx, const QString message); + QString getClientVersion(); + QString getClientOperatingSystem(); + QString getSystemArchitecture(); + QList getLogBuffer() + { + return logBuffer; + } - private: - Logger(); - ~Logger(); - // Singleton - Don't implement copy constructor and assign operator - Logger(Logger const&); - void operator=(Logger const&); +private: + Logger(); + ~Logger(); + // Singleton - Don't implement copy constructor and assign operator + Logger(Logger const &); + void operator=(Logger const &); - bool logToFileEnabled; - QTextStream fileStream; - QFile fileHandle; - QList logBuffer; - QMutex mutex; + bool logToFileEnabled; + QTextStream fileStream; + QFile fileHandle; + QList logBuffer; + QMutex mutex; - protected: - void openLogfileSession(); - void closeLogfileSession(); +protected: + void openLogfileSession(); + void closeLogfileSession(); - protected slots: - void internalLog(const QString message); +protected slots: + void internalLog(const QString message); - signals: - void logEntryAdded(QString message); +signals: + void logEntryAdded(QString message); }; #endif diff --git a/cockatrice/src/main.cpp b/cockatrice/src/main.cpp index 529fb5e2..3d1dc0c0 100644 --- a/cockatrice/src/main.cpp +++ b/cockatrice/src/main.cpp @@ -18,31 +18,31 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "QtNetwork/QNetworkInterface" -#include #include "main.h" -#include "window_main.h" -#include "dlg_settings.h" +#include "QtNetwork/QNetworkInterface" #include "carddatabase.h" -#include "settingscache.h" -#include "thememanager.h" -#include "pixmapgenerator.h" -#include "rng_sfmt.h" -#include "soundengine.h" +#include "dlg_settings.h" #include "featureset.h" #include "logger.h" +#include "pixmapgenerator.h" +#include "rng_sfmt.h" +#include "settingscache.h" +#include "soundengine.h" #include "spoilerbackgroundupdater.h" +#include "thememanager.h" +#include "window_main.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include CardDatabase *db; QTranslator *translator, *qtTranslator; @@ -55,7 +55,8 @@ ThemeManager *themeManager; const QString translationPrefix = "cockatrice"; QString translationPath; -static void CockatriceLogger(QtMsgType type, const QMessageLogContext &ctx, const QString &message) { +static void CockatriceLogger(QtMsgType type, const QMessageLogContext &ctx, const QString &message) +{ Logger::getInstance().log(type, ctx, message); } @@ -72,8 +73,7 @@ void installNewTranslator() QString const generateClientID() { QString macList; - foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()) - { + foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) { if (interface.hardwareAddress() != "") if (interface.hardwareAddress() != "00:00:00:00:00:00:00:E0") macList += interface.hardwareAddress() + "."; @@ -127,7 +127,7 @@ int main(int argc, char *argv[]) qDebug("main(): MainWindow constructor finished"); ui.setWindowIcon(QPixmap("theme:cockatrice")); - + settingsCache->setClientID(generateClientID()); // If spoiler mode is enabled, we will download the spoilers diff --git a/cockatrice/src/main.h b/cockatrice/src/main.h index e40d9f7b..d34e82b4 100644 --- a/cockatrice/src/main.h +++ b/cockatrice/src/main.h @@ -2,8 +2,9 @@ #define MAIN_H class CardDatabase; -class QTranslator; +class QString; class QSystemTrayIcon; +class QTranslator; class SoundEngine; extern CardDatabase *db; diff --git a/cockatrice/src/messagelogwidget.cpp b/cockatrice/src/messagelogwidget.cpp index e6bfd23e..06b0500d 100644 --- a/cockatrice/src/messagelogwidget.cpp +++ b/cockatrice/src/messagelogwidget.cpp @@ -1,11 +1,11 @@ #include "messagelogwidget.h" -#include "player.h" -#include "cardzone.h" #include "carditem.h" -#include "soundengine.h" -#include "pb/serverinfo_user.pb.h" +#include "cardzone.h" #include "pb/context_move_card.pb.h" #include "pb/context_mulligan.pb.h" +#include "pb/serverinfo_user.pb.h" +#include "player.h" +#include "soundengine.h" const QString MessageLogWidget::tableConstant() const { @@ -51,25 +51,16 @@ const QString MessageLogWidget::stackConstant() const 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); } -QPair MessageLogWidget::getFromStr( - CardZone *zone, - QString cardName, - int position, - bool ownerChange) const +QPair +MessageLogWidget::getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const { bool cardNameContainsStartZone = false; QString fromStr; @@ -159,46 +150,43 @@ void MessageLogWidget::logAlwaysRevealTopCard(Player *player, CardZone *zone, bo { appendHtmlServerMessage((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))); + .arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseTopCardsOfZone))); } void MessageLogWidget::logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName) { appendHtmlServerMessage(QString("%1 attaches %2 to %3's %4.") - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(cardName)) - .arg(sanitizeHtml(targetPlayer->getName())) - .arg(cardLink(targetCardName))); + .arg(sanitizeHtml(player->getName())) + .arg(cardLink(cardName)) + .arg(sanitizeHtml(targetPlayer->getName())) + .arg(cardLink(targetCardName))); } void MessageLogWidget::logConcede(Player *player) { soundEngine->playSound("player_concede"); - appendHtmlServerMessage(tr("%1 has conceded the game.") - .arg(sanitizeHtml(player->getName())), true); + appendHtmlServerMessage(tr("%1 has conceded the game.").arg(sanitizeHtml(player->getName())), true); } void MessageLogWidget::logConnectionStateChanged(Player *player, bool connectionState) { if (connectionState) { soundEngine->playSound("player_reconnect"); - appendHtmlServerMessage(tr("%1 has restored connection to the game.") - .arg(sanitizeHtml(player->getName())), true); + appendHtmlServerMessage(tr("%1 has restored connection to the game.").arg(sanitizeHtml(player->getName())), + true); } else { soundEngine->playSound("player_disconnect"); - appendHtmlServerMessage(tr("%1 has lost connection to the game.") - .arg(sanitizeHtml(player->getName())), true); + appendHtmlServerMessage(tr("%1 has lost connection to the game.").arg(sanitizeHtml(player->getName())), true); } } -void MessageLogWidget::logCreateArrow( - Player *player, - Player *startPlayer, - QString startCard, - Player *targetPlayer, - QString targetCard, - bool playerTarget) +void MessageLogWidget::logCreateArrow(Player *player, + Player *startPlayer, + QString startCard, + Player *targetPlayer, + QString targetCard, + bool playerTarget) { startCard = cardLink(startCard); targetCard = cardLink(targetCard); @@ -206,49 +194,45 @@ void MessageLogWidget::logCreateArrow( if (playerTarget) { if (player == startPlayer && player == targetPlayer) { str = tr("%1 points from their %2 to themselves."); - appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(startCard)); + appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())).arg(startCard)); } else if (player == startPlayer) { str = tr("%1 points from their %2 to %3."); - appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(startCard) - .arg(sanitizeHtml(targetPlayer->getName()))); + appendHtmlServerMessage( + str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); } else if (player == targetPlayer) { str = tr("%1 points from %2's %3 to themselves."); - appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(sanitizeHtml(startPlayer->getName())) - .arg(startCard)); + appendHtmlServerMessage( + str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard)); } else { str = tr("%1 points from %2's %3 to %4."); appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(sanitizeHtml(startPlayer->getName())) - .arg(startCard) - .arg(sanitizeHtml(targetPlayer->getName()))); + .arg(sanitizeHtml(startPlayer->getName())) + .arg(startCard) + .arg(sanitizeHtml(targetPlayer->getName()))); } } else { if (player == startPlayer && player == targetPlayer) { str = tr("%1 points from their %2 to their %3."); - appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(startCard).arg(targetCard)); + appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(targetCard)); } else if (player == startPlayer) { str = tr("%1 points from their %2 to %3's %4."); appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(startCard) - .arg(sanitizeHtml(targetPlayer->getName())) - .arg(targetCard)); + .arg(startCard) + .arg(sanitizeHtml(targetPlayer->getName())) + .arg(targetCard)); } else if (player == targetPlayer) { str = tr("%1 points from %2's %3 to their own %4."); appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(sanitizeHtml(startPlayer->getName())) - .arg(startCard) - .arg(targetCard)); + .arg(sanitizeHtml(startPlayer->getName())) + .arg(startCard) + .arg(targetCard)); } else { str = tr("%1 points from %2's %3 to %4's %5."); appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(sanitizeHtml(startPlayer->getName())) - .arg(startCard) - .arg(sanitizeHtml(targetPlayer->getName())) - .arg(targetCard)); + .arg(sanitizeHtml(startPlayer->getName())) + .arg(startCard) + .arg(sanitizeHtml(targetPlayer->getName())) + .arg(targetCard)); } } } @@ -256,30 +240,25 @@ void MessageLogWidget::logCreateArrow( void MessageLogWidget::logCreateToken(Player *player, QString cardName, QString pt) { appendHtmlServerMessage(tr("%1 creates token: %2%3.") - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(cardName)) - .arg(pt.isEmpty() ? QString() : QString(" (%1)") - .arg(sanitizeHtml(pt)))); + .arg(sanitizeHtml(player->getName())) + .arg(cardLink(cardName)) + .arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); } void MessageLogWidget::logDeckSelect(Player *player, QString deckHash, int sideboardSize) { if (sideboardSize < 0) - appendHtmlServerMessage(tr("%1 has loaded a deck (%2).") - .arg(sanitizeHtml(player->getName())) - .arg(deckHash)); + appendHtmlServerMessage(tr("%1 has loaded a deck (%2).").arg(sanitizeHtml(player->getName())).arg(deckHash)); else appendHtmlServerMessage(tr("%1 has loaded a deck with %2 sideboard cards (%3).") - .arg(sanitizeHtml(player->getName())) - .arg("" + QString::number(sideboardSize) + "") - .arg(deckHash)); + .arg(sanitizeHtml(player->getName())) + .arg("" + QString::number(sideboardSize) + "") + .arg(deckHash)); } void MessageLogWidget::logDestroyCard(Player *player, QString cardName) { - appendHtmlServerMessage(tr("%1 destroys %2.") - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(cardName))); + appendHtmlServerMessage(tr("%1 destroys %2.").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); } void MessageLogWidget::logDoMoveCard(LogMoveCard &lmc) @@ -289,9 +268,9 @@ void MessageLogWidget::logDoMoveCard(LogMoveCard &lmc) bool ownerChanged = lmc.startZone->getPlayer() != lmc.targetZone->getPlayer(); // do not log if moved within the same zone - if ((startZone == tableConstant() && targetZone == tableConstant() && !ownerChanged) - || (startZone == handConstant() && targetZone == handConstant()) - || (startZone == exileConstant() && targetZone == exileConstant())) + if ((startZone == tableConstant() && targetZone == tableConstant() && !ownerChanged) || + (startZone == handConstant() && targetZone == handConstant()) || + (startZone == exileConstant() && targetZone == exileConstant())) return; QString cardName = lmc.cardName; @@ -308,11 +287,10 @@ void MessageLogWidget::logDoMoveCard(LogMoveCard &lmc) cardStr = cardLink(cardName); if (ownerChanged && (lmc.startZone->getPlayer() == lmc.player)) { - appendHtmlServerMessage( - tr("%1 gives %2 control over %3.") - .arg(sanitizeHtml(lmc.player->getName())) - .arg(sanitizeHtml(lmc.targetZone->getPlayer()->getName())) - .arg(cardStr)); + appendHtmlServerMessage(tr("%1 gives %2 control over %3.") + .arg(sanitizeHtml(lmc.player->getName())) + .arg(sanitizeHtml(lmc.targetZone->getPlayer()->getName())) + .arg(cardStr)); return; } @@ -351,17 +329,10 @@ void MessageLogWidget::logDoMoveCard(LogMoveCard &lmc) if (usesNewX) { appendHtmlServerMessage( - finalStr.arg(sanitizeHtml(lmc.player->getName())) - .arg(cardStr) - .arg(nameFrom.second) - .arg(lmc.newX)); + finalStr.arg(sanitizeHtml(lmc.player->getName())).arg(cardStr).arg(nameFrom.second).arg(lmc.newX)); } else { - appendHtmlServerMessage( - finalStr.arg(sanitizeHtml(lmc.player->getName())) - .arg(cardStr) - .arg(nameFrom.second)); + appendHtmlServerMessage(finalStr.arg(sanitizeHtml(lmc.player->getName())).arg(cardStr).arg(nameFrom.second)); } - } void MessageLogWidget::logDrawCards(Player *player, int number) @@ -371,8 +342,8 @@ void MessageLogWidget::logDrawCards(Player *player, int number) else { soundEngine->playSound("draw_card"); appendHtmlServerMessage(tr("%1 draws %2 card(s).") - .arg(sanitizeHtml(player->getName())) - .arg("" + QString::number(number) + "")); + .arg(sanitizeHtml(player->getName())) + .arg("" + QString::number(number) + "")); } } @@ -380,25 +351,21 @@ void MessageLogWidget::logDumpZone(Player *player, CardZone *zone, int numberCar { if (numberCards == -1) appendHtmlServerMessage(tr("%1 is looking at %2.") - .arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); + .arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); else appendHtmlServerMessage(tr("%1 is looking at the top %2 card(s) %3.") - .arg(sanitizeHtml(player->getName())) - .arg("" + QString::number(numberCards) + "") - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseTopCardsOfZone))); + .arg(sanitizeHtml(player->getName())) + .arg("" + QString::number(numberCards) + "") + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseTopCardsOfZone))); } void MessageLogWidget::logFlipCard(Player *player, QString cardName, bool faceDown) { if (faceDown) { - appendHtmlServerMessage(tr("%1 flips %2 face-down.") - .arg(sanitizeHtml(player->getName())) - .arg(cardName)); + appendHtmlServerMessage(tr("%1 flips %2 face-down.").arg(sanitizeHtml(player->getName())).arg(cardName)); } else { - appendHtmlServerMessage(tr("%1 flips %2 face-up.") - .arg(sanitizeHtml(player->getName())) - .arg(cardName)); + appendHtmlServerMessage(tr("%1 flips %2 face-up.").arg(sanitizeHtml(player->getName())).arg(cardName)); } } @@ -415,15 +382,13 @@ void MessageLogWidget::logGameStart() void MessageLogWidget::logJoin(Player *player) { soundEngine->playSound("player_join"); - appendHtmlServerMessage(tr("%1 has joined the game.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 has joined the game.").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logJoinSpectator(QString name) { soundEngine->playSound("spectator_join"); - appendHtmlServerMessage(tr("%1 is now watching the game.") - .arg(sanitizeHtml(name))); + appendHtmlServerMessage(tr("%1 is now watching the game.").arg(sanitizeHtml(name))); } void MessageLogWidget::logKicked() @@ -434,30 +399,28 @@ void MessageLogWidget::logKicked() void MessageLogWidget::logLeave(Player *player, QString reason) { soundEngine->playSound("player_leave"); - appendHtmlServerMessage(tr("%1 has left the game (%2).") - .arg(sanitizeHtml(player->getName()), sanitizeHtml(reason)), true); + appendHtmlServerMessage(tr("%1 has left the game (%2).").arg(sanitizeHtml(player->getName()), sanitizeHtml(reason)), + true); } void MessageLogWidget::logLeaveSpectator(QString name, QString reason) { soundEngine->playSound("spectator_leave"); - appendHtmlServerMessage(tr("%1 is not watching the game any more (%2).") - .arg(sanitizeHtml(name), sanitizeHtml(reason))); + appendHtmlServerMessage( + tr("%1 is not watching the game any more (%2).").arg(sanitizeHtml(name), sanitizeHtml(reason))); } void MessageLogWidget::logNotReadyStart(Player *player) { - appendHtmlServerMessage(tr("%1 is not ready to start the game any more.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 is not ready to start the game any more.").arg(sanitizeHtml(player->getName()))); } -void MessageLogWidget::logMoveCard( - Player *player, - CardItem *card, - CardZone *startZone, - int oldX, - CardZone *targetZone, - int 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) @@ -473,32 +436,27 @@ void MessageLogWidget::logMulligan(Player *player, int number) if (!player) return; if (number > -1) - appendHtmlServerMessage(tr("%1 takes a mulligan to %2.") - .arg(sanitizeHtml(player->getName())) - .arg(number)); + appendHtmlServerMessage(tr("%1 takes a mulligan to %2.").arg(sanitizeHtml(player->getName())).arg(number)); else - appendHtmlServerMessage(tr("%1 draws their initial hand.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 draws their initial hand.").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logReplayStarted(int gameId) { - appendHtmlServerMessage(tr("You are watching a replay of game #%1.").arg(gameId)); + appendHtmlServerMessage(tr("You are watching a replay of game #%1.").arg(gameId)); } void MessageLogWidget::logReadyStart(Player *player) { - appendHtmlServerMessage(tr("%1 is ready to start the game.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 is ready to start the game.").arg(sanitizeHtml(player->getName()))); } -void MessageLogWidget::logRevealCards( - Player *player, - CardZone *zone, - int cardId, - QString cardName, - Player *otherPlayer, - bool faceDown) +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; @@ -519,47 +477,42 @@ void MessageLogWidget::logRevealCards( if (cardId == -1) { if (otherPlayer) appendHtmlServerMessage(tr("%1 reveals %2 to %3.") - .arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseRevealZone)) - .arg(sanitizeHtml(otherPlayer->getName()))); + .arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseRevealZone)) + .arg(sanitizeHtml(otherPlayer->getName()))); else appendHtmlServerMessage(tr("%1 reveals %2.") - .arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseRevealZone))); + .arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseRevealZone))); } else if (cardId == -2) { if (otherPlayer) appendHtmlServerMessage(tr("%1 randomly reveals %2%3 to %4.") - .arg(sanitizeHtml(player->getName())) - .arg(cardStr) - .arg(fromStr) - .arg(sanitizeHtml(otherPlayer->getName()))); + .arg(sanitizeHtml(player->getName())) + .arg(cardStr) + .arg(fromStr) + .arg(sanitizeHtml(otherPlayer->getName()))); else - appendHtmlServerMessage(tr("%1 randomly reveals %2%3.") - .arg(sanitizeHtml(player->getName())) - .arg(cardStr) - .arg(fromStr)); + appendHtmlServerMessage( + tr("%1 randomly reveals %2%3.").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); } else { if (faceDown && player == otherPlayer) { if (cardName.isEmpty()) - appendHtmlServerMessage(tr("%1 peeks at face down card #%2.") - .arg(sanitizeHtml(player->getName())) - .arg(cardId)); + appendHtmlServerMessage( + tr("%1 peeks at face down card #%2.").arg(sanitizeHtml(player->getName())).arg(cardId)); else appendHtmlServerMessage(tr("%1 peeks at face down card #%2: %3.") - .arg(sanitizeHtml(player->getName())) - .arg(cardId) - .arg(cardStr)); + .arg(sanitizeHtml(player->getName())) + .arg(cardId) + .arg(cardStr)); } else if (otherPlayer) appendHtmlServerMessage(tr("%1 reveals %2%3 to %4.") - .arg(sanitizeHtml(player->getName())) - .arg(cardStr) - .arg(fromStr) - .arg(sanitizeHtml(otherPlayer->getName()))); + .arg(sanitizeHtml(player->getName())) + .arg(cardStr) + .arg(fromStr) + .arg(sanitizeHtml(otherPlayer->getName()))); else - appendHtmlServerMessage(tr("%1 reveals %2%3.") - .arg(sanitizeHtml(player->getName())) - .arg(cardStr) - .arg(fromStr)); + appendHtmlServerMessage( + tr("%1 reveals %2%3.").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); } } @@ -568,23 +521,19 @@ void MessageLogWidget::logRollDie(Player *player, int sides, int roll) if (sides == 2) { QString coinOptions[2] = {tr("Heads") + " (1)", tr("Tails") + " (2)"}; appendHtmlServerMessage(tr("%1 flipped a coin. It landed as %2.") - .arg(sanitizeHtml(player->getName())) - .arg("" + coinOptions[roll - 1] + "")); - } - else + .arg(sanitizeHtml(player->getName())) + .arg("" + coinOptions[roll - 1] + "")); + } else appendHtmlServerMessage(tr("%1 rolls a %2 with a %3-sided die.") - .arg(sanitizeHtml(player->getName())) - .arg("" + QString::number(roll) + "") - .arg("" + QString::number(sides) + "")); + .arg(sanitizeHtml(player->getName())) + .arg("" + QString::number(roll) + "") + .arg("" + QString::number(sides) + "")); soundEngine->playSound("roll_dice"); } void MessageLogWidget::logSay(Player *player, QString message) { - appendMessage(message, - 0, - player->getName(), - UserLevelFlags(player->getUserInfo()->user_level()), + appendMessage(message, 0, player->getName(), UserLevelFlags(player->getUserInfo()->user_level()), QString::fromStdString(player->getUserInfo()->privlevel()), true); } @@ -611,37 +560,37 @@ void MessageLogWidget::logSetActivePhase(int phase) case 3: phaseName = tr("First Main"); soundEngine->playSound("main_1"); - color="blue"; + color = "blue"; break; case 4: phaseName = tr("Beginning of Combat"); soundEngine->playSound("start_combat"); - color="red"; + color = "red"; break; case 5: phaseName = tr("Declare Attackers"); soundEngine->playSound("attack_step"); - color="red"; + color = "red"; break; case 6: phaseName = tr("Declare Blockers"); soundEngine->playSound("block_step"); - color="red"; + color = "red"; break; case 7: phaseName = tr("Combat Damage"); soundEngine->playSound("damage_step"); - color="red"; + color = "red"; break; case 8: phaseName = tr("End of Combat"); soundEngine->playSound("end_combat"); - color="red"; + color = "red"; break; case 9: phaseName = tr("Second Main"); soundEngine->playSound("main_2"); - color="blue"; + color = "blue"; break; case 10: phaseName = tr("End/Cleanup"); @@ -653,27 +602,23 @@ void MessageLogWidget::logSetActivePhase(int phase) color = "black"; break; } - appendHtml("" - + QDateTime::currentDateTime().toString("[hh:mm:ss] ") - + QString("%1").arg(phaseName) - + ""); + appendHtml("" + QDateTime::currentDateTime().toString("[hh:mm:ss] ") + + QString("%1").arg(phaseName) + ""); } void MessageLogWidget::logSetActivePlayer(Player *player) { - appendHtml("
" - + QDateTime::currentDateTime().toString("[hh:mm:ss] ") - + QString(tr("%1's turn.")).arg(player->getName()) - + "
"); + appendHtml("
" + QDateTime::currentDateTime().toString("[hh:mm:ss] ") + + QString(tr("%1's turn.")).arg(player->getName()) + "
"); } void MessageLogWidget::logSetAnnotation(Player *player, CardItem *card, QString newAnnotation) { - appendHtmlServerMessage(QString(tr("%1 sets annotation of %2 to %3.")) - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(card->getName())) - .arg(QString(""%1"") - .arg(sanitizeHtml(newAnnotation)))); + appendHtmlServerMessage( + QString(tr("%1 sets annotation of %2 to %3.")) + .arg(sanitizeHtml(player->getName())) + .arg(cardLink(card->getName())) + .arg(QString(""%1"").arg(sanitizeHtml(newAnnotation)))); } void MessageLogWidget::logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue) @@ -696,14 +641,14 @@ void MessageLogWidget::logSetCardCounter(Player *player, QString cardName, int c case 2: colorStr = tr("green", "", delta); break; - default: ; + default:; } appendHtmlServerMessage(finalStr.arg(sanitizeHtml(player->getName())) - .arg("" + QString::number(delta) + "") - .arg(colorStr) - .arg(cardLink(cardName)) - .arg(value)); + .arg("" + QString::number(delta) + "") + .arg(colorStr) + .arg(cardLink(cardName)) + .arg(value)); } void MessageLogWidget::logSetCounter(Player *player, QString counterName, int value, int oldValue) @@ -712,13 +657,11 @@ void MessageLogWidget::logSetCounter(Player *player, QString counterName, int va soundEngine->playSound("life_change"); appendHtmlServerMessage(tr("%1 sets counter %2 to %3 (%4%5).") - .arg(sanitizeHtml(player->getName())) - .arg(QString("%1") - .arg(sanitizeHtml(counterName))) - .arg(QString("%1") - .arg(value)) - .arg(value > oldValue ? "+" : "") - .arg(value - oldValue)); + .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) @@ -728,8 +671,7 @@ void MessageLogWidget::logSetDoesntUntap(Player *player, CardItem *card, bool do str = tr("%1 sets %2 to not untap normally."); else str = tr("%1 sets %2 to untap normally."); - appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())) - .arg(cardLink(card->getName()))); + appendHtmlServerMessage(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); } void MessageLogWidget::logSetPT(Player *player, CardItem *card, QString newPT) @@ -738,20 +680,17 @@ void MessageLogWidget::logSetPT(Player *player, CardItem *card, QString newPT) moveCardPT.insert(card, newPT); else appendHtmlServerMessage(tr("%1 sets PT of %2 to %3.") - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(card->getName())) - .arg(QString("%1") - .arg(sanitizeHtml(newPT)))); + .arg(sanitizeHtml(player->getName())) + .arg(cardLink(card->getName())) + .arg(QString("%1").arg(sanitizeHtml(newPT)))); } void MessageLogWidget::logSetSideboardLock(Player *player, bool locked) { if (locked) - appendHtmlServerMessage(tr("%1 has locked their sideboard.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 has locked their sideboard.").arg(sanitizeHtml(player->getName()))); else - appendHtmlServerMessage(tr("%1 has unlocked their sideboard.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 has unlocked their sideboard.").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logSetTapped(Player *player, CardItem *card, bool tapped) @@ -766,14 +705,12 @@ void MessageLogWidget::logSetTapped(Player *player, CardItem *card, bool tapped) else { QString str; if (!card) - appendHtmlServerMessage((tapped ? tr("%1 taps their permanents.") - : tr("%1 untaps their permanents.")) - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage((tapped ? tr("%1 taps their permanents.") : tr("%1 untaps their permanents.")) + .arg(sanitizeHtml(player->getName()))); else - appendHtmlServerMessage((tapped ? tr("%1 taps %2.") - : tr("%1 untaps %2.")) - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(card->getName()))); + appendHtmlServerMessage((tapped ? tr("%1 taps %2.") : tr("%1 untaps %2.")) + .arg(sanitizeHtml(player->getName())) + .arg(cardLink(card->getName()))); } } @@ -782,14 +719,14 @@ void MessageLogWidget::logShuffle(Player *player, CardZone *zone) soundEngine->playSound("shuffle"); if (currentContext != MessageContext_Mulligan) appendHtmlServerMessage(tr("%1 shuffles %2.") - .arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseShuffleZone))); + .arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseShuffleZone))); } void MessageLogWidget::logSpectatorSay(QString spectatorName, - UserLevelFlags spectatorUserLevel, - QString userPrivLevel, - QString message) + UserLevelFlags spectatorUserLevel, + QString userPrivLevel, + QString message) { appendMessage(message, 0, spectatorName, spectatorUserLevel, userPrivLevel, false); } @@ -797,79 +734,68 @@ void MessageLogWidget::logSpectatorSay(QString spectatorName, void MessageLogWidget::logStopDumpZone(Player *player, CardZone *zone) { appendHtmlServerMessage(tr("%1 stops looking at %2.") - .arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); + .arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); } void MessageLogWidget::logUnattachCard(Player *player, QString cardName) { - appendHtmlServerMessage(tr("%1 unattaches %2.") - .arg(sanitizeHtml(player->getName())) - .arg(cardLink(cardName))); + appendHtmlServerMessage(tr("%1 unattaches %2.").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); } void MessageLogWidget::logUndoDraw(Player *player, QString cardName) { if (cardName.isEmpty()) - appendHtmlServerMessage(tr("%1 undoes their last draw.") - .arg(sanitizeHtml(player->getName()))); + appendHtmlServerMessage(tr("%1 undoes their last draw.").arg(sanitizeHtml(player->getName()))); else - appendHtmlServerMessage(tr("%1 undoes their last draw (%2).") - .arg(sanitizeHtml(player->getName())) - .arg(QString("%2") - .arg(sanitizeHtml(cardName)) - .arg(sanitizeHtml(cardName)))); + appendHtmlServerMessage( + tr("%1 undoes their last draw (%2).") + .arg(sanitizeHtml(player->getName())) + .arg(QString("%2").arg(sanitizeHtml(cardName)).arg(sanitizeHtml(cardName)))); } 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, const UserlistProxy *_userlistProxy, TabGame *_game, QWidget *parent) +MessageLogWidget::MessageLogWidget(const TabSupervisor *_tabSupervisor, + const UserlistProxy *_userlistProxy, + TabGame *_game, + QWidget *parent) : ChatView(_tabSupervisor, _userlistProxy, _game, true, parent), currentContext(MessageContext_None) { } diff --git a/cockatrice/src/messagelogwidget.h b/cockatrice/src/messagelogwidget.h index 645cb864..2f6e5a02 100644 --- a/cockatrice/src/messagelogwidget.h +++ b/cockatrice/src/messagelogwidget.h @@ -10,7 +10,8 @@ class CardZone; class GameEventContext; class CardItem; -struct LogMoveCard { +struct LogMoveCard +{ Player *player; CardItem *card; QString cardName; @@ -20,10 +21,12 @@ struct LogMoveCard { int newX; }; -class MessageLogWidget : public ChatView { +class MessageLogWidget : public ChatView +{ Q_OBJECT private: - enum MessageContext { + enum MessageContext + { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan @@ -55,7 +58,12 @@ public slots: void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); void logConcede(Player *player); void logConnectionStateChanged(Player *player, bool connectionState); - void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget); + void logCreateArrow(Player *player, + Player *startPlayer, + QString startCard, + Player *targetPlayer, + QString targetCard, + bool playerTarget); void logCreateToken(Player *player, QString cardName, QString pt); void logDeckSelect(Player *player, QString deckHash, int sideboardSize); void logDestroyCard(Player *player, QString cardName); @@ -75,7 +83,8 @@ public slots: void logMulligan(Player *player, int number); void logReplayStarted(int gameId); void logReadyStart(Player *player); - void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); + void + logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); void logRollDie(Player *player, int sides, int roll); void logSay(Player *player, QString message); void logSetActivePhase(int phase); @@ -88,14 +97,18 @@ public slots: void logSetSideboardLock(Player *player, bool locked); void logSetTapped(Player *player, CardItem *card, bool tapped); void logShuffle(Player *player, CardZone *zone); - void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString userPrivLevel, QString message); + void + logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString userPrivLevel, QString message); void logStopDumpZone(Player *player, CardZone *zone); void logUnattachCard(Player *player, QString cardName); void logUndoDraw(Player *player, QString cardName); public: void connectToPlayer(Player *player); - MessageLogWidget(const TabSupervisor *_tabSupervisor, const UserlistProxy *_userlistProxy, TabGame *_game, QWidget *parent = 0); + MessageLogWidget(const TabSupervisor *_tabSupervisor, + const UserlistProxy *_userlistProxy, + TabGame *_game, + QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/pending_command.cpp b/cockatrice/src/pending_command.cpp index 0ebb1d82..e6a1761b 100644 --- a/cockatrice/src/pending_command.cpp +++ b/cockatrice/src/pending_command.cpp @@ -3,19 +3,20 @@ PendingCommand::PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData) : commandContainer(_commandContainer), extraData(_extraData), ticks(0) { - } -CommandContainer & PendingCommand::getCommandContainer() +CommandContainer &PendingCommand::getCommandContainer() { return commandContainer; } -void PendingCommand::setExtraData(const QVariant &_extraData) { +void PendingCommand::setExtraData(const QVariant &_extraData) +{ extraData = _extraData; } -QVariant PendingCommand::getExtraData() const { +QVariant PendingCommand::getExtraData() const +{ return extraData; } diff --git a/cockatrice/src/pending_command.h b/cockatrice/src/pending_command.h index 4ca9035b..8b6d3cd6 100644 --- a/cockatrice/src/pending_command.h +++ b/cockatrice/src/pending_command.h @@ -5,15 +5,18 @@ #include "pb/response.pb.h" #include -class PendingCommand : public QObject { +class PendingCommand : public QObject +{ Q_OBJECT signals: void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData); void finished(Response::ResponseCode respCode); + private: CommandContainer commandContainer; QVariant extraData; int ticks; + public: PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()); CommandContainer &getCommandContainer(); @@ -23,4 +26,4 @@ public: int tick(); }; -#endif +#endif diff --git a/cockatrice/src/phasestoolbar.cpp b/cockatrice/src/phasestoolbar.cpp index 35265ba8..ec3a78b9 100644 --- a/cockatrice/src/phasestoolbar.cpp +++ b/cockatrice/src/phasestoolbar.cpp @@ -1,8 +1,8 @@ #include +#include #include #include #include -#include #include #ifdef _WIN32 #include "round.h" @@ -10,13 +10,14 @@ #include "phasestoolbar.h" #include "pixmapgenerator.h" -#include "pb/command_set_active_phase.pb.h" -#include "pb/command_next_turn.pb.h" -#include "pb/command_set_card_attr.pb.h" #include "pb/command_draw_cards.pb.h" +#include "pb/command_next_turn.pb.h" +#include "pb/command_set_active_phase.pb.h" +#include "pb/command_set_card_attr.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); @@ -24,7 +25,7 @@ PhaseButton::PhaseButton(const QString &_name, QGraphicsItem *parent, QAction *_ activeAnimationTimer->setSingleShot(false); } else activeAnimationCounter = 9.0; - + setCacheMode(DeviceCoordinateCache); } @@ -39,15 +40,17 @@ void PhaseButton::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*op 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->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->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); @@ -63,7 +66,7 @@ void PhaseButton::setActive(bool _active) { if ((active == _active) || !highlightable) return; - + active = _active; activeAnimationTimer->start(25); } @@ -72,7 +75,7 @@ void PhaseButton::updateAnimation() { if (!highlightable) return; - + if (active) { if (++activeAnimationCounter >= 10) activeAnimationTimer->stop(); @@ -106,7 +109,7 @@ PhasesToolbar::PhasesToolbar(QGraphicsItem *parent) 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); @@ -118,19 +121,18 @@ PhasesToolbar::PhasesToolbar(QGraphicsItem *parent) 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; - + + 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(); } @@ -148,18 +150,30 @@ void PhasesToolbar::retranslateUi() 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(); + 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(); } } @@ -175,7 +189,7 @@ 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); @@ -200,12 +214,12 @@ void PhasesToolbar::rearrangeButtons() void PhasesToolbar::setHeight(double _height) { prepareGeometryChange(); - + height = _height; ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount); symbolSize = ySpacing * 5; width = symbolSize + 2 * marginSize; - + rearrangeButtons(); } @@ -213,7 +227,7 @@ void PhasesToolbar::setActivePhase(int phase) { if (phase >= buttonList.size()) return; - + for (int i = 0; i < buttonList.size(); ++i) buttonList[i]->setActive(i == phase); } @@ -223,10 +237,10 @@ 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); } @@ -241,7 +255,7 @@ void PhasesToolbar::actUntapAll() cmd.set_zone("table"); cmd.set_attribute(AttrTapped); cmd.set_attr_value("0"); - + emit sendGameCommand(cmd, -1); } @@ -249,6 +263,6 @@ void PhasesToolbar::actDrawCard() { Command_DrawCards cmd; cmd.set_number(1); - + emit sendGameCommand(cmd, -1); } diff --git a/cockatrice/src/phasestoolbar.h b/cockatrice/src/phasestoolbar.h index a91b020c..baa6ad91 100644 --- a/cockatrice/src/phasestoolbar.h +++ b/cockatrice/src/phasestoolbar.h @@ -2,14 +2,21 @@ #define PHASESTOOLBAR_H #include -#include #include +#include -namespace google { namespace protobuf { class Message; } } +namespace google +{ +namespace protobuf +{ +class Message; +} +} // namespace google class Player; class GameCommand; -class PhaseButton : public QObject, public QGraphicsItem { +class PhaseButton : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) private: @@ -19,26 +26,35 @@ private: QTimer *activeAnimationTimer; QAction *doubleClickAction; double width; - + void updatePixmap(QPixmap &pixmap); private slots: void updateAnimation(); + public: - PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true); + 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; } + bool getActive() const + { + return active; + } void triggerDoubleClickAction(); signals: void clicked(); + protected: void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); }; -class PhasesToolbar : public QObject, public QGraphicsItem { +class PhasesToolbar : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) private: @@ -49,13 +65,20 @@ private: 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(); } + double getWidth() const + { + return width; + } + int phaseCount() const + { + return buttonList.size(); + } QString getLongPhaseName(int phase) const; public slots: void setActivePhase(int phase); @@ -66,6 +89,7 @@ private slots: void actDrawCard(); signals: void sendGameCommand(const ::google::protobuf::Message &command, int playerId); + protected: void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); }; diff --git a/cockatrice/src/pictureloader.cpp b/cockatrice/src/pictureloader.cpp index 931a53cf..19f4deb5 100644 --- a/cockatrice/src/pictureloader.cpp +++ b/cockatrice/src/pictureloader.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -19,12 +20,12 @@ #include #include #include -#include // never cache more than 300 cards at once for a single deck #define CACHED_CARD_PER_DECK_MAX 300 -class PictureToLoad::SetDownloadPriorityComparator { +class PictureToLoad::SetDownloadPriorityComparator +{ public: /* * Returns true if a has higher download priority than b @@ -33,10 +34,8 @@ public: */ inline bool operator()(CardSet *a, CardSet *b) const { - if(a->getEnabled()) - { - if(b->getEnabled()) - { + if (a->getEnabled()) { + if (b->getEnabled()) { // both enabled: sort by key return a->getSortKey() < b->getSortKey(); } else { @@ -44,8 +43,7 @@ public: return true; } } else { - if(b->getEnabled()) - { + if (b->getEnabled()) { // only b enabled return false; } else { @@ -56,8 +54,7 @@ public: } }; -PictureToLoad::PictureToLoad(CardInfo *_card) - : card(_card), setIndex(0) +PictureToLoad::PictureToLoad(CardInfo *_card) : card(_card), setIndex(0) { if (card) { sortedSets = card->getSets(); @@ -89,12 +86,10 @@ CardSet *PictureToLoad::getCurrentSet() const return 0; } -QStringList PictureLoaderWorker::md5Blacklist = QStringList() - << "db0c48db407a907c16ade38de048a441"; // card back returned by gatherer when card is not found +QStringList PictureLoaderWorker::md5Blacklist = + QStringList() << "db0c48db407a907c16ade38de048a441"; // card back returned by gatherer when card is not found -PictureLoaderWorker::PictureLoaderWorker() - : QObject(0), - downloadRunning(false), loadQueueRunning(false) +PictureLoaderWorker::PictureLoaderWorker() : QObject(0), downloadRunning(false), loadQueueRunning(false) { picsPath = settingsCache->getPicsPath(); customPicsPath = settingsCache->getCustomPicsPath(); @@ -123,7 +118,8 @@ void PictureLoaderWorker::processLoadQueue() return; loadQueueRunning = true; - forever { + forever + { mutex.lock(); if (loadQueue.isEmpty()) { mutex.unlock(); @@ -138,32 +134,33 @@ void PictureLoaderWorker::processLoadQueue() QString correctedCardName = cardBeingLoaded.getCard()->getCorrectedName(); qDebug() << "Trying to load picture (set: " << setName << " card: " << cardName << ")"; - if(cardImageExistsOnDisk(setName, correctedCardName)) + if (cardImageExistsOnDisk(setName, correctedCardName)) continue; if (picDownload) { qDebug() << "Picture NOT found, trying to download (set: " << setName << " card: " << cardName << ")"; cardsToDownload.append(cardBeingLoaded); - cardBeingLoaded=0; + cardBeingLoaded = 0; if (!downloadRunning) startNextPicDownload(); } else { - if (cardBeingLoaded.nextSet()) - { - qDebug() << "Picture NOT found and download disabled, moving to next set (newset: " << setName << " card: " << cardName << ")"; + if (cardBeingLoaded.nextSet()) { + qDebug() << "Picture NOT found and download disabled, moving to next set (newset: " << setName + << " card: " << cardName << ")"; mutex.lock(); loadQueue.prepend(cardBeingLoaded); - cardBeingLoaded=0; + cardBeingLoaded = 0; mutex.unlock(); } else { - qDebug() << "Picture NOT found, download disabled, no more sets to try: BAILING OUT (oldset: " << setName << " card: " << cardName << ")"; + qDebug() << "Picture NOT found, download disabled, no more sets to try: BAILING OUT (oldset: " + << setName << " card: " << cardName << ")"; imageLoaded(cardBeingLoaded.getCard(), QImage()); } } } } -bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & correctedCardname) +bool PictureLoaderWorker::cardImageExistsOnDisk(QString &setName, QString &correctedCardname) { QImage image; QImageReader imgReader; @@ -172,8 +169,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor QDirIterator it(customPicsPath, QDirIterator::Subdirectories); // Recursively check all subdirectories of the CUSTOM folder - while (it.hasNext()) - { + while (it.hasNext()) { QString thisPath(it.next()); QFileInfo thisFileInfo(thisPath); @@ -181,14 +177,14 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor picsPaths << thisPath; // Card found in the CUSTOM directory, somewhere } - if(!setName.isEmpty()) - { - picsPaths << picsPath + "/" + setName + "/" + correctedCardname - << picsPath + "/downloadedPics/" + setName + "/" + correctedCardname; + if (!setName.isEmpty()) { + picsPaths << picsPath + "/" + setName + "/" + correctedCardname + << picsPath + "/downloadedPics/" + setName + "/" + correctedCardname; } - //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension - for (int i = 0; i < picsPaths.length(); i ++) { + // Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported + // extension + for (int i = 0; i < picsPaths.length(); i++) { imgReader.setFileName(picsPaths.at(i)); if (imgReader.read(&image)) { qDebug() << "Picture found on disk (set: " << setName << " file: " << correctedCardname << ")"; @@ -214,15 +210,15 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor QString PictureLoaderWorker::getPicUrl() { - if (!picDownload) return QString(); + if (!picDownload) + return QString(); CardInfo *card = cardBeingDownloaded.getCard(); - CardSet *set=cardBeingDownloaded.getCurrentSet(); + CardSet *set = cardBeingDownloaded.getCurrentSet(); QString picUrl = QString(""); // if sets have been defined for the card, they can contain custom picUrls - if(set) - { + if (set) { picUrl = card->getCustomPicURL(set->getShortName()); if (!picUrl.isEmpty()) return picUrl; @@ -237,8 +233,7 @@ QString PictureLoaderWorker::getPicUrl() picUrl.replace("!corrected_name!", QUrl::toPercentEncoding(card->getCorrectedName())); picUrl.replace("!corrected_name_lower!", QUrl::toPercentEncoding(card->getCorrectedName().toLower())); picUrl.replace("!cardid!", QUrl::toPercentEncoding(QString::number(muid))); - if (set) - { + if (set) { // renamed from !setnumber! to !collectornumber! on 20160819. Remove the old one when convenient. picUrl.replace("!setnumber!", QUrl::toPercentEncoding(card->getCollectorNumber(set->getShortName()))); picUrl.replace("!collectornumber!", QUrl::toPercentEncoding(card->getCollectorNumber(set->getShortName()))); @@ -249,19 +244,10 @@ QString PictureLoaderWorker::getPicUrl() picUrl.replace("!setname_lower!", QUrl::toPercentEncoding(set->getLongName().toLower())); } - if ( - picUrl.contains("!name!") || - picUrl.contains("!name_lower!") || - picUrl.contains("!corrected_name!") || - picUrl.contains("!corrected_name_lower!") || - picUrl.contains("!setnumber!") || - picUrl.contains("!setcode!") || - picUrl.contains("!setcode_lower!") || - picUrl.contains("!setname!") || - picUrl.contains("!setname_lower!") || - picUrl.contains("!cardid!") - ) - { + if (picUrl.contains("!name!") || picUrl.contains("!name_lower!") || picUrl.contains("!corrected_name!") || + picUrl.contains("!corrected_name_lower!") || picUrl.contains("!setnumber!") || picUrl.contains("!setcode!") || + picUrl.contains("!setcode_lower!") || picUrl.contains("!setname!") || picUrl.contains("!setname_lower!") || + picUrl.contains("!cardid!")) { qDebug() << "Insufficient card data to download" << card->getName() << "Url:" << picUrl; return QString(); } @@ -296,14 +282,15 @@ void PictureLoaderWorker::startNextPicDownload() void PictureLoaderWorker::picDownloadFailed() { - if (cardBeingDownloaded.nextSet()) - { - qDebug() << "Picture NOT found, download failed, moving to next set (newset: " << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getName() << ")"; + if (cardBeingDownloaded.nextSet()) { + qDebug() << "Picture NOT found, download failed, moving to next set (newset: " + << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getName() << ")"; mutex.lock(); loadQueue.prepend(cardBeingDownloaded); mutex.unlock(); } else { - qDebug() << "Picture NOT found, download failed, no more sets to try: BAILING OUT (oldset: " << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getName() << ")"; + qDebug() << "Picture NOT found, download failed, no more sets to try: BAILING OUT (oldset: " + << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getName() << ")"; imageLoaded(cardBeingDownloaded.getCard(), QImage()); cardBeingDownloaded = 0; } @@ -331,10 +318,10 @@ void PictureLoaderWorker::picDownloadFinished(QNetworkReply *reply) return; } - const QByteArray &picData = reply->peek(reply->size()); //peek is used to keep the data in the buffer for use by QImageReader + const QByteArray &picData = + reply->peek(reply->size()); // peek is used to keep the data in the buffer for use by QImageReader - if(imageIsBlackListed(picData)) - { + if (imageIsBlackListed(picData)) { qDebug() << "Picture downloaded, but blacklisted, will consider it as not found"; picDownloadFailed(); reply->deleteLater(); @@ -343,24 +330,25 @@ void PictureLoaderWorker::picDownloadFinished(QNetworkReply *reply) } QImage testImage; - + QImageReader imgReader; imgReader.setDecideFormatFromContent(true); imgReader.setDevice(reply); - QString extension = "." + imgReader.format(); //the format is determined prior to reading the QImageReader data into a QImage object, as that wipes the QImageReader buffer + QString extension = "." + imgReader.format(); // the format is determined prior to reading the QImageReader data + // into a QImage object, as that wipes the QImageReader buffer if (extension == ".jpeg") extension = ".jpg"; - + if (imgReader.read(&testImage)) { QString setName = cardBeingDownloaded.getSetName(); - if(!setName.isEmpty()) - { + if (!setName.isEmpty()) { if (!QDir().mkpath(picsPath + "/downloadedPics/" + setName)) { qDebug() << picsPath + "/downloadedPics/" + setName + " could not be created."; return; } - QFile newPic(picsPath + "/downloadedPics/" + setName + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + extension); + QFile newPic(picsPath + "/downloadedPics/" + setName + "/" + + cardBeingDownloaded.getCard()->getCorrectedName() + extension); if (!newPic.open(QIODevice::WriteOnly)) return; newPic.write(picData); @@ -370,7 +358,7 @@ void PictureLoaderWorker::picDownloadFinished(QNetworkReply *reply) imageLoaded(cardBeingDownloaded.getCard(), testImage); } else { picDownloadFailed(); - } + } reply->deleteLater(); startNextPicDownload(); @@ -381,18 +369,16 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card) QMutexLocker locker(&mutex); // avoid queueing the same card more than once - if(!card || card == cardBeingLoaded.getCard() || card == cardBeingDownloaded.getCard()) + if (!card || card == cardBeingLoaded.getCard() || card == cardBeingDownloaded.getCard()) return; - foreach(PictureToLoad pic, loadQueue) - { - if(pic.getCard() == card) + foreach (PictureToLoad pic, loadQueue) { + if (pic.getCard() == card) return; } - foreach(PictureToLoad pic, cardsToDownload) - { - if(pic.getCard() == card) + foreach (PictureToLoad pic, cardsToDownload) { + if (pic.getCard() == card) return; } @@ -413,14 +399,14 @@ void PictureLoaderWorker::picsPathChanged() customPicsPath = settingsCache->getCustomPicsPath(); } -PictureLoader::PictureLoader() - : QObject(0) +PictureLoader::PictureLoader() : QObject(0) { worker = new PictureLoaderWorker; connect(settingsCache, SIGNAL(picsPathChanged()), this, SLOT(picsPathChanged())); connect(settingsCache, SIGNAL(picDownloadChanged()), this, SLOT(picDownloadChanged())); - connect(worker, SIGNAL(imageLoaded(CardInfo *, const QImage &)), this, SLOT(imageLoaded(CardInfo *, const QImage &))); + connect(worker, SIGNAL(imageLoaded(CardInfo *, const QImage &)), this, + SLOT(imageLoaded(CardInfo *, const QImage &))); } PictureLoader::~PictureLoader() @@ -431,29 +417,27 @@ PictureLoader::~PictureLoader() void PictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size) { QString backCacheKey = "_trice_card_back_" + QString::number(size.width()) + QString::number(size.height()); - if(!QPixmapCache::find(backCacheKey, &pixmap)) - { + if (!QPixmapCache::find(backCacheKey, &pixmap)) { qDebug() << "cache fail for" << backCacheKey; pixmap = QPixmap("theme:cardback").scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPixmapCache::insert(backCacheKey, pixmap); - } + } } void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size) { - if(card == nullptr) + if (card == nullptr) return; // search for an exact size copy of the picure in cache QString key = card->getPixmapCacheKey(); QString sizekey = key + QLatin1Char('_') + QString::number(size.width()) + QString::number(size.height()); - if(QPixmapCache::find(sizekey, &pixmap)) + if (QPixmapCache::find(sizekey, &pixmap)) return; // load the image and create a copy of the correct size QPixmap bigPixmap; - if(QPixmapCache::find(key, &bigPixmap)) - { + if (QPixmapCache::find(key, &bigPixmap)) { pixmap = bigPixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPixmapCache::insert(sizekey, pixmap); return; @@ -465,12 +449,10 @@ void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size) void PictureLoader::imageLoaded(CardInfo *card, const QImage &image) { - if(image.isNull()) - { + if (image.isNull()) { QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap()); } else { - if(card->getUpsideDownArt()) - { + if (card->getUpsideDownArt()) { QImage mirrorImage = image.mirrored(true, true); QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap::fromImage(mirrorImage)); } else { @@ -483,7 +465,7 @@ void PictureLoader::imageLoaded(CardInfo *card, const QImage &image) void PictureLoader::clearPixmapCache(CardInfo *card) { - if(card) + if (card) QPixmapCache::remove(card->getPixmapCacheKey()); } @@ -496,14 +478,13 @@ void PictureLoader::cacheCardPixmaps(QList cards) { QPixmap tmp; int max = qMin(cards.size(), CACHED_CARD_PER_DECK_MAX); - for (int i = 0; i < max; ++i) - { - CardInfo * card = cards.at(i); - if(!card) + for (int i = 0; i < max; ++i) { + CardInfo *card = cards.at(i); + if (!card) continue; QString key = card->getPixmapCacheKey(); - if(QPixmapCache::find(key, &tmp)) + if (QPixmapCache::find(key, &tmp)) continue; getInstance().worker->enqueueImageLoad(card); diff --git a/cockatrice/src/pictureloader.h b/cockatrice/src/pictureloader.h index 9a3faf5f..f71d6986 100644 --- a/cockatrice/src/pictureloader.h +++ b/cockatrice/src/pictureloader.h @@ -1,10 +1,10 @@ #ifndef PICTURELOADER_H #define PICTURELOADER_H -#include #include -#include +#include #include +#include class CardInfo; class CardSet; @@ -12,7 +12,8 @@ class QNetworkAccessManager; class QNetworkReply; class QThread; -class PictureToLoad { +class PictureToLoad +{ private: class SetDownloadPriorityComparator; @@ -20,21 +21,27 @@ private: QList sortedSets; int setIndex; bool hq; + public: PictureToLoad(CardInfo *_card = 0); - CardInfo *getCard() const { return card; } + CardInfo *getCard() const + { + return card; + } CardSet *getCurrentSet() const; QString getSetName() const; bool nextSet(); }; -class PictureLoaderWorker : public QObject { -Q_OBJECT +class PictureLoaderWorker : public QObject +{ + Q_OBJECT public: PictureLoaderWorker(); ~PictureLoaderWorker(); void enqueueImageLoad(CardInfo *card); + private: static QStringList md5Blacklist; @@ -49,7 +56,7 @@ private: bool picDownload, downloadRunning, loadQueueRunning; void startNextPicDownload(); QString getPicUrl(); - bool cardImageExistsOnDisk(QString & setName, QString & correctedCardname); + bool cardImageExistsOnDisk(QString &setName, QString &correctedCardname); bool imageIsBlackListed(const QByteArray &picData); private slots: void picDownloadFinished(QNetworkReply *reply); @@ -64,22 +71,25 @@ signals: void imageLoaded(CardInfo *card, const QImage &image); }; -class PictureLoader : public QObject { -Q_OBJECT +class PictureLoader : public QObject +{ + Q_OBJECT public: - static PictureLoader& getInstance() + static PictureLoader &getInstance() { static PictureLoader instance; return instance; } + private: PictureLoader(); ~PictureLoader(); // Singleton - Don't implement copy constructor and assign operator - PictureLoader(PictureLoader const&); - void operator=(PictureLoader const&); + PictureLoader(PictureLoader const &); + void operator=(PictureLoader const &); + + PictureLoaderWorker *worker; - PictureLoaderWorker * worker; public: static void getPixmap(QPixmap &pixmap, CardInfo *card, QSize size); static void getCardBackPixmap(QPixmap &pixmap, QSize size); diff --git a/cockatrice/src/pilezone.cpp b/cockatrice/src/pilezone.cpp index a2ff1d14..db48e686 100644 --- a/cockatrice/src/pilezone.cpp +++ b/cockatrice/src/pilezone.cpp @@ -1,11 +1,11 @@ -#include -#include -#include #include "pilezone.h" -#include "player.h" #include "carddragitem.h" -#include "zoneviewzone.h" #include "carditem.h" +#include "player.h" +#include "zoneviewzone.h" +#include +#include +#include #include "pb/command_move_card.pb.h" @@ -15,8 +15,11 @@ PileZone::PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _c setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor! setAcceptHoverEvents(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)); + + 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 @@ -30,10 +33,10 @@ void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*optio 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->translate((float)CARD_WIDTH / 2, (float)CARD_HEIGHT / 2); painter->rotate(-90); - painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2); + painter->translate((float)-CARD_WIDTH / 2, (float)-CARD_HEIGHT / 2); paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter); } @@ -54,7 +57,9 @@ void PileZone::addCardImpl(CardItem *card, int x, int /*y*/) card->setParentItem(this); } -void PileZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) +void PileZone::handleDropEvent(const QList &dragItems, + CardZone *startZone, + const QPoint & /*dropPoint*/) { Command_MoveCard cmd; cmd.set_start_player_id(startZone->getPlayer()->getId()); @@ -63,7 +68,7 @@ void PileZone::handleDropEvent(const QList &dragItems, CardZone 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()); @@ -90,7 +95,8 @@ void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event) void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance()) + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < + QApplication::startDragDistance()) return; if (cards.isEmpty()) diff --git a/cockatrice/src/pilezone.h b/cockatrice/src/pilezone.h index 2469eb1e..b5ba971e 100644 --- a/cockatrice/src/pilezone.h +++ b/cockatrice/src/pilezone.h @@ -3,16 +3,22 @@ #include "cardzone.h" -class PileZone : public CardZone { +class PileZone : public CardZone +{ 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); + protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); diff --git a/cockatrice/src/pixmapgenerator.cpp b/cockatrice/src/pixmapgenerator.cpp index 720530fa..c65ce12c 100644 --- a/cockatrice/src/pixmapgenerator.cpp +++ b/cockatrice/src/pixmapgenerator.cpp @@ -15,7 +15,8 @@ QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name) if (pmCache.contains(key)) return pmCache.value(key); - QPixmap pixmap = QPixmap("theme:phases/" + name).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap pixmap = + QPixmap("theme:phases/" + name).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); pmCache.insert(key, pixmap); return pixmap; @@ -31,14 +32,14 @@ QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool hi if (pmCache.contains(key)) return pmCache.value(key); - QPixmap pixmap = QPixmap("theme:counters/" + name).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); - if(pixmap.isNull()) - { + QPixmap pixmap = + QPixmap("theme:counters/" + name).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); + if (pixmap.isNull()) { name = "general"; if (highlight) name.append("_highlight"); - pixmap = QPixmap("theme:counters/" + name).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); - + pixmap = + QPixmap("theme:counters/" + name).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); } pmCache.insert(key, pixmap); @@ -58,9 +59,10 @@ QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max) if ((max == -1) || (value == -1)) color = Qt::black; else - color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255); + 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); + 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)); @@ -74,7 +76,7 @@ QMap PingPixmapGenerator::pmCache; QPixmap GenderPixmapGenerator::generatePixmap(int height) { - ServerInfo_User::Gender gender = ServerInfo_User::GenderUnknown; + ServerInfo_User::Gender gender = ServerInfo_User::GenderUnknown; int key = gender * 100000 + height; if (pmCache.contains(key)) @@ -83,8 +85,8 @@ QPixmap GenderPixmapGenerator::generatePixmap(int height) QString genderStr; genderStr = "unknown"; - - QPixmap pixmap = QPixmap("theme:genders/" + genderStr).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap pixmap = + QPixmap("theme:genders/" + genderStr).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); pmCache.insert(key, pixmap); return pixmap; } @@ -100,7 +102,8 @@ QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countr return pmCache.value(key); int width = height * 2; - QPixmap pixmap = QPixmap("theme:countries/" + countryCode.toLower()).scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap pixmap = QPixmap("theme:countries/" + countryCode.toLower()) + .scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPainter painter(&pixmap); painter.setPen(Qt::black); @@ -114,7 +117,7 @@ QMap CountryPixmapGenerator::pmCache; QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel) { - + QString key = QString::number(height * 10000) + ":" + (int)userLevel + ":" + (int)isBuddy + ":" + privLevel; if (pmCache.contains(key)) return pmCache.value(key); @@ -137,15 +140,15 @@ QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags user if (isBuddy) levelString.append("_buddy"); - - QPixmap pixmap = QPixmap("theme:userlevels/" + levelString).scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); + + QPixmap pixmap = QPixmap("theme:userlevels/" + levelString) + .scaled(height, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); pmCache.insert(key, pixmap); return pixmap; } QMap UserLevelPixmapGenerator::pmCache; - QPixmap LockPixmapGenerator::generatePixmap(int height) { diff --git a/cockatrice/src/pixmapgenerator.h b/cockatrice/src/pixmapgenerator.h index 131d1487..27e64961 100644 --- a/cockatrice/src/pixmapgenerator.h +++ b/cockatrice/src/pixmapgenerator.h @@ -1,65 +1,100 @@ #ifndef PIXMAPGENERATOR_H #define PIXMAPGENERATOR_H -#include #include +#include #include "user_level.h" -class PhasePixmapGenerator { +class PhasePixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int size, QString name); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; -class CounterPixmapGenerator { +class CounterPixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int size, QString name, bool highlight); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; -class PingPixmapGenerator { +class PingPixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int size, int value, int max); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; -class GenderPixmapGenerator { +class GenderPixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int height); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; -class CountryPixmapGenerator { +class CountryPixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int height, const QString &countryCode); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; -class UserLevelPixmapGenerator { +class UserLevelPixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel = "NONE"); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; -class LockPixmapGenerator { +class LockPixmapGenerator +{ private: static QMap pmCache; + public: static QPixmap generatePixmap(int height); - static void clear() { pmCache.clear(); } + static void clear() + { + pmCache.clear(); + } }; #endif diff --git a/cockatrice/src/player.cpp b/cockatrice/src/player.cpp index 4a20d5b0..f19679db 100644 --- a/cockatrice/src/player.cpp +++ b/cockatrice/src/player.cpp @@ -1,73 +1,72 @@ #include "player.h" -#include "cardzone.h" -#include "playertarget.h" -#include "counter_general.h" #include "arrowitem.h" -#include "zoneviewzone.h" -#include "zoneviewwidget.h" -#include "pilezone.h" -#include "stackzone.h" -#include "tablezone.h" -#include "handzone.h" -#include "handcounter.h" +#include "carddatabase.h" #include "carditem.h" #include "cardlist.h" -#include "tab_game.h" -#include "gamescene.h" -#include "settingscache.h" -#include "thememanager.h" -#include "dlg_create_token.h" -#include "carddatabase.h" +#include "cardzone.h" #include "color.h" +#include "counter_general.h" #include "deck_loader.h" +#include "dlg_create_token.h" +#include "gamescene.h" +#include "handcounter.h" +#include "handzone.h" #include "main.h" -#include -#include +#include "pilezone.h" +#include "playertarget.h" +#include "settingscache.h" +#include "stackzone.h" +#include "tab_game.h" +#include "tablezone.h" +#include "thememanager.h" +#include "zoneviewwidget.h" +#include "zoneviewzone.h" #include +#include +#include #include -#include "pb/command_change_zone_properties.pb.h" -#include "pb/command_reveal_cards.pb.h" -#include "pb/command_shuffle.pb.h" #include "pb/command_attach_card.pb.h" -#include "pb/command_set_card_attr.pb.h" -#include "pb/command_set_card_counter.pb.h" -#include "pb/command_mulligan.pb.h" -#include "pb/command_move_card.pb.h" -#include "pb/command_draw_cards.pb.h" -#include "pb/command_undo_draw.pb.h" -#include "pb/command_roll_die.pb.h" +#include "pb/command_change_zone_properties.pb.h" #include "pb/command_create_token.pb.h" +#include "pb/command_draw_cards.pb.h" #include "pb/command_flip_card.pb.h" #include "pb/command_game_say.pb.h" -#include "pb/serverinfo_user.pb.h" -#include "pb/serverinfo_player.pb.h" -#include "pb/serverinfo_zone.pb.h" +#include "pb/command_move_card.pb.h" +#include "pb/command_mulligan.pb.h" +#include "pb/command_reveal_cards.pb.h" +#include "pb/command_roll_die.pb.h" +#include "pb/command_set_card_attr.pb.h" +#include "pb/command_set_card_counter.pb.h" +#include "pb/command_shuffle.pb.h" +#include "pb/command_undo_draw.pb.h" #include "pb/context_move_card.pb.h" #include "pb/context_undo_draw.pb.h" -#include "pb/event_game_say.pb.h" -#include "pb/event_shuffle.pb.h" -#include "pb/event_roll_die.pb.h" +#include "pb/event_attach_card.pb.h" +#include "pb/event_change_zone_properties.pb.h" #include "pb/event_create_arrow.pb.h" -#include "pb/event_delete_arrow.pb.h" +#include "pb/event_create_counter.pb.h" #include "pb/event_create_token.pb.h" +#include "pb/event_del_counter.pb.h" +#include "pb/event_delete_arrow.pb.h" +#include "pb/event_destroy_card.pb.h" +#include "pb/event_draw_cards.pb.h" +#include "pb/event_dump_zone.pb.h" +#include "pb/event_flip_card.pb.h" +#include "pb/event_game_say.pb.h" +#include "pb/event_move_card.pb.h" +#include "pb/event_reveal_cards.pb.h" +#include "pb/event_roll_die.pb.h" #include "pb/event_set_card_attr.pb.h" #include "pb/event_set_card_counter.pb.h" -#include "pb/event_create_counter.pb.h" #include "pb/event_set_counter.pb.h" -#include "pb/event_del_counter.pb.h" -#include "pb/event_dump_zone.pb.h" +#include "pb/event_shuffle.pb.h" #include "pb/event_stop_dump_zone.pb.h" -#include "pb/event_move_card.pb.h" -#include "pb/event_flip_card.pb.h" -#include "pb/event_destroy_card.pb.h" -#include "pb/event_attach_card.pb.h" -#include "pb/event_draw_cards.pb.h" -#include "pb/event_reveal_cards.pb.h" -#include "pb/event_change_zone_properties.pb.h" +#include "pb/serverinfo_player.pb.h" +#include "pb/serverinfo_user.pb.h" +#include "pb/serverinfo_zone.pb.h" -PlayerArea::PlayerArea(QGraphicsItem *parentItem) - : QObject(), QGraphicsItem(parentItem) +PlayerArea::PlayerArea(QGraphicsItem *parentItem) : QObject(), QGraphicsItem(parentItem) { setCacheMode(DeviceCoordinateCache); connect(themeManager, SIGNAL(themeChanged()), this, SLOT(updateBg())); @@ -91,27 +90,13 @@ void PlayerArea::setSize(qreal width, qreal height) } Player::Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent) - : QObject(_parent), - game(_parent), - shortcutsActive(false), - defaultNumberTopCards(1), - defaultNumberTopCardsToPlaceBelow(1), - lastTokenDestroy(true), - lastTokenTableRow(0), - id(_id), - active(false), - local(_local), - mirrored(false), - handVisible(false), - conceded(false), - dialogSemaphore(false), - deck(0) + : QObject(_parent), game(_parent), shortcutsActive(false), defaultNumberTopCards(1), + defaultNumberTopCardsToPlaceBelow(1), lastTokenDestroy(true), lastTokenTableRow(0), 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())); connect(settingsCache, SIGNAL(handJustificationChanged()), this, SLOT(rearrangeZones())); @@ -122,7 +107,8 @@ Player::Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_pare 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); + 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; @@ -143,9 +129,10 @@ Player::Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_pare table = new TableZone(this, this); connect(table, SIGNAL(sizeChanged()), this, SLOT(updateBoundingRect())); - stack = new StackZone(this, (int) table->boundingRect().height(), this); + stack = new StackZone(this, (int)table->boundingRect().height(), this); - hand = new HandZone(this, _local || (_parent->getSpectator() && _parent->getSpectatorsSeeEverything()), (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 &))); @@ -459,7 +446,7 @@ Player::Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_pare rearrangeZones(); retranslateUi(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); } @@ -484,8 +471,7 @@ void Player::clear() clearArrows(); QMapIterator i(zones); - while (i.hasNext()) - { + while (i.hasNext()) { i.next().value()->clearContents(); } @@ -534,7 +520,9 @@ void Player::playerListActionTriggered() } else if (menu == mRevealTopCard) { int decksize = zones.value("deck")->getCards().size(); bool ok; - int number = QInputDialog::getInt(0, tr("Reveal top cards of library"), tr("Number of cards: (max. %1)").arg(decksize), defaultNumberTopCards, 1, decksize, 1, &ok); + int number = + QInputDialog::getInt(0, tr("Reveal top cards of library"), tr("Number of cards: (max. %1)").arg(decksize), + defaultNumberTopCards, 1, decksize, 1, &ok); if (ok) { cmd.set_zone_name("deck"); cmd.set_top_cards(number); @@ -613,7 +601,8 @@ void Player::updateBoundingRect() 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()); + bRect = QRectF(0, 0, width + hand->boundingRect().width() + table->boundingRect().width(), + table->boundingRect().height()); playerArea->setSize(CARD_HEIGHT + counterAreaWidth + 15, bRect.height()); emit sizeChanged(); @@ -715,13 +704,13 @@ void Player::retranslateUi() counterColors.append(tr("Yellow")); counterColors.append(tr("Green")); - for (int i = 0; i < aAddCounter.size(); ++i){ + 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){ + 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){ + for (int i = 0; i < aSetCounter.size(); ++i) { aSetCounter[i]->setText(tr("&Set counters (%1)...").arg(counterColors[i])); } @@ -779,13 +768,13 @@ void Player::setShortcutsActive() setCCShortCuts.append(settingsCache->shortcuts().getSingleShortcut("Player/aSCYellow")); setCCShortCuts.append(settingsCache->shortcuts().getSingleShortcut("Player/aSCGreen")); - for (int i = 0; i < aAddCounter.size(); ++i){ + for (int i = 0; i < aAddCounter.size(); ++i) { aAddCounter[i]->setShortcut(addCCShortCuts.at(i)); } - for (int i = 0; i < aRemoveCounter.size(); ++i){ + for (int i = 0; i < aRemoveCounter.size(); ++i) { aRemoveCounter[i]->setShortcut(removeCCShortCuts.at(i)); } - for (int i = 0; i < aSetCounter.size(); ++i){ + for (int i = 0; i < aSetCounter.size(); ++i) { aSetCounter[i]->setShortcut(setCCShortCuts.at(i)); } @@ -841,7 +830,7 @@ void Player::initSayMenu() for (int i = 0; i < count; i++) { QAction *newAction = new QAction(settingsCache->messages().getMessageAt(i), this); - if (i <= 10){ + if (i <= 10) { newAction->setShortcut(QKeySequence("Ctrl+" + QString::number((i + 1) % 10))); } connect(newAction, SIGNAL(triggered()), this, SLOT(actSayMessage())); @@ -863,8 +852,7 @@ void Player::setDeck(const DeckLoader &_deck) const QString tokenName = tokenZone->at(i)->getName(); predefinedTokens.append(tokenName); QAction *a = createPredefinedTokenMenu->addAction(tokenName); - if (i < 10) - { + if (i < 10) { a->setShortcut(QKeySequence("Alt+" + QString::number((i + 1) % 10))); } connect(a, SIGNAL(triggered()), this, SLOT(actCreatePredefinedToken())); @@ -879,7 +867,8 @@ void Player::actViewLibrary() void Player::actViewTopCards() { bool ok; - int number = QInputDialog::getInt(0, tr("View top cards of library"), tr("Number of cards:"), defaultNumberTopCards, 1, 2000000000, 1, &ok); + int number = QInputDialog::getInt(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); @@ -1033,7 +1022,8 @@ void Player::actMoveTopCardToPlayFaceDown() sendGameCommand(cmd); } -void Player::actMoveBottomCardToGrave() { +void Player::actMoveBottomCardToGrave() +{ CardZone *zone = zones.value("deck"); Command_MoveCard cmd; cmd.set_start_zone("deck"); @@ -1059,7 +1049,8 @@ void Player::actUntapAll() void Player::actRollDie() { bool ok; - int sides = QInputDialog::getInt(static_cast(parent()), tr("Roll die"), tr("Number of sides:"), 20, 2, 1000, 1, &ok); + int sides = QInputDialog::getInt(static_cast(parent()), tr("Roll die"), tr("Number of sides:"), 20, 2, + 1000, 1, &ok); if (ok) { Command_RollDie cmd; cmd.set_sides(sides); @@ -1112,7 +1103,7 @@ void Player::actCreatePredefinedToken() { QAction *action = static_cast(sender()); CardInfo *cardInfo = db->getCard(action->text()); - if(!cardInfo) + if (!cardInfo) return; setLastToken(cardInfo); @@ -1122,20 +1113,20 @@ void Player::actCreatePredefinedToken() void Player::actCreateRelatedCard() { - CardItem * sourceCard = game->getActiveCard(); - if(!sourceCard) + CardItem *sourceCard = game->getActiveCard(); + if (!sourceCard) return; QAction *action = static_cast(sender()); - //If there is a better way of passing a CardRelation through a QAction, please add it here. + // If there is a better way of passing a CardRelation through a QAction, please add it here. QList relatedCards = QList(); relatedCards.append(sourceCard->getInfo()->getRelatedCards()); relatedCards.append(sourceCard->getInfo()->getReverseRelatedCards2Me()); - CardRelation * cardRelation = relatedCards.at(action->data().toInt()); + CardRelation *cardRelation = relatedCards.at(action->data().toInt()); - /* - * If we make a token via "Token: TokenName" - * then let's allow it to be created via "create another token" - */ + /* + * If we make a token via "Token: TokenName" + * then let's allow it to be created via "create another token" + */ if (createRelatedFromRelation(sourceCard, cardRelation) && cardRelation->getCanCreateAnother()) { CardInfo *cardInfo = db->getCard(dbNameFromTokenDisplayName(cardRelation->getName())); setLastToken(cardInfo); @@ -1144,8 +1135,8 @@ void Player::actCreateRelatedCard() void Player::actCreateAllRelatedCards() { - CardItem * sourceCard = game->getActiveCard(); - if(!sourceCard) + CardItem *sourceCard = game->getActiveCard(); + if (!sourceCard) return; QList relatedCards = QList(); @@ -1154,54 +1145,54 @@ void Player::actCreateAllRelatedCards() QList nonExcludedRelatedCards = QList(); QString dbName; - CardRelation * cardRelation = nullptr; + CardRelation *cardRelation = nullptr; int tokensTypesCreated = 0; - switch(relatedCards.length()) { //Is an if/elseif/else pattern better? - case 0: //if (relatedCards.length() == 0) + switch (relatedCards.length()) { // Is an if/elseif/else pattern better? + case 0: // if (relatedCards.length() == 0) return; - case 1: //else if (relatedCards.length() == 1) + case 1: // else if (relatedCards.length() == 1) cardRelation = relatedCards.at(0); if (createRelatedFromRelation(sourceCard, cardRelation)) tokensTypesCreated++; break; - default: //else - foreach (CardRelation * cardRelationTemp, relatedCards) { - if(!cardRelationTemp->getIsCreateAllExclusion() && !cardRelationTemp->getDoesAttach()) { + default: // else + foreach (CardRelation *cardRelationTemp, relatedCards) { + if (!cardRelationTemp->getIsCreateAllExclusion() && !cardRelationTemp->getDoesAttach()) { nonExcludedRelatedCards.append(cardRelationTemp); } } - switch(nonExcludedRelatedCards.length()) { - case 1: //if nonExcludedRelatedCards == 1 + switch (nonExcludedRelatedCards.length()) { + case 1: // if nonExcludedRelatedCards == 1 cardRelation = nonExcludedRelatedCards.at(0); if (createRelatedFromRelation(sourceCard, cardRelation)) tokensTypesCreated++; break; - //If all are marked "Exclude", then treat the situation as if none of them are. - //We won't accept "garbage in, garbage out", here. - case 0: //else if nonExcludedRelatedCards == 0 - foreach (CardRelation * cardRelationAll, relatedCards) { + // If all are marked "Exclude", then treat the situation as if none of them are. + // We won't accept "garbage in, garbage out", here. + case 0: // else if nonExcludedRelatedCards == 0 + foreach (CardRelation *cardRelationAll, relatedCards) { if (!cardRelationAll->getDoesAttach() && !cardRelationAll->getIsVariable()) { dbName = dbNameFromTokenDisplayName(cardRelationAll->getName()); for (int i = 0; i < cardRelationAll->getDefaultCount(); i++) { createCard(sourceCard, dbName); } tokensTypesCreated++; - if(tokensTypesCreated == 1) { + if (tokensTypesCreated == 1) { cardRelation = cardRelationAll; } } } break; - default: //else - foreach (CardRelation * cardRelationNotExcluded, nonExcludedRelatedCards) { + default: // else + foreach (CardRelation *cardRelationNotExcluded, nonExcludedRelatedCards) { if (!cardRelationNotExcluded->getDoesAttach() && !cardRelationNotExcluded->getIsVariable()) { dbName = dbNameFromTokenDisplayName(cardRelationNotExcluded->getName()); for (int i = 0; i < cardRelationNotExcluded->getDefaultCount(); i++) { createCard(sourceCard, dbName); } tokensTypesCreated++; - if(tokensTypesCreated == 1) { + if (tokensTypesCreated == 1) { cardRelation = cardRelationNotExcluded; } } @@ -1215,8 +1206,7 @@ void Player::actCreateAllRelatedCards() * If we made at least one token via "Create All Tokens" * then assign the first to the "Create another" shortcut. */ - if (cardRelation != nullptr && cardRelation->getCanCreateAnother()) - { + if (cardRelation != nullptr && cardRelation->getCanCreateAnother()) { CardInfo *cardInfo = db->getCard(dbNameFromTokenDisplayName(cardRelation->getName())); setLastToken(cardInfo); } @@ -1227,10 +1217,11 @@ bool Player::createRelatedFromRelation(const CardItem *sourceCard, const CardRel if (sourceCard == nullptr || cardRelation == nullptr) return false; QString dbName = dbNameFromTokenDisplayName(cardRelation->getName()); - if(cardRelation->getIsVariable()) { + if (cardRelation->getIsVariable()) { bool ok; dialogSemaphore = true; - int count = QInputDialog::getInt(0, tr("Create tokens"), tr("Number:"), cardRelation->getDefaultCount(), 1, MAX_TOKENS_PER_DIALOG, 1, &ok); + int count = QInputDialog::getInt(0, tr("Create tokens"), tr("Number:"), cardRelation->getDefaultCount(), 1, + MAX_TOKENS_PER_DIALOG, 1, &ok); dialogSemaphore = false; if (!ok) return false; @@ -1266,18 +1257,20 @@ void Player::createCard(const CardItem *sourceCard, const QString &dbCardName, b Command_CreateToken cmd; cmd.set_zone("table"); cmd.set_card_name(cardInfo->getName().toStdString()); - if(cardInfo->getColors().length() > 1) //Multicoloured + if (cardInfo->getColors().length() > 1) // Multicoloured cmd.set_color("m"); else - cmd.set_color(cardInfo->getColors().isEmpty() ? QString().toStdString() : cardInfo->getColors().first().toLower().toStdString()); + cmd.set_color(cardInfo->getColors().isEmpty() ? QString().toStdString() + : cardInfo->getColors().first().toLower().toStdString()); cmd.set_pt(cardInfo->getPowTough().toStdString()); - cmd.set_annotation(settingsCache->getAnnotateTokens() ? cardInfo->getText().toStdString() : QString().toStdString()); + cmd.set_annotation(settingsCache->getAnnotateTokens() ? cardInfo->getText().toStdString() + : QString().toStdString()); cmd.set_destroy_on_zone_change(true); cmd.set_target_zone(sourceCard->getZone()->getName().toStdString()); cmd.set_x(gridPoint.x()); cmd.set_y(gridPoint.y()); - if(attach) + if (attach) cmd.set_target_card_id(sourceCard->getId()); sendGameCommand(cmd); @@ -1296,7 +1289,11 @@ void Player::actSayMessage() sendGameCommand(cmd); } -void Player::setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards) +void Player::setCardAttrHelper(const GameEventContext &context, + CardItem *card, + CardAttribute attribute, + const QString &avalue, + bool allCards) { if (card == nullptr) return; @@ -1312,9 +1309,15 @@ void Player::setCardAttrHelper(const GameEventContext &context, CardItem *card, } break; } - case AttrAttacking: card->setAttacking(avalue == "1"); break; - case AttrFaceDown: card->setFaceDown(avalue == "1"); break; - case AttrColor: card->setColor(avalue); 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); @@ -1337,20 +1340,16 @@ void Player::setCardAttrHelper(const GameEventContext &context, CardItem *card, // token names take the form of " / " or " ". // dbName for tokens should take the form of " ". // trailing whitespace is significant; it is hacked on at the end as an additional identifier in our single key database -QString Player::dbNameFromTokenDisplayName(const QString &tokenName) { +QString Player::dbNameFromTokenDisplayName(const QString &tokenName) +{ QRegExp tokenNamePattern(".*/\\S+\\s+(.*)"); int index = tokenNamePattern.indexIn(tokenName); - if (index != -1) - { + if (index != -1) { return tokenNamePattern.capturedTexts()[1]; - } - else if (tokenName.indexOf(tr("Token: ")) != -1) - { + } else if (tokenName.indexOf(tr("Token: ")) != -1) { return tokenName.mid(tr("Token: ").length()); - } - else - { + } else { return tokenName; } } @@ -1385,9 +1384,11 @@ void Player::eventCreateArrow(const Event_CreateArrow &event) 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); + 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); + emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), arrow->getTargetItem()->getOwner(), + QString(), true); } void Player::eventDeleteArrow(const Event_DeleteArrow &event) @@ -1403,12 +1404,11 @@ void Player::eventCreateToken(const Event_CreateToken &event) CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id()); // use db PT if not provided in event - if (!QString::fromStdString(event.pt()).isEmpty()) - { + if (!QString::fromStdString(event.pt()).isEmpty()) { card->setPT(QString::fromStdString(event.pt())); } else { - CardInfo * dbCard = db->getCard(QString::fromStdString(event.card_name())); - if(dbCard) + CardInfo *dbCard = db->getCard(QString::fromStdString(event.card_name())); + if (dbCard) card->setPT(dbCard->getPowTough()); } card->setColor(QString::fromStdString(event.color())); @@ -1417,7 +1417,6 @@ void Player::eventCreateToken(const Event_CreateToken &event) 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) @@ -1429,7 +1428,8 @@ void Player::eventSetCardAttr(const Event_SetCardAttr &event, const GameEventCon 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); + 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 { @@ -1744,26 +1744,66 @@ void Player::eventChangeZoneProperties(const Event_ChangeZoneProperties &event) 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; + 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" << type; } @@ -1841,7 +1881,9 @@ void Player::processCardAttachment(const ServerInfo_Player &info) 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()); + CardItem *targetCard = + game->getCard(cardInfo.attach_player_id(), QString::fromStdString(cardInfo.attach_zone()), + cardInfo.attach_card_id()); if (!targetCard) continue; @@ -1868,11 +1910,11 @@ void Player::playCard(CardItem *c, bool faceDown, bool tapped) cardToMove->set_card_id(c->getId()); CardInfo *ci = c->getInfo(); - if(!ci) + if (!ci) return; if (!faceDown && ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || - ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && - c->getZone()->getName().toStdString() != "stack"))) { + ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && + c->getZone()->getName().toStdString() != "stack"))) { cmd.set_target_zone("stack"); cmd.set_x(0); cmd.set_y(0); @@ -1897,16 +1939,11 @@ void Player::addCard(CardItem *c) void Player::deleteCard(CardItem *c) { - if (c == nullptr) - { + if (c == nullptr) { return; - } - else if (dialogSemaphore) - { + } else if (dialogSemaphore) { cardsToDelete.append(c); - } - else - { + } else { c->deleteLater(); } } @@ -1918,7 +1955,8 @@ void Player::addZone(CardZone *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) @@ -1985,7 +2023,8 @@ ArrowItem *Player::addArrow(const ServerInfo_Arrow &arrow) if (targetCard) return addArrow(arrow.id(), startCard, targetCard, convertColorToQColor(arrow.arrow_color())); else - return addArrow(arrow.id(), startCard, targetPlayer->getPlayerTarget(), convertColorToQColor(arrow.arrow_color())); + return addArrow(arrow.id(), startCard, targetPlayer->getPlayerTarget(), + convertColorToQColor(arrow.arrow_color())); } ArrowItem *Player::addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color) @@ -2035,7 +2074,7 @@ void Player::rearrangeCounters() qreal y = boundingRect().y() + marginTop; // Place objects - for (counterIterator.toFront(); counterIterator.hasNext(); ) { + for (counterIterator.toFront(); counterIterator.hasNext();) { AbstractCounter *c = counterIterator.next().value(); if (!c->getShownInCounterArea()) @@ -2047,12 +2086,12 @@ void Player::rearrangeCounters() } } -PendingCommand * Player::prepareGameCommand(const google::protobuf::Message &cmd) +PendingCommand *Player::prepareGameCommand(const google::protobuf::Message &cmd) { return game->prepareGameCommand(cmd); } -PendingCommand * Player::prepareGameCommand(const QList &cmdList) +PendingCommand *Player::prepareGameCommand(const QList &cmdList) { return game->prepareGameCommand(cmdList); } @@ -2072,10 +2111,8 @@ bool Player::clearCardsToDelete() if (cardsToDelete.isEmpty()) return false; - for (auto &i : cardsToDelete) - { - if (i != nullptr) - { + for (auto &i : cardsToDelete) { + if (i != nullptr) { i->deleteLater(); } } @@ -2087,7 +2124,9 @@ bool Player::clearCardsToDelete() void Player::actMoveCardXCardsFromTop() { bool ok; - int number = QInputDialog::getInt(0, tr("Place card X cards from top of library"), tr("How many cards from the top of the deck should this card be placed:"), defaultNumberTopCardsToPlaceBelow, 1, 2000000000, 1, &ok); + int number = QInputDialog::getInt(0, tr("Place card X cards from top of library"), + tr("How many cards from the top of the deck should this card be placed:"), + defaultNumberTopCardsToPlaceBelow, 1, 2000000000, 1, &ok); number--; if (!ok) @@ -2100,7 +2139,7 @@ void Player::actMoveCardXCardsFromTop() while (!sel.isEmpty()) cardList.append(qgraphicsitem_cast(sel.takeFirst())); - QList< const ::google::protobuf::Message * > commandList; + QList commandList; ListOfCardsToMove idList; for (auto &i : cardList) idList.add_card()->set_card_id(i->getId()); @@ -2135,18 +2174,14 @@ void Player::cardMenuAction() 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) - { + QList 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())) - { + switch (static_cast(a->data().toInt())) { // Leaving both for compatibility with server case cmUntap: - case cmTap: - { + case cmTap: { Command_SetCardAttr *cmd = new Command_SetCardAttr; cmd->set_zone(card->getZone()->getName().toStdString()); cmd->set_card_id(card->getId()); @@ -2155,8 +2190,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmDoesntUntap: - { + case cmDoesntUntap: { Command_SetCardAttr *cmd = new Command_SetCardAttr; cmd->set_zone(card->getZone()->getName().toStdString()); cmd->set_card_id(card->getId()); @@ -2165,8 +2199,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmFlip: - { + case cmFlip: { Command_FlipCard *cmd = new Command_FlipCard; cmd->set_zone(card->getZone()->getName().toStdString()); cmd->set_card_id(card->getId()); @@ -2174,8 +2207,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmPeek: - { + case cmPeek: { Command_RevealCards *cmd = new Command_RevealCards; cmd->set_zone_name(card->getZone()->getName().toStdString()); cmd->set_card_id(card->getId()); @@ -2183,8 +2215,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmClone: - { + case cmClone: { Command_CreateToken *cmd = new Command_CreateToken; cmd->set_zone("table"); cmd->set_card_name(card->getName().toStdString()); @@ -2201,21 +2232,16 @@ void Player::cardMenuAction() break; } } - } - else - { + } else { ListOfCardsToMove idList; - for (int i = 0; i < cardList.size(); i++) - { + 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: - { + 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()); @@ -2227,8 +2253,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmMoveToBottomLibrary: - { + case cmMoveToBottomLibrary: { Command_MoveCard *cmd = new Command_MoveCard; cmd->set_start_player_id(startPlayerId); cmd->set_start_zone(startZone.toStdString()); @@ -2240,8 +2265,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmMoveToHand: - { + case cmMoveToHand: { Command_MoveCard *cmd = new Command_MoveCard; cmd->set_start_player_id(startPlayerId); cmd->set_start_zone(startZone.toStdString()); @@ -2253,8 +2277,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmMoveToGraveyard: - { + case cmMoveToGraveyard: { Command_MoveCard *cmd = new Command_MoveCard; cmd->set_start_player_id(startPlayerId); cmd->set_start_zone(startZone.toStdString()); @@ -2266,8 +2289,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } - case cmMoveToExile: - { + case cmMoveToExile: { Command_MoveCard *cmd = new Command_MoveCard; cmd->set_start_player_id(startPlayerId); cmd->set_start_zone(startZone.toStdString()); @@ -2284,12 +2306,9 @@ void Player::cardMenuAction() } } - if (local) - { + if (local) { sendGameCommand(prepareGameCommand(commandList)); - } - else - { + } else { game->sendGameCommand(prepareGameCommand(commandList)); } } @@ -2299,7 +2318,7 @@ void Player::actIncPT(int deltaP, int deltaT) QString ptString = "+" + QString::number(deltaP) + "/+" + QString::number(deltaT); int playerid = id; - QList< const ::google::protobuf::Message * > commandList; + QList commandList; QListIterator j(scene()->selectedItems()); while (j.hasNext()) { CardItem *card = static_cast(j.next()); @@ -2310,8 +2329,8 @@ void Player::actIncPT(int deltaP, int deltaT) cmd->set_attr_value(ptString.toStdString()); commandList.append(cmd); - if(local) - playerid=card->getZone()->getPlayer()->getId(); + if (local) + playerid = card->getZone()->getPlayer()->getId(); } game->sendGameCommand(prepareGameCommand(commandList), playerid); @@ -2330,14 +2349,15 @@ void Player::actSetPT() } bool ok; dialogSemaphore = true; - QString pt = QInputDialog::getText(0, tr("Set power/toughness"), tr("Please enter the new PT:"), QLineEdit::Normal, oldPT, &ok); + 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; + QList commandList; QListIterator j(scene()->selectedItems()); while (j.hasNext()) { CardItem *card = static_cast(j.next()); @@ -2348,8 +2368,8 @@ void Player::actSetPT() cmd->set_attr_value(pt.toStdString()); commandList.append(cmd); - if(local) - playerid=card->getZone()->getPlayer()->getId(); + if (local) + playerid = card->getZone()->getPlayer()->getId(); } game->sendGameCommand(prepareGameCommand(commandList), playerid); @@ -2357,7 +2377,7 @@ void Player::actSetPT() void Player::actDrawArrow() { - if(!game->getActiveCard()) + if (!game->getActiveCard()) return; game->getActiveCard()->drawArrow(Qt::red); @@ -2405,14 +2425,15 @@ void Player::actSetAnnotation() bool ok; dialogSemaphore = true; - QString annotation = QInputDialog::getText(0, tr("Set annotation"), tr("Please enter the new annotation:"), QLineEdit::Normal, oldAnnotation, &ok); + 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; + QList commandList; i.toFront(); while (i.hasNext()) { CardItem *card = static_cast(i.next()); @@ -2428,7 +2449,7 @@ void Player::actSetAnnotation() void Player::actAttach() { - if(!game->getActiveCard()) + if (!game->getActiveCard()) return; ArrowAttachItem *arrow = new ArrowAttachItem(game->getActiveCard()); @@ -2438,7 +2459,7 @@ void Player::actAttach() void Player::actUnattach() { - if(!game->getActiveCard()) + if (!game->getActiveCard()) return; Command_AttachCard cmd; @@ -2452,7 +2473,7 @@ 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; + QList commandList; switch (action) { case 9: { QListIterator i(scene()->selectedItems()); @@ -2506,23 +2527,23 @@ void Player::actCardCounterTrigger() } break; } - default: ; + default:; } sendGameCommand(prepareGameCommand(commandList)); } void Player::actPlay() { - if(!game->getActiveCard()) + if (!game->getActiveCard()) return; - bool cipt = game->getActiveCard()->getInfo() ? game->getActiveCard()->getInfo()->getCipt(): false; + bool cipt = game->getActiveCard()->getInfo() ? game->getActiveCard()->getInfo()->getCipt() : false; playCard(game->getActiveCard(), false, cipt); } void Player::actHide() { - if(!game->getActiveCard()) + if (!game->getActiveCard()) return; game->getActiveCard()->getZone()->removeCard(game->getActiveCard()); @@ -2530,7 +2551,7 @@ void Player::actHide() void Player::actPlayFacedown() { - if(!game->getActiveCard()) + if (!game->getActiveCard()) return; playCard(game->getActiveCard(), true, false); @@ -2538,12 +2559,10 @@ void Player::actPlayFacedown() void Player::refreshShortcuts() { - if(shortcutsActive) - { + if (shortcutsActive) { setShortcutsActive(); - foreach (const CardItem *cardItem, table->getCards()) - { + foreach (const CardItem *cardItem, table->getCards()) { updateCardMenu(cardItem); } } @@ -2552,8 +2571,7 @@ void Player::refreshShortcuts() void Player::updateCardMenu(const CardItem *card) { // If bad card OR is a spectator (as spectators don't need card menus), return - if (card == nullptr || game->isSpectator()) - { + if (card == nullptr || game->isSpectator()) { return; } @@ -2565,17 +2583,12 @@ void Player::updateCardMenu(const CardItem *card) bool revealedCard = false; bool writeableCard = getLocal(); - if (card->getZone() && card->getZone()->getIsView()) - { + if (card->getZone() && card->getZone()->getIsView()) { auto *view = dynamic_cast(card->getZone()); - if (view->getRevealZone()) - { - if (view->getWriteableRevealZone()) - { + if (view->getRevealZone()) { + if (view->getWriteableRevealZone()) { writeableCard = true; - } - else - { + } else { revealedCard = true; } } @@ -2650,12 +2663,12 @@ void Player::updateCardMenu(const CardItem *card) addRelatedCardActions(card, cardMenu); } else if (card->getZone()->getName() == "rfg" || card->getZone()->getName() == "grave") { - cardMenu->addAction(aPlay); - cardMenu->addAction(aPlayFacedown); - cardMenu->addSeparator(); - cardMenu->addAction(aClone); - cardMenu->addMenu(moveMenu); - } else { + cardMenu->addAction(aPlay); + cardMenu->addAction(aPlayFacedown); + cardMenu->addSeparator(); + cardMenu->addAction(aClone); + cardMenu->addMenu(moveMenu); + } else { cardMenu->addAction(aPlay); cardMenu->addAction(aPlayFacedown); cardMenu->addMenu(moveMenu); @@ -2674,7 +2687,8 @@ void Player::updateCardMenu(const CardItem *card) } } -void Player::addRelatedCardActions(const CardItem *card, QMenu *cardMenu) { +void Player::addRelatedCardActions(const CardItem *card, QMenu *cardMenu) +{ if (card == nullptr || cardMenu == nullptr || card->getInfo() == nullptr) return; @@ -2689,12 +2703,22 @@ void Player::addRelatedCardActions(const CardItem *card, QMenu *cardMenu) { cardMenu->addSeparator(); QAction *createRelatedCards; if (relatedCards.at(0)->getDoesAttach()) { - createRelatedCards = new QAction(tr("Token: ") + tr("Attach to ") + "\"" + relatedCards.at(0)->getName() + "\"", this); + createRelatedCards = + new QAction(tr("Token: ") + tr("Attach to ") + "\"" + relatedCards.at(0)->getName() + "\"", this); } else - createRelatedCards = new QAction(tr("Token: ") + (relatedCards.at(0)->getIsVariable() ? "X " : QString(relatedCards.at(0)->getDefaultCount() == 1 ? QString() : QString::number(relatedCards.at(0)->getDefaultCount()) + "x ")) + relatedCards.at(0)->getName(), this); + createRelatedCards = new QAction( + tr("Token: ") + + (relatedCards.at(0)->getIsVariable() + ? "X " + : QString(relatedCards.at(0)->getDefaultCount() == 1 + ? QString() + : QString::number(relatedCards.at(0)->getDefaultCount()) + "x ")) + + relatedCards.at(0)->getName(), + this); connect(createRelatedCards, SIGNAL(triggered()), this, SLOT(actCreateAllRelatedCards())); if (shortcutsActive) { - createRelatedCards->setShortcut(settingsCache->shortcuts().getSingleShortcut("Player/aCreateRelatedTokens")); + createRelatedCards->setShortcut( + settingsCache->shortcuts().getSingleShortcut("Player/aCreateRelatedTokens")); } cardMenu->addAction(createRelatedCards); break; @@ -2702,14 +2726,21 @@ void Player::addRelatedCardActions(const CardItem *card, QMenu *cardMenu) { default: { cardMenu->addSeparator(); int i = 0; - foreach (CardRelation * cardRelation, relatedCards) - { + foreach (CardRelation *cardRelation, relatedCards) { QString cardName = cardRelation->getName(); QAction *createRelated; if (cardRelation->getDoesAttach()) createRelated = new QAction(tr("Token: ") + tr("Attach to ") + "\"" + cardName + "\"", this); else - createRelated = new QAction(tr("Token: ") + (cardRelation->getIsVariable() ? "X " : QString(cardRelation->getDefaultCount() == 1 ? QString() : QString::number(cardRelation->getDefaultCount()) + "x ")) + cardName, this); + createRelated = + new QAction(tr("Token: ") + + (cardRelation->getIsVariable() + ? "X " + : QString(cardRelation->getDefaultCount() == 1 + ? QString() + : QString::number(cardRelation->getDefaultCount()) + "x ")) + + cardName, + this); createRelated->setData(QVariant(i)); connect(createRelated, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard())); cardMenu->addAction(createRelated); @@ -2718,13 +2749,13 @@ void Player::addRelatedCardActions(const CardItem *card, QMenu *cardMenu) { QAction *createRelatedCards = new QAction(tr("All tokens"), this); connect(createRelatedCards, SIGNAL(triggered()), this, SLOT(actCreateAllRelatedCards())); if (shortcutsActive) { - createRelatedCards->setShortcut(settingsCache->shortcuts().getSingleShortcut("Player/aCreateRelatedTokens")); + createRelatedCards->setShortcut( + settingsCache->shortcuts().getSingleShortcut("Player/aCreateRelatedTokens")); } cardMenu->addAction(createRelatedCards); break; } } - } void Player::setCardMenu(QMenu *menu) diff --git a/cockatrice/src/player.h b/cockatrice/src/player.h index e1f1d295..04c06b84 100644 --- a/cockatrice/src/player.h +++ b/cockatrice/src/player.h @@ -1,15 +1,21 @@ #ifndef PLAYER_H #define PLAYER_H -#include -#include -#include #include "abstractgraphicsitem.h" #include "carddatabase.h" -#include "pb/game_event.pb.h" #include "pb/card_attributes.pb.h" +#include "pb/game_event.pb.h" +#include +#include +#include -namespace google { namespace protobuf { class Message; } } +namespace google +{ +namespace protobuf +{ +class Message; +} +} // namespace google class CardDatabase; class DeckLoader; class QMenu; @@ -59,25 +65,37 @@ class PendingCommand; const int MAX_TOKENS_PER_DIALOG = 99; -class PlayerArea : public QObject, public QGraphicsItem { +class PlayerArea : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) private: QRectF bRect; private slots: void updateBg(); + public: - enum { Type = typeOther }; - int type() const { return Type; } - + enum + { + Type = typeOther + }; + int type() const + { + return Type; + } + PlayerArea(QGraphicsItem *parent = 0); - QRectF boundingRect() const { return bRect; } + 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 { +class Player : public QObject, public QGraphicsItem +{ Q_OBJECT Q_INTERFACES(QGraphicsItem) signals: @@ -87,7 +105,12 @@ signals: 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 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); @@ -104,9 +127,10 @@ signals: 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 + 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: @@ -132,16 +156,16 @@ public slots: void actRevealRandomGraveyardCard(); 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 actCreateRelatedCard(); @@ -168,24 +192,23 @@ private slots: private: TabGame *game; - QMenu *playerMenu, *handMenu, *moveHandMenu, *graveMenu, *moveGraveMenu, *rfgMenu, *moveRfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu, - *mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard, *mRevealRandomGraveyardCard; + QMenu *playerMenu, *handMenu, *moveHandMenu, *graveMenu, *moveGraveMenu, *rfgMenu, *moveRfgMenu, *libraryMenu, + *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu, *mRevealLibrary, *mRevealTopCard, *mRevealHand, + *mRevealRandomHandCard, *mRevealRandomGraveyardCard; 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, *aMoveTopToPlayFaceDown, - *aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken, + *aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg, *aMoveRfgToTopLibrary, + *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave, *aViewLibrary, *aViewTopCards, + *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, + *aMoveTopCardToBottom, *aViewGraveyard, *aViewRfg, *aViewSideboard, *aDrawCard, *aDrawCards, *aUndoDraw, + *aMulligan, *aShuffle, *aMoveTopToPlayFaceDown, *aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken, *aCardMenu, *aMoveBottomCardToGrave; - + QList aAddCounter, aSetCounter, aRemoveCounter; - QAction *aPlay, *aPlayFacedown, - *aHide, - *aTap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone, - *aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToHand, *aMoveToGraveyard, *aMoveToExile, *aMoveToXfromTopOfLibrary; + QAction *aPlay, *aPlayFacedown, *aHide, *aTap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, + *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone, *aMoveToTopLibrary, + *aMoveToBottomLibrary, *aMoveToHand, *aMoveToGraveyard, *aMoveToExile, *aMoveToXfromTopOfLibrary; bool shortcutsActive; int defaultNumberTopCards; @@ -200,22 +223,26 @@ private: 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); + + void setCardAttrHelper(const GameEventContext &context, + CardItem *card, + CardAttribute attribute, + const QString &avalue, + bool allCards); void addRelatedCardActions(const CardItem *card, QMenu *cardMenu); void createCard(const CardItem *sourceCard, const QString &dbCardName, bool attach = false); void createAttachedCard(const CardItem *sourceCard, const QString &dbCardName); @@ -227,9 +254,9 @@ private: 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); @@ -251,16 +278,39 @@ private: 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, cmMoveToHand, cmMoveToGraveyard, cmMoveToExile }; - enum CardsToReveal {RANDOM_CARD_FROM_ZONE = -2}; + enum CardMenuActionType + { + cmTap, + cmUntap, + cmDoesntUntap, + cmFlip, + cmPeek, + cmClone, + cmMoveToTopLibrary, + cmMoveToBottomLibrary, + cmMoveToHand, + cmMoveToGraveyard, + cmMoveToExile + }; + enum CardsToReveal + { + RANDOM_CARD_FROM_ZONE = -2 + }; - enum { Type = typeOther }; - int type() const { return Type; } + 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); @@ -270,53 +320,86 @@ public: 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; } + 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; } + TabGame *getGame() const + { + return game; + } void setDeck(const DeckLoader &_deck); - QMenu *getPlayerMenu() const { return playerMenu; } - int getId() const { return id; } + 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; } + 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(const CardItem *card); - bool getActive() const { return active; } + bool getActive() const + { + return active; + } void setActive(bool _active); void setShortcutsActive(); void setShortcutsInactive(); void updateZones(); - + void setConceded(bool _conceded); - bool getConceded() const { return conceded; } + bool getConceded() const + { + return conceded; + } void setGameStarted(); - + 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); + PendingCommand *prepareGameCommand(const QList &cmdList); void sendGameCommand(PendingCommand *pend); void sendGameCommand(const google::protobuf::Message &command); diff --git a/cockatrice/src/playerlistwidget.cpp b/cockatrice/src/playerlistwidget.cpp index eee0efc6..657c1ca3 100644 --- a/cockatrice/src/playerlistwidget.cpp +++ b/cockatrice/src/playerlistwidget.cpp @@ -1,26 +1,28 @@ -#include #include "playerlistwidget.h" -#include "pixmapgenerator.h" #include "abstractclient.h" +#include "pixmapgenerator.h" #include "tab_game.h" #include "tab_supervisor.h" #include "tab_userlists.h" -#include "userlist.h" #include "user_context_menu.h" -#include +#include "userlist.h" #include +#include #include +#include -#include "pb/session_commands.pb.h" #include "pb/command_kick_from_game.pb.h" #include "pb/serverinfo_playerproperties.pb.h" +#include "pb/session_commands.pb.h" -PlayerListItemDelegate::PlayerListItemDelegate(QObject *const parent) - : QStyledItemDelegate(parent) +PlayerListItemDelegate::PlayerListItemDelegate(QObject *const parent) : QStyledItemDelegate(parent) { } -bool PlayerListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) +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); @@ -32,8 +34,7 @@ bool PlayerListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *mode return QStyledItemDelegate::editorEvent(event, model, option, index); } -PlayerListTWI::PlayerListTWI() - : QTreeWidgetItem(Type) +PlayerListTWI::PlayerListTWI() : QTreeWidgetItem(Type) { } @@ -42,12 +43,15 @@ 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(); } -PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent) +PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor, + AbstractClient *_client, + TabGame *_game, + QWidget *parent) : QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false) { readyIcon = QPixmap("theme:icons/ready_start"); @@ -56,16 +60,17 @@ PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient playerIcon = QPixmap("theme:icons/player"); spectatorIcon = QPixmap("theme:icons/spectator"); lockIcon = QPixmap("theme:icons/lock"); - + 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))); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, + SIGNAL(openMessageDialog(QString, bool))); } else userContextMenu = 0; - + setMinimumHeight(40); setIconSize(QSize(20, 15)); setColumnCount(6); @@ -100,27 +105,29 @@ void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties { if (playerId == -1) playerId = prop.player_id(); - + QTreeWidgetItem *player = players.value(playerId, 0); if (!player) return; - + bool isSpectator = prop.has_spectator() && prop.spectator(); player->setIcon(1, isSpectator ? spectatorIcon : playerIcon); player->setData(1, Qt::UserRole, !isSpectator); - if(!isSpectator) - { + if (!isSpectator) { 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)); + 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()), false, QString::fromStdString(prop.user_info().privlevel())))); + player->setIcon( + 3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level()), false, + QString::fromStdString(prop.user_info().privlevel())))); player->setText(4, QString::fromStdString(prop.user_info().name())); const QString country = QString::fromStdString(prop.user_info().country()); if (!country.isEmpty()) @@ -131,8 +138,7 @@ void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties if (prop.has_player_id()) player->setData(4, Qt::UserRole + 1, prop.player_id()); - if(!isSpectator) - { + if (!isSpectator) { if (prop.has_deck_hash()) { player->setText(5, QString::fromStdString(prop.deck_hash())); } @@ -171,7 +177,7 @@ void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming) QTreeWidgetItem *twi = i.next().value(); bool isPlayer = twi->data(1, Qt::UserRole).toBool(); - if(!isPlayer) + if (!isPlayer) continue; if (gameStarted) { @@ -191,10 +197,10 @@ void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &ind { 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, true, playerId); } diff --git a/cockatrice/src/playerlistwidget.h b/cockatrice/src/playerlistwidget.h index ff932ce7..278bb3c8 100644 --- a/cockatrice/src/playerlistwidget.h +++ b/cockatrice/src/playerlistwidget.h @@ -1,10 +1,10 @@ #ifndef PLAYERLISTWIDGET_H #define PLAYERLISTWIDGET_H -#include -#include #include +#include #include +#include class ServerInfo_PlayerProperties; class TabSupervisor; @@ -12,19 +12,23 @@ class AbstractClient; class TabGame; class UserContextMenu; -class PlayerListItemDelegate : public QStyledItemDelegate { +class PlayerListItemDelegate : public QStyledItemDelegate +{ public: PlayerListItemDelegate(QObject *const parent); - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); + bool + editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; -class PlayerListTWI : public QTreeWidgetItem { +class PlayerListTWI : public QTreeWidgetItem +{ public: PlayerListTWI(); bool operator<(const QTreeWidgetItem &other) const; }; -class PlayerListWidget : public QTreeWidget { +class PlayerListWidget : public QTreeWidget +{ Q_OBJECT private: PlayerListItemDelegate *itemDelegate; @@ -37,6 +41,7 @@ private: bool gameStarted; signals: void openMessageDialog(const QString &userName, bool focus); + public: PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0); void retranslateUi(); diff --git a/cockatrice/src/playertarget.cpp b/cockatrice/src/playertarget.cpp index ad2d660b..585c34a0 100644 --- a/cockatrice/src/playertarget.cpp +++ b/cockatrice/src/playertarget.cpp @@ -1,10 +1,10 @@ #include "playertarget.h" -#include "player.h" -#include "pixmapgenerator.h" #include "pb/serverinfo_user.pb.h" +#include "pixmapgenerator.h" +#include "player.h" +#include #include #include -#include #include #ifdef _WIN32 #include "round.h" @@ -30,19 +30,19 @@ void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /* 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 = path.controlPointRect(); QSize translatedSize = translatedRect.size().toSize(); QFont font("Serif"); font.setWeight(QFont::Bold); - font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9)); + 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)); @@ -52,9 +52,9 @@ PlayerTarget::PlayerTarget(Player *_owner, QGraphicsItem *parentItem) : ArrowTarget(_owner, parentItem), playerCounter(0) { setCacheMode(DeviceCoordinateCache); - + const std::string &bmp = _owner->getUserInfo()->avatar_bmp(); - if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) + if (!fullPixmap.loadFromData((const uchar *)bmp.data(), bmp.size())) fullPixmap = QPixmap(); } @@ -80,27 +80,35 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o 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()); + const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey()); if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); - + QPainter tempPainter(&cachedPixmap); - // pow(foo, 0.5) equals to sqrt(foo), but using sqrt(foo) in this context will produce a compile error with MSVC++ - QRadialGradient grad(translatedRect.center(), pow(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height(), 0.5) / 2); + // pow(foo, 0.5) equals to sqrt(foo), but using sqrt(foo) in this context will produce a compile error with + // MSVC++ + QRadialGradient grad(translatedRect.center(), pow(translatedSize.width() * translatedSize.width() + + translatedSize.height() * translatedSize.height(), + 0.5) / + 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()), false, QString::fromStdString(info->privlevel())); + tempPixmap = + UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level()), + false, QString::fromStdString(info->privlevel())); else tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); + + 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); @@ -110,16 +118,16 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o 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)); + 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); @@ -130,7 +138,7 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o 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))); } @@ -143,9 +151,10 @@ AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, } playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); - playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); + playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), + boundingRect().height() - playerCounter->boundingRect().height()); connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted())); - + return playerCounter; } diff --git a/cockatrice/src/playertarget.h b/cockatrice/src/playertarget.h index 8d36084c..eb7ca07f 100644 --- a/cockatrice/src/playertarget.h +++ b/cockatrice/src/playertarget.h @@ -1,14 +1,15 @@ #ifndef PLAYERTARGET_H #define PLAYERTARGET_H -#include "arrowtarget.h" #include "abstractcounter.h" +#include "arrowtarget.h" #include #include class Player; -class PlayerCounter : public AbstractCounter { +class PlayerCounter : public AbstractCounter +{ Q_OBJECT public: PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0); @@ -16,22 +17,30 @@ public: void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; -class PlayerTarget : public ArrowTarget { +class PlayerTarget : public ArrowTarget +{ Q_OBJECT private: QPixmap fullPixmap; PlayerCounter *playerCounter; public slots: void counterDeleted(); + public: - enum { Type = typePlayerTarget }; - int type() const { return Type; } - + 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); }; diff --git a/cockatrice/src/releasechannel.cpp b/cockatrice/src/releasechannel.cpp index 61d6d2f9..bd2b3f3f 100644 --- a/cockatrice/src/releasechannel.cpp +++ b/cockatrice/src/releasechannel.cpp @@ -2,11 +2,11 @@ #include "qt-json/json.h" #include "version_string.h" -#include -#include +#include #include #include -#include +#include +#include #define STABLERELEASE_URL "https://api.github.com/repos/Cockatrice/Cockatrice/releases/latest" #define STABLETAG_URL "https://api.github.com/repos/Cockatrice/Cockatrice/git/refs/tags/" @@ -20,8 +20,7 @@ int ReleaseChannel::sharedIndex = 0; -ReleaseChannel::ReleaseChannel() -: response(nullptr), lastRelease(nullptr) +ReleaseChannel::ReleaseChannel() : response(nullptr), lastRelease(nullptr) { index = sharedIndex++; netMan = new QNetworkAccessManager(this); @@ -75,7 +74,7 @@ bool ReleaseChannel::downloadMatchesCurrentOS(const QString &fileName) bool ReleaseChannel::downloadMatchesCurrentOS(const QString &) { - //If the OS doesn't fit one of the above #defines, then it will never match + // If the OS doesn't fit one of the above #defines, then it will never match return false; } @@ -110,10 +109,8 @@ void StableReleaseChannel::releaseListFinished() return; } - if(!(resultMap.contains("name") && - resultMap.contains("html_url") && - resultMap.contains("tag_name") && - resultMap.contains("published_at"))) { + if (!(resultMap.contains("name") && resultMap.contains("html_url") && resultMap.contains("tag_name") && + resultMap.contains("published_at"))) { qWarning() << "Invalid received from the release update server:" << tmp; emit error(tr("Invalid reply received from the release update server.")); return; @@ -138,7 +135,7 @@ void StableReleaseChannel::releaseListFinished() }); auto _releaseAsset = std::find_if(assets.begin(), assets.end(), [](std::pair nameAndUrl) { - return downloadMatchesCurrentOS(nameAndUrl.first); + return downloadMatchesCurrentOS(nameAndUrl.first); }); if (_releaseAsset != assets.end()) { @@ -152,11 +149,9 @@ void StableReleaseChannel::releaseListFinished() QString myHash = QString(VERSION_COMMIT); qDebug() << "Current hash=" << myHash << "update hash=" << shortHash; - qDebug() << "Got reply from release server, size=" << tmp.size() - << "name=" << lastRelease->getName() - << "desc=" << lastRelease->getDescriptionUrl() - << "date=" << lastRelease->getPublishDate() - << "url=" << lastRelease->getDownloadUrl(); + qDebug() << "Got reply from release server, size=" << tmp.size() << "name=" << lastRelease->getName() + << "desc=" << lastRelease->getDescriptionUrl() << "date=" << lastRelease->getPublishDate() + << "url=" << lastRelease->getDownloadUrl(); const QString &tagName = resultMap["tag_name"].toString(); QString url = QString(STABLETAG_URL) + tagName; @@ -179,24 +174,20 @@ void StableReleaseChannel::tagListFinished() return; } - if(!(resultMap.contains("object") && - resultMap["object"].toMap().contains("sha"))) { + if (!(resultMap.contains("object") && resultMap["object"].toMap().contains("sha"))) { qWarning() << "Invalid received from the tag update server:" << tmp; emit error(tr("Invalid reply received from the tag update server.")); return; } lastRelease->setCommitHash(resultMap["object"].toMap()["sha"].toString()); - qDebug() << "Got reply from tag server, size=" << tmp.size() - << "commit=" << lastRelease->getCommitHash(); - + qDebug() << "Got reply from tag server, size=" << tmp.size() << "commit=" << lastRelease->getCommitHash(); QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); QString myHash = QString(VERSION_COMMIT); qDebug() << "Current hash=" << myHash << "update hash=" << shortHash; const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); - emit finishedCheck(needToUpdate, lastRelease->isCompatibleVersionFound(), lastRelease); } @@ -221,7 +212,6 @@ QString DevReleaseChannel::getReleaseChannelUrl() const return QString(DEVRELEASE_URL); } - void DevReleaseChannel::releaseListFinished() { QNetworkReply *reply = static_cast(sender()); @@ -245,13 +235,9 @@ void DevReleaseChannel::releaseListFinished() } // Make sure resultMap has all elements we'll need - if (!resultMap.contains("assets") || - !resultMap.contains("author") || - !resultMap.contains("tag_name") || - !resultMap.contains("target_commitish") || - !resultMap.contains("assets_url") || - !resultMap.contains("published_at")) - { + if (!resultMap.contains("assets") || !resultMap.contains("author") || !resultMap.contains("tag_name") || + !resultMap.contains("target_commitish") || !resultMap.contains("assets_url") || + !resultMap.contains("published_at")) { qWarning() << "Invalid received from the release update server:" << resultMap; emit error(tr("Invalid reply received from the release update server.")); return; @@ -266,12 +252,10 @@ void DevReleaseChannel::releaseListFinished() QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); lastRelease->setName(QString("%1 (%2)").arg(resultMap["tag_name"].toString()).arg(shortHash)); lastRelease->setDescriptionUrl(QString(DEVRELEASE_DESCURL).arg(VERSION_COMMIT, shortHash)); - - qDebug() << "Got reply from release server, size=" << resultMap.size() - << "name=" << lastRelease->getName() - << "desc=" << lastRelease->getDescriptionUrl() - << "commit=" << lastRelease->getCommitHash() - << "date=" << lastRelease->getPublishDate(); + + qDebug() << "Got reply from release server, size=" << resultMap.size() << "name=" << lastRelease->getName() + << "desc=" << lastRelease->getDescriptionUrl() << "commit=" << lastRelease->getCommitHash() + << "date=" << lastRelease->getPublishDate(); QString devBuildDownloadUrl = resultMap["assets_url"].toString(); @@ -301,8 +285,7 @@ void DevReleaseChannel::fileListFinished() bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); bool compatibleVersion = false; - foreach(QVariant file, resultList) - { + foreach (QVariant file, resultList) { QVariantMap map = file.toMap(); QString url = map["browser_download_url"].toString(); @@ -315,6 +298,6 @@ void DevReleaseChannel::fileListFinished() qDebug() << "Found compatible version url=" << url; break; } - + emit finishedCheck(needToUpdate, compatibleVersion, lastRelease); } diff --git a/cockatrice/src/releasechannel.h b/cockatrice/src/releasechannel.h index 4bc1dcab..6ad136d8 100644 --- a/cockatrice/src/releasechannel.h +++ b/cockatrice/src/releasechannel.h @@ -1,57 +1,106 @@ #ifndef RELEASECHANNEL_H #define RELEASECHANNEL_H -#include #include #include +#include #include class QNetworkReply; class QNetworkAccessManager; -class Release { +class Release +{ friend class StableReleaseChannel; friend class DevReleaseChannel; + public: - Release() {}; - ~Release() {}; + Release(){}; + ~Release(){}; + private: QString name, descriptionUrl, downloadUrl, commitHash; QDate publishDate; bool compatibleVersionFound = false; + protected: - void setName(QString _name) { name = _name; } - void setDescriptionUrl(QString _descriptionUrl) { descriptionUrl = _descriptionUrl; } - void setDownloadUrl(QString _downloadUrl) { downloadUrl = _downloadUrl; compatibleVersionFound = true; } - void setCommitHash(QString _commitHash) { commitHash = _commitHash; } - void setPublishDate(QDate _publishDate) { publishDate = _publishDate; } + void setName(QString _name) + { + name = _name; + } + void setDescriptionUrl(QString _descriptionUrl) + { + descriptionUrl = _descriptionUrl; + } + void setDownloadUrl(QString _downloadUrl) + { + downloadUrl = _downloadUrl; + compatibleVersionFound = true; + } + void setCommitHash(QString _commitHash) + { + commitHash = _commitHash; + } + void setPublishDate(QDate _publishDate) + { + publishDate = _publishDate; + } + public: - QString getName() const { return name; } - QString getDescriptionUrl() const { return descriptionUrl; } - QString getDownloadUrl() const { return downloadUrl; } - QString getCommitHash() const { return commitHash; } - QDate getPublishDate() const { return publishDate; } - bool isCompatibleVersionFound() const { return compatibleVersionFound; } + QString getName() const + { + return name; + } + QString getDescriptionUrl() const + { + return descriptionUrl; + } + QString getDownloadUrl() const + { + return downloadUrl; + } + QString getCommitHash() const + { + return commitHash; + } + QDate getPublishDate() const + { + return publishDate; + } + bool isCompatibleVersionFound() const + { + return compatibleVersionFound; + } }; -class ReleaseChannel: public QObject { +class ReleaseChannel : public QObject +{ Q_OBJECT public: ReleaseChannel(); ~ReleaseChannel(); + protected: // shared by all instances static int sharedIndex; int index; QNetworkAccessManager *netMan; QNetworkReply *response; - Release * lastRelease; + Release *lastRelease; + protected: static bool downloadMatchesCurrentOS(const QString &fileName); virtual QString getReleaseChannelUrl() const = 0; + public: - int getIndex() const { return index; } - Release * getLastRelease() { return lastRelease; } + int getIndex() const + { + return index; + } + Release *getLastRelease() + { + return lastRelease; + } virtual QString getManualDownloadUrl() const = 0; virtual QString getName() const = 0; void checkForUpdates(); @@ -63,13 +112,15 @@ protected slots: virtual void fileListFinished() = 0; }; -class StableReleaseChannel: public ReleaseChannel { +class StableReleaseChannel : public ReleaseChannel +{ Q_OBJECT public: - StableReleaseChannel() {}; - ~StableReleaseChannel() {}; + StableReleaseChannel(){}; + ~StableReleaseChannel(){}; virtual QString getManualDownloadUrl() const; virtual QString getName() const; + protected: virtual QString getReleaseChannelUrl() const; protected slots: @@ -78,13 +129,15 @@ protected slots: virtual void fileListFinished(); }; -class DevReleaseChannel: public ReleaseChannel { +class DevReleaseChannel : public ReleaseChannel +{ Q_OBJECT public: - DevReleaseChannel() {}; - ~DevReleaseChannel() {}; + DevReleaseChannel(){}; + ~DevReleaseChannel(){}; virtual QString getManualDownloadUrl() const; virtual QString getName() const; + protected: virtual QString getReleaseChannelUrl() const; protected slots: diff --git a/cockatrice/src/remoteclient.cpp b/cockatrice/src/remoteclient.cpp index 5f15d1ea..5d78f7fe 100644 --- a/cockatrice/src/remoteclient.cpp +++ b/cockatrice/src/remoteclient.cpp @@ -1,29 +1,29 @@ -#include -#include -#include -#include -#include -#include -#include #include "remoteclient.h" -#include "settingscache.h" -#include "pending_command.h" +#include "main.h" #include "pb/commands.pb.h" -#include "pb/session_commands.pb.h" -#include "pb/response_login.pb.h" -#include "pb/response_register.pb.h" +#include "pb/event_server_identification.pb.h" #include "pb/response_activate.pb.h" #include "pb/response_forgotpasswordrequest.pb.h" +#include "pb/response_login.pb.h" +#include "pb/response_register.pb.h" #include "pb/server_message.pb.h" -#include "pb/event_server_identification.pb.h" +#include "pb/session_commands.pb.h" +#include "pending_command.h" #include "settingscache.h" -#include "main.h" #include "version_string.h" +#include +#include +#include +#include +#include +#include +#include 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) { clearNewClientFeatures(); @@ -32,21 +32,28 @@ RemoteClient::RemoteClient(QObject *parent) timer->setInterval(keepalive * 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(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())); - connect(this, SIGNAL(sigRegisterToServer(QString, unsigned int, QString, QString, QString, int, QString, QString)), this, SLOT(doRegisterToServer(QString, unsigned int, QString, QString, QString, int, QString, QString))); + connect(this, SIGNAL(sigRegisterToServer(QString, unsigned int, QString, QString, QString, int, QString, QString)), + this, SLOT(doRegisterToServer(QString, unsigned int, QString, QString, QString, int, QString, QString))); connect(this, SIGNAL(sigActivateToServer(QString)), this, SLOT(doActivateToServer(QString))); - connect(this, SIGNAL(sigRequestForgotPasswordToServer(QString, unsigned int, QString)), this, SLOT(doRequestForgotPasswordToServer(QString, unsigned int, QString))); - connect(this, SIGNAL(sigSubmitForgotPasswordResetToServer(QString, unsigned int, QString, QString, QString)), this, SLOT(doSubmitForgotPasswordResetToServer(QString, unsigned int, QString, QString, QString))); - connect(this, SIGNAL(sigSubmitForgotPasswordChallengeToServer(QString, unsigned int, QString, QString)), this, SLOT(doSubmitForgotPasswordChallengeToServer(QString, unsigned int, QString, QString))); + connect(this, SIGNAL(sigRequestForgotPasswordToServer(QString, unsigned int, QString)), this, + SLOT(doRequestForgotPasswordToServer(QString, unsigned int, QString))); + connect(this, SIGNAL(sigSubmitForgotPasswordResetToServer(QString, unsigned int, QString, QString, QString)), this, + SLOT(doSubmitForgotPasswordResetToServer(QString, unsigned int, QString, QString, QString))); + connect(this, SIGNAL(sigSubmitForgotPasswordChallengeToServer(QString, unsigned int, QString, QString)), this, + SLOT(doSubmitForgotPasswordChallengeToServer(QString, unsigned int, QString, QString))); } RemoteClient::~RemoteClient() @@ -81,49 +88,48 @@ void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentifica return; } - if (getStatus() == StatusRequestingForgotPassword) - { + if (getStatus() == StatusRequestingForgotPassword) { Command_ForgotPasswordRequest cmdForgotPasswordRequest; cmdForgotPasswordRequest.set_user_name(userName.toStdString()); cmdForgotPasswordRequest.set_clientid(getSrvClientID(lastHostname).toStdString()); PendingCommand *pend = prepareSessionCommand(cmdForgotPasswordRequest); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(requestForgotPasswordResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(requestForgotPasswordResponse(Response))); sendCommand(pend); return; } - if (getStatus() == StatusSubmitForgotPasswordReset) - { + if (getStatus() == StatusSubmitForgotPasswordReset) { Command_ForgotPasswordReset cmdForgotPasswordReset; cmdForgotPasswordReset.set_user_name(userName.toStdString()); cmdForgotPasswordReset.set_clientid(getSrvClientID(lastHostname).toStdString()); cmdForgotPasswordReset.set_token(token.toStdString()); cmdForgotPasswordReset.set_new_password(password.toStdString()); PendingCommand *pend = prepareSessionCommand(cmdForgotPasswordReset); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(submitForgotPasswordResetResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(submitForgotPasswordResetResponse(Response))); sendCommand(pend); return; } - if (getStatus() == StatusSubmitForgotPasswordChallenge) - { + if (getStatus() == StatusSubmitForgotPasswordChallenge) { Command_ForgotPasswordChallenge cmdForgotPasswordChallenge; cmdForgotPasswordChallenge.set_user_name(userName.toStdString()); cmdForgotPasswordChallenge.set_clientid(getSrvClientID(lastHostname).toStdString()); cmdForgotPasswordChallenge.set_email(email.toStdString()); PendingCommand *pend = prepareSessionCommand(cmdForgotPasswordChallenge); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(submitForgotPasswordChallengeResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(submitForgotPasswordChallengeResponse(Response))); sendCommand(pend); return; } - if(getStatus() == StatusRegistering) - { + if (getStatus() == StatusRegistering) { Command_Register cmdRegister; cmdRegister.set_user_name(userName.toStdString()); cmdRegister.set_password(password.toStdString()); cmdRegister.set_email(email.toStdString()); - cmdRegister.set_gender((ServerInfo_User_Gender) gender); + cmdRegister.set_gender((ServerInfo_User_Gender)gender); cmdRegister.set_country(country.toStdString()); cmdRegister.set_real_name(realName.toStdString()); cmdRegister.set_clientid(getSrvClientID(lastHostname).toStdString()); @@ -134,8 +140,7 @@ void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentifica return; } - if(getStatus() == StatusActivating) - { + if (getStatus() == StatusActivating) { Command_Activate cmdActivate; cmdActivate.set_user_name(userName.toStdString()); cmdActivate.set_token(token.toStdString()); @@ -151,7 +156,8 @@ void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentifica doLogin(); } -void RemoteClient::doLogin() { +void RemoteClient::doLogin() +{ setStatus(StatusLoggingIn); Command_Login cmdLogin; cmdLogin.set_user_name(userName.toStdString()); @@ -177,7 +183,7 @@ void RemoteClient::processConnectionClosedEvent(const Event_ConnectionClosed & / void RemoteClient::loginResponse(const Response &response) { const Response_Login &resp = response.GetExtension(Response_Login::ext); - + QString possibleMissingFeatures; if (resp.missing_features_size() > 0) { for (int i = 0; i < resp.missing_features_size(); ++i) @@ -198,7 +204,8 @@ void RemoteClient::loginResponse(const Response &response) ignoreList.append(resp.ignore_list(i)); emit ignoreListReceived(ignoreList); - if (newMissingFeatureFound(possibleMissingFeatures) && resp.missing_features_size() > 0 && settingsCache->getNotifyAboutUpdates()) { + if (newMissingFeatureFound(possibleMissingFeatures) && resp.missing_features_size() > 0 && + settingsCache->getNotifyAboutUpdates()) { settingsCache->setKnownMissingFeatures(possibleMissingFeatures); emit notifyUserAboutUpdate(); } @@ -209,7 +216,8 @@ void RemoteClient::loginResponse(const Response &response) for (int i = 0; i < resp.missing_features_size(); ++i) missingFeatures << QString::fromStdString(resp.missing_features(i)); } - emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time(), missingFeatures); + emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), + resp.denied_end_time(), missingFeatures); setStatus(StatusDisconnecting); } } @@ -217,8 +225,7 @@ void RemoteClient::loginResponse(const Response &response) void RemoteClient::registerResponse(const Response &response) { const Response_Register &resp = response.GetExtension(Response_Register::ext); - switch(response.response_code()) - { + switch (response.response_code()) { case Response::RespRegistrationAccepted: emit registerAccepted(); doLogin(); @@ -228,7 +235,8 @@ void RemoteClient::registerResponse(const Response &response) doLogin(); break; default: - emit registerError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time()); + emit registerError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), + resp.denied_end_time()); setStatus(StatusDisconnecting); doDisconnectFromServer(); break; @@ -264,11 +272,11 @@ void RemoteClient::readData() messageLength = 60; } } else { - // end of hack - messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24) - + (((quint32) (unsigned char) inputBuffer[1]) << 16) - + (((quint32) (unsigned char) inputBuffer[2]) << 8) - + ((quint32) (unsigned char) inputBuffer[3]); + // end of hack + messageLength = (((quint32)(unsigned char)inputBuffer[0]) << 24) + + (((quint32)(unsigned char)inputBuffer[1]) << 16) + + (((quint32)(unsigned char)inputBuffer[2]) << 8) + + ((quint32)(unsigned char)inputBuffer[3]); inputBuffer.remove(0, 4); messageInProgress = true; } @@ -302,15 +310,18 @@ void RemoteClient::sendCommandContainer(const CommandContainer &cont) #endif 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); + 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) +void RemoteClient::doConnectToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password) { doDisconnectFromServer(); @@ -323,7 +334,14 @@ void RemoteClient::doConnectToServer(const QString &hostname, unsigned int port, setStatus(StatusConnecting); } -void RemoteClient::doRegisterToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password, const QString &_email, const int _gender, const QString &_country, const QString &_realname) +void RemoteClient::doRegisterToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password, + const QString &_email, + const int _gender, + const QString &_country, + const QString &_realname) { doDisconnectFromServer(); @@ -396,12 +414,22 @@ void RemoteClient::ping() } } -void RemoteClient::connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password) +void RemoteClient::connectToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password) { emit sigConnectToServer(hostname, port, _userName, _password); } -void RemoteClient::registerToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password, const QString &_email, const int _gender, const QString &_country, const QString &_realname) +void RemoteClient::registerToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password, + const QString &_email, + const int _gender, + const QString &_country, + const QString &_realname) { emit sigRegisterToServer(hostname, port, _userName, _password, _email, _gender, _country, _realname); } @@ -423,12 +451,12 @@ QString RemoteClient::getSrvClientID(const QString _hostname) if (!hostInfo.error()) { QHostAddress hostAddress = hostInfo.addresses().first(); srvClientID += hostAddress.toString(); - } - else { + } else { qDebug() << "Warning: ClientID generation host lookup failure [" << hostInfo.errorString() << "]"; srvClientID += _hostname; } - QString uniqueServerClientID = QCryptographicHash::hash(srvClientID.toUtf8(), QCryptographicHash::Sha1).toHex().right(15); + QString uniqueServerClientID = + QCryptographicHash::hash(srvClientID.toUtf8(), QCryptographicHash::Sha1).toHex().right(15); return uniqueServerClientID; } @@ -436,7 +464,7 @@ bool RemoteClient::newMissingFeatureFound(QString _serversMissingFeatures) { bool newMissingFeature = false; QStringList serversMissingFeaturesList = _serversMissingFeatures.split(","); - foreach(const QString &feature, serversMissingFeaturesList) { + foreach (const QString &feature, serversMissingFeaturesList) { if (!feature.isEmpty()) { if (!settingsCache->getKnownMissingFeatures().contains(feature)) return true; @@ -449,7 +477,7 @@ void RemoteClient::clearNewClientFeatures() { QString newKnownMissingFeatures; QStringList existingKnownMissingFeatures = settingsCache->getKnownMissingFeatures().split(","); - foreach(const QString &existingKnownFeature, existingKnownMissingFeatures) { + foreach (const QString &existingKnownFeature, existingKnownMissingFeatures) { if (!existingKnownFeature.isEmpty()) { if (!clientFeatures.contains(existingKnownFeature)) newKnownMissingFeatures.append("," + existingKnownFeature); @@ -463,7 +491,11 @@ void RemoteClient::requestForgotPasswordToServer(const QString &hostname, unsign emit sigRequestForgotPasswordToServer(hostname, port, _userName); } -void RemoteClient::submitForgotPasswordResetToServer(const QString & hostname, unsigned int port, const QString & _userName, const QString & _token, const QString & _newpassword) +void RemoteClient::submitForgotPasswordResetToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_token, + const QString &_newpassword) { emit sigSubmitForgotPasswordResetToServer(hostname, port, _userName, _token, _newpassword); } @@ -483,22 +515,22 @@ void RemoteClient::doRequestForgotPasswordToServer(const QString &hostname, unsi void RemoteClient::requestForgotPasswordResponse(const Response &response) { const Response_ForgotPasswordRequest &resp = response.GetExtension(Response_ForgotPasswordRequest::ext); - if (response.response_code() == Response::RespOk) - { + if (response.response_code() == Response::RespOk) { if (resp.challenge_email()) { emit sigPromptForForgotPasswordChallenge(); - } - else + } else emit sigPromptForForgotPasswordReset(); - } - else + } else emit sigForgotPasswordError(); doDisconnectFromServer(); - } -void RemoteClient::doSubmitForgotPasswordResetToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_token, const QString &_newpassword) +void RemoteClient::doSubmitForgotPasswordResetToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_token, + const QString &_newpassword) { doDisconnectFromServer(); @@ -522,12 +554,18 @@ void RemoteClient::submitForgotPasswordResetResponse(const Response &response) doDisconnectFromServer(); } -void RemoteClient::submitForgotPasswordChallengeToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_email) +void RemoteClient::submitForgotPasswordChallengeToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_email) { emit sigSubmitForgotPasswordChallengeToServer(hostname, port, _userName, _email); } -void RemoteClient::doSubmitForgotPasswordChallengeToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_email) +void RemoteClient::doSubmitForgotPasswordChallengeToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_email) { doDisconnectFromServer(); @@ -544,8 +582,7 @@ void RemoteClient::submitForgotPasswordChallengeResponse(const Response &respons { if (response.response_code() == Response::RespOk) { emit sigPromptForForgotPasswordReset(); - } - else + } else emit sigForgotPasswordError(); doDisconnectFromServer(); diff --git a/cockatrice/src/remoteclient.h b/cockatrice/src/remoteclient.h index 7c2e2778..f0bc93bc 100644 --- a/cockatrice/src/remoteclient.h +++ b/cockatrice/src/remoteclient.h @@ -1,12 +1,13 @@ #ifndef REMOTECLIENT_H #define REMOTECLIENT_H -#include #include "abstractclient.h" +#include class QTimer; -class RemoteClient : public AbstractClient { +class RemoteClient : public AbstractClient +{ Q_OBJECT signals: void maxPingTime(int seconds, int maxSeconds); @@ -17,8 +18,16 @@ signals: 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 sigRegisterToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password, const QString &_email, const int _gender, const QString &_country, const QString &_realname); + void + sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void sigRegisterToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password, + const QString &_email, + const int _gender, + const QString &_country, + const QString &_realname); void sigActivateToServer(const QString &_token); void sigDisconnectFromServer(); void notifyUserAboutUpdate(); @@ -26,9 +35,16 @@ signals: void sigForgotPasswordSuccess(); void sigForgotPasswordError(); void sigPromptForForgotPasswordReset(); - void sigSubmitForgotPasswordResetToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_token, const QString &_newpassword); + void sigSubmitForgotPasswordResetToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_token, + const QString &_newpassword); void sigPromptForForgotPasswordChallenge(); - void sigSubmitForgotPasswordChallengeToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_email); + void sigSubmitForgotPasswordChallengeToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_email); private slots: void slotConnected(); void readData(); @@ -39,17 +55,33 @@ private slots: void loginResponse(const Response &response); void registerResponse(const Response &response); void activateResponse(const Response &response); - void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void doRegisterToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password, const QString &_email, const int _gender, const QString &_country, const QString &_realname); + void + doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void doRegisterToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password, + const QString &_email, + const int _gender, + const QString &_country, + const QString &_realname); void doLogin(); void doDisconnectFromServer(); void doActivateToServer(const QString &_token); void doRequestForgotPasswordToServer(const QString &hostname, unsigned int port, const QString &_userName); void requestForgotPasswordResponse(const Response &response); - void doSubmitForgotPasswordResetToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_token, const QString &_newpassword); + void doSubmitForgotPasswordResetToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_token, + const QString &_newpassword); void submitForgotPasswordResetResponse(const Response &response); - void doSubmitForgotPasswordChallengeToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_email); + void doSubmitForgotPasswordChallengeToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_email); void submitForgotPasswordChallengeResponse(const Response &response); + private: static const int maxTimeout = 10; int timeRunning, lastDataReceived; @@ -60,25 +92,44 @@ private: bool newMissingFeatureFound(QString _serversMissingFeatures); void clearNewClientFeatures(); int messageLength; - + QTimer *timer; QTcpSocket *socket; QString lastHostname; int lastPort; QString getSrvClientID(const QString _hostname); -protected slots: +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 registerToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password, const QString &_email, const int _gender, const QString &_country, const QString &_realname); + QString peerName() const + { + return socket->peerName(); + } + void + connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void registerToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_password, + const QString &_email, + const int _gender, + const QString &_country, + const QString &_realname); void activateToServer(const QString &_token); void disconnectFromServer(); void requestForgotPasswordToServer(const QString &hostname, unsigned int port, const QString &_userName); - void submitForgotPasswordResetToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_token, const QString &_newpassword); - void submitForgotPasswordChallengeToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_email); + void submitForgotPasswordResetToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_token, + const QString &_newpassword); + void submitForgotPasswordChallengeToServer(const QString &hostname, + unsigned int port, + const QString &_userName, + const QString &_email); }; #endif diff --git a/cockatrice/src/remotedecklist_treewidget.cpp b/cockatrice/src/remotedecklist_treewidget.cpp index 3f94c785..612987b1 100644 --- a/cockatrice/src/remotedecklist_treewidget.cpp +++ b/cockatrice/src/remotedecklist_treewidget.cpp @@ -1,15 +1,16 @@ +#include "remotedecklist_treewidget.h" +#include "abstractclient.h" #include #include #include -#include "remotedecklist_treewidget.h" -#include "abstractclient.h" -#include "pending_command.h" #include "pb/command_deck_list.pb.h" #include "pb/response_deck_list.pb.h" #include "pb/serverinfo_deckstorage.pb.h" +#include "pending_command.h" -RemoteDeckList_TreeModel::DirectoryNode::DirectoryNode(const QString &_name, RemoteDeckList_TreeModel::DirectoryNode *_parent) +RemoteDeckList_TreeModel::DirectoryNode::DirectoryNode(const QString &_name, + RemoteDeckList_TreeModel::DirectoryNode *_parent) : RemoteDeckList_TreeModel::Node(_name, _parent) { } @@ -48,7 +49,7 @@ RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode if (pathItem.isEmpty() && name.isEmpty()) return this; } - + for (int i = 0; i < size(); ++i) { DirectoryNode *node = dynamic_cast(at(i)); if (!node) @@ -101,7 +102,7 @@ int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const return 0; } -int RemoteDeckList_TreeModel::columnCount(const QModelIndex &/*parent*/) const +int RemoteDeckList_TreeModel::columnCount(const QModelIndex & /*parent*/) const { return 3; } @@ -120,22 +121,27 @@ QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) cons switch (role) { case Qt::DisplayRole: { switch (index.column()) { - case 0: return node->getName(); + case 0: + return node->getName(); default: return QVariant(); } } case Qt::DecorationRole: return index.column() == 0 ? dirIcon : QVariant(); - default: return 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(); + case 0: + return file->getName(); + case 1: + return file->getId(); + case 2: + return file->getUploadTime(); default: return QVariant(); } @@ -144,7 +150,8 @@ QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) cons return index.column() == 0 ? fileIcon : QVariant(); case Qt::TextAlignmentRole: return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft; - default: return QVariant(); + default: + return QVariant(); } } } @@ -158,13 +165,18 @@ QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orien 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(); + case 0: + return tr("Name"); + case 1: + return tr("ID"); + case 2: + return tr("Upload time"); + default: + return QVariant(); } } - default: return QVariant(); + default: + return QVariant(); } } @@ -208,7 +220,7 @@ void RemoteDeckList_TreeModel::addFileToTree(const ServerInfo_DeckStorage_TreeIt 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(); @@ -228,7 +240,8 @@ void RemoteDeckList_TreeModel::addFolderToTree(const ServerInfo_DeckStorage_Tree } } -RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::addNamedFolderToTree(const QString &name, DirectoryNode *parent) +RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::addNamedFolderToTree(const QString &name, + DirectoryNode *parent) { DirectoryNode *newItem = new DirectoryNode(name, parent); beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); @@ -249,8 +262,9 @@ void RemoteDeckList_TreeModel::removeNode(RemoteDeckList_TreeModel::Node *node) void RemoteDeckList_TreeModel::refreshTree() { PendingCommand *pend = client->prepareSessionCommand(Command_DeckList()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &))); - + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(deckListFinished(const Response &))); + client->sendCommand(pend); } @@ -263,17 +277,16 @@ void RemoteDeckList_TreeModel::deckListFinished(const Response &r) root->clearTree(); endResetModel(); - + 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) +RemoteDeckList_TreeWidget::RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent) : QTreeView(parent) { treeModel = new RemoteDeckList_TreeModel(_client, this); proxyModel = new QSortFilterProxyModel(this); @@ -310,12 +323,14 @@ RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeWidget::getNodeById(int i return treeModel->getRoot()->getNodeById(id); } -void RemoteDeckList_TreeWidget::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent) +void RemoteDeckList_TreeWidget::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, + RemoteDeckList_TreeModel::DirectoryNode *parent) { treeModel->addFileToTree(file, parent); } -void RemoteDeckList_TreeWidget::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent) +void RemoteDeckList_TreeWidget::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, + RemoteDeckList_TreeModel::DirectoryNode *parent) { treeModel->addFolderToTree(folder, parent); } diff --git a/cockatrice/src/remotedecklist_treewidget.h b/cockatrice/src/remotedecklist_treewidget.h index ecb2ca18..d880ef1a 100644 --- a/cockatrice/src/remotedecklist_treewidget.h +++ b/cockatrice/src/remotedecklist_treewidget.h @@ -10,23 +10,34 @@ class AbstractClient; class QSortFilterProxyModel; class ServerInfo_DeckStorage_TreeItem; -class RemoteDeckList_TreeModel : public QAbstractItemModel { +class RemoteDeckList_TreeModel : public QAbstractItemModel +{ Q_OBJECT public: class DirectoryNode; class FileNode; - class Node { + 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; } + 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 { + class DirectoryNode : public Node, public QList + { public: DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0); ~DirectoryNode(); @@ -35,46 +46,61 @@ public: DirectoryNode *getNodeByPath(QStringList path); FileNode *getNodeById(int id) const; }; - class FileNode : public Node { + 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; } + : Node(_name, _parent), id(_id), uploadTime(_uploadTime) + { + } + int getId() const + { + return id; + } + QDateTime getUploadTime() const + { + return uploadTime; + } }; - - template T getNode(const QModelIndex &index) const + + 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; signals: void treeRefreshed(); private slots: 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; + 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; } + 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); @@ -82,10 +108,12 @@ public: void refreshTree(); }; -class RemoteDeckList_TreeWidget : public QTreeView { +class RemoteDeckList_TreeWidget : public QTreeView +{ private: RemoteDeckList_TreeModel *treeModel; QSortFilterProxyModel *proxyModel; + public: RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const; @@ -93,7 +121,8 @@ public: 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 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(); diff --git a/cockatrice/src/remotereplaylist_treewidget.cpp b/cockatrice/src/remotereplaylist_treewidget.cpp index 44807efc..6132e9ba 100644 --- a/cockatrice/src/remotereplaylist_treewidget.cpp +++ b/cockatrice/src/remotereplaylist_treewidget.cpp @@ -1,13 +1,13 @@ +#include "remotereplaylist_treewidget.h" +#include "abstractclient.h" #include #include #include -#include "remotereplaylist_treewidget.h" -#include "abstractclient.h" -#include "pending_command.h" #include "pb/command_replay_list.pb.h" #include "pb/response_replay_list.pb.h" #include "pb/serverinfo_replay.pb.h" +#include "pending_command.h" const int RemoteReplayList_TreeModel::numberOfColumns = 6; @@ -49,7 +49,7 @@ 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(); @@ -63,7 +63,7 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co return QVariant(); if (index.column() >= numberOfColumns) return QVariant(); - + ReplayNode *replayNode = dynamic_cast(static_cast(index.internalPointer())); if (replayNode) { const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo(); @@ -72,10 +72,14 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co 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 0: + return replayInfo.replay_id(); + case 1: + return QString::fromStdString(replayInfo.replay_name()); + case 5: + return replayInfo.duration(); + default: + return QVariant(); } } case Qt::DecorationRole: @@ -85,34 +89,42 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co 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::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 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 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(); + case 0: + return dirIcon; + case 3: + return matchInfo.do_not_hide() ? lockIcon : QVariant(); + default: + return QVariant(); } } } @@ -134,16 +146,24 @@ QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation ori } 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(); + 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(); + default: + return QVariant(); } } @@ -151,16 +171,16 @@ QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelI { 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)); + return createIndex(row, column, (void *)matchNode->at(row)); } else { if (row >= replayMatches.size()) return QModelIndex(); - return createIndex(row, column, (void *) replayMatches[row]); + return createIndex(row, column, (void *)replayMatches[row]); } } @@ -183,22 +203,22 @@ Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } -ServerInfo_Replay const* RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const +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(); } -ServerInfo_ReplayMatch const* RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const +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())); @@ -219,8 +239,9 @@ void RemoteReplayList_TreeModel::clearTree() void RemoteReplayList_TreeModel::refreshTree() { PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &))); - + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(replayListFinished(const Response &))); + client->sendCommand(pend); } @@ -229,7 +250,7 @@ void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matc beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size()); replayMatches.append(new MatchNode(matchInfo)); endInsertRows(); - + emit treeRefreshed(); } @@ -238,7 +259,8 @@ void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_Re 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])); + emit dataChanged(createIndex(i, 0, (void *)replayMatches[i]), + createIndex(i, numberOfColumns - 1, (void *)replayMatches[i])); break; } } @@ -257,19 +279,18 @@ void RemoteReplayList_TreeModel::removeMatchInfo(int gameId) 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(); } -RemoteReplayList_TreeWidget::RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent) - : QTreeView(parent) +RemoteReplayList_TreeWidget::RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent) : QTreeView(parent) { treeModel = new RemoteReplayList_TreeModel(_client, this); proxyModel = new QSortFilterProxyModel(this); diff --git a/cockatrice/src/remotereplaylist_treewidget.h b/cockatrice/src/remotereplaylist_treewidget.h index 986e2fa4..635ade10 100644 --- a/cockatrice/src/remotereplaylist_treewidget.h +++ b/cockatrice/src/remotereplaylist_treewidget.h @@ -1,93 +1,130 @@ #ifndef REMOTEREPLAYLIST_TREEWIDGET_H #define REMOTEREPLAYLIST_TREEWIDGET_H +#include "pb/serverinfo_replay.pb.h" +#include "pb/serverinfo_replay_match.pb.h" #include #include #include -#include "pb/serverinfo_replay.pb.h" -#include "pb/serverinfo_replay_match.pb.h" class Response; class AbstractClient; class QSortFilterProxyModel; -class RemoteReplayList_TreeModel : public QAbstractItemModel { +class RemoteReplayList_TreeModel : public QAbstractItemModel +{ Q_OBJECT private: class MatchNode; class ReplayNode; - class Node { + class Node + { protected: QString name; + public: - Node(const QString &_name) - : name(_name) { } - virtual ~Node() { }; - QString getName() const { return name; } + Node(const QString &_name) : name(_name) + { + } + virtual ~Node(){}; + QString getName() const + { + return name; + } }; - class MatchNode : public Node, public QList { + 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; } + const ServerInfo_ReplayMatch &getMatchInfo() + { + return matchInfo; + } void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo); }; - class ReplayNode : public Node { + 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; } + : 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(); private slots: 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; } + 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; + 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 { +class RemoteReplayList_TreeWidget : public QTreeView +{ private: 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); } + 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 e0776358..efcb68bc 100644 --- a/cockatrice/src/replay_timeline_widget.cpp +++ b/cockatrice/src/replay_timeline_widget.cpp @@ -39,7 +39,7 @@ void ReplayTimelineWidget::setTimeline(const QList &_replayTimeline) histogram.append(binValue); if (!replayTimeline.isEmpty()) maxTime = replayTimeline.last(); - + update(); } @@ -47,18 +47,18 @@ void ReplayTimelineWidget::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); painter.drawRect(0, 0, width() - 1, height() - 1); - - qreal binWidth = (qreal) width() / histogram.size(); + + 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(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); - quint64 w = (quint64)(width() - 1) * (quint64) currentTime / maxTime; + quint64 w = (quint64)(width() - 1) * (quint64)currentTime / maxTime; painter.fillRect(0, 0, w, height() - 1, barColor); } @@ -83,7 +83,7 @@ void ReplayTimelineWidget::replayTimerTimeout() emit replayFinished(); replayTimer->stop(); } - + if (!(currentTime % 1000)) update(); } diff --git a/cockatrice/src/replay_timeline_widget.h b/cockatrice/src/replay_timeline_widget.h index 8c668393..1328d41f 100644 --- a/cockatrice/src/replay_timeline_widget.h +++ b/cockatrice/src/replay_timeline_widget.h @@ -1,17 +1,19 @@ #ifndef REPLAY_TIMELINE_WIDGET #define REPLAY_TIMELINE_WIDGET -#include #include +#include class QPaintEvent; class QTimer; -class ReplayTimelineWidget : public QWidget { +class ReplayTimelineWidget : public QWidget +{ Q_OBJECT signals: void processNextEvent(); void replayFinished(); + private: QTimer *replayTimer; QList replayTimeline; @@ -23,16 +25,21 @@ private: int currentEvent; private slots: 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; } + int getCurrentEvent() const + { + return currentEvent; + } public slots: void startReplay(); void stopReplay(); + protected: void paintEvent(QPaintEvent *event); }; diff --git a/cockatrice/src/round.h b/cockatrice/src/round.h index 225da636..fbe811c7 100644 --- a/cockatrice/src/round.h +++ b/cockatrice/src/round.h @@ -1,12 +1,13 @@ #ifndef MSVC_ROUND_FIX #define MSVC_ROUND_FIX /** - * This helper function exists only because MS VC++ 2010 does not support round() in + * This helper function exists only because MS VC++ 2010 does not support round() in * . round() works with g++ and clang++ but is formally a C++11 extension. * So this file exists for MS VC++ only. */ -inline double round(double val) { - return floor(val + 0.5); +inline double round(double val) +{ + return floor(val + 0.5); } #endif /* MSVC_ROUND_FIX */ diff --git a/cockatrice/src/selectzone.cpp b/cockatrice/src/selectzone.cpp index be966352..7546a4c0 100644 --- a/cockatrice/src/selectzone.cpp +++ b/cockatrice/src/selectzone.cpp @@ -1,10 +1,16 @@ -#include #include "selectzone.h" -#include "gamescene.h" #include "carditem.h" +#include "gamescene.h" #include +#include -SelectZone::SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool isView) +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) { } @@ -22,7 +28,7 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) 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()) @@ -30,7 +36,8 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) continue; cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect()))); } - static_cast(scene())->resizeRubberBand(deviceTransform(static_cast(scene())->getViewportTransform()).map(pos)); + static_cast(scene())->resizeRubberBand( + deviceTransform(static_cast(scene())->getViewportTransform()).map(pos)); event->accept(); } } @@ -39,7 +46,7 @@ void SelectZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { scene()->clearSelection(); - + selectionOrigin = event->pos(); static_cast(scene())->startRubberBand(event->scenePos()); event->accept(); @@ -53,4 +60,3 @@ void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) static_cast(scene())->stopRubberBand(); event->accept(); } - diff --git a/cockatrice/src/selectzone.h b/cockatrice/src/selectzone.h index 347e9a52..aa59ad30 100644 --- a/cockatrice/src/selectzone.h +++ b/cockatrice/src/selectzone.h @@ -3,16 +3,25 @@ #include "cardzone.h" -class SelectZone : public CardZone { +class SelectZone : public CardZone +{ Q_OBJECT private: QPointF selectionOrigin; + protected: 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 8cdd4a96..e83b0233 100644 --- a/cockatrice/src/setsmodel.cpp +++ b/cockatrice/src/setsmodel.cpp @@ -1,12 +1,10 @@ #include "setsmodel.h" -SetsModel::SetsModel(CardDatabase *_db, QObject *parent) - : QAbstractTableModel(parent), sets(_db->getSetList()) +SetsModel::SetsModel(CardDatabase *_db, QObject *parent) : QAbstractTableModel(parent), sets(_db->getSetList()) { sets.sortByKey(); - foreach(CardSet *set, sets) - { - if(set->getEnabled()) + foreach (CardSet *set, sets) { + if (set->getEnabled()) enabledSets.insert(set); } } @@ -30,17 +28,15 @@ QVariant SetsModel::data(const QModelIndex &index, int role) const CardSet *set = sets[index.row()]; - if (index.column() == EnabledCol) - { - switch(role) - { + if (index.column() == EnabledCol) { + switch (role) { case SortRole: - return enabledSets.contains(set) ? "1" : "0"; + return enabledSets.contains(set) ? "1" : "0"; case Qt::CheckStateRole: - return static_cast< int >( enabledSets.contains(set) ? Qt::Checked : Qt::Unchecked ); + return static_cast(enabledSets.contains(set) ? Qt::Checked : Qt::Unchecked); case Qt::DisplayRole: default: - return QVariant(); + return QVariant(); } } @@ -48,20 +44,26 @@ QVariant SetsModel::data(const QModelIndex &index, int role) const return QVariant(); switch (index.column()) { - case SortKeyCol: return QString("%1").arg(set->getSortKey(), 8, 10, QChar('0')); - case IsKnownCol: return set->getIsKnown(); - case SetTypeCol: return set->getSetType(); - case ShortNameCol: return set->getShortName(); - case LongNameCol: return set->getLongName(); - case ReleaseDateCol: return set->getReleaseDate().toString(Qt::ISODate); - default: return QVariant(); + case SortKeyCol: + return QString("%1").arg(set->getSortKey(), 8, 10, QChar('0')); + case IsKnownCol: + return set->getIsKnown(); + case SetTypeCol: + return set->getSetType(); + case ShortNameCol: + return set->getShortName(); + case LongNameCol: + return set->getLongName(); + case ReleaseDateCol: + return set->getReleaseDate().toString(Qt::ISODate); + default: + return QVariant(); } } -bool SetsModel::setData(const QModelIndex & index, const QVariant & value, int role) +bool SetsModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if (role == Qt::CheckStateRole && index.column () == EnabledCol) - { + if (role == Qt::CheckStateRole && index.column() == EnabledCol) { toggleRow(index.row(), value == Qt::Checked); return true; } @@ -73,14 +75,23 @@ QVariant SetsModel::headerData(int section, Qt::Orientation orientation, int rol if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) return QVariant(); switch (section) { - case SortKeyCol: return QString("Key"); /* no tr() for translations needed, column just used for sorting --> hidden */ - case IsKnownCol: return QString("Is known"); /* no tr() for translations needed, column is just used for sorting --> hidden */ - case EnabledCol: return tr("Enabled"); - case SetTypeCol: return tr("Set type"); - case ShortNameCol: return tr("Set code"); - case LongNameCol: return tr("Long name"); - case ReleaseDateCol: return tr("Release date"); - default: return QVariant(); + case SortKeyCol: + return QString("Key"); /* no tr() for translations needed, column just used for sorting --> hidden */ + case IsKnownCol: + return QString( + "Is known"); /* no tr() for translations needed, column is just used for sorting --> hidden */ + case EnabledCol: + return tr("Enabled"); + case SetTypeCol: + return tr("Set type"); + case ShortNameCol: + return tr("Set code"); + case LongNameCol: + return tr("Long name"); + case ReleaseDateCol: + return tr("Release date"); + default: + return QVariant(); } } @@ -89,11 +100,9 @@ Qt::ItemFlags SetsModel::flags(const QModelIndex &index) const if (!index.isValid()) return 0; - Qt::ItemFlags flags = QAbstractTableModel::flags(index) | - Qt::ItemIsDragEnabled | - Qt::ItemIsDropEnabled; + Qt::ItemFlags flags = QAbstractTableModel::flags(index) | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; - if ( index.column() == EnabledCol) + if (index.column() == EnabledCol) flags |= Qt::ItemIsUserCheckable; return flags; @@ -113,7 +122,11 @@ QMimeData *SetsModel::mimeData(const QModelIndexList &indexes) const return qobject_cast(result); } -bool SetsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /*column*/, const QModelIndex &parent) +bool SetsModel::dropMimeData(const QMimeData *data, + Qt::DropAction action, + int row, + int /*column*/, + const QModelIndex &parent) { if (action != Qt::MoveAction) return false; @@ -163,7 +176,7 @@ void SetsModel::toggleAll(bool enabled) enabledSets.clear(); if (enabled) - foreach(CardSet *set, sets) + foreach (CardSet *set, sets) enabledSets.insert(set); emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); @@ -188,18 +201,17 @@ void SetsModel::sort(int column, Qt::SortOrder order) int numRows = rowCount(); int row; - for(row = 0; row < numRows; ++row) + for (row = 0; row < numRows; ++row) setMap.insertMulti(index(row, column).data(SetsModel::SortRole).toString(), sets.at(row)); - + QList tmp = setMap.values(); sets.clear(); - if(order == Qt::AscendingOrder) - { - for(row = 0; row < tmp.size(); row++) { + if (order == Qt::AscendingOrder) { + for (row = 0; row < tmp.size(); row++) { sets.append(tmp.at(row)); } } else { - for(row = tmp.size() - 1; row >= 0; row--) { + for (row = tmp.size() - 1; row >= 0; row--) { sets.append(tmp.at(row)); } } @@ -211,10 +223,10 @@ void SetsModel::save(CardDatabase *db) { // order for (int i = 0; i < sets.size(); i++) - sets[i]->setSortKey(i+1); + sets[i]->setSortKey(i + 1); // enabled sets - foreach(CardSet *set, sets) + foreach (CardSet *set, sets) set->setEnabled(enabledSets.contains(set)); sets.sortByKey(); @@ -230,9 +242,8 @@ void SetsModel::restore(CardDatabase *db) // enabled sets enabledSets.clear(); - foreach(CardSet *set, sets) - { - if(set->getEnabled()) + foreach (CardSet *set, sets) { + if (set->getEnabled()) enabledSets.insert(set); } diff --git a/cockatrice/src/setsmodel.h b/cockatrice/src/setsmodel.h index b33a67d4..96687aaf 100644 --- a/cockatrice/src/setsmodel.h +++ b/cockatrice/src/setsmodel.h @@ -1,40 +1,69 @@ #ifndef SETSMODEL_H #define SETSMODEL_H +#include "carddatabase.h" #include #include #include -#include "carddatabase.h" class SetsProxyModel; -class SetsMimeData : public QMimeData { +class SetsMimeData : public QMimeData +{ Q_OBJECT private: 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 { +class SetsModel : public QAbstractTableModel +{ Q_OBJECT friend class SetsProxyModel; + private: static const int NUM_COLS = 7; SetList sets; QSet enabledSets; + public: - enum SetsColumns { SortKeyCol, IsKnownCol, EnabledCol, LongNameCol, ShortNameCol, SetTypeCol, ReleaseDateCol }; - enum Role { SortRole=Qt::UserRole }; + enum SetsColumns + { + SortKeyCol, + IsKnownCol, + EnabledCol, + LongNameCol, + ShortNameCol, + SetTypeCol, + ReleaseDateCol + }; + enum Role + { + SortRole = Qt::UserRole + }; SetsModel(CardDatabase *_db, QObject *parent = 0); ~SetsModel(); int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const { Q_UNUSED(parent); return NUM_COLS; } + int columnCount(const QModelIndex &parent = QModelIndex()) const + { + Q_UNUSED(parent); + return NUM_COLS; + } QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex & index, const QVariant & value, int role); + bool setData(const QModelIndex &index, const QVariant &value, int role); QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex &index) const; Qt::DropActions supportedDropActions() const; diff --git a/cockatrice/src/settingscache.cpp b/cockatrice/src/settingscache.cpp index d78d9b1d..1f66e634 100644 --- a/cockatrice/src/settingscache.cpp +++ b/cockatrice/src/settingscache.cpp @@ -1,16 +1,16 @@ #include "settingscache.h" #include "releasechannel.h" -#include -#include -#include -#include #include +#include +#include +#include +#include #include QString SettingsCache::getDataPath() { - if(isPortableBuild) + if (isPortableBuild) return qApp->applicationDirPath() + "/data/"; else return QStandardPaths::writableLocation(QStandardPaths::DataLocation); @@ -23,22 +23,22 @@ QString SettingsCache::getSettingsPath() void SettingsCache::translateLegacySettings() { - if(isPortableBuild) + if (isPortableBuild) return; - //Layouts - QFile layoutFile(getSettingsPath()+"layouts/deckLayout.ini"); - if(layoutFile.exists()) - if(layoutFile.copy(getSettingsPath()+"layouts.ini")) + // Layouts + QFile layoutFile(getSettingsPath() + "layouts/deckLayout.ini"); + if (layoutFile.exists()) + if (layoutFile.copy(getSettingsPath() + "layouts.ini")) layoutFile.remove(); QStringList usedKeys; QSettings legacySetting; - //Sets + // Sets legacySetting.beginGroup("sets"); QStringList setsGroups = legacySetting.childGroups(); - for(int i = 0; i < setsGroups.size(); i++){ + for (int i = 0; i < setsGroups.size(); i++) { legacySetting.beginGroup(setsGroups.at(i)); cardDatabase().setEnabled(setsGroups.at(i), legacySetting.value("enabled").toBool()); cardDatabase().setIsKnown(setsGroups.at(i), legacySetting.value("isknown").toBool()); @@ -47,11 +47,11 @@ void SettingsCache::translateLegacySettings() } QStringList setsKeys = legacySetting.allKeys(); for (int i = 0; i < setsKeys.size(); ++i) { - usedKeys.append("sets/"+setsKeys.at(i)); + usedKeys.append("sets/" + setsKeys.at(i)); } legacySetting.endGroup(); - //Servers + // Servers legacySetting.beginGroup("server"); servers().setPreviousHostLogin(legacySetting.value("previoushostlogin").toInt()); servers().setPreviousHostList(legacySetting.value("previoushosts").toStringList()); @@ -67,28 +67,28 @@ void SettingsCache::translateLegacySettings() usedKeys.append(legacySetting.allKeys()); QStringList allKeysServer = legacySetting.allKeys(); for (int i = 0; i < allKeysServer.size(); ++i) { - usedKeys.append("server/"+allKeysServer.at(i)); + usedKeys.append("server/" + allKeysServer.at(i)); } legacySetting.endGroup(); - //Messages + // Messages legacySetting.beginGroup("messages"); QStringList allMessages = legacySetting.allKeys(); for (int i = 0; i < allMessages.size(); ++i) { - if(allMessages.at(i) != "count"){ + if (allMessages.at(i) != "count") { QString temp = allMessages.at(i); int index = temp.remove("msg").toInt(); - messages().setMessageAt(index,legacySetting.value(allMessages.at(i)).toString()); + messages().setMessageAt(index, legacySetting.value(allMessages.at(i)).toString()); } } messages().setCount(legacySetting.value("count").toInt()); QStringList allKeysmessages = legacySetting.allKeys(); for (int i = 0; i < allKeysmessages.size(); ++i) { - usedKeys.append("messages/"+allKeysmessages.at(i)); + usedKeys.append("messages/" + allKeysmessages.at(i)); } legacySetting.endGroup(); - //Game filters + // Game filters legacySetting.beginGroup("filter_games"); gameFilters().setUnavailableGamesVisible(legacySetting.value("unavailable_games_visible").toBool()); gameFilters().setShowPasswordProtectedGames(legacySetting.value("show_password_protected_games").toBool()); @@ -103,19 +103,19 @@ void SettingsCache::translateLegacySettings() QStringList allFilters = legacySetting.allKeys(); for (int i = 0; i < allFilters.size(); ++i) { - if(allFilters.at(i).startsWith("game_type")){ + if (allFilters.at(i).startsWith("game_type")) { gameFilters().setGameHashedTypeEnabled(allFilters.at(i), legacySetting.value(allFilters.at(i)).toBool()); } } QStringList allKeysfilter_games = legacySetting.allKeys(); for (int i = 0; i < allKeysfilter_games.size(); ++i) { - usedKeys.append("filter_games/"+allKeysfilter_games.at(i)); + usedKeys.append("filter_games/" + allKeysfilter_games.at(i)); } legacySetting.endGroup(); QStringList allLegacyKeys = legacySetting.allKeys(); for (int i = 0; i < allLegacyKeys.size(); ++i) { - if(usedKeys.contains(allLegacyKeys.at(i))) + if (usedKeys.contains(allLegacyKeys.at(i))) continue; settings->setValue(allLegacyKeys.at(i), legacySetting.value(allLegacyKeys.at(i))); } @@ -127,7 +127,7 @@ QString SettingsCache::getSafeConfigPath(QString configEntry, QString defaultPat // if the config settings is empty or refers to a not-existing folder, // ensure that the defaut path exists and return it if (!QDir(tmp).exists() || tmp.isEmpty()) { - if(!QDir().mkpath(defaultPath)) + if (!QDir().mkpath(defaultPath)) qDebug() << "[SettingsCache] Could not create folder:" << defaultPath; tmp = defaultPath; } @@ -147,7 +147,7 @@ SettingsCache::SettingsCache() { // first, figure out if we are running in portable mode isPortableBuild = QFile::exists(qApp->applicationDirPath() + "/portable.dat"); - if(isPortableBuild) + if (isPortableBuild) qDebug() << "Portable mode enabled"; // define a dummy context that will be used where needed @@ -155,15 +155,15 @@ SettingsCache::SettingsCache() QString dataPath = getDataPath(); QString settingsPath = getSettingsPath(); - settings = new QSettings(settingsPath+"global.ini", QSettings::IniFormat, this); - shortcutsSettings = new ShortcutsSettings(settingsPath,this); - cardDatabaseSettings = new CardDatabaseSettings(settingsPath,this); - serversSettings = new ServersSettings(settingsPath,this); - messageSettings = new MessageSettings(settingsPath,this); + settings = new QSettings(settingsPath + "global.ini", QSettings::IniFormat, this); + shortcutsSettings = new ShortcutsSettings(settingsPath, this); + cardDatabaseSettings = new CardDatabaseSettings(settingsPath, this); + serversSettings = new ServersSettings(settingsPath, this); + messageSettings = new MessageSettings(settingsPath, this); gameFiltersSettings = new GameFiltersSettings(settingsPath, this); layoutsSettings = new LayoutsSettings(settingsPath, this); - if(!QFile(settingsPath+"global.ini").exists()) + if (!QFile(settingsPath + "global.ini").exists()) translateLegacySettings(); // updates - don't reorder them or their index in the settings won't match @@ -185,7 +185,7 @@ SettingsCache::SettingsCache() // this has never been exposed as an user-configurable setting customPicsPath = getSafeConfigPath("paths/custompics", picsPath + "/CUSTOM/"); // this has never been exposed as an user-configurable setting - customCardDatabasePath = getSafeConfigPath("paths/customsets", dataPath + "/customsets/"); + customCardDatabasePath = getSafeConfigPath("paths/customsets", dataPath + "/customsets/"); cardDatabasePath = getSafeConfigFilePath("paths/carddatabase", dataPath + "/cards.xml"); tokenDatabasePath = getSafeConfigFilePath("paths/tokendatabase", dataPath + "/tokens.xml"); @@ -200,11 +200,10 @@ SettingsCache::SettingsCache() settings->setValue("personal/pixmapCacheSize", pixmapCacheSize); settings->setValue("personal/picturedownloadhq", false); settings->setValue("revert/pixmapCacheSize", true); - } - else + } else pixmapCacheSize = settings->value("personal/pixmapCacheSize", PIXMAPCACHE_SIZE_DEFAULT).toInt(); - //sanity check - if(pixmapCacheSize < PIXMAPCACHE_SIZE_MIN || pixmapCacheSize > PIXMAPCACHE_SIZE_MAX) + // sanity check + if (pixmapCacheSize < PIXMAPCACHE_SIZE_MIN || pixmapCacheSize > PIXMAPCACHE_SIZE_MAX) pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT; picDownload = settings->value("personal/picturedownload", true).toBool(); @@ -255,9 +254,9 @@ SettingsCache::SettingsCache() cardInfoViewMode = settings->value("cards/cardinfoviewmode", 0).toInt(); highlightWords = settings->value("personal/highlightWords", QString()).toString(); - gameDescription = settings->value("game/gamedescription","").toString(); + gameDescription = settings->value("game/gamedescription", "").toString(); maxPlayers = settings->value("game/maxplayers", 2).toInt(); - gameTypes = settings->value("game/gametypes","").toString(); + gameTypes = settings->value("game/gametypes", "").toString(); onlyBuddies = settings->value("game/onlybuddies", false).toBool(); onlyRegistered = settings->value("game/onlyregistered", true).toBool(); spectatorsAllowed = settings->value("game/spectatorsallowed", true).toBool(); @@ -269,49 +268,58 @@ SettingsCache::SettingsCache() knownMissingFeatures = settings->value("interface/knownmissingfeatures", "").toString(); } -void SettingsCache::setKnownMissingFeatures(QString _knownMissingFeatures) { +void SettingsCache::setKnownMissingFeatures(QString _knownMissingFeatures) +{ knownMissingFeatures = _knownMissingFeatures; settings->setValue("interface/knownmissingfeatures", knownMissingFeatures); } -void SettingsCache::setCardInfoViewMode(const int _viewMode) { +void SettingsCache::setCardInfoViewMode(const int _viewMode) +{ cardInfoViewMode = _viewMode; settings->setValue("cards/cardinfoviewmode", cardInfoViewMode); } -void SettingsCache::setHighlightWords(const QString &_highlightWords) { +void SettingsCache::setHighlightWords(const QString &_highlightWords) +{ highlightWords = _highlightWords; settings->setValue("personal/highlightWords", highlightWords); } -void SettingsCache::setMasterVolume(int _masterVolume) { +void SettingsCache::setMasterVolume(int _masterVolume) +{ masterVolume = _masterVolume; settings->setValue("sound/mastervolume", masterVolume); emit masterVolumeChanged(masterVolume); } -void SettingsCache::setLeftJustified(const int _leftJustified) { +void SettingsCache::setLeftJustified(const int _leftJustified) +{ leftJustified = _leftJustified; settings->setValue("interface/leftjustified", leftJustified); emit handJustificationChanged(); } -void SettingsCache::setCardScaling(const int _scaleCards) { +void SettingsCache::setCardScaling(const int _scaleCards) +{ scaleCards = _scaleCards; settings->setValue("cards/scaleCards", scaleCards); } -void SettingsCache::setShowMessagePopups(const int _showMessagePopups) { +void SettingsCache::setShowMessagePopups(const int _showMessagePopups) +{ showMessagePopups = _showMessagePopups; settings->setValue("chat/showmessagepopups", showMessagePopups); } -void SettingsCache::setShowMentionPopups(const int _showMentionPopus) { +void SettingsCache::setShowMentionPopups(const int _showMentionPopus) +{ showMentionPopups = _showMentionPopus; settings->setValue("chat/showmentionpopups", showMentionPopups); } -void SettingsCache::setRoomHistory(const int _roomHistory) { +void SettingsCache::setRoomHistory(const int _roomHistory) +{ roomHistory = _roomHistory; settings->setValue("chat/roomhistory", roomHistory); } @@ -397,7 +405,8 @@ void SettingsCache::setNotificationsEnabled(int _notificationsEnabled) settings->setValue("interface/notificationsenabled", notificationsEnabled); } -void SettingsCache::setSpectatorNotificationsEnabled(int _spectatorNotificationsEnabled) { +void SettingsCache::setSpectatorNotificationsEnabled(int _spectatorNotificationsEnabled) +{ spectatorNotificationsEnabled = _spectatorNotificationsEnabled; settings->setValue("interface/specnotificationsenabled", spectatorNotificationsEnabled); } @@ -460,7 +469,8 @@ void SettingsCache::setTapAnimation(int _tapAnimation) settings->setValue("cards/tapanimation", tapAnimation); } -void SettingsCache::setChatMention(int _chatMention) { +void SettingsCache::setChatMention(int _chatMention) +{ chatMention = _chatMention; settings->setValue("chat/mention", chatMention); } @@ -472,22 +482,26 @@ void SettingsCache::setChatMentionCompleter(const int _enableMentionCompleter) emit chatMentionCompleterChanged(); } -void SettingsCache::setChatMentionForeground(int _chatMentionForeground) { +void SettingsCache::setChatMentionForeground(int _chatMentionForeground) +{ chatMentionForeground = _chatMentionForeground; settings->setValue("chat/mentionforeground", chatMentionForeground); } -void SettingsCache::setChatHighlightForeground(int _chatHighlightForeground) { +void SettingsCache::setChatHighlightForeground(int _chatHighlightForeground) +{ chatHighlightForeground = _chatHighlightForeground; settings->setValue("chat/highlightforeground", chatHighlightForeground); } -void SettingsCache::setChatMentionColor(const QString &_chatMentionColor) { +void SettingsCache::setChatMentionColor(const QString &_chatMentionColor) +{ chatMentionColor = _chatMentionColor; settings->setValue("chat/mentioncolor", chatMentionColor); } -void SettingsCache::setChatHighlightColor(const QString &_chatHighlightColor) { +void SettingsCache::setChatHighlightColor(const QString &_chatHighlightColor) +{ chatHighlightColor = _chatHighlightColor; settings->setValue("chat/highlightcolor", chatHighlightColor); } @@ -504,7 +518,8 @@ void SettingsCache::setZoneViewSortByType(int _zoneViewSortByType) settings->setValue("zoneview/sortbytype", zoneViewSortByType); } -void SettingsCache::setZoneViewPileView(int _zoneViewPileView){ +void SettingsCache::setZoneViewPileView(int _zoneViewPileView) +{ zoneViewPileView = _zoneViewPileView; settings->setValue("zoneview/pileview", zoneViewPileView); } @@ -562,32 +577,255 @@ void SettingsCache::setClientID(QString _clientID) QStringList SettingsCache::getCountries() const { - static QStringList countries = QStringList() - << "ad" << "ae" << "af" << "ag" << "ai" << "al" << "am" << "ao" << "aq" << "ar" - << "as" << "at" << "au" << "aw" << "ax" << "az" << "ba" << "bb" << "bd" << "be" - << "bf" << "bg" << "bh" << "bi" << "bj" << "bl" << "bm" << "bn" << "bo" << "bq" - << "br" << "bs" << "bt" << "bv" << "bw" << "by" << "bz" << "ca" << "cc" << "cd" - << "cf" << "cg" << "ch" << "ci" << "ck" << "cl" << "cm" << "cn" << "co" << "cr" - << "cu" << "cv" << "cw" << "cx" << "cy" << "cz" << "de" << "dj" << "dk" << "dm" - << "do" << "dz" << "ec" << "ee" << "eg" << "eh" << "er" << "es" << "et" << "fi" - << "fj" << "fk" << "fm" << "fo" << "fr" << "ga" << "gb" << "gd" << "ge" << "gf" - << "gg" << "gh" << "gi" << "gl" << "gm" << "gn" << "gp" << "gq" << "gr" << "gs" - << "gt" << "gu" << "gw" << "gy" << "hk" << "hm" << "hn" << "hr" << "ht" << "hu" - << "id" << "ie" << "il" << "im" << "in" << "io" << "iq" << "ir" << "is" << "it" - << "je" << "jm" << "jo" << "jp" << "ke" << "kg" << "kh" << "ki" << "km" << "kn" - << "kp" << "kr" << "kw" << "ky" << "kz" << "la" << "lb" << "lc" << "li" << "lk" - << "lr" << "ls" << "lt" << "lu" << "lv" << "ly" << "ma" << "mc" << "md" << "me" - << "mf" << "mg" << "mh" << "mk" << "ml" << "mm" << "mn" << "mo" << "mp" << "mq" - << "mr" << "ms" << "mt" << "mu" << "mv" << "mw" << "mx" << "my" << "mz" << "na" - << "nc" << "ne" << "nf" << "ng" << "ni" << "nl" << "no" << "np" << "nr" << "nu" - << "nz" << "om" << "pa" << "pe" << "pf" << "pg" << "ph" << "pk" << "pl" << "pm" - << "pn" << "pr" << "ps" << "pt" << "pw" << "py" << "qa" << "re" << "ro" << "rs" - << "ru" << "rw" << "sa" << "sb" << "sc" << "sd" << "se" << "sg" << "sh" << "si" - << "sj" << "sk" << "sl" << "sm" << "sn" << "so" << "sr" << "ss" << "st" << "sv" - << "sx" << "sy" << "sz" << "tc" << "td" << "tf" << "tg" << "th" << "tj" << "tk" - << "tl" << "tm" << "tn" << "to" << "tr" << "tt" << "tv" << "tw" << "tz" << "ua" - << "ug" << "um" << "us" << "uy" << "uz" << "va" << "vc" << "ve" << "vg" << "vi" - << "vn" << "vu" << "wf" << "ws" << "ye" << "yt" << "za" << "zm" << "zw"; + static QStringList countries = QStringList() << "ad" + << "ae" + << "af" + << "ag" + << "ai" + << "al" + << "am" + << "ao" + << "aq" + << "ar" + << "as" + << "at" + << "au" + << "aw" + << "ax" + << "az" + << "ba" + << "bb" + << "bd" + << "be" + << "bf" + << "bg" + << "bh" + << "bi" + << "bj" + << "bl" + << "bm" + << "bn" + << "bo" + << "bq" + << "br" + << "bs" + << "bt" + << "bv" + << "bw" + << "by" + << "bz" + << "ca" + << "cc" + << "cd" + << "cf" + << "cg" + << "ch" + << "ci" + << "ck" + << "cl" + << "cm" + << "cn" + << "co" + << "cr" + << "cu" + << "cv" + << "cw" + << "cx" + << "cy" + << "cz" + << "de" + << "dj" + << "dk" + << "dm" + << "do" + << "dz" + << "ec" + << "ee" + << "eg" + << "eh" + << "er" + << "es" + << "et" + << "fi" + << "fj" + << "fk" + << "fm" + << "fo" + << "fr" + << "ga" + << "gb" + << "gd" + << "ge" + << "gf" + << "gg" + << "gh" + << "gi" + << "gl" + << "gm" + << "gn" + << "gp" + << "gq" + << "gr" + << "gs" + << "gt" + << "gu" + << "gw" + << "gy" + << "hk" + << "hm" + << "hn" + << "hr" + << "ht" + << "hu" + << "id" + << "ie" + << "il" + << "im" + << "in" + << "io" + << "iq" + << "ir" + << "is" + << "it" + << "je" + << "jm" + << "jo" + << "jp" + << "ke" + << "kg" + << "kh" + << "ki" + << "km" + << "kn" + << "kp" + << "kr" + << "kw" + << "ky" + << "kz" + << "la" + << "lb" + << "lc" + << "li" + << "lk" + << "lr" + << "ls" + << "lt" + << "lu" + << "lv" + << "ly" + << "ma" + << "mc" + << "md" + << "me" + << "mf" + << "mg" + << "mh" + << "mk" + << "ml" + << "mm" + << "mn" + << "mo" + << "mp" + << "mq" + << "mr" + << "ms" + << "mt" + << "mu" + << "mv" + << "mw" + << "mx" + << "my" + << "mz" + << "na" + << "nc" + << "ne" + << "nf" + << "ng" + << "ni" + << "nl" + << "no" + << "np" + << "nr" + << "nu" + << "nz" + << "om" + << "pa" + << "pe" + << "pf" + << "pg" + << "ph" + << "pk" + << "pl" + << "pm" + << "pn" + << "pr" + << "ps" + << "pt" + << "pw" + << "py" + << "qa" + << "re" + << "ro" + << "rs" + << "ru" + << "rw" + << "sa" + << "sb" + << "sc" + << "sd" + << "se" + << "sg" + << "sh" + << "si" + << "sj" + << "sk" + << "sl" + << "sm" + << "sn" + << "so" + << "sr" + << "ss" + << "st" + << "sv" + << "sx" + << "sy" + << "sz" + << "tc" + << "td" + << "tf" + << "tg" + << "th" + << "tj" + << "tk" + << "tl" + << "tm" + << "tn" + << "to" + << "tr" + << "tt" + << "tv" + << "tw" + << "tz" + << "ua" + << "ug" + << "um" + << "us" + << "uy" + << "uz" + << "va" + << "vc" + << "ve" + << "vg" + << "vi" + << "vn" + << "vu" + << "wf" + << "ws" + << "ye" + << "yt" + << "za" + << "zm" + << "zw"; return countries; } diff --git a/cockatrice/src/settingscache.h b/cockatrice/src/settingscache.h index b4320587..2c931b40 100644 --- a/cockatrice/src/settingscache.h +++ b/cockatrice/src/settingscache.h @@ -1,15 +1,15 @@ #ifndef SETTINGSCACHE_H #define SETTINGSCACHE_H +#include "settings/carddatabasesettings.h" +#include "settings/gamefilterssettings.h" +#include "settings/layoutssettings.h" +#include "settings/messagesettings.h" +#include "settings/serverssettings.h" +#include "shortcutssettings.h" #include #include #include -#include "shortcutssettings.h" -#include "settings/carddatabasesettings.h" -#include "settings/serverssettings.h" -#include "settings/messagesettings.h" -#include "settings/gamefilterssettings.h" -#include "settings/layoutssettings.h" class ReleaseChannel; @@ -28,7 +28,8 @@ class ReleaseChannel; class QSettings; -class SettingsCache : public QObject { +class SettingsCache : public QObject +{ Q_OBJECT signals: void langChanged(); @@ -50,6 +51,7 @@ signals: void chatMentionCompleterChanged(); void downloadSpoilerTimeIndexChanged(); void downloadSpoilerStatusChanged(); + private: QSettings *settings; ShortcutsSettings *shortcutsSettings; @@ -62,7 +64,8 @@ private: QByteArray mainWindowGeometry; QByteArray tokenDialogGeometry; QString lang; - QString deckPath, replaysPath, picsPath, customPicsPath, cardDatabasePath, customCardDatabasePath, spoilerDatabasePath, tokenDatabasePath, themeName; + QString deckPath, replaysPath, picsPath, customPicsPath, cardDatabasePath, customCardDatabasePath, + spoilerDatabasePath, tokenDatabasePath, themeName; bool notifyAboutUpdates; bool mbDownloadSpoilers; int updateReleaseChannel; @@ -112,99 +115,318 @@ private: bool spectatorsNeedPassword; bool spectatorsCanTalk; bool spectatorsCanSeeEverything; - int keepalive; + int keepalive; void translateLegacySettings(); QString getSafeConfigPath(QString configEntry, QString defaultPath) const; QString getSafeConfigFilePath(QString configEntry, QString defaultPath) const; bool rememberGameSettings; - QList releaseChannels; + QList releaseChannels; bool isPortableBuild; public: SettingsCache(); QString getDataPath(); QString getSettingsPath(); - const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; } - const QByteArray &getTokenDialogGeometry() const { return tokenDialogGeometry; } - QString getLang() const { return lang; } - QString getDeckPath() const { return deckPath; } - QString getReplaysPath() const { return replaysPath; } - QString getPicsPath() const { return picsPath; } - QString getCustomPicsPath() const { return customPicsPath; } - QString getCustomCardDatabasePath() const { return customCardDatabasePath; } - QString getCardDatabasePath() const { return cardDatabasePath; } - QString getSpoilerCardDatabasePath() const { return spoilerDatabasePath; } - QString getTokenDatabasePath() const { return tokenDatabasePath; } - QString getThemeName() const { return themeName; } - QString getChatMentionColor() const { return chatMentionColor; } - QString getChatHighlightColor() const { return chatHighlightColor; } - bool getPicDownload() const { return picDownload; } - bool getNotificationsEnabled() const { return notificationsEnabled; } - bool getSpectatorNotificationsEnabled() const { return spectatorNotificationsEnabled; } - bool getNotifyAboutUpdates() const { return notifyAboutUpdates; } - ReleaseChannel * getUpdateReleaseChannel() const { return releaseChannels.at(updateReleaseChannel); } - QList getUpdateReleaseChannels() const { return releaseChannels; } + const QByteArray &getMainWindowGeometry() const + { + return mainWindowGeometry; + } + const QByteArray &getTokenDialogGeometry() const + { + return tokenDialogGeometry; + } + QString getLang() const + { + return lang; + } + QString getDeckPath() const + { + return deckPath; + } + QString getReplaysPath() const + { + return replaysPath; + } + QString getPicsPath() const + { + return picsPath; + } + QString getCustomPicsPath() const + { + return customPicsPath; + } + QString getCustomCardDatabasePath() const + { + return customCardDatabasePath; + } + QString getCardDatabasePath() const + { + return cardDatabasePath; + } + QString getSpoilerCardDatabasePath() const + { + return spoilerDatabasePath; + } + QString getTokenDatabasePath() const + { + return tokenDatabasePath; + } + QString getThemeName() const + { + return themeName; + } + QString getChatMentionColor() const + { + return chatMentionColor; + } + QString getChatHighlightColor() const + { + return chatHighlightColor; + } + bool getPicDownload() const + { + return picDownload; + } + bool getNotificationsEnabled() const + { + return notificationsEnabled; + } + bool getSpectatorNotificationsEnabled() const + { + return spectatorNotificationsEnabled; + } + bool getNotifyAboutUpdates() const + { + return notifyAboutUpdates; + } + ReleaseChannel *getUpdateReleaseChannel() const + { + return releaseChannels.at(updateReleaseChannel); + } + QList getUpdateReleaseChannels() const + { + return releaseChannels; + } - bool getDoubleClickToPlay() const { return doubleClickToPlay; } - bool getPlayToStack() const { return playToStack; } - bool getAnnotateTokens() const { return annotateTokens; } - 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 getChatMention() const { return chatMention; } - bool getChatMentionCompleter() const { return chatMentionCompleter; } - bool getChatMentionForeground() const { return chatMentionForeground; } - bool getChatHighlightForeground() const { return chatHighlightForeground; } - bool getZoneViewSortByName() const { return zoneViewSortByName; } - bool getZoneViewSortByType() const { return zoneViewSortByType; } + bool getDoubleClickToPlay() const + { + return doubleClickToPlay; + } + bool getPlayToStack() const + { + return playToStack; + } + bool getAnnotateTokens() const + { + return annotateTokens; + } + 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 getChatMention() const + { + return chatMention; + } + bool getChatMentionCompleter() const + { + return chatMentionCompleter; + } + bool getChatMentionForeground() const + { + return chatMentionForeground; + } + bool getChatHighlightForeground() const + { + return chatHighlightForeground; + } + bool getZoneViewSortByName() const + { + return zoneViewSortByName; + } + bool getZoneViewSortByType() const + { + return zoneViewSortByType; + } /** Returns if the view should be sorted into pile view. @return zoneViewPileView if the view should be sorted into pile view. */ - bool getZoneViewPileView() const { return zoneViewPileView; } - bool getSoundEnabled() const { return soundEnabled; } - QString getSoundThemeName() const { return soundThemeName; } - bool getIgnoreUnregisteredUsers() const { return ignoreUnregisteredUsers; } - bool getIgnoreUnregisteredUserMessages() const { return ignoreUnregisteredUserMessages; } - QString getPicUrl() const { return picUrl; } - QString getPicUrlFallback() const { return picUrlFallback; } - int getPixmapCacheSize() const { return pixmapCacheSize; } - bool getScaleCards() const { return scaleCards; } - bool getShowMessagePopup() const { return showMessagePopups; } - bool getShowMentionPopup() const { return showMentionPopups; } - bool getRoomHistory() const { return roomHistory; } - bool getLeftJustified() const { return leftJustified; } - int getMasterVolume() const { return masterVolume; } - int getCardInfoViewMode() const { return cardInfoViewMode; } + bool getZoneViewPileView() const + { + return zoneViewPileView; + } + bool getSoundEnabled() const + { + return soundEnabled; + } + QString getSoundThemeName() const + { + return soundThemeName; + } + bool getIgnoreUnregisteredUsers() const + { + return ignoreUnregisteredUsers; + } + bool getIgnoreUnregisteredUserMessages() const + { + return ignoreUnregisteredUserMessages; + } + QString getPicUrl() const + { + return picUrl; + } + QString getPicUrlFallback() const + { + return picUrlFallback; + } + int getPixmapCacheSize() const + { + return pixmapCacheSize; + } + bool getScaleCards() const + { + return scaleCards; + } + bool getShowMessagePopup() const + { + return showMessagePopups; + } + bool getShowMentionPopup() const + { + return showMentionPopups; + } + bool getRoomHistory() const + { + return roomHistory; + } + bool getLeftJustified() const + { + return leftJustified; + } + int getMasterVolume() const + { + return masterVolume; + } + int getCardInfoViewMode() const + { + return cardInfoViewMode; + } QStringList getCountries() const; - QString getHighlightWords() const { return highlightWords; } - QString getGameDescription() const { return gameDescription; } - int getMaxPlayers() const { return maxPlayers; } - QString getGameTypes() const { return gameTypes; } - bool getOnlyBuddies() const { return onlyBuddies; } - bool getOnlyRegistered() const { return onlyRegistered; } - bool getSpectatorsAllowed() const { return spectatorsAllowed; } - bool getSpectatorsNeedPassword() const { return spectatorsNeedPassword; } - bool getSpectatorsCanTalk() const { return spectatorsCanTalk; } - bool getSpectatorsCanSeeEverything() const { return spectatorsCanSeeEverything; } - bool getRememberGameSettings() const { return rememberGameSettings; } - int getKeepAlive() const { return keepalive; } - int getMaxFontSize() const { return maxFontSize; } + QString getHighlightWords() const + { + return highlightWords; + } + QString getGameDescription() const + { + return gameDescription; + } + int getMaxPlayers() const + { + return maxPlayers; + } + QString getGameTypes() const + { + return gameTypes; + } + bool getOnlyBuddies() const + { + return onlyBuddies; + } + bool getOnlyRegistered() const + { + return onlyRegistered; + } + bool getSpectatorsAllowed() const + { + return spectatorsAllowed; + } + bool getSpectatorsNeedPassword() const + { + return spectatorsNeedPassword; + } + bool getSpectatorsCanTalk() const + { + return spectatorsCanTalk; + } + bool getSpectatorsCanSeeEverything() const + { + return spectatorsCanSeeEverything; + } + bool getRememberGameSettings() const + { + return rememberGameSettings; + } + int getKeepAlive() const + { + return keepalive; + } + int getMaxFontSize() const + { + return maxFontSize; + } void setClientID(QString clientID); void setKnownMissingFeatures(QString _knownMissingFeatures); - QString getClientID() { return clientID; } - QString getKnownMissingFeatures() { return knownMissingFeatures; } - ShortcutsSettings& shortcuts() const { return *shortcutsSettings; } - CardDatabaseSettings& cardDatabase() const { return *cardDatabaseSettings; } - ServersSettings& servers() const { return *serversSettings; } - MessageSettings& messages() const { return *messageSettings; } - GameFiltersSettings& gameFilters() const { return *gameFiltersSettings; } - LayoutsSettings& layouts() const { return *layoutsSettings; } - bool getIsPortableBuild() const { return isPortableBuild; } - bool getDownloadSpoilersStatus() const { return mbDownloadSpoilers; } + QString getClientID() + { + return clientID; + } + QString getKnownMissingFeatures() + { + return knownMissingFeatures; + } + ShortcutsSettings &shortcuts() const + { + return *shortcutsSettings; + } + CardDatabaseSettings &cardDatabase() const + { + return *cardDatabaseSettings; + } + ServersSettings &servers() const + { + return *serversSettings; + } + MessageSettings &messages() const + { + return *messageSettings; + } + GameFiltersSettings &gameFilters() const + { + return *gameFiltersSettings; + } + LayoutsSettings &layouts() const + { + return *layoutsSettings; + } + bool getIsPortableBuild() const + { + return isPortableBuild; + } + bool getDownloadSpoilersStatus() const + { + return mbDownloadSpoilers; + } public slots: void setDownloadSpoilerStatus(bool _spoilerStatus); @@ -250,7 +472,7 @@ public slots: void setShowMessagePopups(const int _showMessagePopups); void setShowMentionPopups(const int _showMentionPopups); void setRoomHistory(const int _roomHistory); - void setLeftJustified( const int _leftJustified); + void setLeftJustified(const int _leftJustified); void setMasterVolume(const int _masterVolume); void setCardInfoViewMode(const int _viewMode); void setHighlightWords(const QString &_highlightWords); diff --git a/cockatrice/src/shortcutssettings.cpp b/cockatrice/src/shortcutssettings.cpp index 2f2b0611..36d1986f 100644 --- a/cockatrice/src/shortcutssettings.cpp +++ b/cockatrice/src/shortcutssettings.cpp @@ -8,19 +8,17 @@ ShortcutsSettings::ShortcutsSettings(QString settingsPath, QObject *parent) : QO this->settingsFilePath = std::move(settingsPath); this->settingsFilePath.append("shortcuts.ini"); fillDefaultShorcuts(); - shortCuts = QMap >(defaultShortCuts); + shortCuts = QMap>(defaultShortCuts); bool exists = QFile(settingsFilePath).exists(); QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat); - if (exists) - { + if (exists) { shortCutsFile.beginGroup("Custom"); const QStringList customKeys = shortCutsFile.allKeys(); - for(QStringList::const_iterator it = customKeys.constBegin(); it != customKeys.constEnd(); ++it) - { + for (QStringList::const_iterator it = customKeys.constBegin(); it != customKeys.constEnd(); ++it) { QString stringSequence = shortCutsFile.value(*it).toString(); QList SequenceList = parseSequenceString(stringSequence); shortCuts.insert(*it, SequenceList); @@ -32,8 +30,7 @@ ShortcutsSettings::ShortcutsSettings(QString settingsPath, QObject *parent) : QO QList ShortcutsSettings::getShortcut(QString name) { - if (shortCuts.contains(name)) - { + if (shortCuts.contains(name)) { return shortCuts.value(name); } @@ -58,11 +55,9 @@ QString ShortcutsSettings::getShortcutString(QString name) QString ShortcutsSettings::stringifySequence(QList Sequence) const { QString stringSequence; - for (int i=0; i < Sequence.size(); ++i) - { + for (int i = 0; i < Sequence.size(); ++i) { stringSequence.append(Sequence.at(i).toString(QKeySequence::PortableText)); - if (i < Sequence.size() - 1) - { + if (i < Sequence.size() - 1) { stringSequence.append(";"); } } @@ -74,8 +69,7 @@ QList ShortcutsSettings::parseSequenceString(QString stringSequenc { QStringList Sequences = stringSequence.split(";"); QList SequenceList; - for (QStringList::const_iterator ss = Sequences.constBegin(); ss != Sequences.constEnd(); ++ss) - { + for (QStringList::const_iterator ss = Sequences.constBegin(); ss != Sequences.constEnd(); ++ss) { SequenceList.append(QKeySequence(*ss, QKeySequence::PortableText)); } @@ -111,16 +105,12 @@ bool ShortcutsSettings::isValid(QString name, QString Sequences) QString checkSequence = Sequences.split(";").last(); QList allKeys = shortCuts.keys(); - for (const auto &key : allKeys) - { - if (key.startsWith(checkKey) || key.startsWith("MainWindow") || checkKey.startsWith("MainWindow")) - { + for (const auto &key : allKeys) { + if (key.startsWith(checkKey) || key.startsWith("MainWindow") || checkKey.startsWith("MainWindow")) { QString storedSequence = stringifySequence(shortCuts.value(key)); QStringList stringSequences = storedSequence.split(";"); - for (int j = 0; j < stringSequences.size(); j++) - { - if (checkSequence == stringSequences.at(j)) - { + for (int j = 0; j < stringSequences.size(); j++) { + if (checkSequence == stringSequences.at(j)) { return false; } } @@ -131,17 +121,15 @@ bool ShortcutsSettings::isValid(QString name, QString Sequences) void ShortcutsSettings::resetAllShortcuts() { - for (auto it = defaultShortCuts.begin(); it != defaultShortCuts.end(); ++it) - { - setShortcuts(it.key(), it.value()); - } - emit allShortCutsReset(); + for (auto it = defaultShortCuts.begin(); it != defaultShortCuts.end(); ++it) { + setShortcuts(it.key(), it.value()); + } + emit allShortCutsReset(); } void ShortcutsSettings::clearAllShortcuts() { - for(auto it = shortCuts.begin(); it != shortCuts.end(); ++it) - { + for (auto it = shortCuts.begin(); it != shortCuts.end(); ++it) { setShortcuts(it.key(), ""); } emit allShortCutsClear(); @@ -254,7 +242,6 @@ void ShortcutsSettings::fillDefaultShorcuts() defaultShortCuts["Player/phase8"] = parseSequenceString(""); defaultShortCuts["Player/phase9"] = parseSequenceString("F9"); - defaultShortCuts["Player/aIncCounter_w"] = parseSequenceString(""); defaultShortCuts["Player/aDecCounter_w"] = parseSequenceString(""); defaultShortCuts["Player/aSetCounter_w"] = parseSequenceString(""); diff --git a/cockatrice/src/shortcutssettings.h b/cockatrice/src/shortcutssettings.h index 4e656726..febaa1d5 100644 --- a/cockatrice/src/shortcutssettings.h +++ b/cockatrice/src/shortcutssettings.h @@ -1,45 +1,45 @@ #ifndef SHORTCUTSSETTINGS_H #define SHORTCUTSSETTINGS_H +#include +#include #include #include -#include -#include class ShortcutsSettings : public QObject { Q_OBJECT - public: - ShortcutsSettings(QString settingsFilePath, QObject *parent = nullptr); +public: + ShortcutsSettings(QString settingsFilePath, QObject *parent = nullptr); - QList getShortcut(QString name); - QKeySequence getSingleShortcut(QString name); + QList getShortcut(QString name); + QKeySequence getSingleShortcut(QString name); - QString getDefaultShortcutString(QString name); - QString getShortcutString(QString name); + QString getDefaultShortcutString(QString name); + QString getShortcutString(QString name); - void setShortcuts(QString name, QList Sequence); - void setShortcuts(QString name, QKeySequence Sequence); - void setShortcuts(QString name, QString Sequences); + void setShortcuts(QString name, QList Sequence); + void setShortcuts(QString name, QKeySequence Sequence); + void setShortcuts(QString name, QString Sequences); - bool isValid(QString name, QString Sequences); + bool isValid(QString name, QString Sequences); - void resetAllShortcuts(); - void clearAllShortcuts(); + void resetAllShortcuts(); + void clearAllShortcuts(); - signals: - void shortCutchanged(); - void allShortCutsReset(); - void allShortCutsClear(); +signals: + void shortCutchanged(); + void allShortCutsReset(); + void allShortCutsClear(); - private: - QString settingsFilePath; - QMap > shortCuts; - QMap > defaultShortCuts; - void fillDefaultShorcuts(); +private: + QString settingsFilePath; + QMap> shortCuts; + QMap> defaultShortCuts; + void fillDefaultShorcuts(); - QString stringifySequence(QList Sequence) const; - QList parseSequenceString(QString stringSequence); + QString stringifySequence(QList Sequence) const; + QList parseSequenceString(QString stringSequence); }; #endif // SHORTCUTSSETTINGS_H diff --git a/cockatrice/src/soundengine.cpp b/cockatrice/src/soundengine.cpp index 05aeb0be..4fbfb418 100644 --- a/cockatrice/src/soundengine.cpp +++ b/cockatrice/src/soundengine.cpp @@ -12,8 +12,7 @@ #define DEFAULT_THEME_NAME "Default" #define TEST_SOUND_FILENAME "player_join" -SoundEngine::SoundEngine(QObject *parent) -: QObject(parent), player(0) +SoundEngine::SoundEngine(QObject *parent) : QObject(parent), player(0) { inputBuffer = new QBuffer(this); @@ -27,8 +26,7 @@ SoundEngine::SoundEngine(QObject *parent) SoundEngine::~SoundEngine() { - if(player) - { + if (player) { player->deleteLater(); player = 0; } @@ -40,8 +38,7 @@ void SoundEngine::soundEnabledChanged() { if (settingsCache->getSoundEnabled()) { qDebug("SoundEngine: enabling sound"); - if(!player) - { + if (!player) { QAudioFormat format; format.setSampleRate(44100); format.setChannelCount(1); @@ -53,8 +50,7 @@ void SoundEngine::soundEnabledChanged() } } else { qDebug("SoundEngine: disabling sound"); - if(player) - { + if (player) { player->stop(); player->deleteLater(); player = 0; @@ -64,14 +60,14 @@ void SoundEngine::soundEnabledChanged() void SoundEngine::playSound(QString fileName) { - if(!player) + if (!player) return; // still playing the previous sound? - if(player->state() == QAudio::ActiveState) + if (player->state() == QAudio::ActiveState) return; - if(!audioData.contains(fileName)) + if (!audioData.contains(fileName)) return; qDebug() << "playing" << fileName; @@ -92,40 +88,39 @@ void SoundEngine::testSound() void SoundEngine::ensureThemeDirectoryExists() { - if(settingsCache->getSoundThemeName().isEmpty() || - !getAvailableThemes().contains(settingsCache->getSoundThemeName())) - { + if (settingsCache->getSoundThemeName().isEmpty() || + !getAvailableThemes().contains(settingsCache->getSoundThemeName())) { qDebug() << "Sounds theme name not set, setting default value"; settingsCache->setSoundThemeName(DEFAULT_THEME_NAME); } } -QStringMap & SoundEngine::getAvailableThemes() +QStringMap &SoundEngine::getAvailableThemes() { QDir dir; availableThemes.clear(); // load themes from user profile dir - dir = settingsCache->getDataPath() + "/sounds"; + dir = settingsCache->getDataPath() + "/sounds"; - foreach(QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) - { - if(!availableThemes.contains(themeName)) + foreach (QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) { + if (!availableThemes.contains(themeName)) availableThemes.insert(themeName, dir.absoluteFilePath(themeName)); } // load themes from cockatrice system dir + dir = qApp->applicationDirPath() + #ifdef Q_OS_MAC - dir = qApp->applicationDirPath() + "/../Resources/sounds"; + "/../Resources/sounds"; #elif defined(Q_OS_WIN) - dir = qApp->applicationDirPath() + "/sounds"; + "/sounds"; #else // linux - dir = qApp->applicationDirPath() + "/../share/cockatrice/sounds"; + "/../share/cockatrice/sounds"; #endif - foreach(QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) - { - if(!availableThemes.contains(themeName)) + + foreach (QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) { + if (!availableThemes.contains(themeName)) availableThemes.insert(themeName, dir.absoluteFilePath(themeName)); } @@ -142,24 +137,45 @@ void SoundEngine::themeChangedSlot() audioData.clear(); static const QStringList fileNames = QStringList() - // Phases - << "untap_step" << "upkeep_step" << "draw_step" << "main_1" - << "start_combat" << "attack_step" << "block_step" << "damage_step" << "end_combat" - << "main_2" << "end_step" - // Game Actions - << "draw_card" << "play_card" << "tap_card" << "untap_card" - << "shuffle" << "roll_dice" << "life_change" - // Player - << "player_join" << "player_leave" << "player_disconnect" << "player_reconnect" << "player_concede" - // Spectator - << "spectator_join" << "spectator_leave" - // Buddy - << "buddy_join" << "buddy_leave" - // Chat & UI - << "chat_mention" << "all_mention" << "private_message"; + // Phases + << "untap_step" + << "upkeep_step" + << "draw_step" + << "main_1" + << "start_combat" + << "attack_step" + << "block_step" + << "damage_step" + << "end_combat" + << "main_2" + << "end_step" + // Game Actions + << "draw_card" + << "play_card" + << "tap_card" + << "untap_card" + << "shuffle" + << "roll_dice" + << "life_change" + // Player + << "player_join" + << "player_leave" + << "player_disconnect" + << "player_reconnect" + << "player_concede" + // Spectator + << "spectator_join" + << "spectator_leave" + // Buddy + << "buddy_join" + << "buddy_leave" + // Chat & UI + << "chat_mention" + << "all_mention" + << "private_message"; for (int i = 0; i < fileNames.size(); ++i) { - if(!dir.exists(fileNames[i] + ".wav")) + if (!dir.exists(fileNames[i] + ".wav")) continue; QFile file(dir.filePath(fileNames[i] + ".wav")); diff --git a/cockatrice/src/soundengine.h b/cockatrice/src/soundengine.h index ed15cbbf..d2f969c8 100644 --- a/cockatrice/src/soundengine.h +++ b/cockatrice/src/soundengine.h @@ -1,9 +1,9 @@ #ifndef SOUNDENGINE_H #define SOUNDENGINE_H -#include -#include #include +#include +#include #include class QAudioOutput; @@ -11,18 +11,21 @@ class QBuffer; typedef QMap QStringMap; -class SoundEngine : public QObject { +class SoundEngine : public QObject +{ Q_OBJECT public: SoundEngine(QObject *parent = 0); ~SoundEngine(); void playSound(QString fileName); QStringMap &getAvailableThemes(); + private: QMap audioData; QBuffer *inputBuffer; - QAudioOutput * player; + QAudioOutput *player; QStringMap availableThemes; + protected: void ensureThemeDirectoryExists(); private slots: diff --git a/cockatrice/src/spoilerbackgroundupdater.cpp b/cockatrice/src/spoilerbackgroundupdater.cpp index b0af5b32..495c1fb5 100644 --- a/cockatrice/src/spoilerbackgroundupdater.cpp +++ b/cockatrice/src/spoilerbackgroundupdater.cpp @@ -1,17 +1,17 @@ +#include +#include #include #include -#include -#include -#include #include -#include +#include +#include +#include #include -#include -#include "spoilerbackgroundupdater.h" -#include "settingscache.h" #include "carddatabase.h" #include "main.h" +#include "settingscache.h" +#include "spoilerbackgroundupdater.h" #include "window_main.h" #define SPOILERS_STATUS_URL "https://raw.githubusercontent.com/Cockatrice/Magic-Spoiler/files/SpoilerSeasonEnabled" @@ -20,8 +20,7 @@ SpoilerBackgroundUpdater::SpoilerBackgroundUpdater(QObject *apParent) : QObject(apParent), cardUpdateProcess(nullptr) { isSpoilerDownloadEnabled = settingsCache->getDownloadSpoilersStatus(); - if (isSpoilerDownloadEnabled) - { + if (isSpoilerDownloadEnabled) { // Start the process of checking if we're in spoiler season // File exists means we're in spoiler season // We will load the database before attempting to download spoilers, incase they fail @@ -41,13 +40,10 @@ void SpoilerBackgroundUpdater::downloadFromURL(QUrl url, bool saveResults) auto *nam = new QNetworkAccessManager(this); QNetworkReply *reply = nam->get(QNetworkRequest(url)); - if (saveResults) - { + if (saveResults) { // This will write out to the file (used for spoiler.xml) connect(reply, SIGNAL(finished()), this, SLOT(actDownloadFinishedSpoilersFile())); - } - else - { + } else { // This will check the status (used to see if we're in spoiler season or not) connect(reply, SIGNAL(finished()), this, SLOT(actCheckIfSpoilerSeasonEnabled())); } @@ -59,8 +55,7 @@ void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile() auto *reply = dynamic_cast(sender()); QNetworkReply::NetworkError errorCode = reply->error(); - if (errorCode == QNetworkReply::NoError) - { + if (errorCode == QNetworkReply::NoError) { spoilerData = reply->readAll(); // Save the spoiler.xml file to the disk @@ -68,9 +63,7 @@ void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile() reply->deleteLater(); emit spoilerCheckerDone(); - } - else - { + } else { qDebug() << "Error downloading spoilers file" << errorCode; emit spoilerCheckerDone(); } @@ -84,11 +77,9 @@ bool SpoilerBackgroundUpdater::deleteSpoilerFile() QFile file(fileName); // Delete the spoiler.xml file - if (file.exists() && file.remove()) - { + if (file.exists() && file.remove()) { qDebug() << "Deleting spoiler.xml"; return true; - } qDebug() << "Error: Spoiler.xml not found or not deleted"; @@ -100,37 +91,27 @@ void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled() auto *response = dynamic_cast(sender()); QNetworkReply::NetworkError errorCode = response->error(); - if (errorCode == QNetworkReply::ContentNotFoundError) - { + if (errorCode == QNetworkReply::ContentNotFoundError) { // Spoiler season is offline at this point, so the spoiler.xml file can be safely deleted // The user should run Oracle to get the latest card information - if (deleteSpoilerFile() && trayIcon) - { + if (deleteSpoilerFile() && trayIcon) { trayIcon->showMessage(tr("Spoilers season has ended"), tr("Deleting spoiler.xml. Please run Oracle")); } qDebug() << "Spoiler Season Offline"; emit spoilerCheckerDone(); - } - else if (errorCode == QNetworkReply::NoError) - { + } else if (errorCode == QNetworkReply::NoError) { qDebug() << "Spoiler Service Online"; startSpoilerDownloadProcess(SPOILERS_URL, true); - } - else if (errorCode == QNetworkReply::HostNotFoundError) - { - if (trayIcon) - { + } else if (errorCode == QNetworkReply::HostNotFoundError) { + if (trayIcon) { trayIcon->showMessage(tr("Spoilers download failed"), tr("No internet connection")); } qDebug() << "Spoiler download failed due to no internet connection"; emit spoilerCheckerDone(); - } - else - { - if (trayIcon) - { + } else { + if (trayIcon) { trayIcon->showMessage(tr("Spoilers download failed"), tr("Error") + " " + errorCode); } @@ -145,16 +126,13 @@ bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data) QFileInfo fi(fileName); QDir fileDir(fi.path()); - if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) - { + if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { return false; } // Check if the data matches. If it does, then spoilers are up to date. - if (getHash(fileName) == getHash(data)) - { - if (trayIcon) - { + if (getHash(fileName) == getHash(data)) { + if (trayIcon) { trayIcon->showMessage(tr("Spoilers already up to date"), tr("No new spoilers added")); } @@ -163,15 +141,13 @@ bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data) } QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) - { + if (!file.open(QIODevice::WriteOnly)) { qDebug() << "Spoiler Service Error: File open (w) failed for" << fileName; file.close(); return false; } - if (file.write(data) == -1) - { + if (file.write(data) == -1) { qDebug() << "Spoiler Service Error: File write (w) failed for" << fileName; file.close(); return false; @@ -179,21 +155,17 @@ bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data) file.close(); - // Data written, so reload the card database qDebug() << "Spoiler Service Data Written"; QtConcurrent::run(db, &CardDatabase::loadCardDatabases); // If the user has notifications enabled, let them know // when the database was last updated - if (trayIcon) - { + if (trayIcon) { QList lines = data.split('\n'); - foreach (QByteArray line, lines) - { - if (line.indexOf("created:") > -1) - { + foreach (QByteArray line, lines) { + if (line.indexOf("created:") > -1) { QString timeStamp = QString(line).replace("created:", "").trimmed(); timeStamp.chop(6); // Remove " (UTC)" @@ -216,8 +188,7 @@ QByteArray SpoilerBackgroundUpdater::getHash(const QString fileName) { QFile file(fileName); - if (file.open(QFile::ReadOnly)) - { + if (file.open(QFile::ReadOnly)) { // Only read the first 512 bytes (enough to get the "created" tag) const QByteArray bytes = file.read(512); @@ -228,9 +199,7 @@ QByteArray SpoilerBackgroundUpdater::getHash(const QString fileName) file.close(); return hash.result(); - } - else - { + } else { qDebug() << "getHash ReadOnly failed!"; file.close(); return QByteArray(); diff --git a/cockatrice/src/spoilerbackgroundupdater.h b/cockatrice/src/spoilerbackgroundupdater.h index 8e5a10f7..7d7a2892 100644 --- a/cockatrice/src/spoilerbackgroundupdater.h +++ b/cockatrice/src/spoilerbackgroundupdater.h @@ -1,35 +1,38 @@ #ifndef COCKATRICE_SPOILER_DOWNLOADER_H #define COCKATRICE_SPOILER_DOWNLOADER_H +#include #include #include -#include class SpoilerBackgroundUpdater : public QObject { Q_OBJECT - public: - explicit SpoilerBackgroundUpdater(QObject *apParent = nullptr); - inline QString getCardUpdaterBinaryName() { return "oracle"; }; - QByteArray getHash(const QString fileName); - QByteArray getHash(QByteArray data); - static bool deleteSpoilerFile(); +public: + explicit SpoilerBackgroundUpdater(QObject *apParent = nullptr); + inline QString getCardUpdaterBinaryName() + { + return "oracle"; + }; + QByteArray getHash(const QString fileName); + QByteArray getHash(QByteArray data); + static bool deleteSpoilerFile(); - private slots: - void actDownloadFinishedSpoilersFile(); - void actCheckIfSpoilerSeasonEnabled(); +private slots: + void actDownloadFinishedSpoilersFile(); + void actCheckIfSpoilerSeasonEnabled(); - private: - bool isSpoilerDownloadEnabled; - QProcess *cardUpdateProcess; - QByteArray spoilerData; - void startSpoilerDownloadProcess(QString url, bool saveResults); - void downloadFromURL(QUrl url, bool saveResults); - bool saveDownloadedFile(QByteArray data); +private: + bool isSpoilerDownloadEnabled; + QProcess *cardUpdateProcess; + QByteArray spoilerData; + void startSpoilerDownloadProcess(QString url, bool saveResults); + void downloadFromURL(QUrl url, bool saveResults); + bool saveDownloadedFile(QByteArray data); - signals: - void spoilersUpdatedSuccessfully(); - void spoilerCheckerDone(); +signals: + void spoilersUpdatedSuccessfully(); + void spoilerCheckerDone(); }; -#endif //COCKATRICE_SPOILER_DOWNLOADER_H \ No newline at end of file +#endif // COCKATRICE_SPOILER_DOWNLOADER_H \ No newline at end of file diff --git a/cockatrice/src/stackzone.cpp b/cockatrice/src/stackzone.cpp index bd149c1e..a22ab174 100644 --- a/cockatrice/src/stackzone.cpp +++ b/cockatrice/src/stackzone.cpp @@ -1,12 +1,12 @@ -#include -#include -#include "arrowitem.h" #include "stackzone.h" -#include "settingscache.h" -#include "thememanager.h" -#include "player.h" +#include "arrowitem.h" #include "carddragitem.h" #include "carditem.h" +#include "player.h" +#include "settingscache.h" +#include "thememanager.h" +#include +#include #include "pb/command_move_card.pb.h" @@ -49,11 +49,13 @@ void StackZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*opti painter->fillRect(boundingRect(), themeManager->getStackBgBrush()); } -void StackZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) +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()); @@ -61,7 +63,7 @@ void StackZone::handleDropEvent(const QList &dragItems, CardZone 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()); @@ -72,7 +74,7 @@ void StackZone::reorganizeCards() { if (!cards.isEmpty()) { QList arrowsToUpdate; - + const int cardCount = cards.size(); qreal totalWidth = boundingRect().width(); qreal totalHeight = boundingRect().height(); @@ -81,18 +83,18 @@ void StackZone::reorganizeCards() 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)); + c->setPos(x, ((qreal)i) * (totalHeight - cardHeight) / (cardCount - 1)); else - c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setPos(x, ((qreal)i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); c->setRealZValue(i); - + arrowsToUpdate.append(c->getArrowsFrom()); arrowsToUpdate.append(c->getArrowsTo()); } diff --git a/cockatrice/src/stackzone.h b/cockatrice/src/stackzone.h index 05fb2d24..1d47782d 100644 --- a/cockatrice/src/stackzone.h +++ b/cockatrice/src/stackzone.h @@ -3,21 +3,23 @@ #include "selectzone.h" -class StackZone : public SelectZone { +class StackZone : public SelectZone +{ Q_OBJECT private: qreal zoneHeight; private slots: void updateBg(); + 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(); + protected: void addCardImpl(CardItem *card, int x, int y); }; #endif - diff --git a/cockatrice/src/tab.cpp b/cockatrice/src/tab.cpp index dde9cea1..2bc5aaf1 100644 --- a/cockatrice/src/tab.cpp +++ b/cockatrice/src/tab.cpp @@ -1,8 +1,8 @@ #include "tab.h" #include "cardinfowidget.h" -#include #include #include +#include Tab::Tab(TabSupervisor *_tabSupervisor, QWidget *parent) : QMainWindow(parent), tabSupervisor(_tabSupervisor), contentsChanged(false), infoPopup(0) { @@ -14,14 +14,15 @@ void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName) if (infoPopup) { infoPopup->deleteLater(); } - currentCardName = cardName; - infoPopup = new CardInfoWidget(cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); + currentCardName = cardName; + infoPopup = new CardInfoWidget( + cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); QRect screenRect = qApp->desktop()->screenGeometry(this); - infoPopup->move( - 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->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(); } diff --git a/cockatrice/src/tab.h b/cockatrice/src/tab.h index 3d80e474..a67b55be 100644 --- a/cockatrice/src/tab.h +++ b/cockatrice/src/tab.h @@ -7,32 +7,55 @@ class QMenu; class TabSupervisor; class CardInfoWidget; -class Tab : public QMainWindow { +class Tab : public QMainWindow +{ Q_OBJECT signals: void userEvent(bool globalEvent = true); void tabTextChanged(Tab *tab, const QString &newTabText); + protected: TabSupervisor *tabSupervisor; - void addTabMenu(QMenu *menu) { tabMenus.append(menu); } + void addTabMenu(QMenu *menu) + { + tabMenus.append(menu); + } protected slots: void showCardInfoPopup(const QPoint &pos, const QString &cardName); void deleteCardInfoPopup(const QString &cardName); + private: QString currentCardName; 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; } + 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() { } - virtual void tabActivated() { } + virtual void closeRequest() + { + } + virtual void tabActivated() + { + } }; #endif diff --git a/cockatrice/src/tab_admin.cpp b/cockatrice/src/tab_admin.cpp index 0092d9f3..b7b82218 100644 --- a/cockatrice/src/tab_admin.cpp +++ b/cockatrice/src/tab_admin.cpp @@ -1,20 +1,19 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "tab_admin.h" #include "abstractclient.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "pb/admin_commands.pb.h" -ShutdownDialog::ShutdownDialog(QWidget *parent) - : QDialog(parent) +ShutdownDialog::ShutdownDialog(QWidget *parent) : QDialog(parent) { QLabel *reasonLabel = new QLabel(tr("&Reason for shutdown:")); reasonEdit = new QLineEdit; @@ -25,18 +24,18 @@ ShutdownDialog::ShutdownDialog(QWidget *parent) minutesEdit->setMinimum(0); minutesEdit->setValue(5); minutesEdit->setMaximum(999); - + 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")); } @@ -60,31 +59,31 @@ TabAdmin::TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool connect(shutdownServerButton, SIGNAL(clicked()), this, SLOT(actShutdownServer())); reloadConfigButton = new QPushButton; connect(reloadConfigButton, SIGNAL(clicked()), this, SLOT(actReloadConfig())); - + QVBoxLayout *vbox = new QVBoxLayout; vbox->addWidget(updateServerMessageButton); vbox->addWidget(shutdownServerButton); vbox->addWidget(reloadConfigButton); 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(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(mainLayout); setCentralWidget(mainWidget); @@ -97,7 +96,7 @@ void TabAdmin::retranslateUi() shutdownServerButton->setText(tr("&Shut down server")); reloadConfigButton->setText(tr("&Reload configuration")); adminGroupBox->setTitle(tr("Server administration functions")); - + unlockButton->setText(tr("&Unlock functions")); lockButton->setText(tr("&Lock functions")); } @@ -114,7 +113,7 @@ void TabAdmin::actShutdownServer() Command_ShutdownServer cmd; cmd.set_reason(dlg.getReason().toStdString()); cmd.set_minutes(dlg.getMinutes()); - + client->sendCommand(client->prepareAdminCommand(cmd)); } } @@ -127,12 +126,12 @@ void TabAdmin::actReloadConfig() void TabAdmin::actUnlock() { - if (fullAdmin) - adminGroupBox->setEnabled(true); - lockButton->setEnabled(true); - unlockButton->setEnabled(false); - locked = false; - emit adminLockChanged(false); + if (fullAdmin) + adminGroupBox->setEnabled(true); + lockButton->setEnabled(true); + unlockButton->setEnabled(false); + locked = false; + emit adminLockChanged(false); } void TabAdmin::actLock() diff --git a/cockatrice/src/tab_admin.h b/cockatrice/src/tab_admin.h index d0bd3148..dd2c47b2 100644 --- a/cockatrice/src/tab_admin.h +++ b/cockatrice/src/tab_admin.h @@ -11,18 +11,21 @@ class QPushButton; class QSpinBox; class QLineEdit; -class ShutdownDialog : public QDialog { +class ShutdownDialog : public QDialog +{ Q_OBJECT private: QLineEdit *reasonEdit; QSpinBox *minutesEdit; + public: ShutdownDialog(QWidget *parent = 0); QString getReason() const; int getMinutes() const; }; -class TabAdmin : public Tab { +class TabAdmin : public Tab +{ Q_OBJECT private: bool locked; @@ -37,14 +40,21 @@ private slots: void actUpdateServerMessage(); void actShutdownServer(); void actReloadConfig(); - + 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; } + 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 f660b281..c56de05e 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -1,47 +1,47 @@ -#include -#include -#include -#include -#include -#include -#include -#include +#include "tab_deck_editor.h" +#include "abstractclient.h" +#include "carddatabase.h" +#include "carddatabasemodel.h" +#include "cardframe.h" +#include "decklistmodel.h" +#include "deckstats_interface.h" +#include "dlg_load_deck_from_clipboard.h" +#include "filterbuilder.h" +#include "filtertreemodel.h" +#include "main.h" +#include "pb/command_deck_upload.pb.h" +#include "pb/response.pb.h" +#include "pending_command.h" +#include "pictureloader.h" +#include "settingscache.h" +#include "tab_supervisor.h" +#include "tappedout_interface.h" #include +#include +#include #include +#include +#include +#include #include #include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include #include -#include -#include #include -#include -#include +#include +#include +#include +#include +#include +#include #include -#include "tab_deck_editor.h" -#include "carddatabase.h" -#include "pictureloader.h" -#include "carddatabasemodel.h" -#include "decklistmodel.h" -#include "dlg_load_deck_from_clipboard.h" -#include "main.h" -#include "settingscache.h" -#include "tab_supervisor.h" -#include "deckstats_interface.h" -#include "tappedout_interface.h" -#include "abstractclient.h" -#include "pending_command.h" -#include "pb/response.pb.h" -#include "pb/command_deck_upload.pb.h" -#include "filtertreemodel.h" -#include "cardframe.h" -#include "filterbuilder.h" +#include void SearchLineEdit::keyPressEvent(QKeyEvent *event) { @@ -63,7 +63,8 @@ void TabDeckEditor::createDeckDock() deckView->sortByColumn(1, Qt::AscendingOrder); deckView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); deckView->installEventFilter(&deckViewKeySignals); - connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); + connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, + SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); connect(deckView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actSwapCard())); connect(&deckViewKeySignals, SIGNAL(onS()), this, SLOT(actSwapCard())); connect(&deckViewKeySignals, SIGNAL(onEnter()), this, SLOT(actIncrement())); @@ -112,8 +113,9 @@ void TabDeckEditor::createDeckDock() deckDock->setObjectName("deckDock"); deckDock->setMinimumSize(QSize(200, 41)); - deckDock->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea); - deckDock->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable); + deckDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); + deckDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); QWidget *deckDockContents = new QWidget(); deckDockContents->setObjectName("deckDockContents"); deckDockContents->setLayout(rightFrame); @@ -135,8 +137,9 @@ void TabDeckEditor::createCardInfoDock() cardInfoDock->setObjectName("cardInfoDock"); cardInfoDock->setMinimumSize(QSize(200, 41)); - cardInfoDock->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea); - cardInfoDock->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable); + cardInfoDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); + cardInfoDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); QWidget *cardInfoDockContents = new QWidget(); cardInfoDockContents->setObjectName("cardInfoDockContents"); cardInfoDockContents->setLayout(cardInfoFrame); @@ -160,7 +163,8 @@ void TabDeckEditor::createFiltersDock() filterView->setContextMenuPolicy(Qt::CustomContextMenu); filterView->installEventFilter(&filterViewKeySignals); connect(filterModel, SIGNAL(layoutChanged()), filterView, SLOT(expandAll())); - connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)),this, SLOT(filterViewCustomContextMenu(const QPoint &))); + connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)), this, + SLOT(filterViewCustomContextMenu(const QPoint &))); connect(&filterViewKeySignals, SIGNAL(onDelete()), this, SLOT(actClearFilterOne())); FilterBuilder *filterBuilder = new FilterBuilder; @@ -179,7 +183,7 @@ void TabDeckEditor::createFiltersDock() QGridLayout *filterLayout = new QGridLayout; filterLayout->setObjectName("filterLayout"); - filterLayout->setContentsMargins(0,0,0,0); + filterLayout->setContentsMargins(0, 0, 0, 0); filterLayout->addWidget(filterBuilder, 0, 0, 1, 3); filterLayout->addWidget(filterView, 1, 0, 1, 3); filterLayout->addWidget(filterDelOne, 2, 0, 1, 1); @@ -196,7 +200,8 @@ void TabDeckEditor::createFiltersDock() filterDock = new QDockWidget(this); filterDock->setObjectName("filterDock"); - filterDock->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable); + filterDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); QWidget *filterDockContents = new QWidget(this); filterDockContents->setObjectName("filterDockContents"); filterDockContents->setLayout(filterFrame); @@ -287,29 +292,29 @@ void TabDeckEditor::createMenus() aCardInfoDockVisible = cardInfoDockMenu->addAction(QString()); aCardInfoDockVisible->setCheckable(true); - connect(aCardInfoDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aCardInfoDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aCardInfoDockFloating = cardInfoDockMenu->addAction(QString()); aCardInfoDockFloating->setCheckable(true); - connect(aCardInfoDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aCardInfoDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); aDeckDockVisible = deckDockMenu->addAction(QString()); aDeckDockVisible->setCheckable(true); - connect(aDeckDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aDeckDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aDeckDockFloating = deckDockMenu->addAction(QString()); aDeckDockFloating->setCheckable(true); - connect(aDeckDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aDeckDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); aFilterDockVisible = filterDockMenu->addAction(QString()); aFilterDockVisible->setCheckable(true); - connect(aFilterDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aFilterDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aFilterDockFloating = filterDockMenu->addAction(QString()); aFilterDockFloating->setCheckable(true); - connect(aFilterDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aFilterDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); viewMenu->addSeparator(); aResetLayout = viewMenu->addAction(QString()); - connect(aResetLayout,SIGNAL(triggered()),this,SLOT(restartLayout())); + connect(aResetLayout, SIGNAL(triggered()), this, SLOT(restartLayout())); viewMenu->addAction(aResetLayout); addTabMenu(viewMenu); @@ -356,17 +361,15 @@ void TabDeckEditor::createCentralFrame() databaseView->setSortingEnabled(true); databaseView->sortByColumn(0, Qt::AscendingOrder); databaseView->setModel(databaseDisplayModel); - connect(databaseView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoLeft(const QModelIndex &, const QModelIndex &))); + connect(databaseView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, + SLOT(updateCardInfoLeft(const QModelIndex &, const QModelIndex &))); connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard())); QByteArray dbHeaderState = settingsCache->layouts().getDeckEditorDbHeaderState(); - if (dbHeaderState.isNull()) - { + if (dbHeaderState.isNull()) { // first run databaseView->setColumnWidth(0, 200); - } - else - { + } else { databaseView->header()->restoreState(dbHeaderState); } connect(databaseView->header(), SIGNAL(geometriesChanged()), this, SLOT(saveDbHeaderState())); @@ -415,7 +418,7 @@ void TabDeckEditor::createCentralFrame() centralWidget->setObjectName("centralWidget"); centralWidget->setLayout(centralFrame); setCentralWidget(centralWidget); - setDockOptions(QMainWindow::AnimatedDocks|QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks); + setDockOptions(QMainWindow::AnimatedDocks | QMainWindow::AllowNestedDocks | QMainWindow::AllowTabbedDocks); } void TabDeckEditor::restartLayout() @@ -459,8 +462,8 @@ void TabDeckEditor::freeDocksSize() cardInfoDock->setMinimumSize(100, 100); cardInfoDock->setMaximumSize(5000, 5000); - filterDock->setMinimumSize(100,100); - filterDock->setMaximumSize(5000,5000); + filterDock->setMinimumSize(100, 100); + filterDock->setMaximumSize(5000, 5000); } void TabDeckEditor::refreshShortcuts() @@ -470,7 +473,8 @@ void TabDeckEditor::refreshShortcuts() aSaveDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aSaveDeck")); aExportDeckDecklist->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aExportDeckDecklist")); aSaveDeckAs->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aSaveDeckAs")); - aLoadDeckFromClipboard->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aLoadDeckFromClipboard")); + aLoadDeckFromClipboard->setShortcuts( + settingsCache->shortcuts().getShortcut("TabDeckEditor/aLoadDeckFromClipboard")); aPrintDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aPrintDeck")); aAnalyzeDeckDeckstats->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aAnalyzeDeck")); aClose->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClose")); @@ -479,7 +483,8 @@ void TabDeckEditor::refreshShortcuts() aClearFilterOne->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterOne")); aSaveDeckToClipboard->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aSaveDeckToClipboard")); - aSaveDeckToClipboardRaw->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aSaveDeckToClipboardRaw")); + aSaveDeckToClipboardRaw->setShortcuts( + settingsCache->shortcuts().getShortcut("TabDeckEditor/aSaveDeckToClipboardRaw")); aClearFilterOne->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterOne")); aClose->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClose")); @@ -535,7 +540,7 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) this->installEventFilter(this); retranslateUi(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); QTimer::singleShot(0, this, SLOT(loadLayout())); @@ -628,12 +633,12 @@ void TabDeckEditor::updateComments() setModified(true); } -void TabDeckEditor::updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &/*previous*/) +void TabDeckEditor::updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex & /*previous*/) { cardInfo->setCard(current.sibling(current.row(), 0).data().toString()); } -void TabDeckEditor::updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &/*previous*/) +void TabDeckEditor::updateCardInfoRight(const QModelIndex ¤t, const QModelIndex & /*previous*/) { if (!current.isValid()) return; @@ -646,7 +651,8 @@ void TabDeckEditor::updateSearch(const QString &search) databaseDisplayModel->setCardName(search); QModelIndexList sel = databaseView->selectionModel()->selectedRows(); if (sel.isEmpty() && databaseDisplayModel->rowCount()) - databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), + QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } void TabDeckEditor::updateHash() @@ -658,8 +664,8 @@ bool TabDeckEditor::confirmClose() { if (modified) { tabSupervisor->setCurrentWidget(this); - QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Are you sure?"), - tr("The decklist has been modified.\nDo you want to save the changes?"), + QMessageBox::StandardButton ret = QMessageBox::warning( + this, tr("Are you sure?"), tr("The decklist has been modified.\nDo you want to save the changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); if (ret == QMessageBox::Save) return actSaveDeck(); @@ -722,7 +728,8 @@ bool TabDeckEditor::actSaveDeck() cmd.set_deck_list(deck->writeToString_Native().toStdString()); PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(saveDeckRemoteFinished(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(saveDeckRemoteFinished(Response))); tabSupervisor->getClient()->sendCommand(pend); return true; @@ -732,7 +739,9 @@ bool TabDeckEditor::actSaveDeck() setModified(false); return true; } - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); + QMessageBox::critical( + this, tr("Error"), + tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); return false; } @@ -752,7 +761,9 @@ bool TabDeckEditor::actSaveDeckAs() 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.")); + QMessageBox::critical( + this, tr("Error"), + tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); return false; } setModified(false); @@ -797,52 +808,47 @@ void TabDeckEditor::actPrintDeck() dlg->exec(); } -//Action called when export deck to decklist menu item is pressed. +// Action called when export deck to decklist menu item is pressed. void TabDeckEditor::actExportDeckDecklist() { - //Get the decklist class for the deck. + // Get the decklist class for the deck. DeckLoader *const deck = deckModel->getDeckList(); - //create a string to load the decklist url into. + // create a string to load the decklist url into. QString decklistUrlString; - //check if deck is not null - if(deck){ - //Get the decklist url string from the deck loader class. + // check if deck is not null + if (deck) { + // Get the decklist url string from the deck loader class. decklistUrlString = deck->exportDeckToDecklist(); - //Check to make sure the string isn't empty. - if(QString::compare(decklistUrlString, "", Qt::CaseInsensitive) == 0){ - //Show an error if the deck is empty, and return. + // Check to make sure the string isn't empty. + if (QString::compare(decklistUrlString, "", Qt::CaseInsensitive) == 0) { + // Show an error if the deck is empty, and return. QMessageBox::critical(this, tr("Error"), tr("There are no cards in your deck to be exported")); return; } - //Encode the string recieved from the model to make sure all characters are encoded. - //first we put it into a qurl object + // Encode the string recieved from the model to make sure all characters are encoded. + // first we put it into a qurl object QUrl decklistUrl = QUrl(decklistUrlString); - //we get the correctly encoded url. + // we get the correctly encoded url. decklistUrlString = decklistUrl.toEncoded(); - //We open the url in the user's default browser + // We open the url in the user's default browser QDesktopServices::openUrl(decklistUrlString); - } - else{ - //if there's no deck loader object, return an error + } else { + // if there's no deck loader object, return an error QMessageBox::critical(this, tr("Error"), tr("No deck was selected to be saved.")); } } void TabDeckEditor::actAnalyzeDeckDeckstats() { - DeckStatsInterface *interface = new DeckStatsInterface( - *databaseModel->getDatabase(), - this - ); // it deletes itself when done + DeckStatsInterface *interface = new DeckStatsInterface(*databaseModel->getDatabase(), + this); // it deletes itself when done interface->analyzeDeck(deckModel->getDeckList()); } void TabDeckEditor::actAnalyzeDeckTappedout() { - TappedOutInterface *interface = new TappedOutInterface( - *databaseModel->getDatabase(), - this - ); // it deletes itself when done + TappedOutInterface *interface = new TappedOutInterface(*databaseModel->getDatabase(), + this); // it deletes itself when done interface->analyzeDeck(deckModel->getDeckList()); } @@ -855,7 +861,7 @@ void TabDeckEditor::actClearFilterAll() void TabDeckEditor::actClearFilterOne() { QModelIndexList selIndexes = filterView->selectionModel()->selectedIndexes(); - foreach(QModelIndex idx, selIndexes) + foreach (QModelIndex idx, selIndexes) filterModel->removeRow(idx.row(), idx.parent()); } @@ -881,7 +887,7 @@ void TabDeckEditor::addCardHelper(QString zoneName) const CardInfo *info; info = currentCardInfo(); - if(!info) + if (!info) return; if (info->getIsToken()) zoneName = DECK_ZONE_TOKENS; @@ -902,7 +908,7 @@ void TabDeckEditor::actSwapCard() const QModelIndex gparent = currentIndex.parent().parent(); if (!gparent.isValid()) - return; + return; const QString zoneName = gparent.sibling(gparent.row(), 1).data().toString(); actDecrement(); @@ -917,7 +923,7 @@ void TabDeckEditor::actSwapCard() void TabDeckEditor::actAddCard() { - if(QApplication::keyboardModifiers() & Qt::ControlModifier) + if (QApplication::keyboardModifiers() & Qt::ControlModifier) actAddCardToSideboard(); else addCardHelper(DECK_ZONE_MAIN); @@ -959,7 +965,7 @@ void TabDeckEditor::decrementCardHelper(QString zoneName) QModelIndex idx; info = currentCardInfo(); - if(!info) + if (!info) return; if (info->getIsToken()) zoneName = DECK_ZONE_TOKENS; @@ -990,7 +996,6 @@ void TabDeckEditor::actDecrement() offsetCountAtIndex(currentIndex, -1); } - void TabDeckEditor::setDeck(DeckLoader *_deck) { deckModel->setDeckList(_deck); @@ -1017,7 +1022,8 @@ void TabDeckEditor::setModified(bool _modified) emit tabTextChanged(this, getTabText()); } -void TabDeckEditor::filterViewCustomContextMenu(const QPoint &point) { +void TabDeckEditor::filterViewCustomContextMenu(const QPoint &point) +{ QMenu menu; QAction *action; QModelIndex idx; @@ -1028,12 +1034,12 @@ void TabDeckEditor::filterViewCustomContextMenu(const QPoint &point) { action = menu.addAction(QString("delete")); action->setData(point); - connect(&menu, SIGNAL(triggered(QAction *)), - this, SLOT(filterRemove(QAction *))); + connect(&menu, SIGNAL(triggered(QAction *)), this, SLOT(filterRemove(QAction *))); menu.exec(filterView->mapToGlobal(point)); } -void TabDeckEditor::filterRemove(QAction *action) { +void TabDeckEditor::filterRemove(QAction *action) +{ QPoint point; QModelIndex idx; @@ -1046,23 +1052,21 @@ void TabDeckEditor::filterRemove(QAction *action) { } // Method uses to sync docks state with menu items state -bool TabDeckEditor::eventFilter(QObject * o, QEvent * e) +bool TabDeckEditor::eventFilter(QObject *o, QEvent *e) { - if(e->type() == QEvent::Close) - { - if(o == cardInfoDock) - { + if (e->type() == QEvent::Close) { + if (o == cardInfoDock) { aCardInfoDockVisible->setChecked(false); aCardInfoDockFloating->setEnabled(false); - } else if(o == deckDock) { + } else if (o == deckDock) { aDeckDockVisible->setChecked(false); aDeckDockFloating->setEnabled(false); - } else if(o == filterDock) { + } else if (o == filterDock) { aFilterDockVisible->setChecked(false); aFilterDockFloating->setEnabled(false); } } - if( o == this && e->type() == QEvent::Hide){ + if (o == this && e->type() == QEvent::Hide) { settingsCache->layouts().setDeckEditorLayoutState(saveState()); settingsCache->layouts().setDeckEditorGeometry(saveGeometry()); settingsCache->layouts().setDeckEditorCardSize(cardInfoDock->size()); @@ -1075,22 +1079,19 @@ bool TabDeckEditor::eventFilter(QObject * o, QEvent * e) void TabDeckEditor::dockVisibleTriggered() { QObject *o = sender(); - if(o == aCardInfoDockVisible) - { + if (o == aCardInfoDockVisible) { cardInfoDock->setVisible(aCardInfoDockVisible->isChecked()); aCardInfoDockFloating->setEnabled(aCardInfoDockVisible->isChecked()); return; } - if(o == aDeckDockVisible) - { + if (o == aDeckDockVisible) { deckDock->setVisible(aDeckDockVisible->isChecked()); aDeckDockFloating->setEnabled(aDeckDockVisible->isChecked()); return; } - if(o == aFilterDockVisible) - { + if (o == aFilterDockVisible) { filterDock->setVisible(aFilterDockVisible->isChecked()); aFilterDockFloating->setEnabled(aFilterDockVisible->isChecked()); return; @@ -1100,20 +1101,17 @@ void TabDeckEditor::dockVisibleTriggered() void TabDeckEditor::dockFloatingTriggered() { QObject *o = sender(); - if(o == aCardInfoDockFloating) - { + if (o == aCardInfoDockFloating) { cardInfoDock->setFloating(aCardInfoDockFloating->isChecked()); return; } - if(o == aDeckDockFloating) - { + if (o == aDeckDockFloating) { deckDock->setFloating(aDeckDockFloating->isChecked()); return; } - if(o == aFilterDockFloating) - { + if (o == aFilterDockFloating) { filterDock->setFloating(aFilterDockFloating->isChecked()); return; } @@ -1122,20 +1120,17 @@ void TabDeckEditor::dockFloatingTriggered() void TabDeckEditor::dockTopLevelChanged(bool topLevel) { QObject *o = sender(); - if(o == cardInfoDock) - { + if (o == cardInfoDock) { aCardInfoDockFloating->setChecked(topLevel); return; } - if(o == deckDock) - { + if (o == deckDock) { aDeckDockFloating->setChecked(topLevel); return; } - if(o == filterDock) - { + if (o == filterDock) { aFilterDockFloating->setChecked(topLevel); return; } diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 09df031a..75a0db1b 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -1,11 +1,11 @@ #ifndef WINDOW_DECKEDITOR_H #define WINDOW_DECKEDITOR_H +#include "keysignals.h" #include "tab.h" #include #include #include -#include "keysignals.h" class CardDatabaseModel; class CardDatabaseDisplayModel; @@ -22,67 +22,78 @@ class FilterBuilder; class CardInfo; class QGroupBox; class QHBoxLayout; +class QVBoxLayout; class QPushButton; class QDockWidget; -class SearchLineEdit : public QLineEdit { +class SearchLineEdit : public QLineEdit +{ private: QTreeView *treeView; + protected: void keyPressEvent(QKeyEvent *event); + public: - SearchLineEdit() : QLineEdit(), treeView(0) { } - void setTreeView(QTreeView *_treeView) { treeView = _treeView; } + SearchLineEdit() : QLineEdit(), treeView(0) + { + } + void setTreeView(QTreeView *_treeView) + { + treeView = _treeView; + } }; -class TabDeckEditor : public Tab { +class TabDeckEditor : public Tab +{ Q_OBJECT - private slots: - void updateName(const QString &name); - void updateComments(); - void updateHash(); - void updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &previous); - void updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &previous); - void updateSearch(const QString &search); +private slots: + void updateName(const QString &name); + void updateComments(); + void updateHash(); + void updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &previous); + void updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &previous); + void updateSearch(const QString &search); - void actNewDeck(); - void actLoadDeck(); - bool actSaveDeck(); - bool actSaveDeckAs(); - void actLoadDeckFromClipboard(); - void actSaveDeckToClipboard(); - void actSaveDeckToClipboardRaw(); - void actPrintDeck(); - void actExportDeckDecklist(); - void actAnalyzeDeckDeckstats(); - void actAnalyzeDeckTappedout(); + void actNewDeck(); + void actLoadDeck(); + bool actSaveDeck(); + bool actSaveDeckAs(); + void actLoadDeckFromClipboard(); + void actSaveDeckToClipboard(); + void actSaveDeckToClipboardRaw(); + void actPrintDeck(); + void actExportDeckDecklist(); + void actAnalyzeDeckDeckstats(); + void actAnalyzeDeckTappedout(); - void actClearFilterAll(); - void actClearFilterOne(); + void actClearFilterAll(); + void actClearFilterOne(); - void actSwapCard(); - void actAddCard(); - void actAddCardToSideboard(); - void actRemoveCard(); - void actIncrement(); - void actDecrement(); - void actDecrementCard(); - void actDecrementCardFromSideboard(); + void actSwapCard(); + void actAddCard(); + void actAddCardToSideboard(); + void actRemoveCard(); + void actIncrement(); + void actDecrement(); + void actDecrementCard(); + void actDecrementCardFromSideboard(); - void saveDeckRemoteFinished(const Response &r); - void filterViewCustomContextMenu(const QPoint &point); - void filterRemove(QAction *action); + void saveDeckRemoteFinished(const Response &r); + void filterViewCustomContextMenu(const QPoint &point); + void filterRemove(QAction *action); - void loadLayout(); - void restartLayout(); - void freeDocksSize(); - void refreshShortcuts(); + void loadLayout(); + void restartLayout(); + void freeDocksSize(); + void refreshShortcuts(); + + bool eventFilter(QObject *o, QEvent *e); + void dockVisibleTriggered(); + void dockFloatingTriggered(); + void dockTopLevelChanged(bool topLevel); + void saveDbHeaderState(); - bool eventFilter(QObject *o, QEvent *e); - void dockVisibleTriggered(); - void dockFloatingTriggered(); - void dockTopLevelChanged(bool topLevel); - void saveDbHeaderState(); private: CardInfo *currentCardInfo() const; void addCardHelper(QString zoneName); @@ -112,12 +123,16 @@ private: KeySignals filterViewKeySignals; QWidget *filterBox; - QMenu *deckMenu, *viewMenu, *cardInfoDockMenu, *deckDockMenu, *filterDockMenu, *analyzeDeckMenu, *saveDeckToClipboardMenu; - QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aSaveDeckToClipboardRaw, *aPrintDeck, *aExportDeckDecklist, *aAnalyzeDeckDeckstats, *aAnalyzeDeckTappedout, *aClose; + QMenu *deckMenu, *viewMenu, *cardInfoDockMenu, *deckDockMenu, *filterDockMenu, *analyzeDeckMenu, + *saveDeckToClipboardMenu; + QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, + *aSaveDeckToClipboardRaw, *aPrintDeck, *aExportDeckDecklist, *aAnalyzeDeckDeckstats, *aAnalyzeDeckTappedout, + *aClose; QAction *aClearFilterAll, *aClearFilterOne; QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement; QAction *aResetLayout; - QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aDeckDockVisible, *aDeckDockFloating, *aFilterDockVisible, *aFilterDockFloating; + QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aDeckDockVisible, *aDeckDockFloating, *aFilterDockVisible, + *aFilterDockFloating; bool modified; QVBoxLayout *centralFrame; @@ -126,6 +141,7 @@ private: QDockWidget *deckDock; QDockWidget *filterDock; QWidget *centralWidget; + public: TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent = 0); ~TabDeckEditor(); diff --git a/cockatrice/src/tab_deck_storage.cpp b/cockatrice/src/tab_deck_storage.cpp index 0629df11..371868a6 100644 --- a/cockatrice/src/tab_deck_storage.cpp +++ b/cockatrice/src/tab_deck_storage.cpp @@ -1,30 +1,30 @@ -#include -#include -#include -#include -#include +#include "tab_deck_storage.h" +#include "abstractclient.h" +#include "deck_loader.h" +#include "decklist.h" +#include "remotedecklist_treewidget.h" +#include "settingscache.h" #include -#include -#include #include +#include +#include +#include +#include #include #include -#include "tab_deck_storage.h" -#include "remotedecklist_treewidget.h" -#include "abstractclient.h" -#include "decklist.h" -#include "settingscache.h" -#include "deck_loader.h" +#include +#include +#include -#include "pending_command.h" +#include "pb/command_deck_del.pb.h" +#include "pb/command_deck_del_dir.pb.h" +#include "pb/command_deck_download.pb.h" +#include "pb/command_deck_new_dir.pb.h" +#include "pb/command_deck_upload.pb.h" #include "pb/response.pb.h" #include "pb/response_deck_download.pb.h" #include "pb/response_deck_upload.pb.h" -#include "pb/command_deck_upload.pb.h" -#include "pb/command_deck_download.pb.h" -#include "pb/command_deck_new_dir.pb.h" -#include "pb/command_deck_del_dir.pb.h" -#include "pb/command_deck_del.pb.h" +#include "pending_command.h" TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client) : Tab(_tabSupervisor), client(_client) @@ -32,7 +32,7 @@ TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_c localDirModel = new QFileSystemModel(this); localDirModel->setRootPath(settingsCache->getDeckPath()); localDirModel->sort(0, Qt::AscendingOrder); - + localDirView = new QTreeView; localDirView->setModel(localDirModel); localDirView->setColumnHidden(1, true); @@ -40,7 +40,7 @@ TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_c localDirView->setSortingEnabled(true); localDirView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); - + leftToolBar = new QToolBar; leftToolBar->setOrientation(Qt::Horizontal); leftToolBar->setIconSize(QSize(32, 32)); @@ -54,7 +54,7 @@ TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_c leftVbox->addLayout(leftToolBarLayout); leftGroupBox = new QGroupBox; leftGroupBox->setLayout(leftVbox); - + rightToolBar = new QToolBar; rightToolBar->setOrientation(Qt::Horizontal); rightToolBar->setIconSize(QSize(32, 32)); @@ -70,11 +70,11 @@ TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_c 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(QPixmap("theme:icons/pencil")); connect(aOpenLocalDeck, SIGNAL(triggered()), this, SLOT(actOpenLocalDeck())); @@ -96,7 +96,7 @@ TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_c aDeleteRemoteDeck = new QAction(this); aDeleteRemoteDeck->setIcon(QPixmap("theme:icons/remove_row")); connect(aDeleteRemoteDeck, SIGNAL(triggered()), this, SLOT(actDeleteRemoteDeck())); - + leftToolBar->addAction(aOpenLocalDeck); leftToolBar->addAction(aUpload); leftToolBar->addAction(aDeleteLocalDeck); @@ -104,10 +104,10 @@ TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_c rightToolBar->addAction(aDownload); rightToolBar->addAction(aNewFolder); rightToolBar->addAction(aDeleteRemoteDeck); - + retranslateUi(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(hbox); setCentralWidget(mainWidget); } @@ -116,7 +116,7 @@ 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")); @@ -132,11 +132,11 @@ void TabDeckStorage::actOpenLocalDeck() if (localDirModel->isDir(curLeft)) return; QString filePath = localDirModel->filePath(curLeft); - + DeckLoader deckLoader; if (!deckLoader.loadFromFile(filePath, DeckLoader::CockatriceFormat)) return; - + emit openDeckEditor(&deckLoader); } @@ -153,14 +153,16 @@ void TabDeckStorage::actUpload() 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); + 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) @@ -168,13 +170,14 @@ void TabDeckStorage::actUpload() 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))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(uploadFinished(Response, CommandContainer))); client->sendCommand(pend); } @@ -182,33 +185,37 @@ void TabDeckStorage::uploadFinished(const Response &r, const CommandContainer &c { 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) + 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()); + 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))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(openRemoteDeckFinished(Response, CommandContainer))); client->sendCommand(pend); } @@ -216,14 +223,14 @@ void TabDeckStorage::openRemoteDeckFinished(const Response &r, const CommandCont { 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); } @@ -239,28 +246,32 @@ void TabDeckStorage::actDownload() filePath = localDirModel->filePath(curLeft); } - RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); + 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))); + 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) +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); } @@ -271,7 +282,8 @@ void TabDeckStorage::actNewFolder() if (folderName.isEmpty()) return; - // '/' isn't a valid filename character on *nix so we're choosing to replace it with a different arbitrary character. + // '/' isn't a valid filename character on *nix so we're choosing to replace it with a different arbitrary + // character. std::string folder = folderName.toStdString(); std::replace(folder.begin(), folder.end(), '/', '-'); @@ -283,13 +295,14 @@ void TabDeckStorage::actNewFolder() 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(folder); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(newFolderFinished(Response, CommandContainer))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(newFolderFinished(Response, CommandContainer))); client->sendCommand(pend); } @@ -297,9 +310,10 @@ void TabDeckStorage::newFolderFinished(const Response &response, const CommandCo { 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()))); + serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()), + serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); } void TabDeckStorage::actDeleteRemoteDeck() @@ -313,23 +327,29 @@ void TabDeckStorage::actDeleteRemoteDeck() 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) + 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))); + 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) + 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))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(deleteDeckFinished(Response, CommandContainer))); } - + client->sendCommand(pend); } @@ -337,7 +357,7 @@ void TabDeckStorage::deleteDeckFinished(const Response &response, const CommandC { 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) @@ -348,7 +368,7 @@ void TabDeckStorage::deleteFolderFinished(const Response &response, const Comman { 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) diff --git a/cockatrice/src/tab_deck_storage.h b/cockatrice/src/tab_deck_storage.h index c6567ff1..1deb0845 100644 --- a/cockatrice/src/tab_deck_storage.h +++ b/cockatrice/src/tab_deck_storage.h @@ -15,7 +15,8 @@ class CommandContainer; class Response; class DeckLoader; -class TabDeckStorage : public Tab { +class TabDeckStorage : public Tab +{ Q_OBJECT private: AbstractClient *client; @@ -24,19 +25,19 @@ private: 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); @@ -46,10 +47,14 @@ private slots: 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"); } + QString getTabText() const + { + return tr("Deck storage"); + } signals: void openDeckEditor(const DeckLoader *deckLoader); }; diff --git a/cockatrice/src/tab_game.cpp b/cockatrice/src/tab_game.cpp index 6cb17568..c63e4e74 100644 --- a/cockatrice/src/tab_game.cpp +++ b/cockatrice/src/tab_game.cpp @@ -1,77 +1,76 @@ -#include -#include -#include -#include #include -#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include #include -#include -#include "dlg_creategame.h" -#include "tab_game.h" -#include "tab_supervisor.h" +#include "abstractclient.h" +#include "arrowitem.h" +#include "carddatabase.h" #include "cardframe.h" -#include "playerlistwidget.h" +#include "carditem.h" +#include "deck_loader.h" +#include "deckview.h" +#include "dlg_creategame.h" +#include "dlg_load_remote_deck.h" +#include "gamescene.h" +#include "gameview.h" +#include "lineeditcompleter.h" +#include "main.h" #include "messagelogwidget.h" #include "phasestoolbar.h" -#include "gameview.h" -#include "gamescene.h" -#include "player.h" -#include "zoneviewzone.h" -#include "zoneviewwidget.h" -#include "deckview.h" -#include "deck_loader.h" -#include "dlg_load_remote_deck.h" -#include "abstractclient.h" -#include "carditem.h" -#include "arrowitem.h" -#include "main.h" -#include "settingscache.h" -#include "carddatabase.h" #include "pictureloader.h" +#include "player.h" +#include "playerlistwidget.h" #include "replay_timeline_widget.h" -#include "lineeditcompleter.h" +#include "settingscache.h" +#include "tab_game.h" +#include "tab_supervisor.h" #include "window_sets.h" +#include "zoneviewwidget.h" +#include "zoneviewzone.h" -#include -#include "pending_command.h" -#include "pb/game_replay.pb.h" +#include "get_pb_extension.h" #include "pb/command_concede.pb.h" #include "pb/command_deck_select.pb.h" -#include "pb/command_ready_start.pb.h" -#include "pb/command_set_sideboard_plan.pb.h" -#include "pb/command_set_sideboard_lock.pb.h" -#include "pb/command_leave_game.pb.h" -#include "pb/command_game_say.pb.h" -#include "pb/command_set_active_phase.pb.h" -#include "pb/command_next_turn.pb.h" #include "pb/command_delete_arrow.pb.h" -#include "pb/response_deck_download.pb.h" -#include "pb/game_event_container.pb.h" +#include "pb/command_game_say.pb.h" +#include "pb/command_leave_game.pb.h" +#include "pb/command_next_turn.pb.h" +#include "pb/command_ready_start.pb.h" +#include "pb/command_set_active_phase.pb.h" +#include "pb/command_set_sideboard_lock.pb.h" +#include "pb/command_set_sideboard_plan.pb.h" +#include "pb/context_connection_state_changed.pb.h" +#include "pb/context_deck_select.pb.h" +#include "pb/context_ping_changed.pb.h" +#include "pb/event_game_closed.pb.h" +#include "pb/event_game_host_changed.pb.h" #include "pb/event_game_joined.pb.h" #include "pb/event_game_say.pb.h" #include "pb/event_game_state_changed.pb.h" -#include "pb/event_player_properties_changed.pb.h" #include "pb/event_join.pb.h" -#include "pb/event_leave.pb.h" #include "pb/event_kicked.pb.h" -#include "pb/event_game_host_changed.pb.h" -#include "pb/event_game_closed.pb.h" -#include "pb/event_set_active_player.pb.h" +#include "pb/event_leave.pb.h" +#include "pb/event_player_properties_changed.pb.h" #include "pb/event_set_active_phase.pb.h" -#include "pb/context_deck_select.pb.h" -#include "pb/context_connection_state_changed.pb.h" -#include "pb/context_ping_changed.pb.h" -#include "get_pb_extension.h" +#include "pb/event_set_active_player.pb.h" +#include "pb/game_event_container.pb.h" +#include "pb/game_replay.pb.h" +#include "pb/response_deck_download.pb.h" +#include "pending_command.h" +#include -ToggleButton::ToggleButton(QWidget *parent) - : QPushButton(parent), state(false) +ToggleButton::ToggleButton(QWidget *parent) : QPushButton(parent), state(false) { } @@ -96,7 +95,7 @@ void ToggleButton::setState(bool _state) } DeckViewContainer::DeckViewContainer(int _playerId, TabGame *parent) - : QWidget(0), parentGame(parent), playerId(_playerId) + : QWidget(0), parentGame(parent), playerId(_playerId) { loadLocalButton = new QPushButton; loadRemoteButton = new QPushButton; @@ -131,7 +130,7 @@ DeckViewContainer::DeckViewContainer(int _playerId, TabGame *parent) setLayout(deckViewLayout); retranslateUi(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); } @@ -170,18 +169,40 @@ void TabGame::refreshShortcuts() for (int i = 0; i < phaseActions.size(); ++i) { QAction *temp = phaseActions.at(i); switch (i) { - case 0: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase0")); break; - case 1: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase1")); break; - case 2: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase2")); break; - case 3: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase3")); break; - case 4: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase4")); break; - case 5: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase5")); break; - case 6: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase6")); break; - case 7: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase7")); break; - case 8: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase8")); break; - case 9: temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase9")); break; - case 10:temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase10")); break; - default: ; + case 0: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase0")); + break; + case 1: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase1")); + break; + case 2: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase2")); + break; + case 3: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase3")); + break; + case 4: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase4")); + break; + case 5: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase5")); + break; + case 6: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase6")); + break; + case 7: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase7")); + break; + case 8: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase8")); + break; + case 9: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase9")); + break; + case 10: + temp->setShortcuts(settingsCache->shortcuts().getShortcut("Player/phase10")); + break; + default:; } } @@ -233,7 +254,8 @@ void DeckViewContainer::loadLocalDeck() Command_DeckSelect cmd; cmd.set_deck(deck.writeToString_Native().toStdString()); PendingCommand *pend = parentGame->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(deckSelectFinished(const Response &))); parentGame->sendGameCommand(pend, playerId); } @@ -244,7 +266,8 @@ void DeckViewContainer::loadRemoteDeck() Command_DeckSelect cmd; cmd.set_deck_id(dlg.getDeckId()); PendingCommand *pend = parentGame->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(deckSelectFinished(const Response &))); parentGame->sendGameCommand(pend, playerId); } } @@ -305,21 +328,9 @@ void DeckViewContainer::setDeck(const DeckLoader &deck) } TabGame::TabGame(TabSupervisor *_tabSupervisor, GameReplay *_replay) - : Tab(_tabSupervisor), - secondsElapsed(0), - hostId(-1), - localPlayerId(-1), - isLocalGame(_tabSupervisor->getIsLocalGame()), - spectator(true), - gameStateKnown(false), - resuming(false), - currentPhase(-1), - activeCard(0), - gameClosed(false), - replay(_replay), - currentReplayStep(0), - sayLabel(0), - sayEdit(0) + : Tab(_tabSupervisor), secondsElapsed(0), hostId(-1), localPlayerId(-1), + isLocalGame(_tabSupervisor->getIsLocalGame()), spectator(true), gameStateKnown(false), resuming(false), + currentPhase(-1), activeCard(0), gameClosed(false), replay(_replay), currentReplayStep(0), sayLabel(0), sayEdit(0) { // THIS CTOR IS USED ON REPLAY gameInfo.CopyFrom(replay->game_info()); @@ -336,7 +347,8 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor, GameReplay *_replay) 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)); + 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(); @@ -363,7 +375,7 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor, GameReplay *_replay) createReplayMenuItems(); createViewMenuItems(); retranslateUi(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); messageLog->logReplayStarted(gameInfo.game_id()); @@ -371,22 +383,14 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor, GameReplay *_replay) QTimer::singleShot(0, this, SLOT(loadLayout())); } -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()), - isLocalGame(_tabSupervisor->getIsLocalGame()), - spectator(event.spectator()), - gameStateKnown(false), - resuming(event.resuming()), - currentPhase(-1), - activeCard(0), - gameClosed(false), - replay(0), - replayDock(0) +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()), isLocalGame(_tabSupervisor->getIsLocalGame()), + spectator(event.spectator()), gameStateKnown(false), resuming(event.resuming()), currentPhase(-1), activeCard(0), + gameClosed(false), replay(0), replayDock(0) { // THIS CTOR IS USED ON GAMES gameInfo.set_started(false); @@ -404,13 +408,13 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor, QList &_client mainWidget = new QStackedWidget(this); mainWidget->addWidget(deckViewContainerWidget); mainWidget->addWidget(gamePlayAreaWidget); - mainWidget->setContentsMargins(0,0,0,0); + mainWidget->setContentsMargins(0, 0, 0, 0); setCentralWidget(mainWidget); createMenuItems(); createViewMenuItems(); retranslateUi(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); // append game to rooms game list for others to see @@ -421,12 +425,14 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor, QList &_client QTimer::singleShot(0, this, SLOT(loadLayout())); } -void TabGame::addMentionTag(QString value) { +void TabGame::addMentionTag(QString value) +{ sayEdit->insert(value + " "); sayEdit->setFocus(); } -void TabGame::emitUserEvent() { +void TabGame::emitUserEvent() +{ bool globalEvent = !spectator || settingsCache->getSpectatorNotificationsEnabled(); emit userEvent(globalEvent); updatePlayerListDockTitle(); @@ -437,8 +443,7 @@ TabGame::~TabGame() delete replay; QMapIterator i(players); - while (i.hasNext()) - { + while (i.hasNext()) { delete i.next().value(); } @@ -451,7 +456,8 @@ void TabGame::updatePlayerListDockTitle() { QString tabText = " | " + (replay ? tr("Replay") : tr("Game")) + " #" + QString::number(gameInfo.game_id()); QString userCountInfo = QString(" %1/%2").arg(players.size()).arg(gameInfo.max_players()); - playerListDock->setWindowTitle(tr("Player List") + userCountInfo + (playerListDock->isWindow() ? tabText : QString())); + playerListDock->setWindowTitle(tr("Player List") + userCountInfo + + (playerListDock->isWindow() ? tabText : QString())); } void TabGame::retranslateUi() @@ -461,7 +467,7 @@ void TabGame::retranslateUi() updatePlayerListDockTitle(); cardInfoDock->setWindowTitle(tr("Card Info") + (cardInfoDock->isWindow() ? tabText : QString())); messageLayoutDock->setWindowTitle(tr("Messages") + (messageLayoutDock->isWindow() ? tabText : QString())); - if(replayDock) + if (replayDock) replayDock->setWindowTitle(tr("Replay Timeline") + (replayDock->isWindow() ? tabText : QString())); if (phasesMenu) { @@ -497,7 +503,7 @@ void TabGame::retranslateUi() if (aCloseReplay) { aCloseReplay->setText(tr("C&lose replay")); } - if (sayLabel){ + if (sayLabel) { sayLabel->setText(tr("&Say:")); } @@ -515,8 +521,7 @@ void TabGame::retranslateUi() aPlayerListDockVisible->setText(tr("Visible")); aPlayerListDockFloating->setText(tr("Floating")); - if(replayDock) - { + if (replayDock) { replayDockMenu->setTitle(tr("Replay Timeline")); aReplayDockVisible->setText(tr("Visible")); aReplayDockFloating->setText(tr("Floating")); @@ -553,7 +558,6 @@ void TabGame::replayFinished() replayFastForwardButton->setEnabled(false); } - void TabGame::replayStartButtonClicked() { replayStartButton->setEnabled(false); @@ -585,7 +589,9 @@ void TabGame::incrementGameTime() 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')); + 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) @@ -608,7 +614,8 @@ void TabGame::actGameInfo() 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) + 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()); @@ -618,8 +625,9 @@ 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 (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()); @@ -702,7 +710,7 @@ Player *TabGame::addPlayer(int playerId, const ServerInfo_User &info) Player *newPlayer = new Player(info, playerId, local, this); connect(newPlayer, SIGNAL(openDeckEditor(const DeckLoader *)), this, SIGNAL(openDeckEditor(const DeckLoader *))); QString newPlayerName = "@" + newPlayer->getName(); - if (sayEdit && !autocompleteUserList.contains(newPlayerName)){ + if (sayEdit && !autocompleteUserList.contains(newPlayerName)) { autocompleteUserList << newPlayerName; sayEdit->setCompletionList(autocompleteUserList); } @@ -739,8 +747,12 @@ void TabGame::processGameEventContainer(const GameEventContainer &cont, Abstract 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; + 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" << eventType; break; @@ -748,19 +760,38 @@ void TabGame::processGameEventContainer(const GameEventContainer &cont, Abstract } } else { if ((clients.size() > 1) && (playerId != -1)) - if (clients.at(playerId) != client) - continue; + 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; + 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); @@ -796,7 +827,8 @@ void TabGame::sendGameCommand(PendingCommand *pend, int playerId) if (!client) return; - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(commandFinished(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(commandFinished(const Response &))); client->sendCommand(pend); } @@ -807,7 +839,8 @@ void TabGame::sendGameCommand(const google::protobuf::Message &command, int play return; PendingCommand *pend = prepareGameCommand(command); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(commandFinished(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(commandFinished(const Response &))); client->sendCommand(pend); } @@ -826,13 +859,15 @@ PendingCommand *TabGame::prepareGameCommand(const ::google::protobuf::Message &c return new PendingCommand(cont); } -PendingCommand *TabGame::prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList) +PendingCommand *TabGame::prepareGameCommand(const QList &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]); + c->GetReflection() + ->MutableMessage(c, cmdList[i]->GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(*cmdList[i]); delete cmdList[i]; } return new PendingCommand(cont); @@ -860,7 +895,7 @@ void TabGame::startGame(bool resuming) playerListWidget->setGameStarted(true, resuming); gameInfo.set_started(true); static_cast(gameView->scene())->rearrange(); - if(sayEdit && players.size() > 1) + if (sayEdit && players.size() > 1) sayEdit->setFocus(); } @@ -894,22 +929,26 @@ void TabGame::closeGame() 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(userInfo.privlevel()), QString::fromStdString(event.message())); + messageLog->logSpectatorSay(QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), + QString::fromStdString(userInfo.privlevel()), QString::fromStdString(event.message())); } -void TabGame::eventSpectatorLeave(const Event_Leave & event, int eventPlayerId, const GameEventContext & /*context*/) +void TabGame::eventSpectatorLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext & /*context*/) { QString playerName = "@" + QString::fromStdString(spectators.value(eventPlayerId).name()); if (sayEdit && autocompleteUserList.removeOne(playerName)) sayEdit->setCompletionList(autocompleteUserList); - messageLog->logLeaveSpectator(QString::fromStdString(spectators.value(eventPlayerId).name()), getLeaveReason(event.reason())); + messageLog->logLeaveSpectator(QString::fromStdString(spectators.value(eventPlayerId).name()), + getLeaveReason(event.reason())); playerListWidget->removePlayer(eventPlayerId); spectators.remove(eventPlayerId); emitUserEvent(); } -void TabGame::eventGameStateChanged(const Event_GameStateChanged &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) +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) { @@ -917,7 +956,7 @@ void TabGame::eventGameStateChanged(const Event_GameStateChanged &event, int /*e const ServerInfo_PlayerProperties &prop = playerInfo.properties(); const int playerId = prop.player_id(); QString playerName = "@" + QString::fromStdString(prop.user_info().name()); - if (sayEdit && !autocompleteUserList.contains(playerName)){ + if (sayEdit && !autocompleteUserList.contains(playerName)) { autocompleteUserList << playerName; sayEdit->setCompletionList(autocompleteUserList); } @@ -973,7 +1012,9 @@ void TabGame::eventGameStateChanged(const Event_GameStateChanged &event, int /*e emitUserEvent(); } -void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context) +void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, + int eventPlayerId, + const GameEventContext &context) { Player *player = players.value(eventPlayerId, 0); if (!player) @@ -981,7 +1022,8 @@ void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged & const ServerInfo_PlayerProperties &prop = event.player_properties(); playerListWidget->updatePlayerProperties(prop, eventPlayerId); - const GameEventContext::ContextType contextType = static_cast(getPbExtension(context)); + const GameEventContext::ContextType contextType = + static_cast(getPbExtension(context)); switch (contextType) { case GameEventContext::READY_START: { bool ready = prop.ready_start(); @@ -1005,8 +1047,7 @@ void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged & } case GameEventContext::DECK_SELECT: { Context_DeckSelect deckSelect = context.GetExtension(Context_DeckSelect::ext); - messageLog->logDeckSelect(player, - QString::fromStdString(deckSelect.deck_hash()), + messageLog->logDeckSelect(player, QString::fromStdString(deckSelect.deck_hash()), deckSelect.sideboard_size()); break; } @@ -1020,7 +1061,7 @@ void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged & messageLog->logConnectionStateChanged(player, prop.ping_seconds() != -1); break; } - default: ; + default:; } } @@ -1029,7 +1070,7 @@ void TabGame::eventJoin(const Event_Join &event, int /*eventPlayerId*/, const Ga const ServerInfo_PlayerProperties &playerInfo = event.player_properties(); const int playerId = playerInfo.player_id(); QString playerName = QString::fromStdString(playerInfo.user_info().name()); - if (sayEdit && !autocompleteUserList.contains("@" + playerName)){ + if (sayEdit && !autocompleteUserList.contains("@" + playerName)) { autocompleteUserList << "@" + playerName; sayEdit->setCompletionList(autocompleteUserList); } @@ -1050,8 +1091,7 @@ void TabGame::eventJoin(const Event_Join &event, int /*eventPlayerId*/, const Ga QString TabGame::getLeaveReason(Event_Leave::LeaveReason reason) { - switch(reason) - { + switch (reason) { case Event_Leave::USER_KICKED: return tr("kicked by game host or moderator"); break; @@ -1067,14 +1107,14 @@ QString TabGame::getLeaveReason(Event_Leave::LeaveReason reason) break; } } -void TabGame::eventLeave(const Event_Leave & event, int eventPlayerId, const GameEventContext & /*context*/) +void TabGame::eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext & /*context*/) { Player *player = players.value(eventPlayerId, 0); if (!player) return; QString playerName = "@" + player->getName(); - if(sayEdit && autocompleteUserList.removeOne(playerName)) + if (sayEdit && autocompleteUserList.removeOne(playerName)) sayEdit->setCompletionList(autocompleteUserList); messageLog->logLeave(player, getLeaveReason(event.reason())); @@ -1107,12 +1147,16 @@ void TabGame::eventKicked(const Event_Kicked & /*event*/, int /*eventPlayerId*/, emitUserEvent(); } -void TabGame::eventGameHostChanged(const Event_GameHostChanged & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) +void TabGame::eventGameHostChanged(const Event_GameHostChanged & /*event*/, + int eventPlayerId, + const GameEventContext & /*context*/) { hostId = eventPlayerId; } -void TabGame::eventGameClosed(const Event_GameClosed & /*event*/, int /*eventPlayerId*/, const GameEventContext & /*context*/) +void TabGame::eventGameClosed(const Event_GameClosed & /*event*/, + int /*eventPlayerId*/, + const GameEventContext & /*context*/) { closeGame(); messageLog->logGameClosed(); @@ -1144,7 +1188,9 @@ Player *TabGame::setActivePlayer(int id) return player; } -void TabGame::eventSetActivePlayer(const Event_SetActivePlayer &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) +void TabGame::eventSetActivePlayer(const Event_SetActivePlayer &event, + int /*eventPlayerId*/, + const GameEventContext & /*context*/) { Player *player = setActivePlayer(event.active_player_id()); if (!player) @@ -1161,7 +1207,9 @@ void TabGame::setActivePhase(int phase) } } -void TabGame::eventSetActivePhase(const Event_SetActivePhase &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) +void TabGame::eventSetActivePhase(const Event_SetActivePhase &event, + int /*eventPlayerId*/, + const GameEventContext & /*context*/) { const int phase = event.phase(); if (currentPhase != phase) @@ -1225,8 +1273,8 @@ Player *TabGame::getActiveLocalPlayer() const { Player *active = players.value(activePlayer, 0); if (active) - if (active->getLocal()) - return active; + if (active->getLocal()) + return active; QMapIterator playerIterator(players); while (playerIterator.hasNext()) { @@ -1324,41 +1372,40 @@ void TabGame::createViewMenuItems() aCardInfoDockVisible = cardInfoDockMenu->addAction(QString()); aCardInfoDockVisible->setCheckable(true); - connect(aCardInfoDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aCardInfoDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aCardInfoDockFloating = cardInfoDockMenu->addAction(QString()); aCardInfoDockFloating->setCheckable(true); - connect(aCardInfoDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aCardInfoDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); aMessageLayoutDockVisible = messageLayoutDockMenu->addAction(QString()); aMessageLayoutDockVisible->setCheckable(true); - connect(aMessageLayoutDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aMessageLayoutDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aMessageLayoutDockFloating = messageLayoutDockMenu->addAction(QString()); aMessageLayoutDockFloating->setCheckable(true); - connect(aMessageLayoutDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aMessageLayoutDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); aPlayerListDockVisible = playerListDockMenu->addAction(QString()); aPlayerListDockVisible->setCheckable(true); - connect(aPlayerListDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aPlayerListDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aPlayerListDockFloating = playerListDockMenu->addAction(QString()); aPlayerListDockFloating->setCheckable(true); - connect(aPlayerListDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aPlayerListDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); - if(replayDock) - { + if (replayDock) { replayDockMenu = viewMenu->addMenu(QString()); aReplayDockVisible = replayDockMenu->addAction(QString()); aReplayDockVisible->setCheckable(true); - connect(aReplayDockVisible,SIGNAL(triggered()),this,SLOT(dockVisibleTriggered())); + connect(aReplayDockVisible, SIGNAL(triggered()), this, SLOT(dockVisibleTriggered())); aReplayDockFloating = replayDockMenu->addAction(QString()); aReplayDockFloating->setCheckable(true); - connect(aReplayDockFloating,SIGNAL(triggered()),this,SLOT(dockFloatingTriggered())); + connect(aReplayDockFloating, SIGNAL(triggered()), this, SLOT(dockFloatingTriggered())); } viewMenu->addSeparator(); aResetLayout = viewMenu->addAction(QString()); - connect(aResetLayout,SIGNAL(triggered()),this,SLOT(actResetLayout())); + connect(aResetLayout, SIGNAL(triggered()), this, SLOT(actResetLayout())); viewMenu->addAction(aResetLayout); addTabMenu(viewMenu); @@ -1366,8 +1413,7 @@ void TabGame::createViewMenuItems() void TabGame::loadLayout() { - if(replayDock) - { + if (replayDock) { restoreGeometry(settingsCache->layouts().getReplayPlayAreaGeometry()); restoreState(settingsCache->layouts().getReplayPlayAreaLayoutState()); @@ -1403,8 +1449,7 @@ void TabGame::loadLayout() aMessageLayoutDockFloating->setChecked(messageLayoutDock->isFloating()); aPlayerListDockFloating->setChecked(playerListDock->isFloating()); - if(replayDock) - { + if (replayDock) { aReplayDockVisible->setChecked(replayDock->isVisible()); aReplayDockFloating->setEnabled(aReplayDockVisible->isChecked()); aReplayDockFloating->setChecked(replayDock->isFloating()); @@ -1421,13 +1466,12 @@ void TabGame::freeDocksSize() messageLayoutDock->setMinimumSize(100, 100); messageLayoutDock->setMaximumSize(5000, 5000); - playerListDock->setMinimumSize(100,100); - playerListDock->setMaximumSize(5000,5000); + playerListDock->setMinimumSize(100, 100); + playerListDock->setMaximumSize(5000, 5000); - if(replayDock) - { - replayDock->setMinimumSize(100,100); - replayDock->setMaximumSize(5000,5000); + if (replayDock) { + replayDock->setMinimumSize(100, 100); + replayDock->setMaximumSize(5000, 5000); } } @@ -1453,29 +1497,28 @@ void TabGame::actResetLayout() addDockWidget(Qt::RightDockWidgetArea, playerListDock); addDockWidget(Qt::RightDockWidgetArea, messageLayoutDock); - if(replayDock) - { + if (replayDock) { replayDock->setVisible(true); replayDock->setFloating(false); addDockWidget(Qt::BottomDockWidgetArea, replayDock); aReplayDockVisible->setChecked(true); aReplayDockFloating->setChecked(false); - cardInfoDock->setMinimumSize(250,360); - cardInfoDock->setMaximumSize(250,360); - messageLayoutDock->setMinimumSize(250,200); - messageLayoutDock->setMaximumSize(250,200); - playerListDock->setMinimumSize(250,50); - playerListDock->setMaximumSize(250,50); - replayDock->setMinimumSize(900,100); - replayDock->setMaximumSize(900,100); + cardInfoDock->setMinimumSize(250, 360); + cardInfoDock->setMaximumSize(250, 360); + messageLayoutDock->setMinimumSize(250, 200); + messageLayoutDock->setMaximumSize(250, 200); + playerListDock->setMinimumSize(250, 50); + playerListDock->setMaximumSize(250, 50); + replayDock->setMinimumSize(900, 100); + replayDock->setMaximumSize(900, 100); } else { - cardInfoDock->setMinimumSize(250,360); - cardInfoDock->setMaximumSize(250,360); - messageLayoutDock->setMinimumSize(250,250); - messageLayoutDock->setMaximumSize(250,250); - playerListDock->setMinimumSize(250,50); - playerListDock->setMaximumSize(250,50); + cardInfoDock->setMinimumSize(250, 360); + cardInfoDock->setMaximumSize(250, 360); + messageLayoutDock->setMinimumSize(250, 250); + messageLayoutDock->setMaximumSize(250, 250); + playerListDock->setMinimumSize(250, 50); + playerListDock->setMaximumSize(250, 50); } QTimer::singleShot(100, this, SLOT(freeDocksSize())); @@ -1484,13 +1527,14 @@ void TabGame::actResetLayout() void TabGame::createPlayAreaWidget(bool bReplay) { phasesToolbar = new PhasesToolbar; - if(!bReplay) - connect(phasesToolbar, SIGNAL(sendGameCommand(const ::google::protobuf::Message &, int)), this, SLOT(sendGameCommand(const ::google::protobuf::Message &, int))); + if (!bReplay) + 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); gamePlayAreaVBox = new QVBoxLayout; - gamePlayAreaVBox->setContentsMargins(0,0,0,0); + gamePlayAreaVBox->setContentsMargins(0, 0, 0, 0); gamePlayAreaVBox->addWidget(gameView); gamePlayAreaWidget = new QWidget; @@ -1533,7 +1577,8 @@ void TabGame::createReplayDock() replayDock = new QDockWidget(this); replayDock->setObjectName("replayDock"); - replayDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); + replayDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); replayDock->setWidget(replayControlWidget); replayDock->setFloating(false); @@ -1548,7 +1593,7 @@ void TabGame::createDeckViewContainerWidget(bool bReplay) deckViewContainerWidget = new QWidget(); deckViewContainerWidget->setObjectName("deckViewContainerWidget"); deckViewContainerLayout = new QVBoxLayout; - deckViewContainerLayout->setContentsMargins(0,0,0,0); + deckViewContainerLayout->setContentsMargins(0, 0, 0, 0); deckViewContainerWidget->setLayout(deckViewContainerLayout); } @@ -1568,7 +1613,8 @@ void TabGame::createCardInfoDock(bool bReplay) cardInfoDock = new QDockWidget(this); cardInfoDock->setObjectName("cardInfoDock"); - cardInfoDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); + cardInfoDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); cardInfoDock->setWidget(cardBoxLayoutWidget); cardInfoDock->setFloating(false); @@ -1578,18 +1624,19 @@ void TabGame::createCardInfoDock(bool bReplay) void TabGame::createPlayerListDock(bool bReplay) { - if(bReplay) - { + if (bReplay) { playerListWidget = new PlayerListWidget(0, 0, this); } else { playerListWidget = new PlayerListWidget(tabSupervisor, clients.first(), this); - connect(playerListWidget, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + connect(playerListWidget, SIGNAL(openMessageDialog(QString, bool)), this, + SIGNAL(openMessageDialog(QString, bool))); } playerListWidget->setFocusPolicy(Qt::NoFocus); playerListDock = new QDockWidget(this); playerListDock->setObjectName("playerListDock"); - playerListDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); + playerListDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); playerListDock->setWidget(playerListWidget); playerListDock->setFloating(false); @@ -1604,8 +1651,7 @@ void TabGame::createMessageDock(bool bReplay) connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - if(!bReplay) - { + if (!bReplay) { connect(messageLog, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); connect(messageLog, SIGNAL(addMentionTag(QString)), this, SLOT(addMentionTag(QString))); connect(settingsCache, SIGNAL(chatMentionCompleterChanged()), this, SLOT(actCompleterChanged())); @@ -1638,15 +1684,14 @@ void TabGame::createMessageDock(bool bReplay) sayHLayout = new QHBoxLayout; sayHLayout->addWidget(sayLabel); sayHLayout->addWidget(sayEdit); - } messageLogLayout = new QVBoxLayout; messageLogLayout->setContentsMargins(0, 0, 0, 0); - if(!bReplay) + if (!bReplay) messageLogLayout->addWidget(timeElapsedLabel); messageLogLayout->addWidget(messageLog); - if(!bReplay) + if (!bReplay) messageLogLayout->addLayout(sayHLayout); messageLogLayoutWidget = new QWidget; @@ -1654,7 +1699,8 @@ void TabGame::createMessageDock(bool bReplay) messageLayoutDock = new QDockWidget(this); messageLayoutDock->setObjectName("messageLayoutDock"); - messageLayoutDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); + messageLayoutDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | + QDockWidget::DockWidgetMovable); messageLayoutDock->setWidget(messageLogLayoutWidget); messageLayoutDock->setFloating(false); @@ -1663,29 +1709,26 @@ void TabGame::createMessageDock(bool bReplay) } // Method uses to sync docks state with menu items state -bool TabGame::eventFilter(QObject * o, QEvent * e) +bool TabGame::eventFilter(QObject *o, QEvent *e) { - if(e->type() == QEvent::Close) - { - if(o == cardInfoDock) - { + if (e->type() == QEvent::Close) { + if (o == cardInfoDock) { aCardInfoDockVisible->setChecked(false); aCardInfoDockFloating->setEnabled(false); - } else if(o == messageLayoutDock) { + } else if (o == messageLayoutDock) { aMessageLayoutDockVisible->setChecked(false); aMessageLayoutDockFloating->setEnabled(false); - } else if(o == playerListDock) { + } else if (o == playerListDock) { aPlayerListDockVisible->setChecked(false); aPlayerListDockFloating->setEnabled(false); - } else if(o == replayDock) { + } else if (o == replayDock) { aReplayDockVisible->setChecked(false); aReplayDockFloating->setEnabled(false); } } - if( o == this && e->type() == QEvent::Hide){ - if(replay) - { + if (o == this && e->type() == QEvent::Hide) { + if (replay) { settingsCache->layouts().setReplayPlayAreaState(saveState()); settingsCache->layouts().setReplayPlayAreaGeometry(saveGeometry()); settingsCache->layouts().setReplayCardInfoSize(cardInfoDock->size()); @@ -1706,29 +1749,25 @@ bool TabGame::eventFilter(QObject * o, QEvent * e) void TabGame::dockVisibleTriggered() { QObject *o = sender(); - if(o == aCardInfoDockVisible) - { + if (o == aCardInfoDockVisible) { cardInfoDock->setVisible(aCardInfoDockVisible->isChecked()); aCardInfoDockFloating->setEnabled(aCardInfoDockVisible->isChecked()); return; } - if(o == aMessageLayoutDockVisible) - { + if (o == aMessageLayoutDockVisible) { messageLayoutDock->setVisible(aMessageLayoutDockVisible->isChecked()); aMessageLayoutDockFloating->setEnabled(aMessageLayoutDockVisible->isChecked()); return; } - if(o == aPlayerListDockVisible) - { + if (o == aPlayerListDockVisible) { playerListDock->setVisible(aPlayerListDockVisible->isChecked()); aPlayerListDockFloating->setEnabled(aPlayerListDockVisible->isChecked()); return; } - if(o == aReplayDockVisible) - { + if (o == aReplayDockVisible) { replayDock->setVisible(aReplayDockVisible->isChecked()); aReplayDockFloating->setEnabled(aReplayDockVisible->isChecked()); return; @@ -1738,26 +1777,22 @@ void TabGame::dockVisibleTriggered() void TabGame::dockFloatingTriggered() { QObject *o = sender(); - if(o == aCardInfoDockFloating) - { + if (o == aCardInfoDockFloating) { cardInfoDock->setFloating(aCardInfoDockFloating->isChecked()); return; } - if(o == aMessageLayoutDockFloating) - { + if (o == aMessageLayoutDockFloating) { messageLayoutDock->setFloating(aMessageLayoutDockFloating->isChecked()); return; } - if(o == aPlayerListDockFloating) - { + if (o == aPlayerListDockFloating) { playerListDock->setFloating(aPlayerListDockFloating->isChecked()); return; } - if(o == aReplayDockFloating) - { + if (o == aReplayDockFloating) { replayDock->setFloating(aReplayDockFloating->isChecked()); return; } @@ -1768,26 +1803,22 @@ void TabGame::dockTopLevelChanged(bool topLevel) retranslateUi(); QObject *o = sender(); - if(o == cardInfoDock) - { + if (o == cardInfoDock) { aCardInfoDockFloating->setChecked(topLevel); return; } - if(o == messageLayoutDock) - { + if (o == messageLayoutDock) { aMessageLayoutDockFloating->setChecked(topLevel); return; } - if(o == playerListDock) - { + if (o == playerListDock) { aPlayerListDockFloating->setChecked(topLevel); return; } - if(o == replayDock) - { + if (o == replayDock) { aReplayDockFloating->setChecked(topLevel); return; } diff --git a/cockatrice/src/tab_game.h b/cockatrice/src/tab_game.h index ac4bcbc4..bcb26e80 100644 --- a/cockatrice/src/tab_game.h +++ b/cockatrice/src/tab_game.h @@ -1,12 +1,12 @@ #ifndef TAB_GAME_H #define TAB_GAME_H +#include "pb/event_leave.pb.h" +#include "pb/serverinfo_game.pb.h" +#include "tab.h" +#include #include #include -#include -#include "tab.h" -#include "pb/serverinfo_game.pb.h" -#include "pb/event_leave.pb.h" class AbstractClient; class CardDatabase; @@ -60,21 +60,28 @@ class LineEditCompleter; class QDockWidget; class QStackedWidget; -class ToggleButton : public QPushButton { +class ToggleButton : public QPushButton +{ Q_OBJECT private: bool state; signals: void stateChanged(); + public: ToggleButton(QWidget *parent = 0); - bool getState() const { return state; } + bool getState() const + { + return state; + } void setState(bool _state); + protected: void paintEvent(QPaintEvent *event); }; -class DeckViewContainer : public QWidget { +class DeckViewContainer : public QWidget +{ Q_OBJECT private: QPushButton *loadLocalButton, *loadRemoteButton; @@ -94,6 +101,7 @@ private slots: signals: void newCardAdded(AbstractCardItem *card); void notIdle(); + public: DeckViewContainer(int _playerId, TabGame *parent); void retranslateUi(); @@ -103,7 +111,8 @@ public: void setDeck(const DeckLoader &deck); }; -class TabGame : public Tab { +class TabGame : public Tab +{ Q_OBJECT private: QTimer *gameTimer; @@ -127,8 +136,8 @@ private: QStringList gameTypes; QCompleter *completer; QStringList autocompleteUserList; - QStackedWidget * mainWidget; - + QStackedWidget *mainWidget; + // Replay related members GameReplay *replay; int currentReplayStep; @@ -148,12 +157,16 @@ private: QMap deckViewContainers; QVBoxLayout *cardVInfoLayout, *messageLogLayout, *gamePlayAreaVBox, *deckViewContainerLayout; QHBoxLayout *cardHInfoLayout, *sayHLayout, *mainHLayout, *replayControlLayout; - QWidget *cardBoxLayoutWidget, *messageLogLayoutWidget, *gamePlayAreaWidget, *deckViewContainerWidget, *replayControlWidget; + QWidget *cardBoxLayoutWidget, *messageLogLayoutWidget, *gamePlayAreaWidget, *deckViewContainerWidget, + *replayControlWidget; QDockWidget *cardInfoDock, *messageLayoutDock, *playerListDock, *replayDock; QAction *playersSeparator; - QMenu *gameMenu, *phasesMenu, *viewMenu, *cardInfoDockMenu, *messageLayoutDockMenu, *playerListDockMenu, *replayDockMenu; - QAction *aGameInfo, *aConcede, *aLeaveGame, *aCloseReplay, *aNextPhase, *aNextTurn, *aRemoveLocalArrows, *aRotateViewCW, *aRotateViewCCW, *aResetLayout, *aResetReplayLayout; - QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aMessageLayoutDockVisible, *aMessageLayoutDockFloating, *aPlayerListDockVisible, *aPlayerListDockFloating, *aReplayDockVisible, *aReplayDockFloating; + QMenu *gameMenu, *phasesMenu, *viewMenu, *cardInfoDockMenu, *messageLayoutDockMenu, *playerListDockMenu, + *replayDockMenu; + QAction *aGameInfo, *aConcede, *aLeaveGame, *aCloseReplay, *aNextPhase, *aNextTurn, *aRemoveLocalArrows, + *aRotateViewCW, *aRotateViewCCW, *aResetLayout, *aResetReplayLayout; + QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aMessageLayoutDockVisible, *aMessageLayoutDockFloating, + *aPlayerListDockVisible, *aPlayerListDockFloating, *aReplayDockVisible, *aReplayDockFloating; QList phaseActions; Player *addPlayer(int playerId, const ServerInfo_User &info); @@ -164,9 +177,11 @@ private: 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 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); @@ -181,11 +196,11 @@ private: void createMenuItems(); void createReplayMenuItems(); void createViewMenuItems(); - void createCardInfoDock(bool bReplay=false); - void createPlayerListDock(bool bReplay=false); - void createMessageDock(bool bReplay=false); - void createPlayAreaWidget(bool bReplay=false); - void createDeckViewContainerWidget(bool bReplay=false); + void createCardInfoDock(bool bReplay = false); + void createPlayerListDock(bool bReplay = false); + void createMessageDock(bool bReplay = false); + void createPlayAreaWidget(bool bReplay = false); + void createDeckViewContainerWidget(bool bReplay = false); void createReplayDock(); QString getLeaveReason(Event_Leave::LeaveReason reason); signals: @@ -203,12 +218,12 @@ private slots: void replayStartButtonClicked(); void replayPauseButtonClicked(); void replayFastForwardButtonToggled(bool checked); - + void incrementGameTime(); void adminLockChanged(bool lock); void newCardAdded(AbstractCardItem *card); void updateCardMenu(AbstractCardItem *card); - + void actGameInfo(); void actConcede(); void actLeaveGame(); @@ -222,11 +237,11 @@ private slots: void addMentionTag(QString value); void commandFinished(const Response &response); - + void refreshShortcuts(); - + void loadLayout(); - void actCompleterChanged(); + void actCompleterChanged(); void actResetLayout(); void freeDocksSize(); @@ -234,31 +249,59 @@ private slots: void dockVisibleTriggered(); void dockFloatingTriggered(); void dockTopLevelChanged(bool topLevel); + public: - TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes); + TabGame(TabSupervisor *_tabSupervisor, + QList &_clients, + const Event_GameJoined &event, + const QMap &_roomGameTypes); TabGame(TabSupervisor *_tabSupervisor, GameReplay *replay); ~TabGame(); void retranslateUi(); void updatePlayerListDockTitle(); void closeRequest(); - const QMap &getPlayers() const { return players; } + const QMap &getPlayers() const + { + return players; + } CardItem *getCard(int playerId, const QString &zoneName, int cardId) const; - bool isHost() const { return hostId == localPlayerId; } - bool getIsLocalGame() const { return isLocalGame; } - int getGameId() const { return gameInfo.game_id(); } + bool isHost() const + { + return hostId == localPlayerId; + } + bool getIsLocalGame() const + { + return isLocalGame; + } + int getGameId() const + { + return gameInfo.game_id(); + } QString getTabText() const; - bool getSpectator() const { return spectator; } - bool getSpectatorsSeeEverything() const { return gameInfo.spectators_omniscient(); } + bool getSpectator() const + { + return spectator; + } + bool getSpectatorsSeeEverything() const + { + return gameInfo.spectators_omniscient(); + } bool isSpectator(); Player *getActiveLocalPlayer() const; AbstractClient *getClientForPlayer(int playerId) const; - void setActiveCard(CardItem *_card) { activeCard = _card; } - CardItem *getActiveCard() const { return activeCard; } + 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); + PendingCommand *prepareGameCommand(const QList &cmdList); public slots: void sendGameCommand(PendingCommand *pend, int playerId = -1); void sendGameCommand(const ::google::protobuf::Message &command, int playerId = -1); diff --git a/cockatrice/src/tab_logs.cpp b/cockatrice/src/tab_logs.cpp index 8add93a8..91d2ed17 100644 --- a/cockatrice/src/tab_logs.cpp +++ b/cockatrice/src/tab_logs.cpp @@ -1,20 +1,20 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "tab_logs.h" #include "abstractclient.h" -#include "window_sets.h" -#include "pending_command.h" #include "pb/moderator_commands.pb.h" #include "pb/response_viewlog_history.pb.h" +#include "pending_command.h" +#include "window_sets.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -25,17 +25,20 @@ TabLog::TabLog(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget * roomTable = new QTableWidget(); roomTable->setColumnCount(6); roomTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - roomTable->setHorizontalHeaderLabels(QString(tr("Time;SenderName;SenderIP;Message;TargetID;TargetName")).split(";")); + roomTable->setHorizontalHeaderLabels( + QString(tr("Time;SenderName;SenderIP;Message;TargetID;TargetName")).split(";")); gameTable = new QTableWidget(); gameTable->setColumnCount(6); gameTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - gameTable->setHorizontalHeaderLabels(QString(tr("Time;SenderName;SenderIP;Message;TargetID;TargetName")).split(";")); + gameTable->setHorizontalHeaderLabels( + QString(tr("Time;SenderName;SenderIP;Message;TargetID;TargetName")).split(";")); chatTable = new QTableWidget(); chatTable->setColumnCount(6); chatTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - chatTable->setHorizontalHeaderLabels(QString(tr("Time;SenderName;SenderIP;Message;TargetID;TargetName")).split(";")); + chatTable->setHorizontalHeaderLabels( + QString(tr("Time;SenderName;SenderIP;Message;TargetID;TargetName")).split(";")); QTabWidget *tabManager = new QTabWidget(); tabManager->addTab(roomTable, tr("Room Logs")); @@ -51,22 +54,21 @@ TabLog::TabLog(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget * TabLog::~TabLog() { - } void TabLog::retranslateUi() { - } void TabLog::getClicked() { - if (findUsername->text().isEmpty() && findIPAddress->text().isEmpty() && findGameName->text().isEmpty() && findGameID->text().isEmpty() && findMessage->text().isEmpty()) { + if (findUsername->text().isEmpty() && findIPAddress->text().isEmpty() && findGameName->text().isEmpty() && + findGameID->text().isEmpty() && findMessage->text().isEmpty()) { QMessageBox::critical(this, tr("Error"), tr("You must select at least one filter.")); return; } - if (!lastHour->isChecked() && !today->isChecked() && !pastDays->isChecked()){ + if (!lastHour->isChecked() && !today->isChecked() && !pastDays->isChecked()) { pastDays->setChecked(true); pastXDays->setValue(20); } @@ -101,13 +103,20 @@ void TabLog::getClicked() cmd.set_game_name(findGameName->text().toStdString()); cmd.set_game_id(findGameID->text().toStdString()); cmd.set_message(findMessage->text().toStdString()); - if (mainRoom->isChecked()) { cmd.add_log_location("room"); }; - if (gameRoom->isChecked()) { cmd.add_log_location("game"); }; - if (privateChat->isChecked()) { cmd.add_log_location("chat"); }; + if (mainRoom->isChecked()) { + cmd.add_log_location("room"); + }; + if (gameRoom->isChecked()) { + cmd.add_log_location("game"); + }; + if (privateChat->isChecked()) { + cmd.add_log_location("chat"); + }; cmd.set_date_range(dateRange); cmd.set_maximum_results(maximumResults->value()); PendingCommand *pend = client->prepareModeratorCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(viewLogHistory_processResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(viewLogHistory_processResponse(Response))); client->sendCommand(pend); } @@ -163,12 +172,12 @@ void TabLog::createDock() pastXDays = new QSpinBox; pastXDays->setMaximum(20); - labelMaximum = new QLabel(tr("Maximum Results: ")); maximumResults = new QSpinBox; maximumResults->setMaximum(1000); - labelDescription = new QLabel(tr("At least one filter is required.\nThe more information you put in, the more specific your results will be.")); + labelDescription = new QLabel(tr( + "At least one filter is required.\nThe more information you put in, the more specific your results will be.")); getButton = new QPushButton(tr("Get User Logs")); getButton->setAutoDefault(true); @@ -192,7 +201,7 @@ void TabLog::createDock() criteriaGroupBox = new QGroupBox(tr("Filters")); criteriaGroupBox->setLayout(criteriaGrid); - criteriaGroupBox->setFixedSize(500,300); + criteriaGroupBox->setFixedSize(500, 300); locationGrid = new QGridLayout; locationGrid->addWidget(mainRoom, 0, 0); @@ -244,7 +253,7 @@ void TabLog::createDock() searchDockContents->setLayout(mainLayout); searchDock = new QDockWidget(this); - searchDock->setFeatures(QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable); + searchDock->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); searchDock->setWidget(searchDockContents); } @@ -252,12 +261,14 @@ void TabLog::viewLogHistory_processResponse(const Response &resp) { const Response_ViewLogHistory &response = resp.GetExtension(Response_ViewLogHistory::ext); if (resp.response_code() != Response::RespOk) { - QMessageBox::critical(static_cast(parent()), tr("Message History"), tr("Failed to collect message history information.")); + QMessageBox::critical(static_cast(parent()), tr("Message History"), + tr("Failed to collect message history information.")); return; } if (response.log_message_size() == 0) { - QMessageBox::information(static_cast(parent()), tr("Message History"), tr("There are no messages for the selected filters.")); + QMessageBox::information(static_cast(parent()), tr("Message History"), + tr("There are no messages for the selected filters.")); return; } @@ -266,8 +277,7 @@ void TabLog::viewLogHistory_processResponse(const Response &resp) gameTable->setRowCount(gameCounter); chatTable->setRowCount(chatCounter); - for (int i = 0; i < response.log_message_size(); ++i) - { + for (int i = 0; i < response.log_message_size(); ++i) { ServerInfo_ChatMessage message = response.log_message(i); if (QString::fromStdString(message.target_type()) == "room") { roomTable->insertRow(roomCounter); diff --git a/cockatrice/src/tab_logs.h b/cockatrice/src/tab_logs.h index c6b0cfdb..33063821 100644 --- a/cockatrice/src/tab_logs.h +++ b/cockatrice/src/tab_logs.h @@ -16,16 +16,19 @@ class QLabel; class QDockWidget; class QWidget; class QGridLayout; +class QVBoxLayout; class QTableWidget; class CommandContainer; class Response; class AbstractClient; -class TabLog : public Tab { +class TabLog : public Tab +{ Q_OBJECT private: AbstractClient *client; - QLabel *labelFindUserName, *labelFindIPAddress, *labelFindGameName, *labelFindGameID, *labelMessage, *labelMaximum, *labelDescription; + QLabel *labelFindUserName, *labelFindIPAddress, *labelFindGameName, *labelFindGameID, *labelMessage, *labelMaximum, + *labelDescription; QLineEdit *findUsername, *findIPAddress, *findGameName, *findGameID, *findMessage; QCheckBox *mainRoom, *gameRoom, *privateChat; QRadioButton *pastDays, *today, *lastHour; @@ -34,7 +37,8 @@ private: QWidget *searchDockContents; QPushButton *getButton, *clearButton; QGridLayout *criteriaGrid, *locationGrid, *rangeGrid, *maxResultsGrid, *descriptionGrid, *buttonGrid; - QGroupBox *criteriaGroupBox, *locationGroupBox, *rangeGroupBox, *maxResultsGroupBox, *descriptionGroupBox, *buttonGroupBox; + QGroupBox *criteriaGroupBox, *locationGroupBox, *rangeGroupBox, *maxResultsGroupBox, *descriptionGroupBox, + *buttonGroupBox; QVBoxLayout *mainLayout; QTableWidget *roomTable, *gameTable, *chatTable; @@ -51,7 +55,10 @@ public: TabLog(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent = 0); ~TabLog(); void retranslateUi(); - QString getTabText() const { return tr("Logs"); } + QString getTabText() const + { + return tr("Logs"); + } }; #endif diff --git a/cockatrice/src/tab_message.cpp b/cockatrice/src/tab_message.cpp index c6265c91..e65efd6b 100644 --- a/cockatrice/src/tab_message.cpp +++ b/cockatrice/src/tab_message.cpp @@ -1,23 +1,27 @@ -#include -#include -#include -#include -#include -#include #include "tab_message.h" #include "abstractclient.h" #include "chatview/chatview.h" #include "main.h" #include "settingscache.h" #include "soundengine.h" +#include +#include +#include +#include +#include +#include -#include "pending_command.h" -#include "pb/session_commands.pb.h" #include "pb/event_user_message.pb.h" #include "pb/serverinfo_user.pb.h" +#include "pb/session_commands.pb.h" +#include "pending_command.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) +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) { chatView = new ChatView(tabSupervisor, tabSupervisor, 0, true); connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); @@ -25,11 +29,11 @@ TabMessage::TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, c connect(chatView, SIGNAL(addMentionTag(QString)), this, SLOT(addMentionTag(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())); @@ -39,7 +43,7 @@ TabMessage::TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, c retranslateUi(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(vbox); setCentralWidget(mainWidget); } @@ -51,7 +55,8 @@ TabMessage::~TabMessage() delete otherUserInfo; } -void TabMessage::addMentionTag(QString mentionTag) { +void TabMessage::addMentionTag(QString mentionTag) +{ sayEdit->insert(mentionTag + " "); sayEdit->setFocus(); } @@ -64,7 +69,7 @@ void TabMessage::retranslateUi() void TabMessage::tabActivated() { - if(!sayEdit->hasFocus()) + if (!sayEdit->hasFocus()) sayEdit->setFocus(); } @@ -86,23 +91,24 @@ void TabMessage::closeRequest() void TabMessage::sendMessage() { if (sayEdit->text().isEmpty() || !userOnline) - return; - + 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, they cannot see your messages in main chat and you cannot join their games.")); + chatView->appendMessage(tr( + "This user is ignoring you, they cannot see your messages in main chat and you cannot join their games.")); } void TabMessage::actLeave() @@ -116,7 +122,8 @@ void TabMessage::processUserMessageEvent(const Event_UserMessage &event) const UserLevelFlags userLevel(userInfo->user_level()); const QString userPriv = QString::fromStdString(userInfo->privlevel()); - chatView->appendMessage(QString::fromStdString(event.message()), 0,QString::fromStdString(event.sender_name()), userLevel, userPriv, true); + chatView->appendMessage(QString::fromStdString(event.message()), 0, QString::fromStdString(event.sender_name()), + userLevel, userPriv, true); if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this)) soundEngine->playSound("private_message"); if (settingsCache->getShowMessagePopup() && shouldShowSystemPopup(event)) @@ -127,24 +134,27 @@ void TabMessage::processUserMessageEvent(const Event_UserMessage &event) emit userEvent(); } -bool TabMessage::shouldShowSystemPopup(const Event_UserMessage &event) { +bool TabMessage::shouldShowSystemPopup(const Event_UserMessage &event) +{ return (QApplication::activeWindow() == 0 || QApplication::focusWidget() == 0 || - (event.sender_name() == otherUserInfo->name() && tabSupervisor->currentIndex() != tabSupervisor->indexOf(this))); + (event.sender_name() == otherUserInfo->name() && + tabSupervisor->currentIndex() != tabSupervisor->indexOf(this))); } -void TabMessage::showSystemPopup(const Event_UserMessage &event) { +void TabMessage::showSystemPopup(const Event_UserMessage &event) +{ if (trayIcon) { disconnect(trayIcon, SIGNAL(messageClicked()), 0, 0); - trayIcon->showMessage(tr("Private message from") + " " + otherUserInfo->name().c_str(), event.message().c_str()); + trayIcon->showMessage(tr("Private message from") + " " + otherUserInfo->name().c_str(), + event.message().c_str()); connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked())); - } - else - { + } else { qDebug() << "Error: trayIcon is NULL. TabMessage::showSystemPopup failed"; } } -void TabMessage::messageClicked() { +void TabMessage::messageClicked() +{ tabSupervisor->setCurrentIndex(tabSupervisor->indexOf(this)); QApplication::setActiveWindow(this); emit maximizeClient(); diff --git a/cockatrice/src/tab_message.h b/cockatrice/src/tab_message.h index ac468880..4892c229 100644 --- a/cockatrice/src/tab_message.h +++ b/cockatrice/src/tab_message.h @@ -10,7 +10,8 @@ class Event_UserMessage; class Response; class ServerInfo_User; -class TabMessage : public Tab { +class TabMessage : public Tab +{ Q_OBJECT private: AbstractClient *client; @@ -18,7 +19,7 @@ private: ServerInfo_User *ownUserInfo; ServerInfo_User *otherUserInfo; bool userOnline; - + ChatView *chatView; QLineEdit *sayEdit; @@ -32,8 +33,12 @@ private slots: void messageSent(const Response &response); void addMentionTag(QString mentionTag); void messageClicked(); + public: - TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo); + TabMessage(TabSupervisor *_tabSupervisor, + AbstractClient *_client, + const ServerInfo_User &_ownUserInfo, + const ServerInfo_User &_otherUserInfo); ~TabMessage(); void retranslateUi(); void closeRequest(); @@ -45,6 +50,7 @@ public: void processUserLeft(); void processUserJoined(const ServerInfo_User &_userInfo); + private: bool shouldShowSystemPopup(const Event_UserMessage &event); void showSystemPopup(const Event_UserMessage &event); diff --git a/cockatrice/src/tab_replays.cpp b/cockatrice/src/tab_replays.cpp index 710483c3..557177a0 100644 --- a/cockatrice/src/tab_replays.cpp +++ b/cockatrice/src/tab_replays.cpp @@ -1,36 +1,35 @@ -#include -#include -#include -#include -#include +#include "tab_replays.h" +#include "abstractclient.h" +#include "remotereplaylist_treewidget.h" +#include "settingscache.h" +#include "tab_game.h" #include -#include -#include #include +#include +#include +#include +#include #include #include -#include "tab_replays.h" -#include "remotereplaylist_treewidget.h" -#include "abstractclient.h" -#include "tab_game.h" -#include "settingscache.h" +#include +#include +#include -#include "pending_command.h" +#include "pb/command_replay_delete_match.pb.h" +#include "pb/command_replay_download.pb.h" +#include "pb/command_replay_modify_match.pb.h" +#include "pb/event_replay_added.pb.h" #include "pb/game_replay.pb.h" #include "pb/response.pb.h" #include "pb/response_replay_download.pb.h" -#include "pb/command_replay_download.pb.h" -#include "pb/command_replay_modify_match.pb.h" -#include "pb/command_replay_delete_match.pb.h" -#include "pb/event_replay_added.pb.h" +#include "pending_command.h" -TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) - : Tab(_tabSupervisor), client(_client) +TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_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); @@ -38,7 +37,7 @@ TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) localDirView->setSortingEnabled(true); localDirView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); - + leftToolBar = new QToolBar; leftToolBar->setOrientation(Qt::Horizontal); leftToolBar->setIconSize(QSize(32, 32)); @@ -52,7 +51,7 @@ TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) leftVbox->addLayout(leftToolBarLayout); leftGroupBox = new QGroupBox; leftGroupBox->setLayout(leftVbox); - + rightToolBar = new QToolBar; rightToolBar->setOrientation(Qt::Horizontal); rightToolBar->setIconSize(QSize(32, 32)); @@ -68,11 +67,11 @@ TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) 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(QPixmap("theme:icons/view")); connect(aOpenLocalReplay, SIGNAL(triggered()), this, SLOT(actOpenLocalReplay())); @@ -93,28 +92,29 @@ TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) aDeleteRemoteReplay = new QAction(this); aDeleteRemoteReplay->setIcon(QPixmap("theme:icons/remove_row")); 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(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(hbox); setCentralWidget(mainWidget); - - connect(client, SIGNAL(replayAddedEventReceived(const Event_ReplayAdded &)), this, SLOT(replayAddedEventReceived(const Event_ReplayAdded &))); + + 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")); @@ -129,25 +129,27 @@ void TabReplays::actOpenLocalReplay() 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) + 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); } @@ -156,12 +158,13 @@ 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 &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(openRemoteReplayFinished(const Response &))); client->sendCommand(pend); } @@ -169,11 +172,11 @@ 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); } @@ -191,35 +194,38 @@ void TabReplays::actDownload() ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); - if (!curRight) - { - QMessageBox::information(this, tr("Downloading Replays"), tr("You cannot download replay folders at this time")); + if (!curRight) { + QMessageBox::information(this, tr("Downloading Replays"), + tr("You cannot download replay folders at this time")); 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))); + 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) +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.write((const char *)data.data(), data.size()); f.close(); } @@ -228,13 +234,14 @@ 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))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(keepRemoteReplayFinished(Response, CommandContainer))); client->sendCommand(pend); } @@ -242,12 +249,13 @@ void TabReplays::keepRemoteReplayFinished(const Response &r, const CommandContai { if (r.response_code() != Response::RespOk) return; - - const Command_ReplayModifyMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext); - + + 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); } @@ -256,14 +264,17 @@ 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) + 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))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(deleteRemoteReplayFinished(Response, CommandContainer))); client->sendCommand(pend); } @@ -271,8 +282,9 @@ void TabReplays::deleteRemoteReplayFinished(const Response &r, const CommandCont { if (r.response_code() != Response::RespOk) return; - - const Command_ReplayDeleteMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext); + + const Command_ReplayDeleteMatch &cmd = + commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext); serverDirView->removeMatchInfo(cmd.game_id()); } diff --git a/cockatrice/src/tab_replays.h b/cockatrice/src/tab_replays.h index 99f1c6f4..4641e69e 100644 --- a/cockatrice/src/tab_replays.h +++ b/cockatrice/src/tab_replays.h @@ -14,7 +14,8 @@ class GameReplay; class Event_ReplayAdded; class CommandContainer; -class TabReplays : public Tab { +class TabReplays : public Tab +{ Q_OBJECT private: AbstractClient *client; @@ -23,32 +24,36 @@ private: 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); signals: void openReplay(GameReplay *replay); + public: TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client); void retranslateUi(); - QString getTabText() const { return tr("Game replays"); } + QString getTabText() const + { + return tr("Game replays"); + } }; #endif diff --git a/cockatrice/src/tab_room.cpp b/cockatrice/src/tab_room.cpp index 781f4bbe..c1112c7c 100644 --- a/cockatrice/src/tab_room.cpp +++ b/cockatrice/src/tab_room.cpp @@ -1,50 +1,55 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "tab_supervisor.h" #include "tab_room.h" -#include "tab_userlists.h" -#include "userlist.h" #include "abstractclient.h" #include "chatview/chatview.h" +#include "dlg_settings.h" #include "gameselector.h" -#include "settingscache.h" -#include "main.h" #include "get_pb_extension.h" -#include "pb/room_commands.pb.h" -#include "pb/serverinfo_room.pb.h" -#include "pb/event_list_games.pb.h" +#include "main.h" #include "pb/event_join_room.pb.h" #include "pb/event_leave_room.pb.h" +#include "pb/event_list_games.pb.h" #include "pb/event_room_say.pb.h" +#include "pb/room_commands.pb.h" +#include "pb/serverinfo_room.pb.h" #include "pending_command.h" -#include "dlg_settings.h" +#include "settingscache.h" +#include "tab_supervisor.h" +#include "tab_userlists.h" +#include "userlist.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include - -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) +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) { 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())); + 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, true, true); userList = new UserList(tabSupervisor, client, UserList::RoomList); - connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, + SIGNAL(openMessageDialog(const QString &, bool))); chatView = new ChatView(tabSupervisor, tabSupervisor, 0, true); - connect(chatView, SIGNAL(showMentionPopup(QString&)), this, SLOT(actShowMentionPopup(QString&))); + connect(chatView, SIGNAL(showMentionPopup(QString &)), this, SLOT(actShowMentionPopup(QString &))); connect(chatView, SIGNAL(messageClickedSignal()), this, SLOT(focusTab())); connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); @@ -99,7 +104,7 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerI addTabMenu(roomMenu); const int userListSize = info.user_list_size(); - for (int i = 0; i < userListSize; ++i){ + for (int i = 0; i < userListSize; ++i) { userList->processUserInfo(info.user_list(i), true); autocompleteUserList.append("@" + QString::fromStdString(info.user_list(i).name())); } @@ -116,12 +121,12 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerI sayEdit->setCompleter(completer); actCompleterChanged(); - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); retranslateUi(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(hbox); setCentralWidget(mainWidget); } @@ -144,18 +149,17 @@ void TabRoom::retranslateUi() aOpenChatSettings->setText(tr("Chat Settings...")); } -void TabRoom::focusTab() { +void TabRoom::focusTab() +{ QApplication::setActiveWindow(this); tabSupervisor->setCurrentIndex(tabSupervisor->indexOf(this)); emit maximizeClient(); } -void TabRoom::actShowMentionPopup(QString &sender) { - if (trayIcon - && (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this) - || QApplication::activeWindow() == 0 - || QApplication::focusWidget() == 0) - ) { +void TabRoom::actShowMentionPopup(QString &sender) +{ + if (trayIcon && (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this) || + QApplication::activeWindow() == 0 || QApplication::focusWidget() == 0)) { disconnect(trayIcon, SIGNAL(messageClicked()), 0, 0); trayIcon->showMessage(sender + tr(" mentioned you."), tr("Click to view")); connect(trayIcon, SIGNAL(messageClicked()), chatView, SLOT(actMessageClicked())); @@ -169,16 +173,13 @@ void TabRoom::closeRequest() void TabRoom::tabActivated() { - if(!sayEdit->hasFocus()) + if (!sayEdit->hasFocus()) sayEdit->setFocus(); } QString TabRoom::sanitizeHtml(QString dirty) const { - return dirty - .replace("&", "&") - .replace("<", "<") - .replace(">", ">"); + return dirty.replace("&", "&").replace("<", "<").replace(">", ">"); } void TabRoom::sendMessage() @@ -193,7 +194,8 @@ void TabRoom::sendMessage() cmd.set_message(sayEdit->text().toStdString()); PendingCommand *pend = prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(sayFinished(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(sayFinished(const Response &))); sendRoomCommand(pend); sayEdit->clear(); } @@ -211,11 +213,13 @@ void TabRoom::actLeaveRoom() deleteLater(); } -void TabRoom::actClearChat() { +void TabRoom::actClearChat() +{ chatView->clearChat(); } -void TabRoom::actOpenChatSettings() { +void TabRoom::actOpenChatSettings() +{ DlgSettings settings(this); settings.setTab(4); settings.exec(); @@ -229,11 +233,19 @@ void TabRoom::actCompleterChanged() 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: ; + 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:; } } @@ -248,10 +260,10 @@ void TabRoom::processJoinRoomEvent(const Event_JoinRoom &event) { userList->processUserInfo(event.user_info(), true); userList->sortItems(); - if (!autocompleteUserList.contains("@" + QString::fromStdString(event.user_info().name()))){ + if (!autocompleteUserList.contains("@" + QString::fromStdString(event.user_info().name()))) { autocompleteUserList << "@" + QString::fromStdString(event.user_info().name()); sayEdit->setCompletionList(autocompleteUserList); - } + } } void TabRoom::processLeaveRoomEvent(const Event_LeaveRoom &event) @@ -283,8 +295,10 @@ void TabRoom::processRoomSayEvent(const Event_RoomSay &event) return; if (event.message_type() == Event_RoomSay::ChatHistory) - message = "[" + QString(QDateTime::fromMSecsSinceEpoch(event.time_of()).toLocalTime().toString("d MMM yyyy HH:mm:ss")) + "] " + message; - + message = + "[" + + QString(QDateTime::fromMSecsSinceEpoch(event.time_of()).toLocalTime().toString("d MMM yyyy HH:mm:ss")) + + "] " + message; chatView->appendMessage(message, event.message_type(), senderName, userLevel, userPrivLevel, true); emit userEvent(false); @@ -295,7 +309,8 @@ void TabRoom::refreshShortcuts() aClearChat->setShortcuts(settingsCache->shortcuts().getShortcut("tab_room/aClearChat")); } -void TabRoom::addMentionTag(QString mentionTag) { +void TabRoom::addMentionTag(QString mentionTag) +{ sayEdit->insert(mentionTag + " "); sayEdit->setFocus(); } diff --git a/cockatrice/src/tab_room.h b/cockatrice/src/tab_room.h index 75aacc6d..75fc03b4 100644 --- a/cockatrice/src/tab_room.h +++ b/cockatrice/src/tab_room.h @@ -1,15 +1,21 @@ #ifndef TAB_ROOM_H #define TAB_ROOM_H -#include "tab.h" #include "lineeditcompleter.h" -#include -#include -#include -#include +#include "tab.h" #include +#include +#include +#include +#include -namespace google { namespace protobuf { class Message; } } +namespace google +{ +namespace protobuf +{ +class Message; +} +} // namespace google class AbstractClient; class UserList; class QLabel; @@ -31,7 +37,8 @@ class PendingCommand; class ServerInfo_User; class LineEditCompleter; -class TabRoom : public Tab { +class TabRoom : public Tab +{ Q_OBJECT private: AbstractClient *client; @@ -39,14 +46,14 @@ private: QString roomName; ServerInfo_User *ownUser; QMap gameTypes; - + GameSelector *gameSelector; UserList *userList; ChatView *chatView; QLabel *sayLabel; LineEditCompleter *sayEdit; QGroupBox *chatGroupBox; - + QMenu *roomMenu; QAction *aLeaveRoom; QAction *aOpenChatSettings; @@ -76,18 +83,37 @@ private slots: void processLeaveRoomEvent(const Event_LeaveRoom &event); void processRoomSayEvent(const Event_RoomSay &event); void refreshShortcuts(); + public: - TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info); + TabRoom(TabSupervisor *_tabSupervisor, + AbstractClient *_client, + ServerInfo_User *_ownUser, + const ServerInfo_Room &info); ~TabRoom(); void retranslateUi(); void closeRequest(); void tabActivated(); 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; } + 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); diff --git a/cockatrice/src/tab_server.cpp b/cockatrice/src/tab_server.cpp index a85fe1c0..f92fd596 100644 --- a/cockatrice/src/tab_server.cpp +++ b/cockatrice/src/tab_server.cpp @@ -1,28 +1,27 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "tab_server.h" #include "abstractclient.h" -#include "userlist.h" #include "tab_supervisor.h" +#include "userlist.h" +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include "pending_command.h" -#include "pb/session_commands.pb.h" #include "pb/event_list_rooms.pb.h" #include "pb/event_server_message.pb.h" #include "pb/response_join_room.pb.h" +#include "pb/session_commands.pb.h" +#include "pending_command.h" -RoomSelector::RoomSelector(AbstractClient *_client, QWidget *parent) - : QGroupBox(parent), client(_client) +RoomSelector::RoomSelector(AbstractClient *_client, QWidget *parent) : QGroupBox(parent), client(_client) { roomList = new QTreeWidget; roomList->setRootIsDecorated(false); @@ -41,11 +40,12 @@ RoomSelector::RoomSelector(AbstractClient *_client, QWidget *parent) 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 &))); + + connect(client, SIGNAL(listRoomsEventReceived(const Event_ListRooms &)), this, + SLOT(processListRoomsEvent(const Event_ListRooms &))); connect(roomList, SIGNAL(activated(const QModelIndex &)), this, SLOT(joinClicked())); client->sendCommand(client->prepareSessionCommand(Command_ListRooms())); } @@ -73,7 +73,7 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event) const ServerInfo_Room &room = event.room_list(i); for (int j = 0; j < roomList->topLevelItemCount(); ++j) { - QTreeWidgetItem *twi = roomList->topLevelItem(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())); @@ -101,7 +101,7 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event) twi->setTextAlignment(2, Qt::AlignRight); twi->setTextAlignment(3, Qt::AlignRight); twi->setTextAlignment(4, Qt::AlignRight); - + roomList->addTopLevelItem(twi); if (room.has_auto_join()) if (room.auto_join()) @@ -109,19 +109,19 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event) } } -QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room & room) +QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room &room) { /* - * A room can have a permission level and a privilege level. How ever we want to display only the necessary information - * on the server tab needed to inform users of required permissions to enter a room. If the room has a privilege level - * the server tab will display the privilege level in the "permissions" column in the row however if the room contains - * a permissions level for the room the permissions level defined for the room will be displayed. - */ + * A room can have a permission level and a privilege level. How ever we want to display only the necessary + * information on the server tab needed to inform users of required permissions to enter a room. If the room has a + * privilege level the server tab will display the privilege level in the "permissions" column in the row however if + * the room contains a permissions level for the room the permissions level defined for the room will be displayed. + */ QString roomPermissionDisplay = QString::fromStdString(room.privilegelevel()).toLower(); if (QString::fromStdString(room.permissionlevel()).toLower() != "none") roomPermissionDisplay = QString::fromStdString(room.permissionlevel()).toLower(); - if (roomPermissionDisplay == "") // catch all for misconfigured .ini room definitions + if (roomPermissionDisplay == "") // catch all for misconfigured .ini room definitions roomPermissionDisplay = "none"; return roomPermissionDisplay; @@ -132,7 +132,7 @@ void RoomSelector::joinClicked() QTreeWidgetItem *twi = roomList->currentItem(); if (!twi) return; - + int id = twi->data(0, Qt::UserRole).toInt(); emit joinRoomRequest(id, true); @@ -144,18 +144,19 @@ TabServer::TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWi roomSelector = new RoomSelector(client); serverInfoBox = new QTextBrowser; serverInfoBox->setOpenExternalLinks(true); - + connect(roomSelector, SIGNAL(joinRoomRequest(int, bool)), this, SLOT(joinRoom(int, bool))); - - connect(client, SIGNAL(serverMessageEventReceived(const Event_ServerMessage &)), this, SLOT(processServerMessageEvent(const Event_ServerMessage &))); - + + connect(client, SIGNAL(serverMessageEventReceived(const Event_ServerMessage &)), this, + SLOT(processServerMessageEvent(const Event_ServerMessage &))); + QVBoxLayout *vbox = new QVBoxLayout; vbox->addWidget(roomSelector); vbox->addWidget(serverInfoBox); - + retranslateUi(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(vbox); setCentralWidget(mainWidget); } @@ -179,25 +180,27 @@ void TabServer::processServerMessageEvent(const Event_ServerMessage &event) void TabServer::joinRoom(int id, bool setCurrent) { TabRoom *room = tabSupervisor->getRoomTabs().value(id); - if(!room) - { + if (!room) { 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(joinRoomFinished(Response, CommandContainer, QVariant))); - + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(joinRoomFinished(Response, CommandContainer, QVariant))); + client->sendCommand(pend); - return; + return; } - if(setCurrent) - tabSupervisor->setCurrentWidget((QWidget*)room); + if (setCurrent) + tabSupervisor->setCurrentWidget((QWidget *)room); } -void TabServer::joinRoomFinished(const Response &r, const CommandContainer & /*commandContainer*/, const QVariant &extraData) +void TabServer::joinRoomFinished(const Response &r, + const CommandContainer & /*commandContainer*/, + const QVariant &extraData) { switch (r.response_code()) { case Response::RespOk: @@ -206,13 +209,16 @@ void TabServer::joinRoomFinished(const Response &r, const CommandContainer & /*c QMessageBox::critical(this, tr("Error"), tr("Failed to join the room: it doesn't exists on the server.")); return; case Response::RespContextError: - QMessageBox::critical(this, tr("Error"), tr("The server thinks you are in the room but Cockatrice is unable to display it. Try restarting Cockatrice.")); + QMessageBox::critical(this, tr("Error"), + tr("The server thinks you are in the room but Cockatrice is unable to display it. " + "Try restarting Cockatrice.")); return; case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("You do not have the required permission to join this room.")); return; default: - QMessageBox::critical(this, tr("Error"), tr("Failed to join the room due to an unknown error: %1.").arg(r.response_code())); + QMessageBox::critical(this, tr("Error"), + tr("Failed to join the room due to an unknown error: %1.").arg(r.response_code())); return; } diff --git a/cockatrice/src/tab_server.h b/cockatrice/src/tab_server.h index e52d715c..e7cbdf6c 100644 --- a/cockatrice/src/tab_server.h +++ b/cockatrice/src/tab_server.h @@ -1,10 +1,10 @@ #ifndef TAB_SERVER_H #define TAB_SERVER_H -#include -#include -#include #include "tab.h" +#include +#include +#include class AbstractClient; class QTextEdit; @@ -18,7 +18,8 @@ class Response; class ServerInfo_Room; class CommandContainer; -class RoomSelector : public QGroupBox { +class RoomSelector : public QGroupBox +{ Q_OBJECT private: QTreeWidget *roomList; @@ -30,12 +31,14 @@ private slots: void joinClicked(); signals: void joinRoomRequest(int, bool setCurrent); + public: RoomSelector(AbstractClient *_client, QWidget *parent = 0); void retranslateUi(); }; -class TabServer : public Tab { +class TabServer : public Tab +{ Q_OBJECT signals: void roomJoined(const ServerInfo_Room &info, bool setCurrent); @@ -43,15 +46,20 @@ private slots: void processServerMessageEvent(const Event_ServerMessage &event); void joinRoom(int id, bool setCurrent); void joinRoomFinished(const Response &resp, const CommandContainer &commandContainer, const QVariant &extraData); + private: AbstractClient *client; RoomSelector *roomSelector; QTextBrowser *serverInfoBox; bool shouldEmitUpdate = false; + public: TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent = 0); void retranslateUi(); - QString getTabText() const { return tr("Server"); } + QString getTabText() const + { + return tr("Server"); + } }; #endif diff --git a/cockatrice/src/tab_supervisor.cpp b/cockatrice/src/tab_supervisor.cpp index 4a64bd89..e44c7b18 100644 --- a/cockatrice/src/tab_supervisor.cpp +++ b/cockatrice/src/tab_supervisor.cpp @@ -1,35 +1,34 @@ -#include -#include -#include -#include #include "tab_supervisor.h" #include "abstractclient.h" -#include "tab_server.h" -#include "tab_room.h" -#include "tab_game.h" -#include "tab_deck_storage.h" -#include "tab_replays.h" -#include "tab_admin.h" -#include "tab_message.h" -#include "tab_userlists.h" -#include "tab_deck_editor.h" -#include "tab_logs.h" #include "pixmapgenerator.h" -#include "userlist.h" #include "settingscache.h" +#include "tab_admin.h" +#include "tab_deck_editor.h" +#include "tab_deck_storage.h" +#include "tab_game.h" +#include "tab_logs.h" +#include "tab_message.h" +#include "tab_replays.h" +#include "tab_room.h" +#include "tab_server.h" +#include "tab_userlists.h" +#include "userlist.h" +#include +#include +#include +#include +#include "pb/event_game_joined.pb.h" +#include "pb/event_notify_user.pb.h" +#include "pb/event_user_message.pb.h" +#include "pb/game_event_container.pb.h" +#include "pb/moderator_commands.pb.h" #include "pb/room_commands.pb.h" #include "pb/room_event.pb.h" -#include "pb/game_event_container.pb.h" -#include "pb/event_user_message.pb.h" -#include "pb/event_notify_user.pb.h" -#include "pb/event_game_joined.pb.h" -#include "pb/serverinfo_user.pb.h" #include "pb/serverinfo_room.pb.h" -#include "pb/moderator_commands.pb.h" +#include "pb/serverinfo_user.pb.h" -CloseButton::CloseButton(QWidget *parent) - : QAbstractButton(parent) +CloseButton::CloseButton(QWidget *parent) : QAbstractButton(parent) { setFocusPolicy(Qt::NoFocus); setCursor(Qt::ArrowCursor); @@ -68,19 +67,21 @@ void CloseButton::paintEvent(QPaintEvent * /*event*/) 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); + 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), tabServer(0), tabUserLists(0), tabDeckStorage(0), tabReplays(0), tabAdmin(0), tabLog(0) + : QTabWidget(parent), userInfo(0), client(_client), tabServer(0), tabUserLists(0), tabDeckStorage(0), tabReplays(0), + tabAdmin(0), tabLog(0) { setElideMode(Qt::ElideRight); setMovable(true); @@ -88,12 +89,16 @@ TabSupervisor::TabSupervisor(AbstractClient *_client, QWidget *parent) 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(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))); - connect(client, SIGNAL(notifyUserEventReceived(const Event_NotifyUser &)), this, SLOT(processNotifyUserEvent(const Event_NotifyUser &))); - + connect(client, SIGNAL(notifyUserEventReceived(const Event_NotifyUser &)), this, + SLOT(processNotifyUserEvent(const Event_NotifyUser &))); + retranslateUi(); } @@ -126,7 +131,7 @@ void TabSupervisor::retranslateUi() QMapIterator messageIterator(messageTabs); while (messageIterator.hasNext()) tabs.append(messageIterator.next().value()); - + for (int i = 0; i < tabs.size(); ++i) if (tabs[i]) { int idx = indexOf(tabs[i]); @@ -140,14 +145,15 @@ void TabSupervisor::retranslateUi() bool TabSupervisor::closeRequest() { if (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) { + 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) { return false; } } - foreach(TabDeckEditor *tab, deckEditorTabs) - { - if(!tab->confirmClose()) + foreach (TabDeckEditor *tab, deckEditorTabs) { + if (!tab->confirmClose()) return false; } @@ -166,11 +172,7 @@ QString TabSupervisor::sanitizeTabName(QString dirty) const QString TabSupervisor::sanitizeHtml(QString dirty) const { - return dirty - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - .replace("\"", """); + return dirty.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); } int TabSupervisor::myAddTab(Tab *tab) @@ -185,37 +187,33 @@ int TabSupervisor::myAddTab(Tab *tab) return idx; } -void TabSupervisor::start(const ServerInfo_User &_userInfo) { +void TabSupervisor::start(const ServerInfo_User &_userInfo) +{ isLocalGame = false; 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))); + 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(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 &))); + 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 *))); + 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 * ))); + connect(tabReplays, SIGNAL(openReplay(GameReplay *)), this, SLOT(openReplay(GameReplay *))); myAddTab(tabReplays); } else { tabDeckStorage = 0; @@ -248,20 +246,22 @@ void TabSupervisor::startLocal(const QList &_clients) 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 &))); + 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) @@ -283,7 +283,7 @@ void TabSupervisor::stop() tabReplays = 0; tabAdmin = 0; tabLog = 0; - + QMapIterator roomIterator(roomTabs); while (roomIterator.hasNext()) roomIterator.next().value()->deleteLater(); @@ -309,7 +309,7 @@ void TabSupervisor::updatePingTime(int value, int max) return; if (tabServer->getContentsChanged()) return; - + setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max))); } @@ -321,10 +321,11 @@ void TabSupervisor::closeButtonPressed() void TabSupervisor::addCloseButtonToTab(Tab *tab, int tabIndex) { - QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition) tabBar()->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tabBar()); + 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)); + closeButton->setProperty("tab", qVariantFromValue((QObject *)tab)); tabBar()->setTabButton(tabIndex, closeSide, closeButton); } @@ -336,8 +337,9 @@ void TabSupervisor::gameJoined(const Event_GameJoined &event) 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())); - + 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))); @@ -357,7 +359,7 @@ void TabSupervisor::localGameJoined(const Event_GameJoined &event) 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()); @@ -372,7 +374,7 @@ void TabSupervisor::gameLeft(TabGame *tab) gameTabs.remove(tab->getGameId()); removeTab(indexOf(tab)); - + if (!localClients.isEmpty()) stop(); } @@ -380,7 +382,7 @@ void TabSupervisor::gameLeft(TabGame *tab) void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent) { TabRoom *tab = new TabRoom(this, client, userInfo, info); - connect(tab, SIGNAL(maximizeClient()), this, SLOT(maximizeMainWindow())); + connect(tab, SIGNAL(maximizeClient()), this, SLOT(maximizeMainWindow())); 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); @@ -394,7 +396,7 @@ void TabSupervisor::roomLeft(TabRoom *tab) { if (tab == currentWidget()) emit setMenu(); - + roomTabs.remove(tab->getRoomId()); removeTab(indexOf(tab)); } @@ -413,7 +415,7 @@ void TabSupervisor::replayLeft(TabGame *tab) { if (tab == currentWidget()) emit setMenu(); - + replayTabs.removeAt(replayTabs.indexOf(tab)); } @@ -421,7 +423,7 @@ 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) @@ -433,7 +435,7 @@ TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus tab = messageTabs.value(QString::fromStdString(otherUser.name())); if (tab) { if (focus) - setCurrentWidget(tab); + setCurrentWidget(tab); return tab; } @@ -448,7 +450,8 @@ TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus return tab; } -void TabSupervisor::maximizeMainWindow() { +void TabSupervisor::maximizeMainWindow() +{ emit showWindowIfHidden(); } @@ -478,7 +481,7 @@ void TabSupervisor::deckEditorClosed(TabDeckEditor *tab) { if (tab == currentWidget()) emit setMenu(); - + deckEditorTabs.removeAt(deckEditorTabs.indexOf(tab)); removeTab(indexOf(tab)); } @@ -577,32 +580,49 @@ bool TabSupervisor::getAdminLocked() const void TabSupervisor::processNotifyUserEvent(const Event_NotifyUser &event) { - switch ((Event_NotifyUser::NotificationType) event.type()) { - case Event_NotifyUser::UNKNOWN: QMessageBox::information(this, tr("Unknown Event"), tr("The server has sent you a message that your client does not understand.\nThis message might mean there is a new version of Cockatrice available or this server is running a custom or pre-release version.\n\nTo update your client, go to Help -> Check for Updates.")); break; - case Event_NotifyUser::IDLEWARNING: QMessageBox::information(this, tr("Idle Timeout"), tr("You are about to be logged out due to inactivity.")); break; - case Event_NotifyUser::PROMOTED: QMessageBox::information(this, tr("Promotion"), tr("You have been promoted to moderator. Please log out and back in for changes to take effect.")); break; + switch ((Event_NotifyUser::NotificationType)event.type()) { + case Event_NotifyUser::UNKNOWN: + QMessageBox::information( + this, tr("Unknown Event"), + tr("The server has sent you a message that your client does not understand.\nThis message might mean " + "there is a new version of Cockatrice available or this server is running a custom or pre-release " + "version.\n\nTo update your client, go to Help -> Check for Updates.")); + break; + case Event_NotifyUser::IDLEWARNING: + QMessageBox::information(this, tr("Idle Timeout"), tr("You are about to be logged out due to inactivity.")); + break; + case Event_NotifyUser::PROMOTED: + QMessageBox::information( + this, tr("Promotion"), + tr("You have been promoted to moderator. Please log out and back in for changes to take effect.")); + break; case Event_NotifyUser::WARNING: { if (!QString::fromStdString(event.warning_reason()).simplified().isEmpty()) - QMessageBox::warning(this, tr("Warned"), tr("You have received a warning due to %1.\nPlease refrain from engaging in this activity or further actions may be taken against you. If you have any questions, please private message a moderator.").arg(QString::fromStdString(event.warning_reason()).simplified())); + QMessageBox::warning(this, tr("Warned"), + tr("You have received a warning due to %1.\nPlease refrain from engaging in this " + "activity or further actions may be taken against you. If you have any " + "questions, please private message a moderator.") + .arg(QString::fromStdString(event.warning_reason()).simplified())); break; } case Event_NotifyUser::CUSTOM: { - if (!QString::fromStdString(event.custom_title()).simplified().isEmpty() && !QString::fromStdString(event.custom_content()).simplified().isEmpty()) { + if (!QString::fromStdString(event.custom_title()).simplified().isEmpty() && + !QString::fromStdString(event.custom_content()).simplified().isEmpty()) { QMessageBox msgBox; msgBox.setParent(this); msgBox.setWindowFlags(Qt::Dialog); msgBox.setIcon(QMessageBox::Information); msgBox.setWindowTitle(QString::fromStdString(event.custom_title()).simplified()); - msgBox.setText(tr("You have received the following message from the server.\n(custom messages like these could be untranslated)")); + msgBox.setText(tr("You have received the following message from the server.\n(custom messages like " + "these could be untranslated)")); msgBox.setDetailedText(QString::fromStdString(event.custom_content()).simplified()); msgBox.setMinimumWidth(200); msgBox.exec(); } break; } - default: ; + default:; } - } bool TabSupervisor::isOwnUserRegistered() const @@ -617,8 +637,10 @@ QString TabSupervisor::getOwnUsername() const bool TabSupervisor::isUserBuddy(const QString &userName) const { - if (!getUserListsTab()) return false; - if (!getUserListsTab()->getBuddyList()) return false; + if (!getUserListsTab()) + return false; + if (!getUserListsTab()->getBuddyList()) + return false; QMap buddyList = getUserListsTab()->getBuddyList()->getUsers(); bool senderIsBuddy = buddyList.contains(userName); return senderIsBuddy; @@ -626,17 +648,21 @@ bool TabSupervisor::isUserBuddy(const QString &userName) const bool TabSupervisor::isUserIgnored(const QString &userName) const { - if (!getUserListsTab()) return false; - if (!getUserListsTab()->getIgnoreList()) return false; + if (!getUserListsTab()) + return false; + if (!getUserListsTab()->getIgnoreList()) + return false; QMap buddyList = getUserListsTab()->getIgnoreList()->getUsers(); bool senderIsBuddy = buddyList.contains(userName); return senderIsBuddy; } -const ServerInfo_User * TabSupervisor::getOnlineUser(const QString &userName) const +const ServerInfo_User *TabSupervisor::getOnlineUser(const QString &userName) const { - if (!getUserListsTab()) return nullptr; - if (!getUserListsTab()->getAllUsersList()) return nullptr; + if (!getUserListsTab()) + return nullptr; + if (!getUserListsTab()->getAllUsersList()) + return nullptr; QMap userList = getUserListsTab()->getAllUsersList()->getUsers(); const QString &userNameToMatchLower = userName.toLower(); QMap::iterator i; diff --git a/cockatrice/src/tab_supervisor.h b/cockatrice/src/tab_supervisor.h index 6a7a4a15..6b4c59f6 100644 --- a/cockatrice/src/tab_supervisor.h +++ b/cockatrice/src/tab_supervisor.h @@ -1,11 +1,11 @@ #ifndef TAB_SUPERVISOR_H #define TAB_SUPERVISOR_H -#include -#include -#include -#include "deck_loader.h" #include "chatview/userlistProxy.h" +#include "deck_loader.h" +#include +#include +#include class QMenu; class AbstractClient; @@ -30,19 +30,25 @@ class ServerInfo_User; class GameReplay; class DeckList; -class CloseButton : public QAbstractButton { +class CloseButton : public QAbstractButton +{ Q_OBJECT public: CloseButton(QWidget *parent = 0); QSize sizeHint() const; - inline QSize minimumSizeHint() const { return sizeHint(); } + inline QSize minimumSizeHint() const + { + return sizeHint(); + } + protected: void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); }; -class TabSupervisor : public QTabWidget, public UserlistProxy { +class TabSupervisor : public QTabWidget, public UserlistProxy +{ Q_OBJECT private: ServerInfo_User *userInfo; @@ -64,6 +70,7 @@ private: QString sanitizeTabName(QString dirty) const; QString sanitizeHtml(QString dirty) const; bool isLocalGame; + public: TabSupervisor(AbstractClient *_client, QWidget *parent = 0); ~TabSupervisor(); @@ -71,19 +78,34 @@ public: void start(const ServerInfo_User &userInfo); void startLocal(const QList &_clients); void stop(); - bool getIsLocalGame() const { return isLocalGame; } - int getGameCount() const { return gameTabs.size(); } - TabUserLists *getUserListsTab() const { return tabUserLists; } - ServerInfo_User *getUserInfo() const { return userInfo; } + bool getIsLocalGame() const + { + return isLocalGame; + } + 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; } + const QMap &getRoomTabs() const + { + return roomTabs; + } bool getAdminLocked() const; bool closeRequest(); bool isOwnUserRegistered() const; QString getOwnUsername() const; bool isUserBuddy(const QString &userName) const; bool isUserIgnored(const QString &userName) const; - const ServerInfo_User* getOnlineUser(const QString &userName) const; + const ServerInfo_User *getOnlineUser(const QString &userName) const; signals: void setMenu(const QList &newMenuList = QList()); void localGameEnded(); diff --git a/cockatrice/src/tab_userlists.cpp b/cockatrice/src/tab_userlists.cpp index 0728ab97..ef2da9b2 100644 --- a/cockatrice/src/tab_userlists.cpp +++ b/cockatrice/src/tab_userlists.cpp @@ -1,22 +1,25 @@ #include "tab_userlists.h" -#include "userlist.h" -#include "userinfobox.h" #include "abstractclient.h" #include "soundengine.h" +#include "userinfobox.h" +#include "userlist.h" #include -#include -#include #include +#include +#include -#include "pending_command.h" -#include "pb/session_commands.pb.h" -#include "pb/response_list_users.pb.h" -#include "pb/event_user_joined.pb.h" -#include "pb/event_user_left.pb.h" #include "pb/event_add_to_list.pb.h" #include "pb/event_remove_from_list.pb.h" +#include "pb/event_user_joined.pb.h" +#include "pb/event_user_left.pb.h" +#include "pb/response_list_users.pb.h" +#include "pb/session_commands.pb.h" +#include "pending_command.h" -TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent) +TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, + AbstractClient *_client, + const ServerInfo_User &userInfo, + QWidget *parent) : Tab(_tabSupervisor, parent), client(_client) { allUsersList = new UserList(_tabSupervisor, client, UserList::AllUsersList); @@ -25,19 +28,29 @@ TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_clien userInfoBox = new UserInfoBox(client, true); 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(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 &))); + 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 &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(processListUsersResponse(const Response &))); client->sendCommand(pend); QVBoxLayout *vbox = new QVBoxLayout; @@ -77,7 +90,7 @@ TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_clien retranslateUi(); - QWidget * mainWidget = new QWidget(this); + QWidget *mainWidget = new QWidget(this); mainWidget->setLayout(mainLayout); setCentralWidget(mainWidget); } @@ -85,7 +98,8 @@ TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_clien void TabUserLists::addToBuddyList() { QString userName = addBuddyEdit->text(); - if (userName.length() < 1) return; + if (userName.length() < 1) + return; std::string listName = "buddy"; addToList(listName, userName); @@ -95,7 +109,8 @@ void TabUserLists::addToBuddyList() void TabUserLists::addToIgnoreList() { QString userName = addIgnoreEdit->text(); - if (userName.length() < 1) return; + if (userName.length() < 1) + return; std::string listName = "ignore"; addToList(listName, userName); @@ -111,7 +126,6 @@ void TabUserLists::addToList(const std::string &listName, const QString &userNam client->sendCommand(client->prepareSessionCommand(cmd)); } - void TabUserLists::retranslateUi() { allUsersList->retranslateUi(); @@ -123,7 +137,7 @@ void TabUserLists::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); @@ -132,7 +146,7 @@ void TabUserLists::processListUsersResponse(const Response &response) ignoreList->setUserOnline(userName, true); buddyList->setUserOnline(userName, true); } - + allUsersList->sortItems(); ignoreList->sortItems(); buddyList->sortItems(); @@ -142,15 +156,15 @@ 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(); - + if (buddyList->getUsers().keys().contains(userName)) soundEngine->playSound("buddy_join"); @@ -169,7 +183,7 @@ void TabUserLists::processUserLeftEvent(const Event_UserLeft &event) buddyList->setUserOnline(userName, false); ignoreList->sortItems(); buddyList->sortItems(); - + emit userLeft(userName); } } @@ -200,7 +214,7 @@ void TabUserLists::processAddToListEvent(const Event_AddToList &event) userList = ignoreList; if (!userList) return; - + userList->processUserInfo(info, online); userList->sortItems(); } diff --git a/cockatrice/src/tab_userlists.h b/cockatrice/src/tab_userlists.h index f0228de2..ceb10e27 100644 --- a/cockatrice/src/tab_userlists.h +++ b/cockatrice/src/tab_userlists.h @@ -1,8 +1,8 @@ #ifndef TAB_USERLISTS_H #define TAB_USERLISTS_H -#include "tab.h" #include "pb/serverinfo_user.pb.h" +#include "tab.h" #include class AbstractClient; @@ -17,7 +17,8 @@ class ServerInfo_User; class Event_AddToList; class Event_RemoveFromList; -class TabUserLists : public Tab { +class TabUserLists : public Tab +{ Q_OBJECT signals: void openMessageDialog(const QString &userName, bool focus); @@ -33,6 +34,7 @@ private slots: void processRemoveFromListEvent(const Event_RemoveFromList &event); void addToIgnoreList(); void addToBuddyList(); + private: AbstractClient *client; UserList *allUsersList; @@ -42,13 +44,29 @@ private: QLineEdit *addBuddyEdit; QLineEdit *addIgnoreEdit; void addToList(const std::string &listName, const QString &userName); + public: - TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent = 0); + TabUserLists(TabSupervisor *_tabSupervisor, + AbstractClient *_client, + const ServerInfo_User &userInfo, + QWidget *parent = 0); void retranslateUi(); - QString getTabText() const { return tr("Account"); } - const UserList *getAllUsersList() const { return allUsersList; } - const UserList *getBuddyList() const { return buddyList; } - const UserList *getIgnoreList() const { return ignoreList; } + QString getTabText() const + { + return tr("Account"); + } + 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 532f492d..308084df 100644 --- a/cockatrice/src/tablezone.cpp +++ b/cockatrice/src/tablezone.cpp @@ -1,26 +1,26 @@ +#include #include #include -#include #include #ifdef _WIN32 #include "round.h" #endif /* _WIN32 */ -#include "tablezone.h" +#include "arrowitem.h" +#include "carddatabase.h" +#include "carddragitem.h" +#include "carditem.h" #include "player.h" #include "settingscache.h" +#include "tablezone.h" #include "thememanager.h" -#include "arrowitem.h" -#include "carddragitem.h" -#include "carddatabase.h" -#include "carditem.h" #include "pb/command_move_card.pb.h" #include "pb/command_set_card_attr.pb.h" -const QColor TableZone::BACKGROUND_COLOR = QColor(100, 100, 100); -const QColor TableZone::FADE_MASK = QColor(0, 0, 0, 80); -const QColor TableZone::GRADIENT_COLOR = QColor(255, 255, 255, 150); -const QColor TableZone::GRADIENT_COLORLESS = QColor(255, 255, 255, 0); +const QColor TableZone::BACKGROUND_COLOR = QColor(100, 100, 100); +const QColor TableZone::FADE_MASK = QColor(0, 0, 0, 80); +const QColor TableZone::GRADIENT_COLOR = QColor(255, 255, 255, 150); +const QColor TableZone::GRADIENT_COLORLESS = QColor(255, 255, 255, 0); TableZone::TableZone(Player *_p, QGraphicsItem *parent) : SelectZone(_p, "table", true, false, true, parent), active(false) @@ -30,7 +30,7 @@ TableZone::TableZone(Player *_p, QGraphicsItem *parent) updateBg(); - height = MARGIN_TOP + MARGIN_BOTTOM + TABLEROWS * CARD_HEIGHT + (TABLEROWS-1) * PADDING_Y; + height = MARGIN_TOP + MARGIN_BOTTOM + TABLEROWS * CARD_HEIGHT + (TABLEROWS - 1) * PADDING_Y; width = MIN_WIDTH; currentMinimumWidth = width; @@ -38,25 +38,22 @@ TableZone::TableZone(Player *_p, QGraphicsItem *parent) setAcceptHoverEvents(true); } - void TableZone::updateBg() { update(); } - QRectF TableZone::boundingRect() const { 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*/) { painter->fillRect(boundingRect(), themeManager->getTableBgBrush()); @@ -72,13 +69,13 @@ void TableZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*opti paintLandDivider(painter); } - /** Render a soft outline around the edge of the TableZone. @param painter QPainter object */ -void TableZone::paintZoneOutline(QPainter *painter) { +void TableZone::paintZoneOutline(QPainter *painter) +{ QLinearGradient grad1(0, 0, 0, 1); grad1.setCoordinateMode(QGradient::ObjectBoundingMode); grad1.setColorAt(0, GRADIENT_COLOR); @@ -96,13 +93,13 @@ void TableZone::paintZoneOutline(QPainter *painter) { painter->fillRect(QRectF(width - BOX_LINE_WIDTH, 0, BOX_LINE_WIDTH, height), QBrush(grad1)); } - /** Render a division line for land placement @painter QPainter object */ -void TableZone::paintLandDivider(QPainter *painter){ +void TableZone::paintLandDivider(QPainter *painter) +{ // Place the line 2 grid heights down then back it off just enough to allow // some space between a 3-card stack and the land area. qreal separatorY = MARGIN_TOP + 2 * (CARD_HEIGHT + PADDING_Y) - STACKED_CARD_OFFSET_Y / 2; @@ -112,7 +109,6 @@ void TableZone::paintLandDivider(QPainter *painter){ painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); } - void TableZone::addCardImpl(CardItem *card, int _x, int _y) { cards.append(card); @@ -123,14 +119,14 @@ void TableZone::addCardImpl(CardItem *card, int _x, int _y) card->update(); } - void TableZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint) { handleDropEventByGrid(dragItems, startZone, mapToGrid(dropPoint)); } - -void TableZone::handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint) +void TableZone::handleDropEventByGrid(const QList &dragItems, + CardZone *startZone, + const QPoint &gridPoint) { Command_MoveCard cmd; cmd.set_start_player_id(startZone->getPlayer()->getId()); @@ -139,25 +135,24 @@ void TableZone::handleDropEventByGrid(const QList &dragItems, Ca 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()); - if(startZone->getName() != name && dragItems[i]->getItem()->getInfo()) + if (startZone->getName() != name && dragItems[i]->getItem()->getInfo()) ctm->set_pt(dragItems[i]->getItem()->getInfo()->getPowTough().toStdString()); else ctm->set_pt(std::string()); } - + startZone->getPlayer()->sendGameCommand(cmd); } - void TableZone::reorganizeCards() { QList arrowsToUpdate; - + // Calculate card stack widths so mapping functions work properly computeCardStackWidths(); @@ -165,20 +160,20 @@ void TableZone::reorganizeCards() 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 * STACKED_CARD_OFFSET_X; 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()) { @@ -192,7 +187,7 @@ void TableZone::reorganizeCards() arrowsToUpdate.append(attachedCard->getArrowsFrom()); arrowsToUpdate.append(attachedCard->getArrowsTo()); } - + arrowsToUpdate.append(cards[i]->getArrowsFrom()); arrowsToUpdate.append(cards[i]->getArrowsTo()); } @@ -200,12 +195,11 @@ void TableZone::reorganizeCards() QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); while (arrowIterator.hasNext()) arrowIterator.next()->updatePath(); - + resizeToContents(); update(); } - void TableZone::toggleTapped() { QList selectedItems = scene()->selectedItems(); @@ -215,7 +209,7 @@ void TableZone::toggleTapped() tapAll = true; break; } - QList< const ::google::protobuf::Message * > cmdList; + QList cmdList; for (int i = 0; i < selectedItems.size(); i++) { CardItem *temp = qgraphicsitem_cast(selectedItems[i]); if (temp->getTapped() != tapAll) { @@ -230,7 +224,6 @@ void TableZone::toggleTapped() player->sendGameCommand(player->prepareGameCommand(cmdList)); } - CardItem *TableZone::takeCard(int position, int cardId, bool canResize) { CardItem *result = CardZone::takeCard(position, cardId); @@ -239,7 +232,6 @@ CardItem *TableZone::takeCard(int position, int cardId, bool canResize) return result; } - void TableZone::resizeToContents() { int xMax = 0; @@ -247,7 +239,7 @@ void TableZone::resizeToContents() // Find rightmost card position, which includes the left margin amount. for (int i = 0; i < cards.size(); ++i) if (cards[i]->pos().x() > xMax) - xMax = (int) cards[i]->pos().x(); + xMax = (int)cards[i]->pos().x(); // Minimum width is the rightmost card position plus enough room for // another card with padding, then margin. @@ -263,7 +255,6 @@ void TableZone::resizeToContents() } } - CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const { for (int i = 0; i < cards.size(); i++) @@ -272,14 +263,12 @@ CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const return 0; } - CardItem *TableZone::getCardFromCoords(const QPointF &point) const { QPoint gridPoint = mapToGrid(point); return getCardFromGrid(gridPoint); } - void TableZone::computeCardStackWidths() { // Each card stack is three grid points worth of card locations. @@ -289,7 +278,7 @@ void TableZone::computeCardStackWidths() const QPoint &gridPoint = cards[i]->getGridPos(); if (gridPoint.x() == -1) continue; - + const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y()); cardStackCount.insert(key, cardStackCount.value(key, 0) + 1); } @@ -300,7 +289,7 @@ void TableZone::computeCardStackWidths() const QPoint &gridPoint = cards[i]->getGridPos(); if (gridPoint.x() == -1) continue; - + const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y()); const int stackCount = cardStackCount.value(key, 0); if (stackCount == 1) @@ -310,7 +299,6 @@ void TableZone::computeCardStackWidths() } } - QPointF TableZone::mapFromGrid(QPoint gridPoint) const { qreal x, y; @@ -319,15 +307,14 @@ QPointF TableZone::mapFromGrid(QPoint gridPoint) const x = MARGIN_LEFT + (gridPoint.x() % 3) * STACKED_CARD_OFFSET_X; // Add in width of card stack plus padding for each column - for (int i = 0; i < gridPoint.x() / 3; ++i) - { + for (int i = 0; i < gridPoint.x() / 3; ++i) { const int key = getCardStackMapKey(i, gridPoint.y()); x += cardStackWidth.value(key, CARD_WIDTH) + PADDING_X; } - + if (isInverted()) gridPoint.setY(TABLEROWS - 1 - gridPoint.y()); - + // Start with margin plus stacked card offset y = MARGIN_TOP + (gridPoint.x() % 3) * STACKED_CARD_OFFSET_Y; @@ -338,7 +325,6 @@ QPointF TableZone::mapFromGrid(QPoint gridPoint) const return QPointF(x, y); } - QPoint TableZone::mapToGrid(const QPointF &mapPoint) const { // Begin by calculating the y-coordinate of the grid space, which will be @@ -369,7 +355,7 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const int xStack = 0; int xNextStack = 0; int nextStackCol = 0; - while ((xNextStack <= x) && (xNextStack <= xMax)) { + while ((xNextStack <= x) && (xNextStack <= xMax)) { xStack = xNextStack; const int key = getCardStackMapKey(nextStackCol, gridPointY); xNextStack += cardStackWidth.value(key, CARD_WIDTH) + PADDING_X; @@ -386,7 +372,6 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const return QPoint(gridPointX, gridPointY); } - QPointF TableZone::closestGridPoint(const QPointF &point) { QPoint gridPoint = mapToGrid(point + QPoint(1, 1)); @@ -400,9 +385,9 @@ QPointF TableZone::closestGridPoint(const QPointF &point) int TableZone::clampValidTableRow(const int row) { - if(row < 0) + if (row < 0) return 0; - if(row >= TABLEROWS) + if (row >= TABLEROWS) return TABLEROWS - 1; return row; } diff --git a/cockatrice/src/tablezone.h b/cockatrice/src/tablezone.h index 55b12b8b..65a1217d 100644 --- a/cockatrice/src/tablezone.h +++ b/cockatrice/src/tablezone.h @@ -1,19 +1,18 @@ #ifndef TABLEZONE_H #define TABLEZONE_H - -#include "selectzone.h" #include "abstractcarditem.h" - +#include "selectzone.h" /* -* TableZone is the grid based rect where CardItems may be placed. -* It is the main play zone and can be customized with background images. -* -* TODO: Refactor methods to make more readable, extract some logic to -* private methods (Im looking at you TableZone::reorganizeCards()) -*/ -class TableZone : public SelectZone { + * TableZone is the grid based rect where CardItems may be placed. + * It is the main play zone and can be customized with background images. + * + * TODO: Refactor methods to make more readable, extract some logic to + * private methods (Im looking at you TableZone::reorganizeCards()) + */ +class TableZone : public SelectZone +{ Q_OBJECT signals: @@ -29,7 +28,7 @@ private: static const int MARGIN_RIGHT = 15; static const int MARGIN_TOP = 10; static const int MARGIN_BOTTOM = 30; - static const int PADDING_X = 35; + static const int PADDING_X = 35; static const int PADDING_Y = 30; /* @@ -55,7 +54,7 @@ private: static const QColor FADE_MASK; static const QColor GRADIENT_COLOR; static const QColor GRADIENT_COLORLESS; - + /* Size and shape variables */ @@ -100,7 +99,7 @@ public: @param parent defaults to null */ TableZone(Player *_p, QGraphicsItem *parent = 0); - + /** @return a QRectF of the TableZone bounding box. */ @@ -109,7 +108,7 @@ public: /** Render the TableZone - @param painter + @param painter @param option */ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); @@ -154,15 +153,29 @@ public: CardItem *takeCard(int position, int cardId, bool canResize = true); /** - Resizes the TableZone in case CardItems are within or + Resizes the TableZone in case CardItems are within or outside of the TableZone constraints. */ void resizeToContents(); - int getMinimumWidth() const { return currentMinimumWidth; } - void setWidth(qreal _width) { prepareGeometryChange(); width = _width; } - qreal getWidth() const { return width; } - void setActive(bool _active) { active = _active; update(); } + int getMinimumWidth() const + { + return currentMinimumWidth; + } + void setWidth(qreal _width) + { + prepareGeometryChange(); + width = _width; + } + qreal getWidth() const + { + return width; + } + void setActive(bool _active) + { + active = _active; + update(); + } protected: void addCardImpl(CardItem *card, int x, int y); @@ -185,7 +198,10 @@ private: /* Helper function to create a single key from a card stack location. */ - int getCardStackMapKey (int x, int y) const { return x + (y * 1000); } + int getCardStackMapKey(int x, int y) const + { + return x + (y * 1000); + } }; #endif diff --git a/cockatrice/src/tappedout_interface.cpp b/cockatrice/src/tappedout_interface.cpp index 54158eaf..77e1b83f 100644 --- a/cockatrice/src/tappedout_interface.cpp +++ b/cockatrice/src/tappedout_interface.cpp @@ -1,17 +1,15 @@ #include "tappedout_interface.h" #include "decklist.h" -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include #include -TappedOutInterface::TappedOutInterface( - CardDatabase &_cardDatabase, - QObject *parent -) : QObject(parent), cardDatabase(_cardDatabase) +TappedOutInterface::TappedOutInterface(CardDatabase &_cardDatabase, QObject *parent) + : QObject(parent), cardDatabase(_cardDatabase) { manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); @@ -27,15 +25,14 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply) } int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if(reply->hasRawHeader("Location")) - { + if (reply->hasRawHeader("Location")) { /* * If the reply contains a "Location" header, a relative URL to the deck on TappedOut * can be extracted from the header. The http status is a 302 "redirect". */ QString deckUrl = reply->rawHeader("Location"); qDebug() << "Tappedout: good reply, http status" << httpStatus << "location" << deckUrl; - QDesktopServices::openUrl("http://tappedout.net" + deckUrl); + QDesktopServices::openUrl("http://tappedout.net" + deckUrl); } else { /* * Otherwise, the deck has not been parsed correctly. Error messages can be extracted @@ -43,25 +40,23 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply) */ QString data(reply->readAll()); QString errorMessage = tr("Unable to analyze the deck."); - + QRegExp rx("
(.*)"); rx.setMinimal(true); int found = rx.indexIn(data); - if (found >= 0) - { + if (found >= 0) { QString errors = rx.cap(1); QRegExp rx2("
  • (.*)
  • "); rx2.setMinimal(true); int captures = rx2.captureCount(); - for(int i = 1; i <= captures; i++) - { + for (int i = 1; i <= captures; i++) { errorMessage += QString("\n") + rx2.cap(i).remove(QRegExp("<[^>]*>")).simplified(); } - } - qDebug() << "Tappedout: bad reply, http status" << httpStatus << "size" << data.size() << "message" << errorMessage; + qDebug() << "Tappedout: bad reply, http status" << httpStatus << "size" << data.size() << "message" + << errorMessage; QMessageBox::critical(0, tr("Error"), errorMessage); } @@ -88,28 +83,29 @@ void TappedOutInterface::analyzeDeck(DeckList *deck) { QByteArray data; getAnalyzeRequestData(deck, &data); - + QNetworkRequest request(QUrl("http://tappedout.net/mtg-decks/paste/")); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - + manager->post(request, data); } -struct CopyMainOrSide { +struct CopyMainOrSide +{ CardDatabase &cardDatabase; DeckList &mainboard, &sideboard; CopyMainOrSide(CardDatabase &_cardDatabase, DeckList &_mainboard, DeckList &_sideboard) - : cardDatabase(_cardDatabase), mainboard(_mainboard), sideboard(_sideboard) {}; + : cardDatabase(_cardDatabase), mainboard(_mainboard), sideboard(_sideboard){}; void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const { - CardInfo * dbCard = cardDatabase.getCard(card->getName()); + CardInfo *dbCard = cardDatabase.getCard(card->getName()); if (!dbCard || dbCard->getIsToken()) return; DecklistCardNode *addedCard; - if(node->getName() == DECK_ZONE_SIDE) + if (node->getName() == DECK_ZONE_SIDE) addedCard = sideboard.addCard(card->getName(), node->getName()); else addedCard = mainboard.addCard(card->getName(), node->getName()); diff --git a/cockatrice/src/tappedout_interface.h b/cockatrice/src/tappedout_interface.h index 143a6ba6..a73a7728 100644 --- a/cockatrice/src/tappedout_interface.h +++ b/cockatrice/src/tappedout_interface.h @@ -16,16 +16,18 @@ class DeckList; * logic is implemented in TappedOutInterface::queryFinished(). */ -class TappedOutInterface : public QObject { +class TappedOutInterface : public QObject +{ Q_OBJECT private: QNetworkAccessManager *manager; CardDatabase &cardDatabase; - void copyDeckSplitMainAndSide(const DeckList &source, DeckList& mainboard, DeckList& sideboard); + void copyDeckSplitMainAndSide(const DeckList &source, DeckList &mainboard, DeckList &sideboard); private slots: void queryFinished(QNetworkReply *reply); void getAnalyzeRequestData(DeckList *deck, QByteArray *data); + public: TappedOutInterface(CardDatabase &_cardDatabase, QObject *parent = 0); void analyzeDeck(DeckList *deck); diff --git a/cockatrice/src/thememanager.cpp b/cockatrice/src/thememanager.cpp index 2d5ef71a..86b1f067 100644 --- a/cockatrice/src/thememanager.cpp +++ b/cockatrice/src/thememanager.cpp @@ -1,10 +1,10 @@ #include "thememanager.h" #include "settingscache.h" #include -#include #include -#include +#include #include +#include #include #define DEFAULT_THEME_NAME "Default" @@ -14,8 +14,7 @@ #define STACKZONE_BG_NAME "stackzone" #define TABLEZONE_BG_NAME "tablezone" -ThemeManager::ThemeManager(QObject *parent) - :QObject(parent) +ThemeManager::ThemeManager(QObject *parent) : QObject(parent) { ensureThemeDirectoryExists(); connect(settingsCache, SIGNAL(themeChanged()), this, SLOT(themeChangedSlot())); @@ -24,15 +23,13 @@ ThemeManager::ThemeManager(QObject *parent) void ThemeManager::ensureThemeDirectoryExists() { - if(settingsCache->getThemeName().isEmpty() || - !getAvailableThemes().contains(settingsCache->getThemeName())) - { + if (settingsCache->getThemeName().isEmpty() || !getAvailableThemes().contains(settingsCache->getThemeName())) { qDebug() << "Theme name not set, setting default value"; settingsCache->setThemeName(DEFAULT_THEME_NAME); } } -QStringMap & ThemeManager::getAvailableThemes() +QStringMap &ThemeManager::getAvailableThemes() { QDir dir; availableThemes.clear(); @@ -40,23 +37,23 @@ QStringMap & ThemeManager::getAvailableThemes() // load themes from user profile dir dir = settingsCache->getDataPath() + "/themes"; - foreach(QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) - { - if(!availableThemes.contains(themeName)) + foreach (QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) { + if (!availableThemes.contains(themeName)) availableThemes.insert(themeName, dir.absoluteFilePath(themeName)); } // load themes from cockatrice system dir + dir = qApp->applicationDirPath() + #ifdef Q_OS_MAC - dir = qApp->applicationDirPath() + "/../Resources/themes"; + "/../Resources/themes"; #elif defined(Q_OS_WIN) - dir = qApp->applicationDirPath() + "/themes"; + "/themes"; #else // linux - dir = qApp->applicationDirPath() + "/../share/cockatrice/themes"; + "/../share/cockatrice/themes"; #endif - foreach(QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) - { - if(!availableThemes.contains(themeName)) + + foreach (QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) { + if (!availableThemes.contains(themeName)) availableThemes.insert(themeName, dir.absoluteFilePath(themeName)); } @@ -67,8 +64,7 @@ QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor) { QBrush brush; QPixmap tmp = QPixmap("theme:zones/" + fileName); - if(tmp.isNull()) - { + if (tmp.isNull()) { brush.setColor(fallbackColor); brush.setStyle(Qt::SolidPattern); } else { @@ -86,7 +82,7 @@ void ThemeManager::themeChangedSlot() QDir dir = getAvailableThemes().value(themeName); // css - if(dir.exists(STYLE_CSS_NAME)) + if (dir.exists(STYLE_CSS_NAME)) qApp->setStyleSheet("file:///" + dir.absoluteFilePath(STYLE_CSS_NAME)); else diff --git a/cockatrice/src/thememanager.h b/cockatrice/src/thememanager.h index f83bdcc3..3fcc1d9b 100644 --- a/cockatrice/src/thememanager.h +++ b/cockatrice/src/thememanager.h @@ -1,32 +1,48 @@ #ifndef THEMEMANAGER_H #define THEMEMANAGER_H -#include #include -#include -#include #include +#include +#include +#include #include typedef QMap QStringMap; class QApplication; -class ThemeManager : public QObject { +class ThemeManager : public QObject +{ Q_OBJECT public: ThemeManager(QObject *parent = 0); + private: QBrush handBgBrush, stackBgBrush, tableBgBrush, playerBgBrush; QStringMap availableThemes; + protected: void ensureThemeDirectoryExists(); QBrush loadBrush(QString fileName, QColor fallbackColor); + public: - QBrush &getHandBgBrush() { return handBgBrush; } - QBrush &getStackBgBrush() { return stackBgBrush; } - QBrush &getTableBgBrush() { return tableBgBrush; } - QBrush &getPlayerBgBrush() { return playerBgBrush; } + QBrush &getHandBgBrush() + { + return handBgBrush; + } + QBrush &getStackBgBrush() + { + return stackBgBrush; + } + QBrush &getTableBgBrush() + { + return tableBgBrush; + } + QBrush &getPlayerBgBrush() + { + return playerBgBrush; + } QStringMap &getAvailableThemes(); protected slots: void themeChangedSlot(); @@ -34,6 +50,6 @@ signals: void themeChanged(); }; -extern ThemeManager * themeManager; +extern ThemeManager *themeManager; #endif diff --git a/cockatrice/src/translation.h b/cockatrice/src/translation.h index f690c33f..304a972b 100644 --- a/cockatrice/src/translation.h +++ b/cockatrice/src/translation.h @@ -1,6 +1,13 @@ #ifndef TRANSLATION_H #define TRANSLATION_H -enum GrammaticalCase { CaseNominative, CaseLookAtZone, CaseTopCardsOfZone, CaseRevealZone, CaseShuffleZone }; - +enum GrammaticalCase +{ + CaseNominative, + CaseLookAtZone, + CaseTopCardsOfZone, + CaseRevealZone, + CaseShuffleZone +}; + #endif diff --git a/cockatrice/src/update_downloader.cpp b/cockatrice/src/update_downloader.cpp index 263c12e1..fd9aeead 100644 --- a/cockatrice/src/update_downloader.cpp +++ b/cockatrice/src/update_downloader.cpp @@ -1,14 +1,16 @@ -#include #include +#include #include "update_downloader.h" -UpdateDownloader::UpdateDownloader(QObject *parent) : QObject(parent) { +UpdateDownloader::UpdateDownloader(QObject *parent) : QObject(parent) +{ netMan = new QNetworkAccessManager(this); } -void UpdateDownloader::beginDownload(QUrl downloadUrl) { - //Save the original URL because we need it for the filename +void UpdateDownloader::beginDownload(QUrl downloadUrl) +{ + // Save the original URL because we need it for the filename if (originalUrl.isEmpty()) originalUrl = downloadUrl; @@ -18,33 +20,33 @@ void UpdateDownloader::beginDownload(QUrl downloadUrl) { connect(this, SIGNAL(stopDownload()), response, SLOT(abort())); } -void UpdateDownloader::downloadError(QNetworkReply::NetworkError) { +void UpdateDownloader::downloadError(QNetworkReply::NetworkError) +{ if (response == nullptr) return; emit error(response->errorString().toUtf8()); } -void UpdateDownloader::fileFinished() { - //If we finished but there's a redirect, follow it +void UpdateDownloader::fileFinished() +{ + // If we finished but there's a redirect, follow it QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute); - if (!redirect.isNull()) - { + if (!redirect.isNull()) { beginDownload(redirect.toUrl()); return; } - //Handle any errors we had - if (response->error()) - { + // Handle any errors we had + if (response->error()) { emit error(response->errorString()); return; } - //Work out the file name of the download + // Work out the file name of the download QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1); - //Save the build in a temporary directory + // Save the build in a temporary directory QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { emit error(tr("Could not open the file for reading.")); @@ -54,11 +56,11 @@ void UpdateDownloader::fileFinished() { file.write(response->readAll()); file.close(); - //Emit the success signal with a URL to the download file + // Emit the success signal with a URL to the download file emit downloadSuccessful(QUrl::fromLocalFile(fileName)); } -void UpdateDownloader::downloadProgress(qint64 bytesRead, qint64 totalBytes) { +void UpdateDownloader::downloadProgress(qint64 bytesRead, qint64 totalBytes) +{ emit progressMade(bytesRead, totalBytes); } - diff --git a/cockatrice/src/update_downloader.h b/cockatrice/src/update_downloader.h index f72787bb..bc10fe19 100644 --- a/cockatrice/src/update_downloader.h +++ b/cockatrice/src/update_downloader.h @@ -5,13 +5,14 @@ #ifndef COCKATRICE_UPDATEDOWNLOADER_H #define COCKATRICE_UPDATEDOWNLOADER_H +#include #include #include -#include #include -class UpdateDownloader : public QObject { -Q_OBJECT +class UpdateDownloader : public QObject +{ + Q_OBJECT public: UpdateDownloader(QObject *parent); void beginDownload(QUrl url); @@ -20,6 +21,7 @@ signals: void progressMade(qint64 bytesRead, qint64 totalBytes); void error(QString errorString); void stopDownload(); + private: QUrl originalUrl; QNetworkAccessManager *netMan; @@ -30,5 +32,4 @@ private slots: void downloadError(QNetworkReply::NetworkError); }; - -#endif //COCKATRICE_UPDATEDOWNLOADER_H +#endif // COCKATRICE_UPDATEDOWNLOADER_H diff --git a/cockatrice/src/user_context_menu.cpp b/cockatrice/src/user_context_menu.cpp index d839a551..7968c1b2 100644 --- a/cockatrice/src/user_context_menu.cpp +++ b/cockatrice/src/user_context_menu.cpp @@ -1,29 +1,29 @@ +#include "user_context_menu.h" +#include "abstractclient.h" +#include "gameselector.h" +#include "pending_command.h" +#include "tab_game.h" +#include "tab_supervisor.h" +#include "tab_userlists.h" +#include "userinfobox.h" +#include "userlist.h" #include #include #include -#include "user_context_menu.h" -#include "tab_supervisor.h" -#include "tab_userlists.h" -#include "tab_game.h" -#include "userlist.h" -#include "abstractclient.h" -#include "userinfobox.h" -#include "gameselector.h" -#include "pending_command.h" +#include #include #include -#include -#include "pb/commands.pb.h" -#include "pb/session_commands.pb.h" -#include "pb/moderator_commands.pb.h" #include "pb/command_kick_from_game.pb.h" +#include "pb/commands.pb.h" +#include "pb/moderator_commands.pb.h" +#include "pb/response_ban_history.pb.h" #include "pb/response_get_games_of_user.pb.h" #include "pb/response_get_user_info.pb.h" -#include "pb/response_ban_history.pb.h" #include "pb/response_warn_history.pb.h" #include "pb/response_warn_list.pb.h" +#include "pb/session_commands.pb.h" UserContextMenu::UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *parent, TabGame *_game) : QObject(parent), client(_tabSupervisor->getClient()), tabSupervisor(_tabSupervisor), game(_game) @@ -135,12 +135,13 @@ void UserContextMenu::warnUser_processUserInfoResponse(const Response &resp) cmd.set_user_name(userInfo.name()); cmd.set_user_clientid(userInfo.clientid()); PendingCommand *pend = client->prepareModeratorCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(warnUser_processGetWarningsListResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(warnUser_processGetWarningsListResponse(Response))); client->sendCommand(pend); - } -void UserContextMenu::banUserHistory_processResponse(const Response &resp) { +void UserContextMenu::banUserHistory_processResponse(const Response &resp) +{ const Response_BanHistory &response = resp.GetExtension(Response_BanHistory::ext); if (resp.response_code() == Response::RespOk) { @@ -152,9 +153,10 @@ void UserContextMenu::banUserHistory_processResponse(const Response &resp) { table->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); table->setHorizontalHeaderLabels( - QString(tr("Ban Time;Moderator;Ban Length;Ban Reason;Visible Reason")).split(";")); + QString(tr("Ban Time;Moderator;Ban Length;Ban Reason;Visible Reason")).split(";")); - ServerInfo_Ban ban; for (int i = 0; i < response.ban_list_size(); ++i) { + ServerInfo_Ban ban; + for (int i = 0; i < response.ban_list_size(); ++i) { ban = response.ban_list(i); table->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(ban.ban_time()))); table->setItem(i, 1, new QTableWidgetItem(QString::fromStdString(ban.admin_name()))); @@ -164,16 +166,20 @@ void UserContextMenu::banUserHistory_processResponse(const Response &resp) { } table->resizeColumnsToContents(); - table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5), table->verticalHeader()->length() + (table->rowCount() * 3)); + table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5), + table->verticalHeader()->length() + (table->rowCount() * 3)); table->show(); } else - QMessageBox::information(static_cast(parent()), tr("Ban History"), tr("User has never been banned.")); + QMessageBox::information(static_cast(parent()), tr("Ban History"), + tr("User has never been banned.")); } else - QMessageBox::critical(static_cast(parent()), tr("Ban History"), tr("Failed to collecting ban information.")); + QMessageBox::critical(static_cast(parent()), tr("Ban History"), + tr("Failed to collecting ban information.")); } -void UserContextMenu::warnUserHistory_processResponse(const Response &resp) { +void UserContextMenu::warnUserHistory_processResponse(const Response &resp) +{ const Response_WarnHistory &response = resp.GetExtension(Response_WarnHistory::ext); if (resp.response_code() == Response::RespOk) { @@ -184,10 +190,10 @@ void UserContextMenu::warnUserHistory_processResponse(const Response &resp) { table->setColumnCount(4); table->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - table->setHorizontalHeaderLabels( - QString(tr("Warning Time;Moderator;User Name;Reason")).split(";")); + table->setHorizontalHeaderLabels(QString(tr("Warning Time;Moderator;User Name;Reason")).split(";")); - ServerInfo_Warning warn; for (int i = 0; i < response.warn_list_size(); ++i) { + ServerInfo_Warning warn; + for (int i = 0; i < response.warn_list_size(); ++i) { warn = response.warn_list(i); table->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(warn.time_of()))); table->setItem(i, 1, new QTableWidgetItem(QString::fromStdString(warn.admin_name()))); @@ -196,13 +202,16 @@ void UserContextMenu::warnUserHistory_processResponse(const Response &resp) { } table->resizeColumnsToContents(); - table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5), table->verticalHeader()->length() + (table->rowCount() * 3)); + table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5), + table->verticalHeader()->length() + (table->rowCount() * 3)); table->show(); } else - QMessageBox::information(static_cast(parent()), tr("Warning History"), tr("User has never been warned.")); + QMessageBox::information(static_cast(parent()), tr("Warning History"), + tr("User has never been warned.")); } else - QMessageBox::critical(static_cast(parent()), tr("Warning History"), tr("Failed to collecting warning information.")); + QMessageBox::critical(static_cast(parent()), tr("Warning History"), + tr("Failed to collecting warning information.")); } void UserContextMenu::adjustMod_processUserResponse(const Response &resp, const CommandContainer &commandContainer) @@ -212,7 +221,8 @@ void UserContextMenu::adjustMod_processUserResponse(const Response &resp, const if (resp.response_code() == Response::RespOk) { if (cmd.should_be_mod()) { - QMessageBox::information(static_cast(parent()), tr("Success"), tr("Successfully promoted user.")); + QMessageBox::information(static_cast(parent()), tr("Success"), + tr("Successfully promoted user.")); } else { QMessageBox::information(static_cast(parent()), tr("Success"), tr("Successfully demoted user.")); } @@ -254,10 +264,13 @@ void UserContextMenu::warnUser_dialogFinished() cmd.set_clientid(dlg->getWarnID().toStdString()); client->sendCommand(client->prepareModeratorCommand(cmd)); - } -void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, bool online, int playerId) +void UserContextMenu::showContextMenu(const QPoint &pos, + const QString &userName, + UserLevelFlags userLevel, + bool online, + int playerId) { aUserName->setText(userName); @@ -291,10 +304,12 @@ void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName menu->addAction(aBanHistory); menu->addSeparator(); - if (userLevel.testFlag(ServerInfo_User::IsModerator) && (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsAdmin)) { + if (userLevel.testFlag(ServerInfo_User::IsModerator) && + (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsAdmin)) { menu->addAction(aDemoteFromMod); - } else if (userLevel.testFlag(ServerInfo_User::IsRegistered) && (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsAdmin)) { + } else if (userLevel.testFlag(ServerInfo_User::IsRegistered) && + (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsAdmin)) { menu->addAction(aPromoteToMod); } } @@ -316,7 +331,9 @@ void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName QAction *actionClicked = menu->exec(pos); if (actionClicked == aDetails) { - UserInfoBox *infoWidget = new UserInfoBox(client, false, static_cast(parent()), Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); + UserInfoBox *infoWidget = + new UserInfoBox(client, false, static_cast(parent()), + Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); infoWidget->setAttribute(Qt::WA_DeleteOnClose); infoWidget->updateInfo(userName); } else if (actionClicked == aChat) @@ -326,7 +343,8 @@ void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName cmd.set_user_name(userName.toStdString()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(gamesOfUserReceived(Response, CommandContainer))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(gamesOfUserReceived(Response, CommandContainer))); client->sendCommand(pend); } else if (actionClicked == aAddToBuddyList) { @@ -363,7 +381,8 @@ void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName cmd.set_user_name(userName.toStdString()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(banUser_processUserInfoResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(banUser_processUserInfoResponse(Response))); client->sendCommand(pend); } else if (actionClicked == aPromoteToMod || actionClicked == aDemoteFromMod) { Command_AdjustMod cmd; @@ -371,25 +390,29 @@ void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName cmd.set_should_be_mod(actionClicked == aPromoteToMod); PendingCommand *pend = client->prepareAdminCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(adjustMod_processUserResponse(Response, CommandContainer))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(adjustMod_processUserResponse(Response, CommandContainer))); client->sendCommand(pend); } else if (actionClicked == aBanHistory) { Command_GetBanHistory cmd; cmd.set_user_name(userName.toStdString()); PendingCommand *pend = client->prepareModeratorCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(banUserHistory_processResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(banUserHistory_processResponse(Response))); client->sendCommand(pend); } else if (actionClicked == aWarnUser) { Command_GetUserInfo cmd; cmd.set_user_name(userName.toStdString()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(warnUser_processUserInfoResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(warnUser_processUserInfoResponse(Response))); client->sendCommand(pend); } else if (actionClicked == aWarnHistory) { Command_GetWarnHistory cmd; cmd.set_user_name(userName.toStdString()); PendingCommand *pend = client->prepareModeratorCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(warnUserHistory_processResponse(Response))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(warnUserHistory_processResponse(Response))); client->sendCommand(pend); } diff --git a/cockatrice/src/user_context_menu.h b/cockatrice/src/user_context_menu.h index 442fd067..894ba617 100644 --- a/cockatrice/src/user_context_menu.h +++ b/cockatrice/src/user_context_menu.h @@ -1,8 +1,8 @@ #ifndef USER_CONTEXT_MENU_H #define USER_CONTEXT_MENU_H -#include #include "user_level.h" +#include class QAction; class TabSupervisor; @@ -13,13 +13,14 @@ class Response; class AbstractClient; class ServerInfo_User; -class UserContextMenu : public QObject { +class UserContextMenu : public QObject +{ Q_OBJECT private: AbstractClient *client; const TabSupervisor *tabSupervisor; TabGame *game; - + QAction *aUserName; QAction *aDetails; QAction *aShowGames; @@ -42,10 +43,15 @@ private slots: void banUser_dialogFinished(); void warnUser_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, bool online = true, int playerId = -1); + void showContextMenu(const QPoint &pos, + const QString &userName, + UserLevelFlags userLevel, + bool online = true, + int playerId = -1); }; #endif diff --git a/cockatrice/src/userconnection_information.cpp b/cockatrice/src/userconnection_information.cpp index 558b8cc4..48b7f53b 100644 --- a/cockatrice/src/userconnection_information.cpp +++ b/cockatrice/src/userconnection_information.cpp @@ -6,29 +6,39 @@ UserConnection_Information::UserConnection_Information() { } -UserConnection_Information::UserConnection_Information(QString _saveName, QString _serverName, QString _portNum, QString _userName, QString _pass, bool _savePass) - : saveName(_saveName), server(_serverName), port(_portNum), username(_userName), password(_pass), savePassword(_savePass) +UserConnection_Information::UserConnection_Information(QString _saveName, + QString _serverName, + QString _portNum, + QString _userName, + QString _pass, + bool _savePass) + : saveName(_saveName), server(_serverName), port(_portNum), username(_userName), password(_pass), + savePassword(_savePass) { - } QMap UserConnection_Information::getServerInfo() { QMap serverList; - + int size = settingsCache->servers().getValue("totalServers", "server", "server_details").toInt() + 1; - for (int i = 0; i < size; i++) - { - QString saveName = settingsCache->servers().getValue(QString("saveName%1").arg(i), "server", "server_details").toString(); - QString serverName = settingsCache->servers().getValue(QString("server%1").arg(i), "server", "server_details").toString(); - QString portNum = settingsCache->servers().getValue(QString("port%1").arg(i), "server", "server_details").toString(); - QString userName = settingsCache->servers().getValue(QString("username%1").arg(i), "server", "server_details").toString(); - QString pass = settingsCache->servers().getValue(QString("password%1").arg(i), "server", "server_details").toString(); - bool savePass =settingsCache->servers().getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); + for (int i = 0; i < size; i++) { + QString saveName = + settingsCache->servers().getValue(QString("saveName%1").arg(i), "server", "server_details").toString(); + QString serverName = + settingsCache->servers().getValue(QString("server%1").arg(i), "server", "server_details").toString(); + QString portNum = + settingsCache->servers().getValue(QString("port%1").arg(i), "server", "server_details").toString(); + QString userName = + settingsCache->servers().getValue(QString("username%1").arg(i), "server", "server_details").toString(); + QString pass = + settingsCache->servers().getValue(QString("password%1").arg(i), "server", "server_details").toString(); + bool savePass = + settingsCache->servers().getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); UserConnection_Information userInfo(saveName, serverName, portNum, userName, pass, savePass); - serverList.insert(saveName, userInfo); + serverList.insert(saveName, userInfo); } return serverList; @@ -37,21 +47,26 @@ QMap UserConnection_Information::getServerI QStringList UserConnection_Information::getServerInfo(const QString &find) { QStringList server; - + int size = settingsCache->servers().getValue("totalServers", "server", "server_details").toInt() + 1; - for (int i = 0; i < size; i++) - { - QString saveName = settingsCache->servers().getValue(QString("saveName%1").arg(i), "server", "server_details").toString(); + for (int i = 0; i < size; i++) { + QString saveName = + settingsCache->servers().getValue(QString("saveName%1").arg(i), "server", "server_details").toString(); if (find != saveName) continue; - QString serverName = settingsCache->servers().getValue(QString("server%1").arg(i), "server", "server_details").toString(); - QString portNum = settingsCache->servers().getValue(QString("port%1").arg(i), "server", "server_details").toString(); - QString userName = settingsCache->servers().getValue(QString("username%1").arg(i), "server", "server_details").toString(); - QString pass = settingsCache->servers().getValue(QString("password%1").arg(i), "server", "server_details").toString(); - bool savePass =settingsCache->servers().getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); - + QString serverName = + settingsCache->servers().getValue(QString("server%1").arg(i), "server", "server_details").toString(); + QString portNum = + settingsCache->servers().getValue(QString("port%1").arg(i), "server", "server_details").toString(); + QString userName = + settingsCache->servers().getValue(QString("username%1").arg(i), "server", "server_details").toString(); + QString pass = + settingsCache->servers().getValue(QString("password%1").arg(i), "server", "server_details").toString(); + bool savePass = + settingsCache->servers().getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); + server.append(saveName); server.append(serverName); server.append(portNum); @@ -60,7 +75,7 @@ QStringList UserConnection_Information::getServerInfo(const QString &find) server.append(savePass ? "1" : "0"); break; } - + if (!server.size()) qDebug() << "There was a problem!"; diff --git a/cockatrice/src/userconnection_information.h b/cockatrice/src/userconnection_information.h index d3c7331d..1dbf0e4a 100644 --- a/cockatrice/src/userconnection_information.h +++ b/cockatrice/src/userconnection_information.h @@ -1,31 +1,50 @@ #ifndef USERCONNECTION_INFORMATION_H #define USERCONNECTION_INFORMATION_H -#include -#include -#include #include +#include +#include +#include #include -class UserConnection_Information { - private: - QString saveName; - QString server; - QString port; - QString username; - QString password; - bool savePassword; - - public: - UserConnection_Information(); - UserConnection_Information(QString, QString, QString, QString, QString, bool); - QString getSaveName() { return saveName; } - QString getServer() { return server; } - QString getPort() { return port; } - QString getUsername() { return username; } - QString getPassword() { return password; } - bool getSavePassword() { return savePassword; } - QMap getServerInfo(); - QStringList getServerInfo(const QString &find); +class UserConnection_Information +{ +private: + QString saveName; + QString server; + QString port; + QString username; + QString password; + bool savePassword; + +public: + UserConnection_Information(); + UserConnection_Information(QString, QString, QString, QString, QString, bool); + QString getSaveName() + { + return saveName; + } + QString getServer() + { + return server; + } + QString getPort() + { + return port; + } + QString getUsername() + { + return username; + } + QString getPassword() + { + return password; + } + bool getSavePassword() + { + return savePassword; + } + QMap getServerInfo(); + QStringList getServerInfo(const QString &find); }; #endif diff --git a/cockatrice/src/userinfobox.cpp b/cockatrice/src/userinfobox.cpp index 384a3f01..d4d22e76 100644 --- a/cockatrice/src/userinfobox.cpp +++ b/cockatrice/src/userinfobox.cpp @@ -1,19 +1,19 @@ #include "userinfobox.h" -#include "pixmapgenerator.h" #include "abstractclient.h" -#include "dlg_edit_user.h" -#include "dlg_edit_password.h" #include "dlg_edit_avatar.h" +#include "dlg_edit_password.h" +#include "dlg_edit_user.h" +#include "pixmapgenerator.h" -#include #include #include #include +#include #include -#include "pending_command.h" -#include "pb/session_commands.pb.h" #include "pb/response_get_user_info.pb.h" +#include "pb/session_commands.pb.h" +#include "pending_command.h" const qint64 SIXTY = 60; const qint64 HOURS_IN_A_DAY = 24; @@ -45,9 +45,8 @@ UserInfoBox::UserInfoBox(AbstractClient *_client, bool _editable, QWidget *paren mainLayout->addWidget(&accountAgeLabel2, 6, 2, 1, 1); mainLayout->setColumnStretch(2, 10); - if(editable) - { - QHBoxLayout * buttonsLayout = new QHBoxLayout; + if (editable) { + QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addWidget(&editButton); buttonsLayout->addWidget(&passwordButton); buttonsLayout->addWidget(&avatarButton); @@ -81,26 +80,25 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user) QPixmap avatarPixmap; const std::string bmp = user.avatar_bmp(); - if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) - avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel, false, QString::fromStdString(user.privlevel())); + if (!avatarPixmap.loadFromData((const uchar *)bmp.data(), bmp.size())) + avatarPixmap = + UserLevelPixmapGenerator::generatePixmap(64, userLevel, false, QString::fromStdString(user.privlevel())); avatarLabel.setPixmap(avatarPixmap.scaled(avatarLabel.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); nameLabel.setText(QString::fromStdString(user.name())); realNameLabel2.setText(QString::fromStdString(user.real_name())); QString country = QString::fromStdString(user.country()); - if (country.length() != 0) - { + if (country.length() != 0) { countryLabel2.setPixmap(CountryPixmapGenerator::generatePixmap(15, country)); countryLabel3.setText(QString("(%1)").arg(country.toUpper())); - } - else - { + } else { countryLabel2.setText(""); countryLabel3.setText(""); } - userLevelLabel2.setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel, false, QString::fromStdString(user.privlevel()))); + userLevelLabel2.setPixmap( + UserLevelPixmapGenerator::generatePixmap(15, userLevel, false, QString::fromStdString(user.privlevel()))); QString userLevelText; if (userLevel.testFlag(ServerInfo_User::IsAdmin)) userLevelText = tr("Administrator"); @@ -118,12 +116,13 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user) userLevelLabel3.setText(userLevelText); QString accountAgeString = tr("Unregistered user"); - if (userLevel.testFlag(ServerInfo_User::IsAdmin) || userLevel.testFlag(ServerInfo_User::IsModerator) || userLevel.testFlag(ServerInfo_User::IsRegistered)) { + if (userLevel.testFlag(ServerInfo_User::IsAdmin) || userLevel.testFlag(ServerInfo_User::IsModerator) || + userLevel.testFlag(ServerInfo_User::IsRegistered)) { if (user.accountage_secs() == 0) accountAgeString = tr("Unknown"); else { qint64 seconds = user.accountage_secs(); - qint64 minutes = seconds / SIXTY; + qint64 minutes = seconds / SIXTY; qint64 hours = minutes / SIXTY; qint64 days = hours / HOURS_IN_A_DAY; qint64 years = days / DAYS_IN_A_YEAR; @@ -151,7 +150,8 @@ void UserInfoBox::updateInfo(const QString &userName) cmd.set_user_name(userName.toStdString()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processResponse(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(processResponse(const Response &))); client->sendCommand(pend); } @@ -169,7 +169,8 @@ void UserInfoBox::actEdit() Command_GetUserInfo cmd; PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(actEditInternal(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(actEditInternal(const Response &))); client->sendCommand(pend); } @@ -184,17 +185,18 @@ void UserInfoBox::actEditInternal(const Response &r) QString realName = QString::fromStdString(user.real_name()); DlgEditUser dlg(this, email, country, realName); - if(!dlg.exec()) + if (!dlg.exec()) return; Command_AccountEdit cmd; cmd.set_real_name(dlg.getRealName().toStdString()); cmd.set_email(dlg.getEmail().toStdString()); - cmd.set_gender((ServerInfo_User_Gender) dlg.getGender()); + cmd.set_gender((ServerInfo_User_Gender)dlg.getGender()); cmd.set_country(dlg.getCountry().toStdString()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processEditResponse(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(processEditResponse(const Response &))); client->sendCommand(pend); } @@ -202,7 +204,7 @@ void UserInfoBox::actEditInternal(const Response &r) void UserInfoBox::actPassword() { DlgEditPassword dlg(this); - if(!dlg.exec()) + if (!dlg.exec()) return; Command_AccountPassword cmd; @@ -210,7 +212,8 @@ void UserInfoBox::actPassword() cmd.set_new_password(dlg.getNewPassword().toStdString()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processPasswordResponse(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(processPasswordResponse(const Response &))); client->sendCommand(pend); } @@ -218,14 +221,15 @@ void UserInfoBox::actPassword() void UserInfoBox::actAvatar() { DlgEditAvatar dlg(this); - if(!dlg.exec()) + if (!dlg.exec()) return; Command_AccountImage cmd; cmd.set_image(dlg.getImage().data(), dlg.getImage().size()); PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processAvatarResponse(const Response &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(processAvatarResponse(const Response &))); client->sendCommand(pend); } @@ -238,11 +242,13 @@ void UserInfoBox::processEditResponse(const Response &r) QMessageBox::information(this, tr("Information"), tr("User information updated.")); break; case Response::RespFunctionNotAllowed: - QMessageBox::critical(this, tr("Error"), tr("This server does not permit you to update your user informations.")); + QMessageBox::critical(this, tr("Error"), + tr("This server does not permit you to update your user informations.")); break; case Response::RespInternalError: default: - QMessageBox::critical(this, tr("Error"), tr("An error occured while trying to update your user informations.")); + QMessageBox::critical(this, tr("Error"), + tr("An error occured while trying to update your user informations.")); break; } } @@ -264,7 +270,8 @@ void UserInfoBox::processPasswordResponse(const Response &r) break; case Response::RespInternalError: default: - QMessageBox::critical(this, tr("Error"), tr("An error occured while trying to update your user informations.")); + QMessageBox::critical(this, tr("Error"), + tr("An error occured while trying to update your user informations.")); break; } } diff --git a/cockatrice/src/userinfobox.h b/cockatrice/src/userinfobox.h index b06fbd1c..6d93b69d 100644 --- a/cockatrice/src/userinfobox.h +++ b/cockatrice/src/userinfobox.h @@ -1,21 +1,22 @@ #ifndef USERINFOBOX_H #define USERINFOBOX_H -#include #include #include +#include class ServerInfo_User; class AbstractClient; class Response; -class UserInfoBox : public QWidget { +class UserInfoBox : public QWidget +{ Q_OBJECT private: AbstractClient *client; bool editable; - QLabel avatarLabel, nameLabel, realNameLabel1, realNameLabel2, countryLabel1, - countryLabel2, countryLabel3, userLevelLabel1, userLevelLabel2, userLevelLabel3, accountAgeLebel1, accountAgeLabel2; + QLabel avatarLabel, nameLabel, realNameLabel1, realNameLabel2, countryLabel1, countryLabel2, countryLabel3, + userLevelLabel1, userLevelLabel2, userLevelLabel3, accountAgeLebel1, accountAgeLabel2; QPushButton editButton, passwordButton, avatarButton; public: diff --git a/cockatrice/src/userlist.cpp b/cockatrice/src/userlist.cpp index 57958a94..4e5600bc 100644 --- a/cockatrice/src/userlist.cpp +++ b/cockatrice/src/userlist.cpp @@ -1,34 +1,33 @@ #include "userlist.h" -#include "tab_userlists.h" -#include "tab_supervisor.h" #include "abstractclient.h" -#include "pixmapgenerator.h" -#include "user_context_menu.h" #include "gameselector.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "pending_command.h" -#include "pb/session_commands.pb.h" #include "pb/moderator_commands.pb.h" #include "pb/response_get_games_of_user.pb.h" #include "pb/response_get_user_info.pb.h" +#include "pb/session_commands.pb.h" +#include "pending_command.h" +#include "pixmapgenerator.h" +#include "tab_supervisor.h" +#include "tab_userlists.h" +#include "user_context_menu.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) - : QDialog(parent) +BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) : QDialog(parent) { setAttribute(Qt::WA_DeleteOnClose); - + nameBanCheckBox = new QCheckBox(tr("ban &user name")); nameBanCheckBox->setChecked(true); nameBanEdit = new QLineEdit(QString::fromStdString(info.name())); @@ -50,7 +49,7 @@ BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) banTypeGrid->addWidget(idBanEdit, 2, 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); @@ -84,24 +83,26 @@ BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) 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.")); + + 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.")); + + 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); @@ -110,13 +111,12 @@ BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) vbox->addWidget(visibleReasonLabel); vbox->addWidget(visibleReasonEdit); vbox->addLayout(buttonLayout); - + setLayout(vbox); setWindowTitle(tr("Ban user from server")); } -WarningDialog::WarningDialog(const QString userName, const QString clientID, QWidget *parent) - : QDialog(parent) +WarningDialog::WarningDialog(const QString userName, const QString clientID, QWidget *parent) : QDialog(parent) { setAttribute(Qt::WA_DeleteOnClose); descriptionLabel = new QLabel(tr("Which warning would you like to send?")); @@ -148,12 +148,14 @@ WarningDialog::WarningDialog(const QString userName, const QString clientID, QWi void WarningDialog::okClicked() { if (nameWarning->text().simplified().isEmpty()) { - QMessageBox::critical(this, tr("Error"), tr("User name to send a warning to can not be blank, please specify a user to warn.")); + QMessageBox::critical(this, tr("Error"), + tr("User name to send a warning to can not be blank, please specify a user to warn.")); return; } if (warningOption->currentText().simplified().isEmpty()) { - QMessageBox::critical(this, tr("Error"), tr("Warning to use can not be blank, please select a valid warning to send.")); + QMessageBox::critical(this, tr("Error"), + tr("Warning to use can not be blank, please select a valid warning to send.")); return; } @@ -183,25 +185,31 @@ void WarningDialog::addWarningOption(const QString warning) void BanDialog::okClicked() { if (!nameBanCheckBox->isChecked() && !ipBanCheckBox->isChecked() && !idBanCheckBox->isChecked()) { - QMessageBox::critical(this, tr("Error"), tr("You have to select a name-based, IP-based, clientId based, or some combination of the three to place a ban.")); + QMessageBox::critical(this, tr("Error"), + tr("You have to select a name-based, IP-based, clientId based, or some combination of " + "the three to place a ban.")); return; } if (nameBanCheckBox->isChecked()) - if (nameBanEdit->text().simplified() == ""){ - QMessageBox::critical(this, tr("Error"), tr("You must have a value in the name ban when selecting the name ban checkbox.")); + if (nameBanEdit->text().simplified() == "") { + QMessageBox::critical(this, tr("Error"), + tr("You must have a value in the name ban when selecting the name ban checkbox.")); return; } if (ipBanCheckBox->isChecked()) - if (ipBanEdit->text().simplified() == ""){ - QMessageBox::critical(this, tr("Error"), tr("You must have a value in the ip ban when selecting the ip ban checkbox.")); + if (ipBanEdit->text().simplified() == "") { + QMessageBox::critical(this, tr("Error"), + tr("You must have a value in the ip ban when selecting the ip ban checkbox.")); return; } if (idBanCheckBox->isChecked()) - if (idBanEdit->text().simplified() == ""){ - QMessageBox::critical(this, tr("Error"), tr("You must have a value in the clientid ban when selecting the clientid ban checkbox.")); + if (idBanEdit->text().simplified() == "") { + QMessageBox::critical( + this, tr("Error"), + tr("You must have a value in the clientid ban when selecting the clientid ban checkbox.")); return; } @@ -235,7 +243,8 @@ QString BanDialog::getBanIP() const 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 @@ -248,12 +257,14 @@ QString BanDialog::getVisibleReason() const return visibleReasonEdit->toPlainText(); } -UserListItemDelegate::UserListItemDelegate(QObject *const parent) - : QStyledItemDelegate(parent) +UserListItemDelegate::UserListItemDelegate(QObject *const parent) : QStyledItemDelegate(parent) { } -bool UserListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) +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); @@ -265,8 +276,7 @@ bool UserListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, return QStyledItemDelegate::editorEvent(event, model, option, index); } -UserListTWI::UserListTWI(const ServerInfo_User &_userInfo) - : QTreeWidgetItem(Type) +UserListTWI::UserListTWI(const ServerInfo_User &_userInfo) : QTreeWidgetItem(Type) { setUserInfo(_userInfo); } @@ -276,7 +286,8 @@ void UserListTWI::setUserInfo(const ServerInfo_User &_userInfo) userInfo = _userInfo; setData(0, Qt::UserRole, userInfo.user_level()); - setIcon(0, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(userInfo.user_level()), false, QString::fromStdString(userInfo.privlevel())))); + setIcon(0, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(userInfo.user_level()), false, + QString::fromStdString(userInfo.privlevel())))); 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())); @@ -293,11 +304,11 @@ 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; } @@ -308,7 +319,7 @@ UserList::UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserL 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()->setSectionResizeMode(QHeaderView::ResizeToContents); @@ -318,12 +329,12 @@ UserList::UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserL 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(); } @@ -331,10 +342,18 @@ void UserList::retranslateUi() { userContextMenu->retranslateUi(); switch (type) { - case AllUsersList: titleStr = tr("Users connected to server: %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; + case AllUsersList: + titleStr = tr("Users connected to server: %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(); } @@ -368,7 +387,7 @@ bool UserList::deleteUser(const QString &userName) updateCount(); return true; } - + return false; } @@ -377,7 +396,7 @@ void UserList::setUserOnline(const QString &userName, bool online) UserListTWI *twi = users.value(userName); if (!twi) return; - + twi->setOnline(online); if (online) ++onlineCount; @@ -404,7 +423,8 @@ void UserList::showContextMenu(const QPoint &pos, const QModelIndex &index) const ServerInfo_User &userInfo = static_cast(userTree->topLevelItem(index.row()))->getUserInfo(); bool online = index.sibling(index.row(), 0).data(Qt::UserRole + 1).toBool(); - userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), online); + userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), + UserLevelFlags(userInfo.user_level()), online); } void UserList::sortItems() diff --git a/cockatrice/src/userlist.h b/cockatrice/src/userlist.h index ab9146dc..d4a2a398 100644 --- a/cockatrice/src/userlist.h +++ b/cockatrice/src/userlist.h @@ -1,13 +1,13 @@ #ifndef USERLIST_H #define USERLIST_H +#include "pb/moderator_commands.pb.h" +#include "user_level.h" +#include #include #include -#include -#include #include -#include "user_level.h" -#include "pb/moderator_commands.pb.h" +#include class QTreeWidget; class ServerInfo_User; @@ -22,7 +22,8 @@ class Response; class CommandContainer; class UserContextMenu; -class BanDialog : public QDialog { +class BanDialog : public QDialog +{ Q_OBJECT private: QLabel *daysLabel, *hoursLabel, *minutesLabel; @@ -34,6 +35,7 @@ private: private slots: void okClicked(); void enableTemporaryEdits(bool enabled); + public: BanDialog(const ServerInfo_User &info, QWidget *parent = 0); QString getBanName() const; @@ -44,15 +46,17 @@ public: QString getVisibleReason() const; }; -class WarningDialog : public QDialog { +class WarningDialog : public QDialog +{ Q_OBJECT private: QLabel *descriptionLabel; QLineEdit *nameWarning; QComboBox *warningOption; - QLineEdit * warnClientID; + QLineEdit *warnClientID; private slots: void okClicked(); + public: WarningDialog(const QString userName, const QString clientID, QWidget *parent = 0); QString getName() const; @@ -61,27 +65,42 @@ public: void addWarningOption(const QString warning); }; -class UserListItemDelegate : public QStyledItemDelegate { +class UserListItemDelegate : public QStyledItemDelegate +{ public: UserListItemDelegate(QObject *const parent); - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); + bool + editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; -class UserListTWI : public QTreeWidgetItem { +class UserListTWI : public QTreeWidgetItem +{ private: ServerInfo_User userInfo; + public: UserListTWI(const ServerInfo_User &_userInfo); - const ServerInfo_User &getUserInfo() const { return 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 { +class UserList : public QGroupBox +{ Q_OBJECT public: - enum UserListType { AllUsersList, RoomList, BuddyList, IgnoreList }; + enum UserListType + { + AllUsersList, + RoomList, + BuddyList, + IgnoreList + }; + private: QMap users; TabSupervisor *tabSupervisor; @@ -101,13 +120,17 @@ signals: 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; } + const QMap &getUsers() const + { + return users; + } void showContextMenu(const QPoint &pos, const QModelIndex &index); void sortItems(); }; diff --git a/cockatrice/src/window_main.cpp b/cockatrice/src/window_main.cpp index 8cb32e4d..02a7a1dd 100644 --- a/cockatrice/src/window_main.cpp +++ b/cockatrice/src/window_main.cpp @@ -17,49 +17,49 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include #include +#include #include -#include -#include -#include -#include +#include #include #include -#include -#include +#include +#include +#include +#include +#include #include -#include -#include +#include #include +#include -#include "main.h" -#include "window_main.h" +#include "carddatabase.h" #include "dlg_connect.h" +#include "dlg_edit_tokens.h" +#include "dlg_forgotpasswordchallenge.h" #include "dlg_forgotpasswordrequest.h" #include "dlg_forgotpasswordreset.h" -#include "dlg_forgotpasswordchallenge.h" #include "dlg_register.h" #include "dlg_settings.h" #include "dlg_update.h" #include "dlg_viewlog.h" -#include "tab_supervisor.h" -#include "remoteclient.h" +#include "localclient.h" #include "localserver.h" #include "localserverinterface.h" -#include "localclient.h" #include "logger.h" +#include "main.h" +#include "remoteclient.h" #include "settingscache.h" #include "tab_game.h" +#include "tab_supervisor.h" #include "version_string.h" -#include "carddatabase.h" +#include "window_main.h" #include "window_sets.h" -#include "dlg_edit_tokens.h" -#include "pb/game_replay.pb.h" -#include "pb/room_commands.pb.h" #include "pb/event_connection_closed.pb.h" #include "pb/event_server_shutdown.pb.h" +#include "pb/game_replay.pb.h" +#include "pb/room_commands.pb.h" #define GITHUB_PAGES_URL "https://cockatrice.github.io" #define GITHUB_CONTRIBUTORS_URL "https://github.com/Cockatrice/Cockatrice/graphs/contributors?type=c" @@ -71,9 +71,8 @@ #define GITHUB_FAQ_URL "https://github.com/Cockatrice/Cockatrice/wiki/Frequently-Asked-Questions" const QString MainWindow::appName = "Cockatrice"; -const QStringList MainWindow::fileNameFilters = QStringList() - << QObject::tr("Cockatrice card database (*.xml)") - << QObject::tr("All files (*.*)"); +const QStringList MainWindow::fileNameFilters = QStringList() << QObject::tr("Cockatrice card database (*.xml)") + << QObject::tr("All files (*.*)"); void MainWindow::updateTabMenu(const QList &newMenuList) { @@ -89,29 +88,45 @@ void MainWindow::processConnectionClosedEvent(const Event_ConnectionClosed &even client->disconnectFromServer(); QString reasonStr; switch (event.reason()) { - case Event_ConnectionClosed::USER_LIMIT_REACHED: reasonStr = tr("The server has reached its maximum user capacity, please check back later."); break; - case Event_ConnectionClosed::TOO_MANY_CONNECTIONS: reasonStr = tr("There are too many concurrent connections from your address."); break; + case Event_ConnectionClosed::USER_LIMIT_REACHED: + reasonStr = tr("The server has reached its maximum user capacity, please check back later."); + break; + 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())); + 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; - case Event_ConnectionClosed::LOGGEDINELSEWERE: reasonStr = tr("You have been logged out due to logging in at another location."); break; - default: reasonStr = QString::fromStdString(event.reason_str()); + case Event_ConnectionClosed::SERVER_SHUTDOWN: + reasonStr = tr("Scheduled server shutdown."); + break; + case Event_ConnectionClosed::USERNAMEINVALID: + reasonStr = tr("Invalid username."); + break; + case Event_ConnectionClosed::LOGGEDINELSEWERE: + reasonStr = tr("You have been logged out due to logging in at another location."); + 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)); + QMessageBox::critical(this, tr("Connection closed"), + tr("The server has terminated your connection.\nReason: %1").arg(reasonStr)); } void MainWindow::processServerShutdownEvent(const Event_ServerShutdown &event) { - serverShutdownMessageBox.setInformativeText(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()))); + serverShutdownMessageBox.setInformativeText(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()))); serverShutdownMessageBox.setIconPixmap(QPixmap("theme:cockatrice").scaled(64, 64)); serverShutdownMessageBox.setText(tr("Scheduled server shutdown")); serverShutdownMessageBox.setWindowModality(Qt::ApplicationModal); @@ -170,24 +185,17 @@ void MainWindow::actConnect() auto *dlg = new DlgConnect(this); connect(dlg, SIGNAL(sigStartForgotPasswordRequest()), this, SLOT(actForgotPasswordRequest())); if (dlg->exec()) - client->connectToServer(dlg->getHost(), static_cast(dlg->getPort()), dlg->getPlayerName(), dlg->getPassword()); + client->connectToServer(dlg->getHost(), static_cast(dlg->getPort()), dlg->getPlayerName(), + dlg->getPassword()); } void MainWindow::actRegister() { DlgRegister dlg(this); - if (dlg.exec()) - { - client->registerToServer( - dlg.getHost(), - static_cast(dlg.getPort()), - dlg.getPlayerName(), - dlg.getPassword(), - dlg.getEmail(), - dlg.getGender(), - dlg.getCountry(), - dlg.getRealName() - ); + if (dlg.exec()) { + client->registerToServer(dlg.getHost(), static_cast(dlg.getPort()), dlg.getPlayerName(), + dlg.getPassword(), dlg.getEmail(), dlg.getGender(), dlg.getCountry(), + dlg.getRealName()); } } @@ -199,7 +207,8 @@ void MainWindow::actDisconnect() void MainWindow::actSinglePlayer() { bool ok; - int numberPlayers = QInputDialog::getInt(this, tr("Number of players"), tr("Please enter the number of players."), 1, 1, 8, 1, &ok); + int numberPlayers = + QInputDialog::getInt(this, tr("Number of players"), tr("Please enter the number of players."), 1, 1, 8, 1, &ok); if (!ok) return; @@ -215,7 +224,8 @@ void MainWindow::actSinglePlayer() for (int i = 0; i < numberPlayers - 1; ++i) { LocalServerInterface *slaveLsi = localServer->newConnection(); - LocalClient *slaveClient = new LocalClient(slaveLsi, tr("Player %1").arg(i + 2), settingsCache->getClientID(), this); + LocalClient *slaveClient = + new LocalClient(slaveLsi, tr("Player %1").arg(i + 2), settingsCache->getClientID(), this); localClients.append(slaveClient); } tabSupervisor->startLocal(localClients); @@ -282,24 +292,21 @@ void MainWindow::actExit() void MainWindow::actAbout() { - QMessageBox mb(QMessageBox::NoIcon, tr("About Cockatrice"), QString( - "Cockatrice (" + QString::fromStdString(BUILD_ARCHITECTURE) + ")
    " - + tr("Version") + QString(" %1").arg(VERSION_STRING) - + "

    " + tr("Cockatrice Webpage") + "
    " - + "

    " + tr("Project Manager:") + "
    Gavin Bisesi

    " - + "" + tr("Past Project Managers:") + "
    Max-Wilhelm Bruker
    Marcus Schütz

    " - + "" + tr("Developers:") + "
    " - + "" + tr("Our Developers") + "
    " - + "" + tr("Help Develop!") + "

    " - + "" + tr("Translators:") + "
    " - + "" + tr("Our Translators") + "
    " - + "" + tr("Help Translate!") + "

    " - + "" + tr("Support:") + "
    " - + "" + tr("Report an Issue") + "
    " - + "" + tr("Troubleshooting") + "
    " - + "" + tr("F.A.Q.") + "
    "), - QMessageBox::Ok, this - ); + QMessageBox mb( + QMessageBox::NoIcon, tr("About Cockatrice"), + QString("Cockatrice (" + QString::fromStdString(BUILD_ARCHITECTURE) + ")
    " + + tr("Version") + QString(" %1").arg(VERSION_STRING) + "

    " + + tr("Cockatrice Webpage") + "
    " + "

    " + tr("Project Manager:") + + "
    Gavin Bisesi

    " + "" + tr("Past Project Managers:") + + "
    Max-Wilhelm Bruker
    Marcus Schütz

    " + "" + tr("Developers:") + "
    " + + "" + tr("Our Developers") + "
    " + "" + tr("Help Develop!") + "

    " + "" + tr("Translators:") + + "
    " + "" + tr("Our Translators") + + "
    " + "" + tr("Help Translate!") + "

    " + + "" + tr("Support:") + "
    " + "" + tr("Report an Issue") + + "
    " + "" + tr("Troubleshooting") + "
    " + + "" + tr("F.A.Q.") + "
    "), + QMessageBox::Ok, this); mb.setIconPixmap(QPixmap("theme:cockatrice").scaled(64, 64)); mb.setTextInteractionFlags(Qt::TextBrowserInteraction); mb.exec(); @@ -328,14 +335,18 @@ void MainWindow::serverTimeout() actConnect(); } -void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime, QList missingFeatures) +void MainWindow::loginError(Response::ResponseCode r, + QString reasonStr, + quint32 endTime, + QList missingFeatures) { switch (r) { case Response::RespClientUpdateRequired: { QString formattedMissingFeatures; formattedMissingFeatures = "Missing Features: "; for (int i = 0; i < missingFeatures.size(); ++i) - formattedMissingFeatures.append(QString("\n %1").arg(QChar(0x2022)) + " " + missingFeatures.value(i) ); + formattedMissingFeatures.append(QString("\n %1").arg(QChar(0x2022)) + " " + + missingFeatures.value(i)); formattedMissingFeatures.append("\nTo update your client, go to Help -> Check for Updates."); QMessageBox msgBox; @@ -347,10 +358,14 @@ void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32 break; } case Response::RespWrongPassword: - QMessageBox::critical(this, tr("Error"), tr("Incorrect username or password. Please check your authentication information and try again.")); + QMessageBox::critical( + this, tr("Error"), + tr("Incorrect username or password. Please check your authentication information and try again.")); 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.")); + 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; @@ -369,21 +384,31 @@ void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32 break; } case Response::RespRegistrationRequired: - if (QMessageBox::question(this, tr("Error"), tr("This server requires user registration. Do you want to register now?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + if (QMessageBox::question(this, tr("Error"), + tr("This server requires user registration. Do you want to register now?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { actRegister(); } break; case Response::RespClientIdRequired: - QMessageBox::critical(this, tr("Error"), tr("This server requires client ID's. Your client is either failing to generate an ID or you are running a modified client.\nPlease close and reopen your client to try again.")); + QMessageBox::critical( + this, tr("Error"), + tr("This server requires client ID's. Your client is either failing to generate an ID or you are " + "running a modified client.\nPlease close and reopen your client to try again.")); break; case Response::RespContextError: - QMessageBox::critical(this, tr("Error"), tr("An internal error has occurred, please try closing and reopening your client and try again. If the error persists try updating your client to the most recent build and if need be contact your software provider.")); + QMessageBox::critical(this, tr("Error"), + tr("An internal error has occurred, please try closing and reopening your client and " + "try again. If the error persists try updating your client to the most recent " + "build and if need be contact your software provider.")); break; case Response::RespAccountNotActivated: { bool ok = false; - QString token = QInputDialog::getText(this, tr("Account activation"), tr("Your account has not been activated yet.\nYou need to provide the activation token received in the activation email."), QLineEdit::Normal, QString(), &ok); - if(ok && !token.isEmpty()) - { + QString token = QInputDialog::getText(this, tr("Account activation"), + tr("Your account has not been activated yet.\nYou need to provide " + "the activation token received in the activation email."), + QLineEdit::Normal, QString(), &ok); + if (ok && !token.isEmpty()) { client->activateToServer(token); return; } @@ -391,47 +416,55 @@ void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32 break; } case Response::RespServerFull: { - QMessageBox::critical(this, tr("Server Full"), tr("The server has reached its maximum user capacity, please check back later.")); + QMessageBox::critical(this, tr("Server Full"), + tr("The server has reached its maximum user capacity, please check back later.")); break; } default: - QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast(r)) + tr("\nThis usually means that your client version is out of date, and the server sent a reply your client doesn't understand.")); + QMessageBox::critical(this, tr("Error"), + tr("Unknown login error: %1").arg(static_cast(r)) + + tr("\nThis usually means that your client version is out of date, and the server " + "sent a reply your client doesn't understand.")); break; } actConnect(); } -QString MainWindow::extractInvalidUsernameMessage(QString & in) +QString MainWindow::extractInvalidUsernameMessage(QString &in) { QString out = tr("Invalid username.") + "
    "; QStringList rules = in.split(QChar('|')); - if (rules.size() == 7 || rules.size() == 9) - { + if (rules.size() == 7 || rules.size() == 9) { out += tr("Your username must respect these rules:") + "
      "; out += "
    • " + tr("is %1 - %2 characters long").arg(rules.at(0)).arg(rules.at(1)) + "
    • "; - out += "
    • " + tr("can %1 contain lowercase characters").arg((rules.at(2).toInt() > 0) ? "" : tr("NOT")) + "
    • "; - out += "
    • " + tr("can %1 contain uppercase characters").arg((rules.at(3).toInt() > 0) ? "" : tr("NOT")) + "
    • "; - out += "
    • " + tr("can %1 contain numeric characters").arg((rules.at(4).toInt() > 0) ? "" : tr("NOT")) + "
    • "; + out += "
    • " + tr("can %1 contain lowercase characters").arg((rules.at(2).toInt() > 0) ? "" : tr("NOT")) + + "
    • "; + out += "
    • " + tr("can %1 contain uppercase characters").arg((rules.at(3).toInt() > 0) ? "" : tr("NOT")) + + "
    • "; + out += + "
    • " + tr("can %1 contain numeric characters").arg((rules.at(4).toInt() > 0) ? "" : tr("NOT")) + "
    • "; if (rules.at(6).size() > 0) out += "
    • " + tr("can contain the following punctuation: %1").arg(rules.at(6).toHtmlEscaped()) + "
    • "; - out += "
    • " + tr("first character can %1 be a punctuation mark").arg((rules.at(5).toInt() > 0) ? "" : tr("NOT")) + "
    • "; + out += "
    • " + + tr("first character can %1 be a punctuation mark").arg((rules.at(5).toInt() > 0) ? "" : tr("NOT")) + + "
    • "; - if (rules.size() == 9) - { + if (rules.size() == 9) { if (rules.at(7).size() > 0) - out += "
    • " + tr("can not contain any of the following words: %1").arg(rules.at(7).toHtmlEscaped()) + "
    • "; + out += "
    • " + tr("can not contain any of the following words: %1").arg(rules.at(7).toHtmlEscaped()) + + "
    • "; if (rules.at(8).size() > 0) - out += "
    • " + tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) + "
    • "; + out += "
    • " + + tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) + + "
    • "; } out += "
    "; - } - else - { + } else { out += tr("You may only use A-Z, a-z, 0-9, _, ., and - in your username."); } @@ -442,19 +475,29 @@ void MainWindow::registerError(Response::ResponseCode r, QString reasonStr, quin { switch (r) { case Response::RespRegistrationDisabled: - QMessageBox::critical(this, tr("Registration denied"), tr("Registration is currently disabled on this server")); + QMessageBox::critical(this, tr("Registration denied"), + tr("Registration is currently disabled on this server")); break; case Response::RespUserAlreadyExists: - QMessageBox::critical(this, tr("Registration denied"), tr("There is already an existing account with the same user name.")); + QMessageBox::critical(this, tr("Registration denied"), + tr("There is already an existing account with the same user name.")); break; case Response::RespEmailRequiredToRegister: - QMessageBox::critical(this, tr("Registration denied"), tr("It's mandatory to specify a valid email address when registering.")); + QMessageBox::critical(this, tr("Registration denied"), + tr("It's mandatory to specify a valid email address when registering.")); break; case Response::RespEmailBlackListed: - QMessageBox::critical(this, tr("Registration denied"), tr("The email address provider used during registration has been blacklisted for use on this server.")); + QMessageBox::critical( + this, tr("Registration denied"), + tr("The email address provider used during registration has been blacklisted for use on this server.")); break; case Response::RespTooManyRequests: - QMessageBox::critical(this, tr("Registration denied"), tr("It appears you are attempting to register a new account on this server yet you already have an account registered with the email provided. This server restricts the number of accounts a user can register per address. Please contact the server operator for further assistance or to obtain your credential information.")); + QMessageBox::critical( + this, tr("Registration denied"), + tr("It appears you are attempting to register a new account on this server yet you already have an " + "account registered with the email provided. This server restricts the number of accounts a user " + "can register per address. Please contact the server operator for further assistance or to obtain " + "your credential information.")); break; case Response::RespPasswordTooShort: QMessageBox::critical(this, tr("Registration denied"), tr("Password too short.")); @@ -479,7 +522,10 @@ void MainWindow::registerError(Response::ResponseCode r, QString reasonStr, quin QMessageBox::critical(this, tr("Error"), tr("Registration failed for a technical problem on the server.")); break; default: - QMessageBox::critical(this, tr("Error"), tr("Unknown registration error: %1").arg(static_cast(r)) + tr("\nThis usually means that your client version is out of date, and the server sent a reply your client doesn't understand.")); + QMessageBox::critical(this, tr("Error"), + tr("Unknown registration error: %1").arg(static_cast(r)) + + tr("\nThis usually means that your client version is out of date, and the server " + "sent a reply your client doesn't understand.")); } actRegister(); } @@ -500,23 +546,55 @@ void MainWindow::socketError(const QString &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)); + 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)); + 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 StatusRegistering: setWindowTitle(appName + " - " + tr("Registering to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); 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(client->getUserName() + "@" + client->peerName()); break; - case StatusRequestingForgotPassword: setWindowTitle(appName + " - " + tr("Requesting forgot password to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); break; - case StatusSubmitForgotPasswordChallenge: setWindowTitle(appName + " - " + tr("Requesting forgot password to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); break; - case StatusSubmitForgotPasswordReset: setWindowTitle(appName + " - " + tr("Requesting forgot password to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); break; - default: setWindowTitle(appName); + case StatusConnecting: + setWindowTitle(appName + " - " + tr("Connecting to %1...").arg(client->peerName())); + break; + case StatusRegistering: + setWindowTitle(appName + " - " + + tr("Registering to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); + 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(client->getUserName() + "@" + client->peerName()); + break; + case StatusRequestingForgotPassword: + setWindowTitle( + appName + " - " + + tr("Requesting forgot password to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); + break; + case StatusSubmitForgotPasswordChallenge: + setWindowTitle( + appName + " - " + + tr("Requesting forgot password to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); + break; + case StatusSubmitForgotPasswordReset: + setWindowTitle( + appName + " - " + + tr("Requesting forgot password to %1 as %2...").arg(client->peerName()).arg(client->getUserName())); + break; + default: + setWindowTitle(appName); } } @@ -535,7 +613,7 @@ void MainWindow::retranslateUi() aSettings->setIcon(QPixmap("theme:icons/settings")); aExit->setText(tr("&Exit")); -#if defined(__APPLE__) /* For OSX */ +#if defined(__APPLE__) /* For OSX */ cockatriceMenu->setTitle(tr("A&ctions")); #else cockatriceMenu->setTitle(tr("&Cockatrice")); @@ -604,19 +682,19 @@ void MainWindow::createActions() aEditTokens = new QAction(QString(), this); connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens())); -#if defined(__APPLE__) /* For OSX */ +#if defined(__APPLE__) /* For OSX */ aSettings->setMenuRole(QAction::PreferencesRole); aExit->setMenuRole(QAction::QuitRole); aAbout->setMenuRole(QAction::AboutRole); - char const * foo; // avoid "warning: expression result unused" under clang - foo = QT_TRANSLATE_NOOP("QMenuBar","Services"); - foo = QT_TRANSLATE_NOOP("QMenuBar","Hide %1"); - foo = QT_TRANSLATE_NOOP("QMenuBar","Hide Others"); - foo = QT_TRANSLATE_NOOP("QMenuBar","Show All"); - foo = QT_TRANSLATE_NOOP("QMenuBar","Preferences..."); - foo = QT_TRANSLATE_NOOP("QMenuBar","Quit %1"); - foo = QT_TRANSLATE_NOOP("QMenuBar","About %1"); + char const *foo; // avoid "warning: expression result unused" under clang + foo = QT_TRANSLATE_NOOP("QMenuBar", "Services"); + foo = QT_TRANSLATE_NOOP("QMenuBar", "Hide %1"); + foo = QT_TRANSLATE_NOOP("QMenuBar", "Hide Others"); + foo = QT_TRANSLATE_NOOP("QMenuBar", "Show All"); + foo = QT_TRANSLATE_NOOP("QMenuBar", "Preferences..."); + foo = QT_TRANSLATE_NOOP("QMenuBar", "Quit %1"); + foo = QT_TRANSLATE_NOOP("QMenuBar", "About %1"); #endif } @@ -656,24 +734,30 @@ void MainWindow::createMenus() } MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), localServer(nullptr), bHasActivated(false), cardUpdateProcess(nullptr), logviewDialog(nullptr) + : QMainWindow(parent), localServer(nullptr), bHasActivated(false), cardUpdateProcess(nullptr), + logviewDialog(nullptr) { connect(settingsCache, SIGNAL(pixmapCacheSizeChanged(int)), this, SLOT(pixmapCacheSizeChanged(int))); pixmapCacheSizeChanged(settingsCache->getPixmapCacheSize()); 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, QList)), this, SLOT(loginError(Response::ResponseCode, QString, quint32, QList))); + 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, QList)), this, + SLOT(loginError(Response::ResponseCode, QString, quint32, QList))); 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); + connect(client, SIGNAL(userInfoChanged(const ServerInfo_User &)), this, + SLOT(userInfoReceived(const ServerInfo_User &)), Qt::BlockingQueuedConnection); connect(client, SIGNAL(notifyUserAboutUpdate()), this, SLOT(notifyUserAboutUpdate())); connect(client, SIGNAL(registerAccepted()), this, SLOT(registerAccepted())); connect(client, SIGNAL(registerAcceptedNeedsActivate()), this, SLOT(registerAcceptedNeedsActivate())); - connect(client, SIGNAL(registerError(Response::ResponseCode, QString, quint32)), this, SLOT(registerError(Response::ResponseCode, QString, quint32))); + connect(client, SIGNAL(registerError(Response::ResponseCode, QString, quint32)), this, + SLOT(registerError(Response::ResponseCode, QString, quint32))); connect(client, SIGNAL(activateAccepted()), this, SLOT(activateAccepted())); connect(client, SIGNAL(activateError()), this, SLOT(activateError())); connect(client, SIGNAL(sigForgotPasswordSuccess()), this, SLOT(forgotPasswordSuccess())); @@ -707,15 +791,15 @@ MainWindow::MainWindow(QWidget *parent) createTrayIcon(); } - connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); + connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts())); refreshShortcuts(); connect(db, SIGNAL(cardDatabaseLoadingFailed()), this, SLOT(cardDatabaseLoadingFailed())); - connect(db, SIGNAL(cardDatabaseNewSetsFound(int, QStringList)), this, SLOT(cardDatabaseNewSetsFound(int, QStringList))); + connect(db, SIGNAL(cardDatabaseNewSetsFound(int, QStringList)), this, + SLOT(cardDatabaseNewSetsFound(int, QStringList))); connect(db, SIGNAL(cardDatabaseAllNewSetsEnabled()), this, SLOT(cardDatabaseAllNewSetsEnabled())); - if (! settingsCache->getDownloadSpoilersStatus()) - { + if (!settingsCache->getDownloadSpoilersStatus()) { qDebug() << "Spoilers Disabled"; QtConcurrent::run(db, &CardDatabase::loadCardDatabases); } @@ -732,7 +816,8 @@ MainWindow::~MainWindow() clientThread->wait(); } -void MainWindow::createTrayIcon() { +void MainWindow::createTrayIcon() +{ auto *trayIconMenu = new QMenu(this); trayIconMenu->addAction(closeAction); @@ -741,11 +826,12 @@ void MainWindow::createTrayIcon() { trayIcon->setIcon(QPixmap("theme:cockatrice")); trayIcon->show(); - connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this, - SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); + connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, + SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); } -void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) { +void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) +{ if (reason == QSystemTrayIcon::DoubleClick) { if (windowState() != Qt::WindowMinimized && windowState() != Qt::WindowMinimized + Qt::WindowMaximized) showMinimized(); @@ -760,28 +846,27 @@ void MainWindow::promptForgotPasswordChallenge() { DlgForgotPasswordChallenge dlg(this); if (dlg.exec()) - client->submitForgotPasswordChallengeToServer(dlg.getHost(), static_cast(dlg.getPort()), dlg.getPlayerName(), dlg.getEmail()); + client->submitForgotPasswordChallengeToServer(dlg.getHost(), static_cast(dlg.getPort()), + dlg.getPlayerName(), dlg.getEmail()); } - -void MainWindow::createTrayActions() { +void MainWindow::createTrayActions() +{ closeAction = new QAction(tr("&Exit"), this); connect(closeAction, SIGNAL(triggered()), this, SLOT(close())); } - void MainWindow::closeEvent(QCloseEvent *event) { // workaround Qt bug where closeEvent gets called twice - static bool bClosingDown=false; - if(bClosingDown) + static bool bClosingDown = false; + if (bClosingDown) return; - bClosingDown=true; + bClosingDown = true; - if (!tabSupervisor->closeRequest()) - { + if (!tabSupervisor->closeRequest()) { event->ignore(); - bClosingDown=false; + bClosingDown = false; return; } @@ -794,13 +879,14 @@ void MainWindow::changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) retranslateUi(); - else if(event->type() == QEvent::ActivationChange) { - if(isActiveWindow() && !bHasActivated){ + else if (event->type() == QEvent::ActivationChange) { + if (isActiveWindow() && !bHasActivated) { bHasActivated = true; - if(settingsCache->servers().getAutoConnect()) { + if (settingsCache->servers().getAutoConnect()) { qDebug() << "Attempting auto-connect..."; - DlgConnect dlg(this); - client->connectToServer(dlg.getHost(), static_cast(dlg.getPort()), dlg.getPlayerName(), dlg.getPassword()); + DlgConnect dlg(this); + client->connectToServer(dlg.getHost(), static_cast(dlg.getPort()), dlg.getPlayerName(), + dlg.getPassword()); } } } @@ -810,12 +896,13 @@ void MainWindow::changeEvent(QEvent *event) void MainWindow::pixmapCacheSizeChanged(int newSizeInMBs) { - //qDebug() << "Setting pixmap cache size to " << value << " MBs"; + // qDebug() << "Setting pixmap cache size to " << value << " MBs"; // translate MBs to KBs QPixmapCache::setCacheLimit(newSizeInMBs * 1024); } -void MainWindow::showWindowIfHidden() { +void MainWindow::showWindowIfHidden() +{ // keep the previous window state setWindowState(windowState() & ~Qt::WindowMinimized); show(); @@ -827,8 +914,8 @@ void MainWindow::cardDatabaseLoadingFailed() msgBox.setWindowTitle(tr("Card database")); msgBox.setIcon(QMessageBox::Question); msgBox.setText(tr("Cockatrice is unable to load the card database.\n" - "Do you want to update your card database now?\n" - "If unsure or first time user, choose \"Yes\"")); + "Do you want to update your card database now?\n" + "If unsure or first time user, choose \"Yes\"")); QPushButton *yesButton = msgBox.addButton(tr("Yes"), QMessageBox::YesRole); msgBox.addButton(tr("No"), QMessageBox::NoRole); @@ -849,11 +936,11 @@ void MainWindow::cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknow QMessageBox msgBox; msgBox.setWindowTitle(tr("New sets found")); msgBox.setIcon(QMessageBox::Question); - msgBox.setText( - tr("%1 new set(s) found in the card database\n" - "Set code(s): %2\n" - "Do you want to enable it/them?" - ).arg(numUnknownSets).arg(unknownSetsNames.join(", "))); + msgBox.setText(tr("%1 new set(s) found in the card database\n" + "Set code(s): %2\n" + "Do you want to enable it/them?") + .arg(numUnknownSets) + .arg(unknownSetsNames.join(", "))); QPushButton *yesButton = msgBox.addButton(tr("Yes"), QMessageBox::YesRole); QPushButton *noButton = msgBox.addButton(tr("No"), QMessageBox::NoRole); @@ -862,17 +949,12 @@ void MainWindow::cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknow msgBox.exec(); - if (msgBox.clickedButton() == yesButton) - { + if (msgBox.clickedButton() == yesButton) { db->enableAllUnknownSets(); QtConcurrent::run(db, &CardDatabase::loadCardDatabases); - } - else if (msgBox.clickedButton() == noButton) - { + } else if (msgBox.clickedButton() == noButton) { db->markAllSetsAsKnown(); - } - else if (msgBox.clickedButton() == settingsButton) - { + } else if (msgBox.clickedButton() == settingsButton) { db->markAllSetsAsKnown(); actManageSets(); } @@ -880,22 +962,27 @@ void MainWindow::cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknow void MainWindow::cardDatabaseAllNewSetsEnabled() { - QMessageBox::information(this, tr("Welcome"), tr("Hi! It seems like you're running this version of Cockatrice for the first time.\nAll the sets in the card database have been enabled.\nRead more about changing the set order or disabling specific sets and consequent effects in the \"Manage Sets\" dialog.")); + QMessageBox::information( + this, tr("Welcome"), + tr("Hi! It seems like you're running this version of Cockatrice for the first time.\nAll the sets in the card " + "database have been enabled.\nRead more about changing the set order or disabling specific sets and " + "consequent effects in the \"Manage Sets\" dialog.")); actManageSets(); } /* CARD UPDATER */ void MainWindow::actCheckCardUpdates() { - if (cardUpdateProcess) - { + if (cardUpdateProcess) { QMessageBox::information(this, tr("Information"), tr("A card database update is already running.")); return; } cardUpdateProcess = new QProcess(this); - connect(cardUpdateProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(cardUpdateError(QProcess::ProcessError))); - connect(cardUpdateProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(cardUpdateFinished(int, QProcess::ExitStatus))); + connect(cardUpdateProcess, SIGNAL(error(QProcess::ProcessError)), this, + SLOT(cardUpdateError(QProcess::ProcessError))); + connect(cardUpdateProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, + SLOT(cardUpdateFinished(int, QProcess::ExitStatus))); // full "run the update" command; leave empty if not present QString updaterCmd; @@ -918,12 +1005,12 @@ void MainWindow::actCheckCardUpdates() binaryName = getCardUpdaterBinaryName(); #endif - if(dir.exists(binaryName)) + if (dir.exists(binaryName)) updaterCmd = dir.absoluteFilePath(binaryName); - if(updaterCmd.isEmpty()) - { - QMessageBox::warning(this, tr("Error"), tr("Unable to run the card database updater: ") + dir.absoluteFilePath(binaryName)); + if (updaterCmd.isEmpty()) { + QMessageBox::warning(this, tr("Error"), + tr("Unable to run the card database updater: ") + dir.absoluteFilePath(binaryName)); return; } @@ -933,8 +1020,7 @@ void MainWindow::actCheckCardUpdates() void MainWindow::cardUpdateError(QProcess::ProcessError err) { QString error; - switch(err) - { + switch (err) { case QProcess::FailedToStart: error = tr("failed to start."); break; @@ -967,7 +1053,8 @@ void MainWindow::cardUpdateFinished(int, QProcess::ExitStatus) cardUpdateProcess->deleteLater(); cardUpdateProcess = nullptr; - QMessageBox::information(this, tr("Information"), tr("Update completed successfully.\nCockatrice will now reload the card database.")); + QMessageBox::information(this, tr("Information"), + tr("Update completed successfully.\nCockatrice will now reload the card database.")); QtConcurrent::run(db, &CardDatabase::loadCardDatabases); } @@ -990,7 +1077,11 @@ void MainWindow::refreshShortcuts() void MainWindow::notifyUserAboutUpdate() { - QMessageBox::information(this, tr("Information"), tr("This server supports additional features that your client doesn't have.\nThis is most likely not a problem, but this message might mean there is a new version of Cockatrice available or this server is running a custom or pre-release version.\n\nTo update your client, go to Help -> Check for Updates.")); + QMessageBox::information( + this, tr("Information"), + tr("This server supports additional features that your client doesn't have.\nThis is most likely not a " + "problem, but this message might mean there is a new version of Cockatrice available or this server is " + "running a custom or pre-release version.\n\nTo update your client, go to Help -> Check for Updates.")); } void MainWindow::actOpenCustomFolder() @@ -1034,15 +1125,13 @@ void MainWindow::actAddCustomSet() { QFileDialog dialog(this, tr("Load sets/cards"), QDir::homePath()); dialog.setNameFilters(MainWindow::fileNameFilters); - if (!dialog.exec()) - { + if (!dialog.exec()) { return; } QString fullFilePath = dialog.selectedFiles().at(0); - if (!QFile::exists(fullFilePath)) - { + if (!QFile::exists(fullFilePath)) { QMessageBox::warning(this, tr("Load sets/cards"), tr("Selected file cannot be found.")); return; } @@ -1059,35 +1148,28 @@ void MainWindow::actAddCustomSet() bool res; QString fileName = QFileInfo(fullFilePath).fileName(); - if (fileName.compare("spoiler.xml", Qt::CaseInsensitive) == 0) - { + if (fileName.compare("spoiler.xml", Qt::CaseInsensitive) == 0) { /* * If the file being added is "spoiler.xml" * then we'll want to overwrite the old version * and replace it with the new one */ - if (QFile::exists(dir.absolutePath() + "/spoiler.xml")) - { + if (QFile::exists(dir.absolutePath() + "/spoiler.xml")) { QFile::remove(dir.absolutePath() + "/spoiler.xml"); } res = QFile::copy(fullFilePath, dir.absolutePath() + "/spoiler.xml"); - } - else - { - res = QFile::copy( - fullFilePath, - dir.absolutePath() + "/" + (nextPrefix > 9 ? "" : "0") + QString::number(nextPrefix) + "." + fileName - ); + } else { + res = QFile::copy(fullFilePath, dir.absolutePath() + "/" + (nextPrefix > 9 ? "" : "0") + + QString::number(nextPrefix) + "." + fileName); } - if (res) - { - QMessageBox::information(this, tr("Load sets/cards"), tr("The new sets/cards have been added successfully.\nCockatrice will now reload the card database.")); + if (res) { + QMessageBox::information( + this, tr("Load sets/cards"), + tr("The new sets/cards have been added successfully.\nCockatrice will now reload the card database.")); QtConcurrent::run(db, &CardDatabase::loadCardDatabases); - } - else - { + } else { QMessageBox::warning(this, tr("Load sets/cards"), tr("Sets/cards failed to import.")); } } @@ -1125,12 +1207,15 @@ void MainWindow::actForgotPasswordRequest() { DlgForgotPasswordRequest dlg(this); if (dlg.exec()) - client->requestForgotPasswordToServer(dlg.getHost(), static_cast(dlg.getPort()), dlg.getPlayerName()); + client->requestForgotPasswordToServer(dlg.getHost(), static_cast(dlg.getPort()), + dlg.getPlayerName()); } void MainWindow::forgotPasswordSuccess() { - QMessageBox::information(this, tr("Forgot Password"), tr("Your password has been reset successfully, you now may log in using the new credentials.")); + QMessageBox::information( + this, tr("Forgot Password"), + tr("Your password has been reset successfully, you now may log in using the new credentials.")); settingsCache->servers().setFPHostName(""); settingsCache->servers().setFPPort(""); settingsCache->servers().setFPPlayerName(""); @@ -1138,7 +1223,9 @@ void MainWindow::forgotPasswordSuccess() void MainWindow::forgotPasswordError() { - QMessageBox::warning(this, tr("Forgot Password"), tr("Failed to reset user account password, please contact the server operator to reset your password.")); + QMessageBox::warning( + this, tr("Forgot Password"), + tr("Failed to reset user account password, please contact the server operator to reset your password.")); settingsCache->servers().setFPHostName(""); settingsCache->servers().setFPPort(""); settingsCache->servers().setFPPlayerName(""); @@ -1146,10 +1233,10 @@ void MainWindow::forgotPasswordError() void MainWindow::promptForgotPasswordReset() { - QMessageBox::information(this, tr("Forgot Password"), tr("Activation request received, please check your email for an activation token.")); + QMessageBox::information(this, tr("Forgot Password"), + tr("Activation request received, please check your email for an activation token.")); DlgForgotPasswordReset dlg(this); - if (dlg.exec()) - { + if (dlg.exec()) { client->submitForgotPasswordResetToServer(dlg.getHost(), static_cast(dlg.getPort()), dlg.getPlayerName(), dlg.getToken(), dlg.getPassword()); } diff --git a/cockatrice/src/window_main.h b/cockatrice/src/window_main.h index 8212a063..44ffb716 100644 --- a/cockatrice/src/window_main.h +++ b/cockatrice/src/window_main.h @@ -22,9 +22,9 @@ #include #include -#include -#include #include +#include +#include #include #include "abstractclient.h" @@ -38,7 +38,8 @@ class ServerInfo_User; class QThread; class DlgViewLog; -class MainWindow : public QMainWindow { +class MainWindow : public QMainWindow +{ Q_OBJECT public slots: void actCheckCardUpdates(); @@ -93,6 +94,7 @@ private slots: void actManageSets(); void actEditTokens(); + private: static const QString appName; static const QStringList fileNameFilters; @@ -105,7 +107,10 @@ private: void createTrayActions(); int getNextCustomSetPrefix(QDir dataDir); // TODO: add a preference item to choose updater name for other games - inline QString getCardUpdaterBinaryName() { return "oracle"; }; + inline QString getCardUpdaterBinaryName() + { + return "oracle"; + }; QList tabMenus; QMenu *cockatriceMenu, *dbMenu, *helpMenu; @@ -120,21 +125,23 @@ private: RemoteClient *client; QThread *clientThread; - + LocalServer *localServer; bool bHasActivated; QMessageBox serverShutdownMessageBox; - QProcess * cardUpdateProcess; + QProcess *cardUpdateProcess; + + DlgViewLog *logviewDialog; - DlgViewLog * logviewDialog; public: MainWindow(QWidget *parent = 0); ~MainWindow(); + protected: void closeEvent(QCloseEvent *event); void changeEvent(QEvent *event); - QString extractInvalidUsernameMessage(QString & in); + QString extractInvalidUsernameMessage(QString &in); }; #endif diff --git a/cockatrice/src/window_sets.cpp b/cockatrice/src/window_sets.cpp index 9974fa88..f3c967bf 100644 --- a/cockatrice/src/window_sets.cpp +++ b/cockatrice/src/window_sets.cpp @@ -1,24 +1,23 @@ #include "window_sets.h" -#include "setsmodel.h" -#include "pictureloader.h" #include "main.h" +#include "pictureloader.h" +#include "setsmodel.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -WndSets::WndSets(QWidget *parent) - : QMainWindow(parent) +WndSets::WndSets(QWidget *parent) : QMainWindow(parent) { // left toolbar setsEditToolBar = new QToolBar; @@ -54,7 +53,7 @@ WndSets::WndSets(QWidget *parent) connect(aBottom, SIGNAL(triggered()), this, SLOT(actBottom())); setsEditToolBar->addAction(aBottom); - // view + // view model = new SetsModel(db, this); view = new QTreeView; view->setModel(model); @@ -90,20 +89,22 @@ WndSets::WndSets(QWidget *parent) connect(disableAllButton, SIGNAL(clicked()), this, SLOT(actDisableAll())); connect(enableSomeButton, SIGNAL(clicked()), this, SLOT(actEnableSome())); connect(disableSomeButton, SIGNAL(clicked()), this, SLOT(actDisableSome())); - connect(view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), - this, SLOT(actToggleButtons(const QItemSelection &, const QItemSelection &))); + connect(view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, + SLOT(actToggleButtons(const QItemSelection &, const QItemSelection &))); labNotes = new QLabel; labNotes->setWordWrap(true); labNotes->setTextInteractionFlags(Qt::TextBrowserInteraction); labNotes->setOpenExternalLinks(true); labNotes->setText( - "" + tr("Deck Editor") + ": " - + tr("Only cards in enabled sets will appear in the deck editor card list") - + "
    " + tr("Card Art") + ": " + tr("Image priority is decided in the following order") - + "
    1. " + tr("The") + " " - + tr("CUSTOM Folder") + "
    2. " + tr("Enabled Sets (Top to Bottom)") + "
    3. " + tr("Disabled Sets (Top to Bottom)") + "
    " - ); + "" + tr("Deck Editor") + ": " + + tr("Only cards in enabled sets will appear in the deck editor card list") + "
    " + tr("Card Art") + + ": " + tr("Image priority is decided in the following order") + "
    1. " + tr("The") + + " " + + tr("CUSTOM Folder") + "
    2. " + tr("Enabled Sets (Top to Bottom)") + "
    3. " + + tr("Disabled Sets (Top to Bottom)") + "
    "); buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(actSave())); @@ -141,8 +142,7 @@ void WndSets::rebuildMainLayout(int actionToTake) if (mainLayout == nullptr) return; - switch (actionToTake) - { + switch (actionToTake) { case NO_SETS_SELECTED: enableAllButton->show(); disableAllButton->show(); @@ -173,7 +173,7 @@ void WndSets::actRestore() close(); } -void WndSets::actToggleButtons(const QItemSelection & selected, const QItemSelection &) +void WndSets::actToggleButtons(const QItemSelection &selected, const QItemSelection &) { bool disabled = selected.empty(); aTop->setDisabled(disabled); @@ -183,24 +183,20 @@ void WndSets::actToggleButtons(const QItemSelection & selected, const QItemSelec int rows = view->selectionModel()->selectedRows().size(); rebuildMainLayout((rows > 1) ? SOME_SETS_SELECTED : NO_SETS_SELECTED); - } void WndSets::selectRows(QSet rows) { - foreach (int i, rows) - { + foreach (int i, rows) { QModelIndex idx = model->index(i, 0); view->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); view->scrollTo(idx, QAbstractItemView::EnsureVisible); } } - void WndSets::actEnableAll() { model->toggleAll(true); - } void WndSets::actDisableAll() @@ -212,16 +208,15 @@ void WndSets::actEnableSome() { QModelIndexList rows = view->selectionModel()->selectedRows(); - foreach(QModelIndex i, rows) + foreach (QModelIndex i, rows) model->toggleRow(i.row(), true); - } void WndSets::actDisableSome() { QModelIndexList rows = view->selectionModel()->selectedRows(); - foreach(QModelIndex i, rows) + foreach (QModelIndex i, rows) model->toggleRow(i.row(), false); } @@ -234,8 +229,7 @@ void WndSets::actUp() if (rows.empty()) return; - foreach (QModelIndex i, rows) - { + foreach (QModelIndex i, rows) { int oldRow = i.row(); int newRow = oldRow - 1; if (oldRow <= 0) @@ -257,8 +251,7 @@ void WndSets::actDown() if (rows.empty()) return; - foreach (QModelIndex i, rows) - { + foreach (QModelIndex i, rows) { int oldRow = i.row(); int newRow = oldRow + 1; if (oldRow >= model->rowCount() - 1) @@ -281,8 +274,7 @@ void WndSets::actTop() if (rows.empty()) return; - for (int i = 0; i < rows.length(); i++) - { + for (int i = 0; i < rows.length(); i++) { int oldRow = rows.at(i).row(); if (oldRow <= 0) { @@ -307,8 +299,7 @@ void WndSets::actBottom() if (rows.empty()) return; - for (int i = 0; i < rows.length(); i++) - { + for (int i = 0; i < rows.length(); i++) { int oldRow = rows.at(i).row(); if (oldRow >= newRow) { diff --git a/cockatrice/src/window_sets.h b/cockatrice/src/window_sets.h index fd8e0ca8..bf02428d 100644 --- a/cockatrice/src/window_sets.h +++ b/cockatrice/src/window_sets.h @@ -1,11 +1,11 @@ #ifndef WINDOW_SETS_H #define WINDOW_SETS_H +#include +#include +#include #include #include -#include -#include -#include class SetsModel; class SetsProxyModel; @@ -14,7 +14,8 @@ class CardDatabase; class QItemSelection; class QTreeView; -class WndSets : public QMainWindow { +class WndSets : public QMainWindow +{ Q_OBJECT private: SetsModel *model; @@ -27,10 +28,16 @@ private: QLabel *labNotes; QGridLayout *mainLayout; void rebuildMainLayout(int actionToTake); - enum {NO_SETS_SELECTED, SOME_SETS_SELECTED}; + enum + { + NO_SETS_SELECTED, + SOME_SETS_SELECTED + }; + public: WndSets(QWidget *parent = 0); ~WndSets(); + protected: void selectRows(QSet rows); private slots: @@ -44,7 +51,7 @@ private slots: void actDown(); void actTop(); void actBottom(); - void actToggleButtons(const QItemSelection & selected, const QItemSelection & deselected); + void actToggleButtons(const QItemSelection &selected, const QItemSelection &deselected); }; #endif diff --git a/cockatrice/src/zoneviewwidget.cpp b/cockatrice/src/zoneviewwidget.cpp index fa176f0a..dc8f5ba5 100644 --- a/cockatrice/src/zoneviewwidget.cpp +++ b/cockatrice/src/zoneviewwidget.cpp @@ -1,23 +1,28 @@ +#include "zoneviewwidget.h" +#include "carditem.h" +#include "gamescene.h" +#include "player.h" +#include "settingscache.h" +#include "zoneviewzone.h" +#include #include #include #include -#include #include #include #include #include #include -#include "zoneviewwidget.h" -#include "carditem.h" -#include "zoneviewzone.h" -#include "player.h" -#include "gamescene.h" -#include "settingscache.h" -#include "pb/command_stop_dump_zone.pb.h" #include "pb/command_shuffle.pb.h" +#include "pb/command_stop_dump_zone.pb.h" -ZoneViewWidget::ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards, bool _revealZone, bool _writeableRevealZone, const QList &cardList) +ZoneViewWidget::ZoneViewWidget(Player *_player, + CardZone *_origZone, + int numberCards, + bool _revealZone, + bool _writeableRevealZone, + const QList &cardList) : QGraphicsWidget(0, Qt::Window), canBeShuffled(_origZone->getIsShufflable()), player(_player) { setAcceptHoverEvents(true); @@ -85,7 +90,8 @@ ZoneViewWidget::ZoneViewWidget(Player *_player, CardZone *_origZone, int numberC vbox->addItem(zoneHBox); zone = new ZoneViewZone(player, _origZone, numberCards, _revealZone, _writeableRevealZone, zoneContainer); - connect(zone, SIGNAL(wheelEventReceived(QGraphicsSceneWheelEvent *)), this, SLOT(handleWheelEvent(QGraphicsSceneWheelEvent *))); + connect(zone, SIGNAL(wheelEventReceived(QGraphicsSceneWheelEvent *)), this, + SLOT(handleWheelEvent(QGraphicsSceneWheelEvent *))); // numberCard is the num of cards we want to reveal from an area. Ex: scry the top 3 cards. // If the number is < 0 then it means that we can make the area sorted and we dont care about the order. @@ -108,19 +114,22 @@ ZoneViewWidget::ZoneViewWidget(Player *_player, CardZone *_origZone, int numberC zone->initializeCards(cardList); } -void ZoneViewWidget::processSortByType(int value) { +void ZoneViewWidget::processSortByType(int value) +{ pileViewCheckBox.setEnabled(value); settingsCache->setZoneViewSortByType(value); zone->setPileView(pileViewCheckBox.isChecked()); zone->setSortByType(value); } -void ZoneViewWidget::processSortByName(int value) { +void ZoneViewWidget::processSortByName(int value) +{ settingsCache->setZoneViewSortByName(value); zone->setSortByName(value); } -void ZoneViewWidget::processSetPileView(int value) { +void ZoneViewWidget::processSetPileView(int value) +{ settingsCache->setZoneViewPileView(value); zone->setPileView(value); } @@ -136,32 +145,30 @@ void ZoneViewWidget::retranslateUi() void ZoneViewWidget::moveEvent(QGraphicsSceneMoveEvent * /* event */) { - if(!scene()) + if (!scene()) return; int titleBarHeight = 24; QPointF scenePos = pos(); - if(scenePos.x() < 0) - { + if (scenePos.x() < 0) { scenePos.setX(0); } else { qreal maxw = scene()->sceneRect().width() - 100; - if(scenePos.x() > maxw) + if (scenePos.x() > maxw) scenePos.setX(maxw); } - if(scenePos.y() < titleBarHeight) - { + if (scenePos.y() < titleBarHeight) { scenePos.setY(titleBarHeight); } else { qreal maxh = scene()->sceneRect().height() - titleBarHeight; - if(scenePos.y() > maxh) + if (scenePos.y() > maxh) scenePos.setY(maxh); } - if(scenePos != pos()) + if (scenePos != pos()) setPos(scenePos); } @@ -171,7 +178,9 @@ void ZoneViewWidget::resizeToZoneContents() 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); + QSizeF newSize(qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), + zoneRect.width() + scrollBar->width() + 10), + zoneRect.height() + extraHeight + 10); setMaximumSize(newSize); resize(newSize); @@ -215,7 +224,8 @@ void ZoneViewWidget::zoneDeleted() deleteLater(); } -void ZoneViewWidget::initStyleOption(QStyleOption *option) const { +void ZoneViewWidget::initStyleOption(QStyleOption *option) const +{ QStyleOptionTitleBar *titleBar = qstyleoption_cast(option); if (titleBar) titleBar->icon = QPixmap("theme:cockatrice"); diff --git a/cockatrice/src/zoneviewwidget.h b/cockatrice/src/zoneviewwidget.h index 744b3794..2a0dc6d4 100644 --- a/cockatrice/src/zoneviewwidget.h +++ b/cockatrice/src/zoneviewwidget.h @@ -1,8 +1,8 @@ #ifndef ZONEVIEWWIDGET_H #define ZONEVIEWWIDGET_H -#include #include +#include class QLabel; class QPushButton; @@ -18,7 +18,8 @@ class QGraphicsSceneMouseEvent; class QGraphicsSceneWheelEvent; class QStyleOption; -class ZoneViewWidget : public QGraphicsWidget { +class ZoneViewWidget : public QGraphicsWidget +{ Q_OBJECT private: ZoneViewZone *zone; @@ -30,7 +31,7 @@ private: QCheckBox sortByTypeCheckBox; QCheckBox shuffleCheckBox; QCheckBox pileViewCheckBox; - + bool canBeShuffled; int extraHeight; Player *player; @@ -45,10 +46,20 @@ private slots: void handleScrollBarChange(int value); void zoneDeleted(); void moveEvent(QGraphicsSceneMoveEvent * /* event */); + public: - ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards = 0, bool _revealZone = false, bool _writeableRevealZone = false, const QList &cardList = QList()); - ZoneViewZone *getZone() const { return zone; } + 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 initStyleOption(QStyleOption *option) const; diff --git a/cockatrice/src/zoneviewzone.cpp b/cockatrice/src/zoneviewzone.cpp index 4532875b..51d44513 100644 --- a/cockatrice/src/zoneviewzone.cpp +++ b/cockatrice/src/zoneviewzone.cpp @@ -1,21 +1,28 @@ -#include -#include -#include -#include -#include #include "zoneviewzone.h" -#include "player.h" +#include "carddatabase.h" #include "carddragitem.h" #include "carditem.h" -#include "carddatabase.h" #include "pb/command_dump_zone.pb.h" #include "pb/command_move_card.pb.h" -#include "pb/serverinfo_card.pb.h" #include "pb/response_dump_zone.pb.h" +#include "pb/serverinfo_card.pb.h" #include "pending_command.h" +#include "player.h" +#include +#include +#include +#include +#include -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) +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) { if (!(revealZone && !writeableRevealZone)) origZone->setView(this); @@ -34,9 +41,9 @@ QRectF ZoneViewZone::boundingRect() const return bRect; } -void ZoneViewZone::paint(QPainter * painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) +void ZoneViewZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush windowBrush(QColor(240,240,240)); + QBrush windowBrush(QColor(240, 240, 240)); windowBrush.setColor(windowBrush.color().darker(150)); painter->fillRect(boundingRect(), windowBrush); } @@ -45,16 +52,19 @@ void ZoneViewZone::initializeCards(const QList &cardLis { 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); + 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 &))); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, + SLOT(zoneDumpReceived(const Response &))); player->sendGameCommand(pend); } else { const CardList &c = origZone->getCards(); @@ -76,7 +86,7 @@ void ZoneViewZone::zoneDumpReceived(const Response &r) CardItem *card = new CardItem(player, QString::fromStdString(cardInfo.name()), cardInfo.id(), revealZone, this); addCard(card, false, i); } - + reorganizeCards(); } @@ -88,21 +98,21 @@ void ZoneViewZone::reorganizeCards() for (int i = 0; i < cardCount; ++i) cards[i]->setId(i); - int cols = floor(sqrt((double) cardCount / 2)); + int cols = floor(sqrt((double)cardCount / 2)); if (cols > 7) cols = 7; - int rows = ceil((double) cardCount / cols); + 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); + cols = ceil((double)cardCount / minRows); } if (cols < 2) cols = 2; - + qDebug() << "reorganizeCards: rows=" << rows << "cols=" << cols; CardList cardsToDisplay(cards); @@ -118,10 +128,10 @@ void ZoneViewZone::reorganizeCards() CardItem *c = cardsToDisplay.at(i); QString cardType = c->getInfo() ? c->getInfo()->getMainCardType() : ""; - if (i){ // if not the first card + if (i) { // if not the first card if (cardType == lastCardType) typeRow++; // add below current card - else { // if no match then move card to next column + else { // if no match then move card to next column typeColumn++; typeRow = 0; } @@ -143,11 +153,13 @@ void ZoneViewZone::reorganizeCards() c->setRealZValue(i); } } - + qreal aleft = 0; qreal atop = 0; - qreal awidth = (pileView && sortByType) ? qMax(typeColumn + 1, 3) * CARD_WIDTH + (CARD_WIDTH/2) : qMax(cols, 1) * CARD_WIDTH + (CARD_WIDTH/2); - qreal aheight = (pileView && sortByType) ? (longestRow * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3 : (rows * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3; + qreal awidth = (pileView && sortByType) ? qMax(typeColumn + 1, 3) * CARD_WIDTH + (CARD_WIDTH / 2) + : qMax(cols, 1) * CARD_WIDTH + (CARD_WIDTH / 2); + qreal aheight = (pileView && sortByType) ? (longestRow * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3 + : (rows * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3; optimumRect = QRectF(aleft, atop, awidth, aheight); updateGeometry(); @@ -168,7 +180,8 @@ void ZoneViewZone::setSortByType(int _sortByType) reorganizeCards(); } -void ZoneViewZone::setPileView(int _pileView) { +void ZoneViewZone::setPileView(int _pileView) +{ pileView = _pileView; reorganizeCards(); } @@ -180,7 +193,9 @@ void ZoneViewZone::addCardImpl(CardItem *card, int x, int /*y*/) card->update(); } -void ZoneViewZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) +void ZoneViewZone::handleDropEvent(const QList &dragItems, + CardZone *startZone, + const QPoint & /*dropPoint*/) { Command_MoveCard cmd; cmd.set_start_player_id(startZone->getPlayer()->getId()); @@ -189,7 +204,7 @@ void ZoneViewZone::handleDropEvent(const QList &dragItems, CardZ 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()); @@ -224,9 +239,8 @@ void ZoneViewZone::setWriteableRevealZone(bool _writeableRevealZone) origZone->setView(this); else if (!writeableRevealZone && _writeableRevealZone) origZone->setView(NULL); - + writeableRevealZone = _writeableRevealZone; - } void ZoneViewZone::wheelEvent(QGraphicsSceneWheelEvent *event) diff --git a/cockatrice/src/zoneviewzone.h b/cockatrice/src/zoneviewzone.h index 4c071589..c9394adf 100644 --- a/cockatrice/src/zoneviewzone.h +++ b/cockatrice/src/zoneviewzone.h @@ -9,7 +9,8 @@ class Response; class ServerInfo_Card; class QGraphicsSceneWheelEvent; -class ZoneViewZone : public SelectZone, public QGraphicsLayoutItem { +class ZoneViewZone : public SelectZone, public QGraphicsLayoutItem +{ Q_OBJECT Q_INTERFACES(QGraphicsLayoutItem) private: @@ -20,19 +21,37 @@ private: bool revealZone, writeableRevealZone; bool sortByName, sortByType; bool pileView; + public: - ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards = -1, bool _revealZone = false, bool _writeableRevealZone = false, QGraphicsItem *parent = 0); + 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; } + 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; } + 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); @@ -44,6 +63,7 @@ signals: 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; diff --git a/common/decklist.cpp b/common/decklist.cpp index 71ea5094..b100962d 100644 --- a/common/decklist.cpp +++ b/common/decklist.cpp @@ -1,8 +1,8 @@ -#include -#include +#include "decklist.h" #include #include -#include "decklist.h" +#include +#include SideboardPlan::SideboardPlan(const QString &_name, const QList &_moveList) : name(_name), moveList(_moveList) @@ -50,8 +50,7 @@ void SideboardPlan::write(QXmlStreamWriter *xml) { xml->writeStartElement("sideboard_plan"); xml->writeTextElement("name", name); - for (auto &i : moveList) - { + for (auto &i : moveList) { xml->writeStartElement("move_card_to_zone"); xml->writeTextElement("card_name", QString::fromStdString(i.card_name())); xml->writeTextElement("start_zone", QString::fromStdString(i.start_zone())); @@ -63,35 +62,28 @@ void SideboardPlan::write(QXmlStreamWriter *xml) AbstractDecklistNode::AbstractDecklistNode(InnerDecklistNode *_parent) : parent(_parent), sortMethod(Default) { - if (parent) - { + if (parent) { parent->append(this); } } int AbstractDecklistNode::depth() const { - if (parent) - { + if (parent) { return parent->depth() + 1; - } - else - { + } else { return 0; } } -InnerDecklistNode::InnerDecklistNode(InnerDecklistNode *other, InnerDecklistNode *_parent) : AbstractDecklistNode(_parent), name(other->getName()) +InnerDecklistNode::InnerDecklistNode(InnerDecklistNode *other, InnerDecklistNode *_parent) + : AbstractDecklistNode(_parent), name(other->getName()) { - for (int i = 0; i < other->size(); ++i) - { + for (int i = 0; i < other->size(); ++i) { auto *inner = dynamic_cast(other->at(i)); - if (inner) - { + if (inner) { new InnerDecklistNode(inner, this); - } - else - { + } else { new DecklistCardNode(dynamic_cast(other->at(i)), this); } } @@ -104,20 +96,13 @@ InnerDecklistNode::~InnerDecklistNode() QString InnerDecklistNode::visibleNameFromName(const QString &_name) { - if (_name == DECK_ZONE_MAIN) - { + if (_name == DECK_ZONE_MAIN) { return QObject::tr("Maindeck"); - } - else if (_name == DECK_ZONE_SIDE) - { + } else if (_name == DECK_ZONE_SIDE) { return QObject::tr("Sideboard"); - } - else if (_name == DECK_ZONE_TOKENS) - { + } else if (_name == DECK_ZONE_TOKENS) { return QObject::tr("Tokens"); - } - else - { + } else { return _name; } } @@ -125,8 +110,7 @@ QString InnerDecklistNode::visibleNameFromName(const QString &_name) void InnerDecklistNode::setSortMethod(DeckSortMethod method) { sortMethod = method; - for (int i = 0; i < size(); i++) - { + for (int i = 0; i < size(); i++) { at(i)->setSortMethod(method); } } @@ -143,17 +127,15 @@ void InnerDecklistNode::clearTree() clear(); } -DecklistCardNode::DecklistCardNode(DecklistCardNode *other, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), name(other->getName()), number(other->getNumber()) +DecklistCardNode::DecklistCardNode(DecklistCardNode *other, InnerDecklistNode *_parent) + : AbstractDecklistCardNode(_parent), name(other->getName()), number(other->getNumber()) { - } AbstractDecklistNode *InnerDecklistNode::findChild(const QString &name) { - for (int i = 0; i < size(); i++) - { - if (at(i)->getName() == name) - { + for (int i = 0; i < size(); i++) { + if (at(i)->getName() == name) { return at(i); } } @@ -168,20 +150,14 @@ int InnerDecklistNode::height() const int InnerDecklistNode::recursiveCount(bool countTotalCards) const { int result = 0; - for (int i = 0; i < size(); i++) - { + for (int i = 0; i < size(); i++) { auto *node = dynamic_cast(at(i)); - if (node) - { + if (node) { result += node->recursiveCount(countTotalCards); - } - else if (countTotalCards) - { + } else if (countTotalCards) { result += dynamic_cast(at(i))->getNumber(); - } - else - { + } else { result++; } } @@ -190,8 +166,7 @@ int InnerDecklistNode::recursiveCount(bool countTotalCards) const bool InnerDecklistNode::compare(AbstractDecklistNode *other) const { - switch (sortMethod) - { + switch (sortMethod) { case ByNumber: return compareNumber(other); case ByName: @@ -216,20 +191,16 @@ bool InnerDecklistNode::compareNumber(AbstractDecklistNode *other) const bool InnerDecklistNode::compareName(AbstractDecklistNode *other) const { auto *other2 = dynamic_cast(other); - if (other2) - { + if (other2) { return (getName() > other2->getName()); - } - else - { + } else { return false; } } bool AbstractDecklistCardNode::compare(AbstractDecklistNode *other) const { - switch (sortMethod) - { + switch (sortMethod) { case ByNumber: return compareNumber(other); case ByName: @@ -242,14 +213,11 @@ bool AbstractDecklistCardNode::compare(AbstractDecklistNode *other) const bool AbstractDecklistCardNode::compareNumber(AbstractDecklistNode *other) const { auto *other2 = dynamic_cast(other); - if (other2) - { + if (other2) { int n1 = getNumber(); int n2 = other2->getNumber(); return (n1 != n2) ? (n1 > n2) : compareName(other); - } - else - { + } else { return true; } } @@ -257,21 +225,22 @@ bool AbstractDecklistCardNode::compareNumber(AbstractDecklistNode *other) const bool AbstractDecklistCardNode::compareName(AbstractDecklistNode *other) const { auto *other2 = dynamic_cast(other); - if (other2) - { + if (other2) { return (getName() > other2->getName()); - } - else - { + } else { return true; } } -class InnerDecklistNode::compareFunctor { +class InnerDecklistNode::compareFunctor +{ private: Qt::SortOrder order; + public: - explicit compareFunctor(Qt::SortOrder _order) : order(_order) { } + explicit compareFunctor(Qt::SortOrder _order) : order(_order) + { + } inline bool operator()(QPair a, QPair b) const { return (order == Qt::AscendingOrder) ^ (a.second->compare(b.second)); @@ -288,7 +257,9 @@ bool InnerDecklistNode::readElement(QXmlStreamReader *xml) InnerDecklistNode *newZone = new InnerDecklistNode(xml->attributes().value("name").toString(), this); newZone->readElement(xml); } else if (childName == "card") { - DecklistCardNode *newCard = new DecklistCardNode(xml->attributes().value("name").toString(), xml->attributes().value("number").toString().toInt(), this); + DecklistCardNode *newCard = + new DecklistCardNode(xml->attributes().value("name").toString(), + xml->attributes().value("number").toString().toInt(), this); newCard->readElement(xml); } } else if (xml->isEndElement() && (childName == "zone")) @@ -323,12 +294,12 @@ void AbstractDecklistCardNode::writeElement(QXmlStreamWriter *xml) xml->writeAttribute("name", getName()); } -QVector > InnerDecklistNode::sort(Qt::SortOrder order) +QVector> InnerDecklistNode::sort(Qt::SortOrder order) { - QVector > result(size()); + QVector> result(size()); // Initialize temporary list with contents of current list - QVector > tempList(size()); + QVector> tempList(size()); for (int i = size() - 1; i >= 0; --i) { tempList[i].first = i; tempList[i].second = at(i); @@ -355,13 +326,13 @@ DeckList::DeckList() } // TODO: http://qt-project.org/doc/qt-4.8/qobject.html#no-copy-constructor-or-assignment-operator -DeckList::DeckList(const DeckList &other) : QObject(), name(other.name), comments(other.comments), deckHash(other.deckHash) +DeckList::DeckList(const DeckList &other) + : QObject(), name(other.name), comments(other.comments), deckHash(other.deckHash) { root = new InnerDecklistNode(other.getRoot()); QMapIterator spIterator(other.getSideboardPlans()); - while (spIterator.hasNext()) - { + while (spIterator.hasNext()) { spIterator.next(); sideboardPlans.insert(spIterator.key(), new SideboardPlan(spIterator.key(), spIterator.value()->getMoveList())); } @@ -511,8 +482,7 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) bool priorEntryIsBlank = true, isAtBeginning = true; int blankLines = 0; - while (!in.atEnd()) - { + while (!in.atEnd()) { QString line = in.readLine().simplified().toLower(); /* @@ -522,18 +492,14 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) * This will also concise multiple blank lines in a row to just one blank * Ex: ("Card1", "Card2", "", "", "", "Card3") => ("Card1", "Card2", "", "Card3") */ - if (line.isEmpty()) - { - if (priorEntryIsBlank || isAtBeginning) - { + if (line.isEmpty()) { + if (priorEntryIsBlank || isAtBeginning) { continue; } priorEntryIsBlank = true; blankLines++; - } - else - { + } else { isAtBeginning = false; priorEntryIsBlank = false; } @@ -547,32 +513,27 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) * NOTE: Any duplicates were taken care of above, so there can be * at most one blank line at the very end */ - if (!inputs.empty() && inputs.last().isEmpty()) - { + if (!inputs.empty() && inputs.last().isEmpty()) { blankLines--; inputs.erase(inputs.end() - 1); } // If "Sideboard" line appears in inputs, then blank lines mean nothing - if (inputs.contains("sideboard")) - { + if (inputs.contains("sideboard")) { blankLines = 2; } bool inSideboard = false, titleFound = false, isSideboard; int okRows = 0; - foreach(QString line, inputs) - { + foreach (QString line, inputs) { // This is a comment line, ignore it - if (line.startsWith("//")) - { + if (line.startsWith("//")) { if (!titleFound) // Set the title to the first comment { name = line.mid(2).trimmed(); titleFound = true; - } - else if (okRows == 0) // We haven't processed any cards yet + } else if (okRows == 0) // We haven't processed any cards yet { comments += line.mid(2).trimmed() + "\n"; } @@ -584,22 +545,19 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) // Then we assume it means to start the sideboard section of the paste. // If we have the word "Sideboard" appear on any line, then that will // also indicate the start of the sideboard. - if ((line.isEmpty() && blankLines == 1) || line.startsWith("sideboard")) - { + if ((line.isEmpty() && blankLines == 1) || line.startsWith("sideboard")) { inSideboard = true; continue; // The line isn't actually a card } isSideboard = inSideboard; - if (line.startsWith("sb:")) - { + if (line.startsWith("sb:")) { line = line.mid(3).trimmed(); isSideboard = true; } - if (line.trimmed().isEmpty()) - { + if (line.trimmed().isEmpty()) { continue; // The line was " " instead of "\n" } @@ -618,16 +576,12 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) int i = line.indexOf(' '); int cardNameStart = i + 1; - if (i > 0) - { + if (i > 0) { // If the count ends with an 'x', ignore it. For example, // "4x Storm Crow" will count 4 correctly. - if (line.at(i-1) == 'x') - { + if (line.at(i - 1) == 'x') { i--; - } - else if (! line.at(i-1).isDigit()) - { + } else if (!line.at(i - 1).isDigit()) { // If the user inputs "Quicksilver Elemental" then it will work as 1x of that card cardNameStart = 0; } @@ -636,14 +590,12 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) bool ok; int number = line.left(i).toInt(&ok); - if (!ok) - { + if (!ok) { number = 1; // If input is "cardName" assume it's "1x cardName" } QString cardName = line.mid(cardNameStart); - // Common differences between Cockatrice's card names // and what's commonly used in decklists rx.setPattern("’"); @@ -658,8 +610,7 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) // 'R&D' or 'R & D'. // Qt regexes don't support lookbehind so we capture and replace instead. rx.setPattern("([^A-Z])\\s*&\\s*"); - if (rx.indexIn(cardName) != -1) - { + if (rx.indexIn(cardName) != -1) { cardName.replace(rx, QString("%1 // ").arg(rx.cap(1))); } @@ -682,13 +633,11 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) return (okRows > 0); } -InnerDecklistNode * DeckList::getZoneObjFromName(const QString zoneName) +InnerDecklistNode *DeckList::getZoneObjFromName(const QString zoneName) { - for (int i = 0; i < root->size(); i++) - { + for (int i = 0; i < root->size(); i++) { auto *node = dynamic_cast(root->at(i)); - if (node->getName() == zoneName) - { + if (node->getName() == zoneName) { return node; } } @@ -702,37 +651,32 @@ bool DeckList::loadFromFile_Plain(QIODevice *device) return loadFromStream_Plain(in); } -struct WriteToStream { +struct WriteToStream +{ QTextStream &stream; bool prefixSideboardCards; bool slashTappedOutSplitCards; - WriteToStream(QTextStream &_stream, bool _prefixSideboardCards, bool _slashTappedOutSplitCards): stream(_stream), prefixSideboardCards(_prefixSideboardCards), slashTappedOutSplitCards(_slashTappedOutSplitCards) {} + WriteToStream(QTextStream &_stream, bool _prefixSideboardCards, bool _slashTappedOutSplitCards) + : stream(_stream), prefixSideboardCards(_prefixSideboardCards), + slashTappedOutSplitCards(_slashTappedOutSplitCards) + { + } - void operator()( - const InnerDecklistNode *node, - const DecklistCardNode *card - ) { - if (prefixSideboardCards && node->getName() == DECK_ZONE_SIDE) { - stream << "SB: "; - } - if (!slashTappedOutSplitCards) { - stream << QString("%1 %2\n").arg( - card->getNumber() - ).arg( - card->getName() - ); - } else { - stream << QString("%1 %2\n").arg( - card->getNumber() - ).arg( - card->getName().replace("//", "/") - ); - } + void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) + { + if (prefixSideboardCards && node->getName() == DECK_ZONE_SIDE) { + stream << "SB: "; + } + if (!slashTappedOutSplitCards) { + stream << QString("%1 %2\n").arg(card->getNumber()).arg(card->getName()); + } else { + stream << QString("%1 %2\n").arg(card->getNumber()).arg(card->getName().replace("//", "/")); + } } }; - bool DeckList::saveToStream_Plain(QTextStream &out, bool prefixSideboardCards, bool slashTappedOutSplitCards) +bool DeckList::saveToStream_Plain(QTextStream &out, bool prefixSideboardCards, bool slashTappedOutSplitCards) { WriteToStream writeToStream(out, prefixSideboardCards, slashTappedOutSplitCards); forEachCard(writeToStream); @@ -764,16 +708,12 @@ void DeckList::cleanList() void DeckList::getCardListHelper(InnerDecklistNode *item, QSet &result) const { - for (int i = 0; i < item->size(); ++i) - { + for (int i = 0; i < item->size(); ++i) { auto *node = dynamic_cast(item->at(i)); - if (node) - { + if (node) { result.insert(node->getName()); - } - else - { + } else { getCardListHelper(dynamic_cast(item->at(i)), result); } } @@ -789,16 +729,13 @@ QStringList DeckList::getCardList() const int DeckList::getSideboardSize() const { int size = 0; - for (int i = 0; i < root->size(); ++i) - { + for (int i = 0; i < root->size(); ++i) { auto *node = dynamic_cast(root->at(i)); - if (node->getName() != DECK_ZONE_SIDE) - { + if (node->getName() != DECK_ZONE_SIDE) { continue; } - for (int j = 0; j < node->size(); j++) - { + for (int j = 0; j < node->size(); j++) { auto *card = dynamic_cast(node->at(j)); size += card->getNumber(); } @@ -809,8 +746,7 @@ int DeckList::getSideboardSize() const DecklistCardNode *DeckList::addCard(const QString &cardName, const QString &zoneName) { auto *zoneNode = dynamic_cast(root->findChild(zoneName)); - if (zoneNode == nullptr) - { + if (zoneNode == nullptr) { zoneNode = new InnerDecklistNode(zoneName, root); } @@ -822,45 +758,36 @@ DecklistCardNode *DeckList::addCard(const QString &cardName, const QString &zone bool DeckList::deleteNode(AbstractDecklistNode *node, InnerDecklistNode *rootNode) { - if (node == root) - { + if (node == root) { return true; } bool updateHash = false; - if (rootNode == nullptr) - { + if (rootNode == nullptr) { rootNode = root; updateHash = true; } int index = rootNode->indexOf(node); - if (index != -1) - { + if (index != -1) { delete rootNode->takeAt(index); - if (rootNode->empty()) - { + if (rootNode->empty()) { deleteNode(rootNode, rootNode->getParent()); } - if (updateHash) - { + if (updateHash) { updateDeckHash(); } return true; } - for (int i = 0; i < rootNode->size(); i++) - { + for (int i = 0; i < rootNode->size(); i++) { auto *inner = dynamic_cast(rootNode->at(i)); - if (inner) - { - if (deleteNode(node, inner)) - { - if (updateHash) - { + if (inner) { + if (deleteNode(node, inner)) { + if (updateHash) { updateDeckHash(); } @@ -879,22 +806,18 @@ void DeckList::updateDeckHash() QSet hashZones, optionalZones; hashZones << DECK_ZONE_MAIN << DECK_ZONE_SIDE; // Zones in deck to be included in hashing process - optionalZones << DECK_ZONE_TOKENS; // Optional zones in deck not included in hashing process + optionalZones << DECK_ZONE_TOKENS; // Optional zones in deck not included in hashing process - for (int i = 0; i < root->size(); i++) - { + for (int i = 0; i < root->size(); i++) { auto *node = dynamic_cast(root->at(i)); - for (int j = 0; j < node->size(); j++) - { + for (int j = 0; j < node->size(); j++) { if (hashZones.contains(node->getName())) // Mainboard or Sideboard { auto *card = dynamic_cast(node->at(j)); - for (int k = 0; k < card->getNumber(); ++k) - { + for (int k = 0; k < card->getNumber(); ++k) { cardList.append((node->getName() == DECK_ZONE_SIDE ? "SB:" : "") + card->getName().toLower()); } - } - else if (!optionalZones.contains(node->getName())) // Not a valid zone -> cheater? + } else if (!optionalZones.contains(node->getName())) // Not a valid zone -> cheater? { isValidDeckList = false; // Deck is invalid } @@ -902,11 +825,10 @@ void DeckList::updateDeckHash() } cardList.sort(); QByteArray deckHashArray = QCryptographicHash::hash(cardList.join(";").toUtf8(), QCryptographicHash::Sha1); - quint64 number = (((quint64) (unsigned char) deckHashArray[0]) << 32) - + (((quint64) (unsigned char) deckHashArray[1]) << 24) - + (((quint64) (unsigned char) deckHashArray[2] << 16)) - + (((quint64) (unsigned char) deckHashArray[3]) << 8) - + (quint64) (unsigned char) deckHashArray[4]; + quint64 number = (((quint64)(unsigned char)deckHashArray[0]) << 32) + + (((quint64)(unsigned char)deckHashArray[1]) << 24) + + (((quint64)(unsigned char)deckHashArray[2] << 16)) + + (((quint64)(unsigned char)deckHashArray[3]) << 8) + (quint64)(unsigned char)deckHashArray[4]; deckHash = (isValidDeckList) ? QString::number(number, 32).rightJustified(8, '0') : "INVALID"; emit deckHashChanged(); diff --git a/common/decklist.h b/common/decklist.h index 20845bc5..9236a77b 100644 --- a/common/decklist.h +++ b/common/decklist.h @@ -2,12 +2,12 @@ #define DECKLIST_H #include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include // Required on Mac. Forward declaration doesn't work. Don't ask why. #include @@ -27,181 +27,255 @@ class InnerDecklistNode; class SideboardPlan { - private: - QString name; - QList moveList; +private: + QString name; + QList moveList; - public: - explicit SideboardPlan(const QString &_name = QString(), const QList &_moveList = QList()); - bool readElement(QXmlStreamReader *xml); - void write(QXmlStreamWriter *xml); +public: + explicit SideboardPlan(const QString &_name = QString(), + const QList &_moveList = QList()); + bool readElement(QXmlStreamReader *xml); + void write(QXmlStreamWriter *xml); - QString getName() const { return name; } - const QList &getMoveList() const { return moveList; } - void setMoveList(const QList &_moveList); + QString getName() const + { + return name; + } + const QList &getMoveList() const + { + return moveList; + } + void setMoveList(const QList &_moveList); }; -enum DeckSortMethod { ByNumber, ByName, Default }; +enum DeckSortMethod +{ + ByNumber, + ByName, + Default +}; class AbstractDecklistNode { - protected: - InnerDecklistNode *parent; - DeckSortMethod sortMethod; +protected: + InnerDecklistNode *parent; + DeckSortMethod sortMethod; - public: - explicit AbstractDecklistNode(InnerDecklistNode *_parent = nullptr); - virtual ~AbstractDecklistNode() = default; - virtual void setSortMethod(DeckSortMethod method) { sortMethod = method; } - virtual QString getName() const = 0; - InnerDecklistNode *getParent() const { return parent; } - int depth() const; - virtual int height() const = 0; - virtual bool compare(AbstractDecklistNode *other) const = 0; +public: + explicit AbstractDecklistNode(InnerDecklistNode *_parent = nullptr); + virtual ~AbstractDecklistNode() = default; + virtual void setSortMethod(DeckSortMethod method) + { + sortMethod = method; + } + virtual QString getName() const = 0; + InnerDecklistNode *getParent() const + { + return parent; + } + int depth() const; + virtual int height() const = 0; + virtual bool compare(AbstractDecklistNode *other) const = 0; - virtual bool readElement(QXmlStreamReader *xml) = 0; - virtual void writeElement(QXmlStreamWriter *xml) = 0; + virtual bool readElement(QXmlStreamReader *xml) = 0; + virtual void writeElement(QXmlStreamWriter *xml) = 0; }; class InnerDecklistNode : public AbstractDecklistNode, public QList { - private: - QString name; - class compareFunctor; +private: + QString name; + class compareFunctor; - public: - explicit InnerDecklistNode(QString _name = QString(), InnerDecklistNode *_parent = nullptr) : AbstractDecklistNode(_parent), name(std::move(_name)) { } - explicit InnerDecklistNode(InnerDecklistNode *other, InnerDecklistNode *_parent = nullptr); - ~InnerDecklistNode() override; - void setSortMethod(DeckSortMethod method) override; - QString getName() const override { return name; } - void setName(const QString &_name) { name = _name; } - static QString visibleNameFromName(const QString &_name); - virtual QString getVisibleName() const; - void clearTree(); - AbstractDecklistNode *findChild(const QString &name); - int height() const override; - int recursiveCount(bool countTotalCards = false) const; - bool compare(AbstractDecklistNode *other) const override; - bool compareNumber(AbstractDecklistNode *other) const; - bool compareName(AbstractDecklistNode *other) const; - QVector > sort(Qt::SortOrder order = Qt::AscendingOrder); +public: + explicit InnerDecklistNode(QString _name = QString(), InnerDecklistNode *_parent = nullptr) + : AbstractDecklistNode(_parent), name(std::move(_name)) + { + } + explicit InnerDecklistNode(InnerDecklistNode *other, InnerDecklistNode *_parent = nullptr); + ~InnerDecklistNode() override; + void setSortMethod(DeckSortMethod method) override; + QString getName() const override + { + return name; + } + void setName(const QString &_name) + { + name = _name; + } + static QString visibleNameFromName(const QString &_name); + virtual QString getVisibleName() const; + void clearTree(); + AbstractDecklistNode *findChild(const QString &name); + int height() const override; + int recursiveCount(bool countTotalCards = false) const; + bool compare(AbstractDecklistNode *other) const override; + bool compareNumber(AbstractDecklistNode *other) const; + bool compareName(AbstractDecklistNode *other) const; + QVector> sort(Qt::SortOrder order = Qt::AscendingOrder); - bool readElement(QXmlStreamReader *xml) override; - void writeElement(QXmlStreamWriter *xml) override; + bool readElement(QXmlStreamReader *xml) override; + void writeElement(QXmlStreamWriter *xml) override; }; class AbstractDecklistCardNode : public AbstractDecklistNode { - public: - explicit AbstractDecklistCardNode(InnerDecklistNode *_parent = nullptr) : AbstractDecklistNode(_parent) { } - virtual int getNumber() const = 0; - virtual void setNumber(int _number) = 0; - QString getName() const override = 0; - virtual void setName(const QString &_name) = 0; - int height() const override { return 0; } - bool compare(AbstractDecklistNode *other) const override; - bool compareNumber(AbstractDecklistNode *other) const; - bool compareName(AbstractDecklistNode *other) const; +public: + explicit AbstractDecklistCardNode(InnerDecklistNode *_parent = nullptr) : AbstractDecklistNode(_parent) + { + } + virtual int getNumber() const = 0; + virtual void setNumber(int _number) = 0; + QString getName() const override = 0; + virtual void setName(const QString &_name) = 0; + int height() const override + { + return 0; + } + bool compare(AbstractDecklistNode *other) const override; + bool compareNumber(AbstractDecklistNode *other) const; + bool compareName(AbstractDecklistNode *other) const; - bool readElement(QXmlStreamReader *xml) override; - void writeElement(QXmlStreamWriter *xml) override; + bool readElement(QXmlStreamReader *xml) override; + void writeElement(QXmlStreamWriter *xml) override; }; class DecklistCardNode : public AbstractDecklistCardNode { - private: - QString name; - int number; - public: - explicit DecklistCardNode(QString _name = QString(), int _number = 1, InnerDecklistNode *_parent = nullptr) : AbstractDecklistCardNode(_parent), name(std::move(_name)), number(_number) { } - explicit DecklistCardNode(DecklistCardNode *other, InnerDecklistNode *_parent); - int getNumber() const override { return number; } - void setNumber(int _number) override { number = _number; } - QString getName() const override { return name; } - void setName(const QString &_name) override { name = _name; } +private: + QString name; + int number; + +public: + explicit DecklistCardNode(QString _name = QString(), int _number = 1, InnerDecklistNode *_parent = nullptr) + : AbstractDecklistCardNode(_parent), name(std::move(_name)), number(_number) + { + } + explicit DecklistCardNode(DecklistCardNode *other, InnerDecklistNode *_parent); + int getNumber() const override + { + return number; + } + void setNumber(int _number) override + { + number = _number; + } + QString getName() const override + { + return name; + } + void setName(const QString &_name) override + { + name = _name; + } }; class DeckList : public QObject { Q_OBJECT - private: - QString name, comments; - QString deckHash; - QMap sideboardPlans; - InnerDecklistNode *root; - void getCardListHelper(InnerDecklistNode *node, QSet &result) const; - InnerDecklistNode *getZoneObjFromName(QString zoneName); +private: + QString name, comments; + QString deckHash; + QMap sideboardPlans; + InnerDecklistNode *root; + void getCardListHelper(InnerDecklistNode *node, QSet &result) const; + InnerDecklistNode *getZoneObjFromName(QString zoneName); - protected: - virtual QString getCardZoneFromName(const QString /*cardName*/, QString currentZoneName) { return currentZoneName; }; - virtual QString getCompleteCardName(const QString cardName) const { return cardName; }; +protected: + virtual QString getCardZoneFromName(const QString /*cardName*/, QString currentZoneName) + { + return currentZoneName; + }; + virtual QString getCompleteCardName(const QString cardName) const + { + return cardName; + }; - signals: - void deckHashChanged(); +signals: + void deckHashChanged(); - public slots: - void setName(const QString &_name = QString()) { name = _name; } - void setComments(const QString &_comments = QString()) { comments = _comments; } +public slots: + void setName(const QString &_name = QString()) + { + name = _name; + } + void setComments(const QString &_comments = QString()) + { + comments = _comments; + } - public: - explicit DeckList(); - DeckList(const DeckList &other); - explicit DeckList(const QString &nativeString); - ~DeckList() override; - QString getName() const { return name; } - QString getComments() const { return comments; } - QList getCurrentSideboardPlan(); - void setCurrentSideboardPlan(const QList &plan); - const QMap &getSideboardPlans() const { return sideboardPlans; } +public: + explicit DeckList(); + DeckList(const DeckList &other); + explicit DeckList(const QString &nativeString); + ~DeckList() override; + QString getName() const + { + return name; + } + QString getComments() const + { + return comments; + } + QList getCurrentSideboardPlan(); + void setCurrentSideboardPlan(const QList &plan); + const QMap &getSideboardPlans() const + { + return sideboardPlans; + } - bool readElement(QXmlStreamReader *xml); - void write(QXmlStreamWriter *xml); - bool loadFromXml(QXmlStreamReader *xml); - bool loadFromString_Native(const QString &nativeString); - QString writeToString_Native(); - bool loadFromFile_Native(QIODevice *device); - bool saveToFile_Native(QIODevice *device); - bool loadFromStream_Plain(QTextStream &stream); - bool loadFromFile_Plain(QIODevice *device); - bool saveToStream_Plain(QTextStream &stream, bool prefixSideboardCards, bool slashTappedOutSplitCards); - bool saveToFile_Plain(QIODevice *device, bool prefixSideboardCards=true, bool slashTappedOutSplitCards=false); - QString writeToString_Plain(bool prefixSideboardCards=true, bool slashTappedOutSplitCards=false); + bool readElement(QXmlStreamReader *xml); + void write(QXmlStreamWriter *xml); + bool loadFromXml(QXmlStreamReader *xml); + bool loadFromString_Native(const QString &nativeString); + QString writeToString_Native(); + bool loadFromFile_Native(QIODevice *device); + bool saveToFile_Native(QIODevice *device); + bool loadFromStream_Plain(QTextStream &stream); + bool loadFromFile_Plain(QIODevice *device); + bool saveToStream_Plain(QTextStream &stream, bool prefixSideboardCards, bool slashTappedOutSplitCards); + bool saveToFile_Plain(QIODevice *device, bool prefixSideboardCards = true, bool slashTappedOutSplitCards = false); + QString writeToString_Plain(bool prefixSideboardCards = true, bool slashTappedOutSplitCards = false); - void cleanList(); - bool isEmpty() const { return root->isEmpty() && name.isEmpty() && comments.isEmpty() && sideboardPlans.isEmpty(); } - QStringList getCardList() const; + void cleanList(); + bool isEmpty() const + { + return root->isEmpty() && name.isEmpty() && comments.isEmpty() && sideboardPlans.isEmpty(); + } + QStringList getCardList() const; - int getSideboardSize() const; + int getSideboardSize() const; - QString getDeckHash() const { return deckHash; } - void updateDeckHash(); + QString getDeckHash() const + { + return deckHash; + } + void updateDeckHash(); - InnerDecklistNode *getRoot() const { return root; } - DecklistCardNode *addCard(const QString &cardName, const QString &zoneName); - bool deleteNode(AbstractDecklistNode *node, InnerDecklistNode *rootNode = nullptr); + InnerDecklistNode *getRoot() const + { + return root; + } + DecklistCardNode *addCard(const QString &cardName, const QString &zoneName); + bool deleteNode(AbstractDecklistNode *node, InnerDecklistNode *rootNode = nullptr); - /** - * Calls a given function object for each card in the deck. It must - * take a InnerDecklistNode* as its first argument and a - * DecklistCardNode* as its second. - */ - template - void forEachCard(Callback &callback) const { - // Support for this is only possible if the internal structure - // doesn't get more complicated. - for (int i = 0; i < root->size(); i++) { - const InnerDecklistNode *node = - dynamic_cast(root->at(i)); - for (int j = 0; j < node->size(); j++) { - const DecklistCardNode *card = - dynamic_cast( - node->at(j) - ); - callback(node, card); - } + /** + * Calls a given function object for each card in the deck. It must + * take a InnerDecklistNode* as its first argument and a + * DecklistCardNode* as its second. + */ + template void forEachCard(Callback &callback) const + { + // Support for this is only possible if the internal structure + // doesn't get more complicated. + for (int i = 0; i < root->size(); i++) { + const InnerDecklistNode *node = dynamic_cast(root->at(i)); + for (int j = 0; j < node->size(); j++) { + const DecklistCardNode *card = dynamic_cast(node->at(j)); + callback(node, card); } } + } }; #endif diff --git a/common/featureset.cpp b/common/featureset.cpp index 2200ad6f..2e9947b9 100644 --- a/common/featureset.cpp +++ b/common/featureset.cpp @@ -1,18 +1,19 @@ #include "featureset.h" -#include #include +#include FeatureSet::FeatureSet() { - } -QMap FeatureSet::getDefaultFeatureList() { +QMap FeatureSet::getDefaultFeatureList() +{ initalizeFeatureList(featureList); return featureList; } -void FeatureSet::initalizeFeatureList(QMap &featureList) { +void FeatureSet::initalizeFeatureList(QMap &featureList) +{ featureList.insert("client_id", false); featureList.insert("client_ver", false); featureList.insert("feature_set", false); @@ -24,22 +25,28 @@ void FeatureSet::initalizeFeatureList(QMap &featureList) { featureList.insert("forgot_password", false); } -void FeatureSet::enableRequiredFeature(QMap &featureList, QString featureName){ +void FeatureSet::enableRequiredFeature(QMap &featureList, QString featureName) +{ if (featureList.contains(featureName)) - featureList.insert(featureName,true); + featureList.insert(featureName, true); } -void FeatureSet::disableRequiredFeature(QMap &featureList, QString featureName){ +void FeatureSet::disableRequiredFeature(QMap &featureList, QString featureName) +{ if (featureList.contains(featureName)) - featureList.insert(featureName,false); + featureList.insert(featureName, false); } -QMap FeatureSet::addFeature(QMap &featureList, QString featureName, bool isFeatureRequired){ - featureList.insert(featureName,isFeatureRequired); +QMap +FeatureSet::addFeature(QMap &featureList, QString featureName, bool isFeatureRequired) +{ + featureList.insert(featureName, isFeatureRequired); return featureList; } -QMap FeatureSet::identifyMissingFeatures(QMap suppliedFeatures, QMap requiredFeatures){ +QMap FeatureSet::identifyMissingFeatures(QMap suppliedFeatures, + QMap requiredFeatures) +{ QMap missingList; QMap::iterator i; for (i = requiredFeatures.begin(); i != requiredFeatures.end(); ++i) { @@ -50,11 +57,12 @@ QMap FeatureSet::identifyMissingFeatures(QMap supp return missingList; } -bool FeatureSet::isRequiredFeaturesMissing(QMap suppliedFeatures, QMap requiredFeatures) { +bool FeatureSet::isRequiredFeaturesMissing(QMap suppliedFeatures, QMap requiredFeatures) +{ QMap::iterator i; for (i = requiredFeatures.begin(); i != requiredFeatures.end(); ++i) { if (i.value() && suppliedFeatures.contains(i.key())) { - return true; + return true; } } return false; diff --git a/common/featureset.h b/common/featureset.h index 620ba96a..eb73471b 100644 --- a/common/featureset.h +++ b/common/featureset.h @@ -14,11 +14,12 @@ public: void enableRequiredFeature(QMap &featureList, QString featureName); void disableRequiredFeature(QMap &featureList, QString featureName); QMap addFeature(QMap &featureList, QString featureName, bool isFeatureRequired); - QMap identifyMissingFeatures(QMap featureListToCheck, QMap featureListToCompareTo); + QMap identifyMissingFeatures(QMap featureListToCheck, + QMap featureListToCompareTo); bool isRequiredFeaturesMissing(QMap featureListToCheck, QMap featureListToCompareTo); + private: QMap featureList; }; - #endif // FEEATURESET_H diff --git a/common/get_pb_extension.cpp b/common/get_pb_extension.cpp index 1e980f4b..f685ceb3 100644 --- a/common/get_pb_extension.cpp +++ b/common/get_pb_extension.cpp @@ -1,10 +1,10 @@ #include "get_pb_extension.h" -#include #include +#include int getPbExtension(const ::google::protobuf::Message &message) { - std::vector< const ::google::protobuf::FieldDescriptor * > fieldList; + std::vector fieldList; message.GetReflection()->ListFields(message, &fieldList); for (unsigned int j = 0; j < fieldList.size(); ++j) if (fieldList[j]->is_extension()) diff --git a/common/get_pb_extension.h b/common/get_pb_extension.h index bebef39e..4a89e170 100644 --- a/common/get_pb_extension.h +++ b/common/get_pb_extension.h @@ -1,11 +1,13 @@ #ifndef GET_PB_EXTENSION_H #define GET_PB_EXTENSION_H -namespace google { - namespace protobuf { - class Message; - } +namespace google +{ +namespace protobuf +{ +class Message; } +} // namespace google int getPbExtension(const ::google::protobuf::Message &message); diff --git a/common/rng_abstract.cpp b/common/rng_abstract.cpp index 79054908..c016244d 100644 --- a/common/rng_abstract.cpp +++ b/common/rng_abstract.cpp @@ -1,7 +1,6 @@ #include "rng_abstract.h" #include - QVector RNG_Abstract::makeNumbersVector(int n, int min, int max) { const int bins = max - min + 1; @@ -21,10 +20,10 @@ double RNG_Abstract::testRandom(const QVector &numbers) const int n = 0; for (int i = 0; i < numbers.size(); ++i) n += numbers[i]; - double expected = (double) n / (double) numbers.size(); + double expected = (double)n / (double)numbers.size(); double chisq = 0; for (int i = 0; i < numbers.size(); ++i) - chisq += ((double) numbers[i] - expected) * ((double) numbers[i] - expected) / expected; - + chisq += ((double)numbers[i] - expected) * ((double)numbers[i] - expected) / expected; + return chisq; } diff --git a/common/rng_abstract.h b/common/rng_abstract.h index 0423930c..84c7066c 100644 --- a/common/rng_abstract.h +++ b/common/rng_abstract.h @@ -4,10 +4,13 @@ #include #include -class RNG_Abstract : public QObject { +class RNG_Abstract : public QObject +{ Q_OBJECT public: - RNG_Abstract(QObject *parent = 0) : QObject(parent) { } + RNG_Abstract(QObject *parent = 0) : QObject(parent) + { + } virtual unsigned int rand(int min, int max) = 0; QVector makeNumbersVector(int n, int min, int max); double testRandom(const QVector &numbers) const; diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index 783594a0..7667dcd5 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -10,8 +10,7 @@ #define UINT64_MAX (~(uint64_t)0) #endif -RNG_SFMT::RNG_SFMT(QObject *parent) - : RNG_Abstract(parent) +RNG_SFMT::RNG_SFMT(QObject *parent) : RNG_Abstract(parent) { // initialize the random number generator with a 32bit integer seed (timestamp) sfmt_init_gen_rand(&sfmt, QDateTime::currentDateTime().toTime_t()); @@ -26,33 +25,33 @@ RNG_SFMT::RNG_SFMT(QObject *parent) * It is only necessary that the upper bound is larger or equal to the lower bound - with the exception * that someone wants something like rand() % -foo. */ -unsigned int RNG_SFMT::rand(int min, int max) { - /* If min is negative, it would be possible to calculate - * cdf(0, max - min) + min - * There has been no use for negative random numbers with rand() though, so it's treated as error. - */ - if(min < 0) { - throw std::invalid_argument( - QString("Invalid bounds for RNG: Got min " + - QString::number(min) + " < 0!\n").toStdString()); - // at this point, the method exits. No return value is needed, because - // basically the exception itself is returned. - } +unsigned int RNG_SFMT::rand(int min, int max) +{ + /* If min is negative, it would be possible to calculate + * cdf(0, max - min) + min + * There has been no use for negative random numbers with rand() though, so it's treated as error. + */ + if (min < 0) { + throw std::invalid_argument( + QString("Invalid bounds for RNG: Got min " + QString::number(min) + " < 0!\n").toStdString()); + // at this point, the method exits. No return value is needed, because + // basically the exception itself is returned. + } - // For complete fairness and equal timing, this should be a roll, but let's skip it anyway - if(min == max) - return max; + // For complete fairness and equal timing, this should be a roll, but let's skip it anyway + if (min == max) + return max; - // This is actually not used in Cockatrice: - // Someone wants rand() % -foo, so we compute -rand(0, +foo) - // This is the only time where min > max is (sort of) legal. - // Not handling this will cause the application to crash. - if(min == 0 && max < 0) { - return -cdf(0, -max); - } + // This is actually not used in Cockatrice: + // Someone wants rand() % -foo, so we compute -rand(0, +foo) + // This is the only time where min > max is (sort of) legal. + // Not handling this will cause the application to crash. + if (min == 0 && max < 0) { + return -cdf(0, -max); + } - // No special cases are left, except !(min > max) which is caught in the cdf itself. - return cdf(min, max); + // No special cases are left, except !(min > max) which is caught in the cdf itself. + return cdf(min, max); } /** @@ -89,9 +88,9 @@ unsigned int RNG_SFMT::rand(int min, int max) { * This can be compared to an ideal six sided die that is rolled until only sides * 1-5 show up, while 6 represents something that you don't want. So you basically roll * a five sided die. - * + * * Note: If you replace the SFMT RNG with some other rand() function in the future, - * then you _need_ to change the UINT64_MAX constant to the largest possible random + * then you _need_ to change the UINT64_MAX constant to the largest possible random * number which can be created by the new rand() function. This value is often defined * in a RAND_MAX constant. * Otherwise you will probably skew the outcome of the rand() method or worsen the @@ -100,11 +99,10 @@ unsigned int RNG_SFMT::rand(int min, int max) { unsigned int RNG_SFMT::cdf(unsigned int min, unsigned int max) { // This all makes no sense if min > max, which should never happen. - if(min > max) { - throw std::invalid_argument( - QString("Invalid bounds for RNG: min > max! Values were: min = " + - QString::number(min) + ", max = " + - QString::number(max)).toStdString()); + if (min > max) { + throw std::invalid_argument(QString("Invalid bounds for RNG: min > max! Values were: min = " + + QString::number(min) + ", max = " + QString::number(max)) + .toStdString()); // at this point, the method exits. No return value is needed, because // basically the exception itself is returned. } @@ -132,5 +130,5 @@ unsigned int RNG_SFMT::cdf(unsigned int min, unsigned int max) // Now determine the bucket containing the SFMT() random number and after adding // the lower bound, a random number from [min, max] can be returned. - return (unsigned int) (rand / buckets + min); + return (unsigned int)(rand / buckets + min); } diff --git a/common/rng_sfmt.h b/common/rng_sfmt.h index ec7a75c9..f5497799 100644 --- a/common/rng_sfmt.h +++ b/common/rng_sfmt.h @@ -1,10 +1,10 @@ #ifndef RNG_SFMT_H #define RNG_SFMT_H -#include -#include -#include "sfmt/SFMT.h" #include "rng_abstract.h" +#include "sfmt/SFMT.h" +#include +#include /** * This class encapsulates a state of the art PRNG and can be used @@ -25,17 +25,18 @@ * Edition Volume 2 / Seminumerical Algorithms". */ -class RNG_SFMT : public RNG_Abstract { +class RNG_SFMT : public RNG_Abstract +{ Q_OBJECT private: QMutex mutex; sfmt_t sfmt; // The discrete cumulative distribution function for the RNG unsigned int cdf(unsigned int min, unsigned int max); + public: RNG_SFMT(QObject *parent = 0); unsigned int rand(int min, int max); }; #endif - diff --git a/common/server.cpp b/common/server.cpp index 3a413540..526d98b7 100644 --- a/common/server.cpp +++ b/common/server.cpp @@ -18,27 +18,26 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "server.h" -#include "server_game.h" -#include "server_player.h" -#include "server_counter.h" -#include "server_room.h" -#include "server_protocolhandler.h" -#include "server_remoteuserinterface.h" -#include "server_metatypes.h" -#include "server_database_interface.h" +#include "featureset.h" +#include "pb/event_connection_closed.pb.h" +#include "pb/event_list_rooms.pb.h" #include "pb/event_user_joined.pb.h" #include "pb/event_user_left.pb.h" -#include "pb/event_list_rooms.pb.h" -#include "pb/session_event.pb.h" -#include "pb/event_connection_closed.pb.h" #include "pb/isl_message.pb.h" -#include "featureset.h" +#include "pb/session_event.pb.h" +#include "server_counter.h" +#include "server_database_interface.h" +#include "server_game.h" +#include "server_metatypes.h" +#include "server_player.h" +#include "server_protocolhandler.h" +#include "server_remoteuserinterface.h" +#include "server_room.h" #include -#include #include +#include -Server::Server(QObject *parent) - : QObject(parent), nextLocalGameId(0), tcpUserCount(0), webSocketUserCount(0) +Server::Server(QObject *parent) : QObject(parent), nextLocalGameId(0), tcpUserCount(0), webSocketUserCount(0) { qRegisterMetaType("ServerInfo_Ban"); qRegisterMetaType("ServerInfo_Game"); @@ -50,7 +49,8 @@ Server::Server(QObject *parent) qRegisterMetaType("IslMessage"); qRegisterMetaType("Command_JoinGame"); - connect(this, SIGNAL(sigSendIslMessage(IslMessage, int)), this, SLOT(doSendIslMessage(IslMessage, int)), Qt::QueuedConnection); + connect(this, SIGNAL(sigSendIslMessage(IslMessage, int)), this, SLOT(doSendIslMessage(IslMessage, int)), + Qt::QueuedConnection); } Server::~Server() @@ -78,15 +78,24 @@ Server_DatabaseInterface *Server::getDatabaseInterface() const return databaseInterfaces.value(QThread::currentThread()); } -AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft, QString &clientid, QString &clientVersion, QString & /* connectionType */) +AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, + QString &name, + const QString &password, + QString &reasonStr, + int &secondsLeft, + QString &clientid, + QString &clientVersion, + QString & /* connectionType */) { if (name.size() > 35) name = name.left(35); Server_DatabaseInterface *databaseInterface = getDatabaseInterface(); - AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, clientid, reasonStr, secondsLeft); - if (authState == NotLoggedIn || authState == UserIsBanned || authState == UsernameInvalid || authState == UserIsInactive) + AuthenticationResult authState = + databaseInterface->checkUserPassword(session, name, password, clientid, reasonStr, secondsLeft); + if (authState == NotLoggedIn || authState == UserIsBanned || authState == UsernameInvalid || + authState == UserIsInactive) return authState; ServerInfo_User data = databaseInterface->getUserData(name, true); @@ -108,7 +117,9 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString users.value(name)->prepareDestroy(); } else { - qDebug() << "Active session and sessions table inconsistent, please validate session table information for user " << name; + qDebug() << "Active session and sessions table inconsistent, please validate session table information " + "for user " + << name; } } @@ -123,7 +134,8 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString QString tempName = name; int i = 0; - while (users.contains(tempName) || databaseInterface->activeUserExists(tempName) || databaseInterface->userSessionExists(tempName)) + while (users.contains(tempName) || databaseInterface->activeUserExists(tempName) || + databaseInterface->userSessionExists(tempName)) tempName = name + "_" + QString::number(++i); name = tempName; data.set_name(name.toStdString()); @@ -134,7 +146,8 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString users.insert(name, session); qDebug() << "Server::loginUser:" << session << "name=" << name; - data.set_session_id(databaseInterface->startSession(name, session->getAddress(), clientid, session->getConnectionType())); + data.set_session_id( + databaseInterface->startSession(name, session->getAddress(), clientid, session->getConnectionType())); databaseInterface->unlockSessionTables(); usersBySessionId.insert(data.session_id(), session); @@ -153,12 +166,11 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString event.mutable_user_info()->CopyFrom(session->copyUserInfo(true, true, true)); locker.unlock(); - if (clientid.isEmpty()){ + if (clientid.isEmpty()) { // client id is empty, either out dated client or client has been modified if (getClientIDRequiredEnabled()) return ClientIdRequired; - } - else { + } else { // update users database table with client id databaseInterface->updateUsersClientID(name, clientid); } @@ -214,7 +226,7 @@ void Server::addClient(Server_ProtocolHandler *client) void Server::removeClient(Server_ProtocolHandler *client) { - + if (client->getConnectionType() == "tcp") tcpUserCount--; @@ -244,7 +256,8 @@ void Server::removeClient(Server_ProtocolHandler *client) qDebug() << "closed session id:" << sessionId; } } - qDebug() << "Server::removeClient: removed" << (void *) client << ";" << clients.size() << "clients; " << users.size() << "users left"; + qDebug() << "Server::removeClient: removed" << (void *)client << ";" << clients.size() << "clients; " + << users.size() << "users left"; } QList Server::getOnlineModeratorList() @@ -254,11 +267,9 @@ QList Server::getOnlineModeratorList() for (int i = 0; i < clients.size(); ++i) { ServerInfo_User *data = clients[i]->getUserInfo(); - //TODO: this line should be updated in the event there is any type of new user level created + // TODO: this line should be updated in the event there is any type of new user level created if (data && - (data->user_level() & ServerInfo_User::IsModerator || - data->user_level() & ServerInfo_User::IsAdmin) - ) + (data->user_level() & ServerInfo_User::IsModerator || data->user_level() & ServerInfo_User::IsAdmin)) results << QString::fromStdString(data->name()).simplified(); } return results; @@ -297,8 +308,8 @@ void Server::externalUserLeft(const QString &userName) externalUsersBySessionId.remove(user->getUserInfo()->session_id()); clientsLock.unlock(); - QMap > userGames(user->getGames()); - QMapIterator > userGamesIterator(userGames); + QMap> userGames(user->getGames()); + QMapIterator> userGamesIterator(userGames); roomsLock.lockForRead(); while (userGamesIterator.hasNext()) { userGamesIterator.next(); @@ -372,7 +383,8 @@ void Server::externalRoomSay(int roomId, const QString &userName, const QString } room->say(userName, message, false); - getDatabaseInterface()->logMessage(0, userName, "ISL", message, Server_DatabaseInterface::MessageTargetIslRoom, room->getId(), room->getName()); + getDatabaseInterface()->logMessage(0, userName, "ISL", message, Server_DatabaseInterface::MessageTargetIslRoom, + room->getId(), room->getName()); } void Server::externalRoomGameListChanged(int roomId, const ServerInfo_Game &gameInfo) @@ -388,7 +400,11 @@ void Server::externalRoomGameListChanged(int roomId, const ServerInfo_Game &game room->updateExternalGameList(gameInfo); } -void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cmdId, int roomId, int serverId, qint64 sessionId) +void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, + int cmdId, + int roomId, + int serverId, + qint64 sessionId) { // This function is always called from the main thread via signal/slot. @@ -419,7 +435,10 @@ void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cm } } -void Server::externalGameCommandContainerReceived(const CommandContainer &cont, int playerId, int serverId, qint64 sessionId) +void Server::externalGameCommandContainerReceived(const CommandContainer &cont, + int playerId, + int serverId, + qint64 sessionId) { // This function is always called from the main thread via signal/slot. @@ -528,7 +547,8 @@ void Server::addRoom(Server_Room *newRoom) QWriteLocker locker(&roomsLock); qDebug() << "Adding room: ID=" << newRoom->getId() << "name=" << newRoom->getName(); rooms.insert(newRoom->getId(), newRoom); - connect(newRoom, SIGNAL(roomInfoChanged(ServerInfo_Room)), this, SLOT(broadcastRoomUpdate(const ServerInfo_Room &)), Qt::QueuedConnection); + connect(newRoom, SIGNAL(roomInfoChanged(ServerInfo_Room)), this, SLOT(broadcastRoomUpdate(const ServerInfo_Room &)), + Qt::QueuedConnection); } int Server::getUsersCount() const diff --git a/common/server.h b/common/server.h index a345e00a..301dbc11 100644 --- a/common/server.h +++ b/common/server.h @@ -1,18 +1,18 @@ #ifndef SERVER_H #define SERVER_H -#include -#include +#include "pb/commands.pb.h" +#include "pb/serverinfo_ban.pb.h" +#include "pb/serverinfo_chat_message.pb.h" +#include "pb/serverinfo_user.pb.h" +#include "pb/serverinfo_warning.pb.h" +#include "server_player_reference.h" #include #include #include +#include #include -#include "pb/commands.pb.h" -#include "pb/serverinfo_user.pb.h" -#include "pb/serverinfo_ban.pb.h" -#include "pb/serverinfo_warning.pb.h" -#include "pb/serverinfo_chat_message.pb.h" -#include "server_player_reference.h" +#include class Server_DatabaseInterface; class Server_Game; @@ -31,7 +31,18 @@ class GameEventContainer; class CommandContainer; class Command_JoinGame; -enum AuthenticationResult { NotLoggedIn, PasswordRight, UnknownUser, WouldOverwriteOldSession, UserIsBanned, UsernameInvalid, RegistrationRequired, UserIsInactive, ClientIdRequired }; +enum AuthenticationResult +{ + NotLoggedIn, + PasswordRight, + UnknownUser, + WouldOverwriteOldSession, + UserIsBanned, + UsernameInvalid, + RegistrationRequired, + UserIsInactive, + ClientIdRequired +}; class Server : public QObject { @@ -42,45 +53,132 @@ signals: void endSession(qint64 sessionId); private slots: void broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl = false); + public: mutable QReadWriteLock clientsLock, roomsLock; // locking order: roomsLock before clientsLock Server(QObject *parent = 0); ~Server(); - AuthenticationResult loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reason, int &secondsLeft, QString &clientid, QString &clientVersion, QString &connectionType); + AuthenticationResult loginUser(Server_ProtocolHandler *session, + QString &name, + const QString &password, + QString &reason, + int &secondsLeft, + QString &clientid, + QString &clientVersion, + QString &connectionType); - const QMap &getRooms() { return rooms; } + const QMap &getRooms() + { + return rooms; + } Server_AbstractUserInterface *findUser(const QString &userName) const; - const QMap &getUsers() const { return users; } - const QMap &getUsersBySessionId() const { return usersBySessionId; } - virtual QMap getServerRequiredFeatureList() const { return QMap(); } + const QMap &getUsers() const + { + return users; + } + const QMap &getUsersBySessionId() const + { + return usersBySessionId; + } + virtual QMap getServerRequiredFeatureList() const + { + return QMap(); + } void addClient(Server_ProtocolHandler *player); void removeClient(Server_ProtocolHandler *player); QList getOnlineModeratorList(); - virtual QString getLoginMessage() const { return QString(); } - virtual QString getRequiredFeatures() const { return QString(); } - virtual bool permitUnregisteredUsers() const { return true; } - virtual bool getGameShouldPing() const { return false; } - virtual bool getClientIDRequiredEnabled() const { return false; } - virtual bool getRegOnlyServerEnabled() const { return false; } - virtual bool getMaxUserLimitEnabled() const { return false; } - virtual bool getEnableLogQuery() const { return false; } - virtual bool getStoreReplaysEnabled() const { return true; } - virtual int getIdleClientTimeout() const { return 0; } - virtual int getClientKeepAlive() const { return 0; } - virtual int getMaxGameInactivityTime() const { return 9999999; } - virtual int getMaxPlayerInactivityTime() const { return 9999999; } - virtual int getMessageCountingInterval() const { return 0; } - virtual int getMaxMessageCountPerInterval() const { return 0; } - virtual int getMaxMessageSizePerInterval() const { return 0; } - virtual int getMaxGamesPerUser() const { return 0; } - virtual int getCommandCountingInterval() const { return 0; } - virtual int getMaxCommandCountPerInterval() const { return 0; } - virtual int getMaxUserTotal() const { return 9999999; } - virtual int getServerID() const { return 0; } + virtual QString getLoginMessage() const + { + return QString(); + } + virtual QString getRequiredFeatures() const + { + return QString(); + } + virtual bool permitUnregisteredUsers() const + { + return true; + } + virtual bool getGameShouldPing() const + { + return false; + } + virtual bool getClientIDRequiredEnabled() const + { + return false; + } + virtual bool getRegOnlyServerEnabled() const + { + return false; + } + virtual bool getMaxUserLimitEnabled() const + { + return false; + } + virtual bool getEnableLogQuery() const + { + return false; + } + virtual bool getStoreReplaysEnabled() const + { + return true; + } + virtual int getIdleClientTimeout() const + { + return 0; + } + virtual int getClientKeepAlive() const + { + return 0; + } + virtual int getMaxGameInactivityTime() const + { + return 9999999; + } + virtual int getMaxPlayerInactivityTime() const + { + return 9999999; + } + virtual int getMessageCountingInterval() const + { + return 0; + } + virtual int getMaxMessageCountPerInterval() const + { + return 0; + } + virtual int getMaxMessageSizePerInterval() const + { + return 0; + } + virtual int getMaxGamesPerUser() const + { + return 0; + } + virtual int getCommandCountingInterval() const + { + return 0; + } + virtual int getMaxCommandCountPerInterval() const + { + return 0; + } + virtual int getMaxUserTotal() const + { + return 9999999; + } + virtual int getServerID() const + { + return 0; + } Server_DatabaseInterface *getDatabaseInterface() const; - int getNextLocalGameId() { QMutexLocker locker(&nextLocalGameIdMutex); return ++nextLocalGameId; } + int getNextLocalGameId() + { + QMutexLocker locker(&nextLocalGameIdMutex); + return ++nextLocalGameId; + } void sendIsl_Response(const Response &item, int serverId = -1, qint64 sessionId = -1); void sendIsl_SessionEvent(const SessionEvent &item, int serverId = -1, qint64 sessionId = -1); @@ -91,15 +189,25 @@ public: void addExternalUser(const ServerInfo_User &userInfo); void removeExternalUser(const QString &userName); - const QMap &getExternalUsers() const { return externalUsers; } + const QMap &getExternalUsers() const + { + return externalUsers; + } void addPersistentPlayer(const QString &userName, int roomId, int gameId, int playerId); void removePersistentPlayer(const QString &userName, int roomId, int gameId, int playerId); QList getPersistentPlayerReferences(const QString &userName) const; int getUsersCount() const; int getGamesCount() const; - int getTCPUserCount() const { return tcpUserCount; } - int getWebSocketUserCount() const { return webSocketUserCount; } + int getTCPUserCount() const + { + return tcpUserCount; + } + int getWebSocketUserCount() const + { + return webSocketUserCount; + } + private: QMultiMap persistentPlayers; mutable QReadWriteLock persistentPlayersLock; @@ -113,12 +221,17 @@ protected slots: void externalRoomUserLeft(int roomId, const QString &userName); void externalRoomSay(int roomId, const QString &userName, const QString &message); void externalRoomGameListChanged(int roomId, const ServerInfo_Game &gameInfo); - void externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cmdId, int roomId, int serverId, qint64 sessionId); - void externalGameCommandContainerReceived(const CommandContainer &cont, int playerId, int serverId, qint64 sessionId); + void + externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cmdId, int roomId, int serverId, qint64 sessionId); + void + externalGameCommandContainerReceived(const CommandContainer &cont, int playerId, int serverId, qint64 sessionId); void externalGameEventContainerReceived(const GameEventContainer &cont, qint64 sessionId); void externalResponseReceived(const Response &resp, qint64 sessionId); - virtual void doSendIslMessage(const IslMessage & /* msg */, int /* serverId */) { } + virtual void doSendIslMessage(const IslMessage & /* msg */, int /* serverId */) + { + } + protected: void prepareDestroy(); void setDatabaseInterface(Server_DatabaseInterface *_databaseInterface); diff --git a/common/server_abstractuserinterface.cpp b/common/server_abstractuserinterface.cpp index 632bd320..b5cd502e 100644 --- a/common/server_abstractuserinterface.cpp +++ b/common/server_abstractuserinterface.cpp @@ -1,52 +1,67 @@ -#include -#include -#include #include "server_abstractuserinterface.h" -#include "server_game.h" -#include "server_response_containers.h" -#include "server_player_reference.h" -#include "server.h" -#include "server_room.h" -#include "server_game.h" -#include "server_player.h" #include "pb/event_game_joined.pb.h" #include "pb/event_game_state_changed.pb.h" +#include "server.h" +#include "server_game.h" +#include "server_player.h" +#include "server_player_reference.h" +#include "server_response_containers.h" +#include "server_room.h" +#include +#include +#include #include -void Server_AbstractUserInterface::sendProtocolItemByType(ServerMessage::MessageType type, const ::google::protobuf::Message &item) +void Server_AbstractUserInterface::sendProtocolItemByType(ServerMessage::MessageType type, + const ::google::protobuf::Message &item) { switch (type) { - case ServerMessage::RESPONSE: sendProtocolItem(static_cast(item)); break; - case ServerMessage::SESSION_EVENT: sendProtocolItem(static_cast(item)); break; - case ServerMessage::GAME_EVENT_CONTAINER: sendProtocolItem(static_cast(item)); break; - case ServerMessage::ROOM_EVENT: sendProtocolItem(static_cast(item)); break; + case ServerMessage::RESPONSE: + sendProtocolItem(static_cast(item)); + break; + case ServerMessage::SESSION_EVENT: + sendProtocolItem(static_cast(item)); + break; + case ServerMessage::GAME_EVENT_CONTAINER: + sendProtocolItem(static_cast(item)); + break; + case ServerMessage::ROOM_EVENT: + sendProtocolItem(static_cast(item)); + break; } } SessionEvent *Server_AbstractUserInterface::prepareSessionEvent(const ::google::protobuf::Message &sessionEvent) { SessionEvent *event = new SessionEvent; - event->GetReflection()->MutableMessage(event, sessionEvent.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(sessionEvent); + event->GetReflection() + ->MutableMessage(event, sessionEvent.GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(sessionEvent); return event; } -void Server_AbstractUserInterface::sendResponseContainer(const ResponseContainer &responseContainer, Response::ResponseCode responseCode) +void Server_AbstractUserInterface::sendResponseContainer(const ResponseContainer &responseContainer, + Response::ResponseCode responseCode) { - const QList > &preResponseQueue = responseContainer.getPreResponseQueue(); + const QList> &preResponseQueue = + responseContainer.getPreResponseQueue(); for (int i = 0; i < preResponseQueue.size(); ++i) sendProtocolItemByType(preResponseQueue[i].first, *preResponseQueue[i].second); - + if (responseCode != Response::RespNothing) { Response response; response.set_cmd_id(responseContainer.getCmdId()); response.set_response_code(responseCode); ::google::protobuf::Message *responseExtension = responseContainer.getResponseExtension(); if (responseExtension) - response.GetReflection()->MutableMessage(&response, responseExtension->GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(*responseExtension); + response.GetReflection() + ->MutableMessage(&response, responseExtension->GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(*responseExtension); sendProtocolItem(response); } - - const QList > &postResponseQueue = responseContainer.getPostResponseQueue(); + + const QList> &postResponseQueue = + responseContainer.getPostResponseQueue(); for (int i = 0; i < postResponseQueue.size(); ++i) sendProtocolItemByType(postResponseQueue[i].first, *postResponseQueue[i].second); } @@ -54,7 +69,7 @@ void Server_AbstractUserInterface::sendResponseContainer(const ResponseContainer void Server_AbstractUserInterface::playerRemovedFromGame(Server_Game *game) { qDebug() << "Server_AbstractUserInterface::playerRemovedFromGame(): gameId =" << game->getGameId(); - + QMutexLocker locker(&gameListMutex); games.remove(game->getGameId()); } @@ -62,36 +77,37 @@ void Server_AbstractUserInterface::playerRemovedFromGame(Server_Game *game) void Server_AbstractUserInterface::playerAddedToGame(int gameId, int roomId, int playerId) { qDebug() << "Server_AbstractUserInterface::playerAddedToGame(): gameId =" << gameId; - + QMutexLocker locker(&gameListMutex); games.insert(gameId, QPair(roomId, playerId)); } void Server_AbstractUserInterface::joinPersistentGames(ResponseContainer &rc) { - QList gamesToJoin = server->getPersistentPlayerReferences(QString::fromStdString(userInfo->name())); - + QList gamesToJoin = + server->getPersistentPlayerReferences(QString::fromStdString(userInfo->name())); + server->roomsLock.lockForRead(); for (int i = 0; i < gamesToJoin.size(); ++i) { const PlayerReference &pr = gamesToJoin.at(i); - + Server_Room *room = server->getRooms().value(pr.getRoomId()); if (!room) continue; QReadLocker roomGamesLocker(&room->gamesLock); - + Server_Game *game = room->getGames().value(pr.getGameId()); if (!game) continue; QMutexLocker gameLocker(&game->gameMutex); - + Server_Player *player = game->getPlayers().value(pr.getPlayerId()); if (!player) continue; - + player->setUserInterface(this); playerAddedToGame(game->getGameId(), room->getId(), player->getPlayerId()); - + game->createGameJoinedEvent(player, rc, true); } server->roomsLock.unlock(); diff --git a/common/server_abstractuserinterface.h b/common/server_abstractuserinterface.h index 1253c0f4..a40a9b76 100644 --- a/common/server_abstractuserinterface.h +++ b/common/server_abstractuserinterface.h @@ -1,12 +1,12 @@ #ifndef SERVER_ABSTRACTUSERINTERFACE #define SERVER_ABSTRACTUSERINTERFACE -#include -#include -#include -#include "serverinfo_user_container.h" -#include "pb/server_message.pb.h" #include "pb/response.pb.h" +#include "pb/server_message.pb.h" +#include "serverinfo_user_container.h" +#include +#include +#include class SessionEvent; class GameEventContainer; @@ -16,31 +16,44 @@ class ResponseContainer; class Server; class Server_Game; -class Server_AbstractUserInterface : public ServerInfo_User_Container { +class Server_AbstractUserInterface : public ServerInfo_User_Container +{ private: mutable QMutex gameListMutex; - QMap > games; // gameId -> (roomId, playerId) + QMap> games; // gameId -> (roomId, playerId) protected: Server *server; + public: - Server_AbstractUserInterface(Server *_server) : server(_server) { } - Server_AbstractUserInterface(Server *_server, const ServerInfo_User_Container &other) : ServerInfo_User_Container(other), server(_server) { } - virtual ~Server_AbstractUserInterface() { } - + Server_AbstractUserInterface(Server *_server) : server(_server) + { + } + Server_AbstractUserInterface(Server *_server, const ServerInfo_User_Container &other) + : ServerInfo_User_Container(other), server(_server) + { + } + virtual ~Server_AbstractUserInterface() + { + } + virtual int getLastCommandTime() const = 0; - + void playerRemovedFromGame(Server_Game *game); void playerAddedToGame(int gameId, int roomId, int playerId); void joinPersistentGames(ResponseContainer &rc); - - QMap > getGames() const { QMutexLocker locker(&gameListMutex); return games; } - + + QMap> getGames() const + { + QMutexLocker locker(&gameListMutex); + return games; + } + virtual void sendProtocolItem(const Response &item) = 0; virtual void sendProtocolItem(const SessionEvent &item) = 0; virtual void sendProtocolItem(const GameEventContainer &item) = 0; virtual void sendProtocolItem(const RoomEvent &item) = 0; void sendProtocolItemByType(ServerMessage::MessageType type, const ::google::protobuf::Message &item); - + static SessionEvent *prepareSessionEvent(const ::google::protobuf::Message &sessionEvent); void sendResponseContainer(const ResponseContainer &responseContainer, Response::ResponseCode responseCode); }; diff --git a/common/server_arrow.cpp b/common/server_arrow.cpp index a668cc25..978115d0 100644 --- a/common/server_arrow.cpp +++ b/common/server_arrow.cpp @@ -1,14 +1,11 @@ #include "server_arrow.h" -#include "server_player.h" +#include "pb/serverinfo_arrow.pb.h" #include "server_card.h" #include "server_cardzone.h" -#include "pb/serverinfo_arrow.pb.h" +#include "server_player.h" Server_Arrow::Server_Arrow(int _id, Server_Card *_startCard, Server_ArrowTarget *_targetItem, const color &_arrowColor) - : id(_id), - startCard(_startCard), - targetItem(_targetItem), - arrowColor(_arrowColor) + : id(_id), startCard(_startCard), targetItem(_targetItem), arrowColor(_arrowColor) { } diff --git a/common/server_arrow.h b/common/server_arrow.h index 01c472ef..305a97f8 100644 --- a/common/server_arrow.h +++ b/common/server_arrow.h @@ -7,19 +7,33 @@ class Server_Card; class Server_ArrowTarget; class ServerInfo_Arrow; -class Server_Arrow { +class Server_Arrow +{ private: int id; Server_Card *startCard; Server_ArrowTarget *targetItem; color arrowColor; + public: Server_Arrow(int _id, Server_Card *_startCard, Server_ArrowTarget *_targetItem, const color &_arrowColor); - int getId() const { return id; } - Server_Card *getStartCard() const { return startCard; } - Server_ArrowTarget *getTargetItem() const { return targetItem; } - const color &getColor() const { return arrowColor; } - + int getId() const + { + return id; + } + Server_Card *getStartCard() const + { + return startCard; + } + Server_ArrowTarget *getTargetItem() const + { + return targetItem; + } + const color &getColor() const + { + return arrowColor; + } + void getInfo(ServerInfo_Arrow *info); }; diff --git a/common/server_arrowtarget.h b/common/server_arrowtarget.h index d94fc4b7..5a080018 100644 --- a/common/server_arrowtarget.h +++ b/common/server_arrowtarget.h @@ -3,7 +3,8 @@ #include -class Server_ArrowTarget : public QObject { +class Server_ArrowTarget : public QObject +{ Q_OBJECT }; diff --git a/common/server_card.cpp b/common/server_card.cpp index 13289e55..b1af9d5b 100644 --- a/common/server_card.cpp +++ b/common/server_card.cpp @@ -18,12 +18,14 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "server_card.h" +#include "pb/serverinfo_card.pb.h" #include "server_cardzone.h" #include "server_player.h" -#include "pb/serverinfo_card.pb.h" Server_Card::Server_Card(QString _name, int _id, int _coord_x, int _coord_y, Server_CardZone *_zone) - : zone(_zone), id(_id), coord_x(_coord_x), coord_y(_coord_y), name(_name), tapped(false), attacking(false), facedown(false), color(QString()), power(-1), toughness(-1), annotation(QString()), destroyOnZoneChange(false), doesntUntap(false), parentCard(0) + : zone(_zone), id(_id), coord_x(_coord_x), coord_y(_coord_y), name(_name), tapped(false), attacking(false), + facedown(false), color(QString()), power(-1), toughness(-1), annotation(QString()), destroyOnZoneChange(false), + doesntUntap(false), parentCard(0) { } @@ -32,7 +34,7 @@ Server_Card::~Server_Card() // setParentCard(0) leads to the item being removed from our list, so we can't iterate properly while (!attachedCards.isEmpty()) attachedCards.first()->setParentCard(0); - + if (parentCard) parentCard->removeAttachedCard(this); } @@ -57,12 +59,24 @@ QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue setTapped(value); break; } - case AttrAttacking: setAttacking(avalue == "1"); break; - case AttrFaceDown: setFaceDown(avalue == "1"); break; - case AttrColor: setColor(avalue); break; - case AttrPT: setPT(avalue); return getPT(); - case AttrAnnotation: setAnnotation(avalue); break; - case AttrDoesntUntap: setDoesntUntap(avalue == "1"); break; + case AttrAttacking: + setAttacking(avalue == "1"); + break; + case AttrFaceDown: + setFaceDown(avalue == "1"); + break; + case AttrColor: + setColor(avalue); + break; + case AttrPT: + setPT(avalue); + return getPT(); + case AttrAnnotation: + setAnnotation(avalue); + break; + case AttrDoesntUntap: + setDoesntUntap(avalue == "1"); + break; } return avalue; } @@ -121,14 +135,13 @@ void Server_Card::setParentCard(Server_Card *_parentCard) void Server_Card::getInfo(ServerInfo_Card *info) { QString displayedName = facedown ? QString() : name; - + info->set_id(id); info->set_name(displayedName.toStdString()); info->set_x(coord_x); info->set_y(coord_y); QString ptStr = getPT(); - if (facedown) - { + if (facedown) { info->set_face_down(true); ptStr = getPT(); } @@ -145,7 +158,7 @@ void Server_Card::getInfo(ServerInfo_Card *info) info->set_destroy_on_zone_change(true); if (doesntUntap) info->set_doesnt_untap(true); - + QMapIterator cardCounterIterator(counters); while (cardCounterIterator.hasNext()) { cardCounterIterator.next(); diff --git a/common/server_card.h b/common/server_card.h index e3c76f05..a3564bbc 100644 --- a/common/server_card.h +++ b/common/server_card.h @@ -20,15 +20,16 @@ #ifndef SERVER_CARD_H #define SERVER_CARD_H -#include "server_arrowtarget.h" #include "pb/card_attributes.pb.h" -#include +#include "server_arrowtarget.h" #include +#include class Server_CardZone; class ServerInfo_Card; -class Server_Card : public Server_ArrowTarget { +class Server_Card : public Server_ArrowTarget +{ Q_OBJECT private: Server_CardZone *zone; @@ -44,52 +45,141 @@ private: QString annotation; bool destroyOnZoneChange; bool doesntUntap; - + Server_Card *parentCard; QList attachedCards; + public: Server_Card(QString _name, int _id, int _coord_x, int _coord_y, Server_CardZone *_zone = 0); ~Server_Card(); - - Server_CardZone *getZone() const { return zone; } - void setZone(Server_CardZone *_zone) { zone = _zone; } - - int getId() const { return id; } - int getX() const { return coord_x; } - int getY() const { return coord_y; } - QString getName() const { return name; } - const QMap &getCounters() const { return counters; } - int getCounter(int id) const { return counters.value(id, 0); } - bool getTapped() const { return tapped; } - bool getAttacking() const { return attacking; } - bool getFaceDown() const { return facedown; } - QString getColor() const { return color; } - QString getPT() const; - QString getAnnotation() const { return annotation; } - bool getDoesntUntap() const { return doesntUntap; } - bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } - Server_Card *getParentCard() const { return parentCard; } - const QList &getAttachedCards() const { return attachedCards; } - void setId(int _id) { id = _id; } - void setCoords(int x, int y) { coord_x = x; coord_y = y; } - void setName(const QString &_name) { name = _name; } + Server_CardZone *getZone() const + { + return zone; + } + void setZone(Server_CardZone *_zone) + { + zone = _zone; + } + + int getId() const + { + return id; + } + int getX() const + { + return coord_x; + } + int getY() const + { + return coord_y; + } + QString getName() const + { + return name; + } + const QMap &getCounters() const + { + return counters; + } + int getCounter(int id) const + { + return counters.value(id, 0); + } + bool getTapped() const + { + return tapped; + } + bool getAttacking() const + { + return attacking; + } + bool getFaceDown() const + { + return facedown; + } + QString getColor() const + { + return color; + } + QString getPT() const; + QString getAnnotation() const + { + return annotation; + } + bool getDoesntUntap() const + { + return doesntUntap; + } + bool getDestroyOnZoneChange() const + { + return destroyOnZoneChange; + } + Server_Card *getParentCard() const + { + return parentCard; + } + const QList &getAttachedCards() const + { + return attachedCards; + } + + void setId(int _id) + { + id = _id; + } + void setCoords(int x, int y) + { + coord_x = x; + coord_y = y; + } + void setName(const QString &_name) + { + name = _name; + } void setCounter(int id, int value); - void setTapped(bool _tapped) { tapped = _tapped; } - void setAttacking(bool _attacking) { attacking = _attacking; } - void setFaceDown(bool _facedown) { facedown = _facedown; } - void setColor(const QString &_color) { color = _color; } + void setTapped(bool _tapped) + { + tapped = _tapped; + } + void setAttacking(bool _attacking) + { + attacking = _attacking; + } + void setFaceDown(bool _facedown) + { + facedown = _facedown; + } + void setColor(const QString &_color) + { + color = _color; + } void setPT(const QString &_pt); - void setAnnotation(const QString &_annotation) { annotation = _annotation; } - void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } - void setDoesntUntap(bool _doesntUntap) { doesntUntap = _doesntUntap; } + void setAnnotation(const QString &_annotation) + { + annotation = _annotation; + } + void setDestroyOnZoneChange(bool _destroy) + { + destroyOnZoneChange = _destroy; + } + void setDoesntUntap(bool _doesntUntap) + { + doesntUntap = _doesntUntap; + } void setParentCard(Server_Card *_parentCard); - void addAttachedCard(Server_Card *card) { attachedCards.append(card); } - void removeAttachedCard(Server_Card *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } - + void addAttachedCard(Server_Card *card) + { + attachedCards.append(card); + } + void removeAttachedCard(Server_Card *card) + { + attachedCards.removeAt(attachedCards.indexOf(card)); + } + void resetState(); QString setAttribute(CardAttribute attribute, const QString &avalue, bool allCards); - + void getInfo(ServerInfo_Card *info); }; diff --git a/common/server_cardzone.cpp b/common/server_cardzone.cpp index 3e128a3e..fbf0cf2f 100644 --- a/common/server_cardzone.cpp +++ b/common/server_cardzone.cpp @@ -18,20 +18,19 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "server_cardzone.h" +#include "pb/command_move_card.pb.h" +#include "rng_abstract.h" #include "server_card.h" #include "server_player.h" -#include "rng_abstract.h" -#include #include -#include "pb/command_move_card.pb.h" +#include -Server_CardZone::Server_CardZone(Server_Player *_player, const QString &_name, bool _has_coords, ServerInfo_Zone::ZoneType _type) - : player(_player), - name(_name), - has_coords(_has_coords), - type(_type), - cardsBeingLookedAt(0), - alwaysRevealTopCard(false) +Server_CardZone::Server_CardZone(Server_Player *_player, + const QString &_name, + bool _has_coords, + ServerInfo_Zone::ZoneType _type) + : player(_player), name(_name), has_coords(_has_coords), type(_type), cardsBeingLookedAt(0), + alwaysRevealTopCard(false) { } @@ -44,33 +43,35 @@ Server_CardZone::~Server_CardZone() void Server_CardZone::shuffle() { // Size 0 or 1 decks are sorted - if (cards.size() < 2) return; - for (int i = cards.size() - 1; i > 0; i--){ + if (cards.size() < 2) + return; + for (int i = cards.size() - 1; i > 0; i--) { int j = rng->rand(0, i); - cards.swap(j,i); + cards.swap(j, i); } playersWithWritePermission.clear(); } - void Server_CardZone::removeCardFromCoordMap(Server_Card *card, int oldX, int oldY) { if (oldX < 0) return; - + const int baseX = (oldX / 3) * 3; QMap &coordMap = coordinateMap[oldY]; - + if (coordMap.contains(baseX) && coordMap.contains(baseX + 1) && coordMap.contains(baseX + 2)) // If the removal of this card has opened up a previously full pile... freePilesMap[oldY].insert(coordMap.value(baseX)->getName(), baseX); - + coordMap.remove(oldX); - - if (!(coordMap.contains(baseX) && coordMap.value(baseX)->getName() == card->getName()) && !(coordMap.contains(baseX + 1) && coordMap.value(baseX + 1)->getName() == card->getName()) && !(coordMap.contains(baseX + 2) && coordMap.value(baseX + 2)->getName() == card->getName())) + + if (!(coordMap.contains(baseX) && coordMap.value(baseX)->getName() == card->getName()) && + !(coordMap.contains(baseX + 1) && coordMap.value(baseX + 1)->getName() == card->getName()) && + !(coordMap.contains(baseX + 2) && coordMap.value(baseX + 2)->getName() == card->getName())) // If this card was the last one with this name... freePilesMap[oldY].remove(card->getName(), baseX); - + if (!coordMap.contains(baseX) && !coordMap.contains(baseX + 1) && !coordMap.contains(baseX + 2)) { // If the removal of this card has freed a whole pile, i.e. it was the last card in it... if (baseX < freeSpaceMap[oldY]) @@ -82,7 +83,7 @@ void Server_CardZone::insertCardIntoCoordMap(Server_Card *card, int x, int y) { if (x < 0) return; - + coordinateMap[y].insert(x, card); if (!(x % 3)) { if (!card->getFaceDown() && !freePilesMap[y].contains(card->getName(), x) && card->getAttachedCards().isEmpty()) @@ -91,7 +92,8 @@ void Server_CardZone::insertCardIntoCoordMap(Server_Card *card, int x, int y) int nextFreeX = x; do { nextFreeX += 3; - } while (coordinateMap[y].contains(nextFreeX) || coordinateMap[y].contains(nextFreeX + 1) || coordinateMap[y].contains(nextFreeX + 2)); + } while (coordinateMap[y].contains(nextFreeX) || coordinateMap[y].contains(nextFreeX + 1) || + coordinateMap[y].contains(nextFreeX + 2)); freeSpaceMap[y] = nextFreeX; } } else if (!((x - 2) % 3)) { @@ -107,7 +109,7 @@ int Server_CardZone::removeCard(Server_Card *card) if (has_coords) removeCardFromCoordMap(card, card->getX(), card->getY()); card->setZone(0); - + return index; } @@ -147,10 +149,8 @@ int Server_CardZone::getFreeGridColumn(int x, int y, const QString &cardName, bo if (x == -1) { if (!dontStackSameName && freePilesMap[y].contains(cardName)) { x = (freePilesMap[y].value(cardName) / 3) * 3; - - if(coordMap.contains(x) && - (coordMap[x]->getFaceDown() || - !coordMap[x]->getAttachedCards().isEmpty())) { + + if (coordMap.contains(x) && (coordMap[x]->getFaceDown() || !coordMap[x]->getAttachedCards().isEmpty())) { // don't pile up on: 1. facedown cards 2. cards with attached cards } else if (!coordMap.contains(x)) return x; @@ -181,7 +181,7 @@ int Server_CardZone::getFreeGridColumn(int x, int y, const QString &cardName, bo return resultX; } - + return freeSpaceMap[y]; } @@ -189,7 +189,7 @@ bool Server_CardZone::isColumnStacked(int x, int y) const { if (!has_coords) return false; - + return coordinateMap[y].contains((x / 3) * 3 + 1); } @@ -197,7 +197,7 @@ bool Server_CardZone::isColumnEmpty(int x, int y) const { if (!has_coords) return true; - + return !coordinateMap[y].contains((x / 3) * 3); } @@ -213,17 +213,17 @@ void Server_CardZone::fixFreeSpaces(GameEventStorage &ges) { if (!has_coords) return; - - QSet > placesToLook; + + QSet> placesToLook; for (int i = 0; i < cards.size(); ++i) placesToLook.insert(QPair((cards[i]->getX() / 3) * 3, cards[i]->getY())); - - QSetIterator > placeIterator(placesToLook); + + QSetIterator> placeIterator(placesToLook); while (placeIterator.hasNext()) { const QPair &foo = placeIterator.next(); int baseX = foo.first; int y = foo.second; - + if (!coordinateMap[y].contains(baseX)) { if (coordinateMap[y].contains(baseX + 1)) moveCardInRow(ges, coordinateMap[y].value(baseX + 1), baseX, y); @@ -242,7 +242,7 @@ void Server_CardZone::updateCardCoordinates(Server_Card *card, int oldX, int old { if (!has_coords) return; - + if (oldX != -1) removeCardFromCoordMap(card, oldX, oldY); insertCardIntoCoordMap(card, card->getX(), card->getY()); @@ -287,10 +287,8 @@ void Server_CardZone::getInfo(ServerInfo_Zone *info, Server_Player *playerWhosAs info->set_with_coords(has_coords); info->set_card_count(cards.size()); info->set_always_reveal_top_card(alwaysRevealTopCard); - if ( - (((playerWhosAsking == player) || omniscient) && (type != ServerInfo_Zone::HiddenZone)) - || ((playerWhosAsking != player) && (type == ServerInfo_Zone::PublicZone)) - ) { + if ((((playerWhosAsking == player) || omniscient) && (type != ServerInfo_Zone::HiddenZone)) || + ((playerWhosAsking != player) && (type == ServerInfo_Zone::PublicZone))) { QListIterator cardIterator(cards); while (cardIterator.hasNext()) cardIterator.next()->getInfo(info->add_card_list()); diff --git a/common/server_cardzone.h b/common/server_cardzone.h index 102aebb0..a2061540 100644 --- a/common/server_cardzone.h +++ b/common/server_cardzone.h @@ -20,18 +20,19 @@ #ifndef SERVER_CARDZONE_H #define SERVER_CARDZONE_H +#include "pb/serverinfo_zone.pb.h" #include -#include #include #include -#include "pb/serverinfo_zone.pb.h" +#include class Server_Card; class Server_Player; class Server_Game; class GameEventStorage; -class Server_CardZone { +class Server_CardZone +{ private: Server_Player *player; QString name; @@ -41,27 +42,49 @@ private: QSet playersWithWritePermission; bool alwaysRevealTopCard; QList cards; - QMap > coordinateMap; // y -> (x -> card) - QMap > freePilesMap; // y -> (cardName -> x) - QMap freeSpaceMap; // y -> x + QMap> coordinateMap; // y -> (x -> card) + QMap> freePilesMap; // y -> (cardName -> x) + QMap freeSpaceMap; // y -> x void removeCardFromCoordMap(Server_Card *card, int oldX, int oldY); void insertCardIntoCoordMap(Server_Card *card, int x, int y); + public: Server_CardZone(Server_Player *_player, const QString &_name, bool _has_coords, ServerInfo_Zone::ZoneType _type); ~Server_CardZone(); - - const QList &getCards() const { return cards; } + + const QList &getCards() const + { + return cards; + } int removeCard(Server_Card *card); Server_Card *getCard(int id, int *position = NULL, bool remove = false); - int getCardsBeingLookedAt() const { return cardsBeingLookedAt; } - void setCardsBeingLookedAt(int _cardsBeingLookedAt) { cardsBeingLookedAt = _cardsBeingLookedAt; } - bool hasCoords() const { return has_coords; } - ServerInfo_Zone::ZoneType getType() const { return type; } - QString getName() const { return name; } - Server_Player *getPlayer() const { return player; } + int getCardsBeingLookedAt() const + { + return cardsBeingLookedAt; + } + void setCardsBeingLookedAt(int _cardsBeingLookedAt) + { + cardsBeingLookedAt = _cardsBeingLookedAt; + } + bool hasCoords() const + { + return has_coords; + } + ServerInfo_Zone::ZoneType getType() const + { + return type; + } + QString getName() const + { + return name; + } + Server_Player *getPlayer() const + { + return player; + } void getInfo(ServerInfo_Zone *info, Server_Player *playerWhosAsking, bool omniscient); - + int getFreeGridColumn(int x, int y, const QString &cardName, bool dontStackSameName) const; bool isColumnEmpty(int x, int y) const; bool isColumnStacked(int x, int y) const; @@ -72,9 +95,18 @@ public: void shuffle(); void clear(); void addWritePermission(int playerId); - const QSet &getPlayersWithWritePermission() const { return playersWithWritePermission; } - bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } - void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } + const QSet &getPlayersWithWritePermission() const + { + return playersWithWritePermission; + } + bool getAlwaysRevealTopCard() const + { + return alwaysRevealTopCard; + } + void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) + { + alwaysRevealTopCard = _alwaysRevealTopCard; + } }; #endif diff --git a/common/server_counter.cpp b/common/server_counter.cpp index df8dcd03..14f52617 100644 --- a/common/server_counter.cpp +++ b/common/server_counter.cpp @@ -2,11 +2,7 @@ #include "pb/serverinfo_counter.pb.h" Server_Counter::Server_Counter(int _id, const QString &_name, const color &_counterColor, int _radius, int _count) - : id(_id), - name(_name), - counterColor(_counterColor), - radius(_radius), - count(_count) + : id(_id), name(_name), counterColor(_counterColor), radius(_radius), count(_count) { } diff --git a/common/server_counter.h b/common/server_counter.h index 60b70e69..30cfb588 100644 --- a/common/server_counter.h +++ b/common/server_counter.h @@ -20,28 +20,50 @@ #ifndef SERVER_COUNTER_H #define SERVER_COUNTER_H -#include #include "pb/color.pb.h" +#include class ServerInfo_Counter; -class Server_Counter { +class Server_Counter +{ protected: int id; QString name; color counterColor; int radius; int count; + public: Server_Counter(int _id, const QString &_name, const color &_counterColor, int _radius, int _count = 0); - ~Server_Counter() { } - int getId() const { return id; } - QString getName() const { return name; } - const color &getColor() const { return counterColor; } - int getRadius() const { return radius; } - int getCount() const { return count; } - void setCount(int _count) { count = _count; } - + ~Server_Counter() + { + } + int getId() const + { + return id; + } + QString getName() const + { + return name; + } + const color &getColor() const + { + return counterColor; + } + int getRadius() const + { + return radius; + } + int getCount() const + { + return count; + } + void setCount(int _count) + { + count = _count; + } + void getInfo(ServerInfo_Counter *info); }; diff --git a/common/server_database_interface.h b/common/server_database_interface.h index e36629f6..037353ba 100644 --- a/common/server_database_interface.h +++ b/common/server_database_interface.h @@ -1,53 +1,162 @@ #ifndef SERVER_DATABASE_INTERFACE_H #define SERVER_DATABASE_INTERFACE_H -#include #include "server.h" +#include -class Server_DatabaseInterface : public QObject { +class Server_DatabaseInterface : public QObject +{ Q_OBJECT public: - Server_DatabaseInterface(QObject *parent = 0) - : QObject(parent) { } - - virtual AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, const QString &clientId, QString &reasonStr, int &secondsLeft) = 0; - virtual bool checkUserIsBanned(const QString & /* ipAddress */, const QString & /* userName */, const QString & /* clientId */, QString & /* banReason */, int & /* banSecondsRemaining */) { return false; } - virtual bool activeUserExists(const QString & /* user */) { return false; } - virtual bool userExists(const QString & /* user */) { return false; } - virtual QMap getBuddyList(const QString & /* name */) { return QMap(); } - virtual QMap getIgnoreList(const QString & /* name */) { return QMap(); } - virtual bool isInBuddyList(const QString & /* whoseList */, const QString & /* who */) { return false; } - virtual bool isInIgnoreList(const QString & /* whoseList */, const QString & /* who */) { return false; } + Server_DatabaseInterface(QObject *parent = 0) : QObject(parent) + { + } + + virtual AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, + const QString &user, + const QString &password, + const QString &clientId, + QString &reasonStr, + int &secondsLeft) = 0; + virtual bool checkUserIsBanned(const QString & /* ipAddress */, + const QString & /* userName */, + const QString & /* clientId */, + QString & /* banReason */, + int & /* banSecondsRemaining */) + { + return false; + } + virtual bool activeUserExists(const QString & /* user */) + { + return false; + } + virtual bool userExists(const QString & /* user */) + { + return false; + } + virtual QMap getBuddyList(const QString & /* name */) + { + return QMap(); + } + virtual QMap getIgnoreList(const QString & /* name */) + { + return QMap(); + } + virtual bool isInBuddyList(const QString & /* whoseList */, const QString & /* who */) + { + return false; + } + virtual bool isInIgnoreList(const QString & /* whoseList */, const QString & /* who */) + { + return false; + } virtual ServerInfo_User getUserData(const QString &name, bool withId = false) = 0; - virtual void storeGameInformation(const QString & /* roomName */, const QStringList & /* roomGameTypes */, const ServerInfo_Game & /* gameInfo */, const QSet & /* allPlayersEver */, const QSet & /* allSpectatorsEver */, const QList & /* replayList */) { } - virtual DeckList *getDeckFromDatabase(int /* deckId */, int /* userId */) { return 0; } - virtual bool removeForgotPassword(const QString & /* user */) { return false; } - virtual qint64 startSession(const QString & /* userName */, const QString & /* address */, const QString & /* clientId */, const QString & /* connectionType */) { return 0; } - virtual bool usernameIsValid(const QString & /*userName */, QString & /* error */) { return true; }; + virtual void storeGameInformation(const QString & /* roomName */, + const QStringList & /* roomGameTypes */, + const ServerInfo_Game & /* gameInfo */, + const QSet & /* allPlayersEver */, + const QSet & /* allSpectatorsEver */, + const QList & /* replayList */) + { + } + virtual DeckList *getDeckFromDatabase(int /* deckId */, int /* userId */) + { + return 0; + } + virtual bool removeForgotPassword(const QString & /* user */) + { + return false; + } + virtual qint64 startSession(const QString & /* userName */, + const QString & /* address */, + const QString & /* clientId */, + const QString & /* connectionType */) + { + return 0; + } + virtual bool usernameIsValid(const QString & /*userName */, QString & /* error */) + { + return true; + }; public slots: - virtual void endSession(qint64 /* sessionId */ ) { } + virtual void endSession(qint64 /* sessionId */) + { + } + public: virtual int getNextGameId() = 0; virtual int getNextReplayId() = 0; virtual int getActiveUserCount(QString connectionType = QString()) = 0; - - virtual void clearSessionTables() { } - virtual void lockSessionTables() { } - virtual void unlockSessionTables() { } - virtual bool userSessionExists(const QString & /* userName */) { return false; } - virtual bool getRequireRegistration() { return false; } - virtual bool registerUser(const QString & /* userName */, const QString & /* realName */, ServerInfo_User_Gender const & /* gender */, const QString & /* password */, const QString & /* emailAddress */, const QString & /* country */, bool /* active = false */) { return false; } - virtual bool activateUser(const QString & /* userName */, const QString & /* token */) { return false; } - virtual void updateUsersClientID(const QString & /* userName */, const QString & /* userClientID */) { } - virtual void updateUsersLastLoginData(const QString & /* userName */, const QString & /* clientVersion */) { } + virtual void clearSessionTables() + { + } + virtual void lockSessionTables() + { + } + virtual void unlockSessionTables() + { + } + virtual bool userSessionExists(const QString & /* userName */) + { + return false; + } - enum LogMessage_TargetType { MessageTargetRoom, MessageTargetGame, MessageTargetChat, MessageTargetIslRoom }; - virtual void logMessage(const int /* senderId */, const QString & /* senderName */, const QString & /* senderIp */, const QString & /* logMessage */, LogMessage_TargetType /* targetType */, const int /* targetId */, const QString & /* targetName */) { }; + virtual bool getRequireRegistration() + { + return false; + } + virtual bool registerUser(const QString & /* userName */, + const QString & /* realName */, + ServerInfo_User_Gender const & /* gender */, + const QString & /* password */, + const QString & /* emailAddress */, + const QString & /* country */, + bool /* active = false */) + { + return false; + } + virtual bool activateUser(const QString & /* userName */, const QString & /* token */) + { + return false; + } + virtual void updateUsersClientID(const QString & /* userName */, const QString & /* userClientID */) + { + } + virtual void updateUsersLastLoginData(const QString & /* userName */, const QString & /* clientVersion */) + { + } + + enum LogMessage_TargetType + { + MessageTargetRoom, + MessageTargetGame, + MessageTargetChat, + MessageTargetIslRoom + }; + virtual void logMessage(const int /* senderId */, + const QString & /* senderName */, + const QString & /* senderIp */, + const QString & /* logMessage */, + LogMessage_TargetType /* targetType */, + const int /* targetId */, + const QString & /* targetName */){}; bool checkUserIsBanned(Server_ProtocolHandler *session, QString &banReason, int &banSecondsRemaining); - virtual int checkNumberOfUserAccounts(const QString & /* email */) { return 0; }; - virtual bool changeUserPassword(const QString & /* user */, const QString & /* oldPassword */, const QString & /* newPassword */, const bool & /* force */) { return false; }; - virtual QChar getGenderChar(ServerInfo_User_Gender const & /* gender */) { return QChar('u'); }; + virtual int checkNumberOfUserAccounts(const QString & /* email */) + { + return 0; + }; + virtual bool changeUserPassword(const QString & /* user */, + const QString & /* oldPassword */, + const QString & /* newPassword */, + const bool & /* force */) + { + return false; + }; + virtual QChar getGenderChar(ServerInfo_User_Gender const & /* gender */) + { + return QChar('u'); + }; }; #endif diff --git a/common/server_game.cpp b/common/server_game.cpp index 87f5fcd3..859ae81f 100644 --- a/common/server_game.cpp +++ b/common/server_game.cpp @@ -17,62 +17,56 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include "server.h" -#include "server_room.h" #include "server_game.h" -#include "server_player.h" -#include "server_protocolhandler.h" +#include "decklist.h" +#include "pb/context_connection_state_changed.pb.h" +#include "pb/context_ping_changed.pb.h" +#include "pb/event_delete_arrow.pb.h" +#include "pb/event_game_closed.pb.h" +#include "pb/event_game_host_changed.pb.h" +#include "pb/event_game_joined.pb.h" +#include "pb/event_game_state_changed.pb.h" +#include "pb/event_join.pb.h" +#include "pb/event_kicked.pb.h" +#include "pb/event_leave.pb.h" +#include "pb/event_player_properties_changed.pb.h" +#include "pb/event_replay_added.pb.h" +#include "pb/event_set_active_phase.pb.h" +#include "pb/event_set_active_player.pb.h" +#include "pb/game_replay.pb.h" +#include "pb/serverinfo_playerping.pb.h" +#include "server.h" #include "server_arrow.h" #include "server_card.h" #include "server_cardzone.h" #include "server_database_interface.h" -#include "decklist.h" -#include "pb/context_connection_state_changed.pb.h" -#include "pb/context_ping_changed.pb.h" -#include "pb/event_player_properties_changed.pb.h" -#include "pb/event_game_closed.pb.h" -#include "pb/event_game_joined.pb.h" -#include "pb/event_game_host_changed.pb.h" -#include "pb/event_game_state_changed.pb.h" -#include "pb/event_kicked.pb.h" -#include "pb/event_join.pb.h" -#include "pb/event_leave.pb.h" -#include "pb/event_delete_arrow.pb.h" -#include "pb/event_set_active_player.pb.h" -#include "pb/event_set_active_phase.pb.h" -#include "pb/serverinfo_playerping.pb.h" -#include "pb/game_replay.pb.h" -#include "pb/event_replay_added.pb.h" -#include -#include +#include "server_player.h" +#include "server_protocolhandler.h" +#include "server_room.h" #include +#include +#include -Server_Game::Server_Game(const ServerInfo_User &_creatorInfo, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, const QList &_gameTypes, bool _onlyBuddies, bool _onlyRegistered, bool _spectatorsAllowed, bool _spectatorsNeedPassword, bool _spectatorsCanTalk, bool _spectatorsSeeEverything, Server_Room *_room) - : QObject(), - room(_room), - nextPlayerId(0), - hostId(0), - creatorInfo(new ServerInfo_User(_creatorInfo)), - gameStarted(false), - gameClosed(false), - gameId(_gameId), - password(_password), - maxPlayers(_maxPlayers), - gameTypes(_gameTypes), - activePlayer(-1), - activePhase(-1), - onlyBuddies(_onlyBuddies), - onlyRegistered(_onlyRegistered), - spectatorsAllowed(_spectatorsAllowed), - spectatorsNeedPassword(_spectatorsNeedPassword), - spectatorsCanTalk(_spectatorsCanTalk), - spectatorsSeeEverything(_spectatorsSeeEverything), - inactivityCounter(0), - startTimeOfThisGame(0), - secondsElapsed(0), - firstGameStarted(false), - startTime(QDateTime::currentDateTime()), - gameMutex(QMutex::Recursive) +Server_Game::Server_Game(const ServerInfo_User &_creatorInfo, + int _gameId, + const QString &_description, + const QString &_password, + int _maxPlayers, + const QList &_gameTypes, + bool _onlyBuddies, + bool _onlyRegistered, + bool _spectatorsAllowed, + bool _spectatorsNeedPassword, + bool _spectatorsCanTalk, + bool _spectatorsSeeEverything, + Server_Room *_room) + : QObject(), room(_room), nextPlayerId(0), hostId(0), creatorInfo(new ServerInfo_User(_creatorInfo)), + gameStarted(false), gameClosed(false), gameId(_gameId), password(_password), maxPlayers(_maxPlayers), + gameTypes(_gameTypes), activePlayer(-1), activePhase(-1), onlyBuddies(_onlyBuddies), + onlyRegistered(_onlyRegistered), spectatorsAllowed(_spectatorsAllowed), + spectatorsNeedPassword(_spectatorsNeedPassword), spectatorsCanTalk(_spectatorsCanTalk), + spectatorsSeeEverything(_spectatorsSeeEverything), inactivityCounter(0), startTimeOfThisGame(0), + secondsElapsed(0), firstGameStarted(false), startTime(QDateTime::currentDateTime()), gameMutex(QMutex::Recursive) { currentReplay = new GameReplay; currentReplay->set_replay_id(room->getServer()->getDatabaseInterface()->getNextReplayId()); @@ -154,14 +148,14 @@ void Server_Game::storeGameInformation() while (allUsersIterator.hasNext()) { Server_AbstractUserInterface *userHandler = server->findUser(allUsersIterator.next()); if (userHandler && server->getStoreReplaysEnabled()) - userHandler->sendProtocolItem(*sessionEvent); + userHandler->sendProtocolItem(*sessionEvent); } server->clientsLock.unlock(); delete sessionEvent; if (server->getStoreReplaysEnabled()) - server->getDatabaseInterface()->storeGameInformation(room->getName(), gameTypes, gameInfo, allPlayersEver, allSpectatorsEver, replayList); - + server->getDatabaseInterface()->storeGameInformation(room->getName(), gameTypes, gameInfo, allPlayersEver, + allSpectatorsEver, replayList); } void Server_Game::pingClockTimeout() @@ -193,7 +187,8 @@ void Server_Game::pingClockTimeout() if ((newPingTime != -1) && !player->getSpectator()) allPlayersInactive = false; - if ((abs(oldPingTime - newPingTime) > 1) || ((newPingTime == -1) && (oldPingTime != -1)) || ((newPingTime != -1) && (oldPingTime == -1))) { + if ((abs(oldPingTime - newPingTime) > 1) || ((newPingTime == -1) && (oldPingTime != -1)) || + ((newPingTime != -1) && (oldPingTime == -1))) { player->setPingTime(newPingTime); Event_PlayerPropertiesChanged event; @@ -235,7 +230,10 @@ int Server_Game::getSpectatorCount() const return result; } -void Server_Game::createGameStateChangedEvent(Event_GameStateChanged *event, Server_Player *playerWhosAsking, bool omniscient, bool withUserInfo) +void Server_Game::createGameStateChangedEvent(Event_GameStateChanged *event, + Server_Player *playerWhosAsking, + bool omniscient, + bool withUserInfo) { event->set_seconds_elapsed(secondsElapsed); if (gameStarted) { @@ -262,8 +260,9 @@ void Server_Game::sendGameStateToPlayers() currentReplay->add_event_list()->CopyFrom(*replayCont); delete replayCont; - // If spectators are not omniscient, we need an additional createGameStateChangedEvent call, otherwise we can use the data we used for the replay. - // All spectators are equal, so we don't need to make a createGameStateChangedEvent call for each one. + // If spectators are not omniscient, we need an additional createGameStateChangedEvent call, otherwise we can use + // the data we used for the replay. All spectators are equal, so we don't need to make a createGameStateChangedEvent + // call for each one. Event_GameStateChanged spectatorEvent; if (spectatorsSeeEverything) spectatorEvent = omniscientEvent; @@ -391,7 +390,8 @@ void Server_Game::stopGameIfFinished() emit gameInfoChanged(gameInfo); } -Response::ResponseCode Server_Game::checkJoin(ServerInfo_User *user, const QString &_password, bool spectator, bool overrideRestrictions) +Response::ResponseCode +Server_Game::checkJoin(ServerInfo_User *user, const QString &_password, bool spectator, bool overrideRestrictions) { Server_DatabaseInterface *databaseInterface = room->getServer()->getDatabaseInterface(); { @@ -406,9 +406,11 @@ Response::ResponseCode Server_Game::checkJoin(ServerInfo_User *user, const QStri if (!(user->user_level() & ServerInfo_User::IsRegistered) && onlyRegistered) return Response::RespUserLevelTooLow; if (onlyBuddies && (user->name() != creatorInfo->name())) - if (!databaseInterface->isInBuddyList(QString::fromStdString(creatorInfo->name()), QString::fromStdString(user->name()))) + if (!databaseInterface->isInBuddyList(QString::fromStdString(creatorInfo->name()), + QString::fromStdString(user->name()))) return Response::RespOnlyBuddies; - if (databaseInterface->isInIgnoreList(QString::fromStdString(creatorInfo->name()), QString::fromStdString(user->name()))) + if (databaseInterface->isInIgnoreList(QString::fromStdString(creatorInfo->name()), + QString::fromStdString(user->name()))) return Response::RespInIgnoreList; if (spectator) { if (!spectatorsAllowed) @@ -432,11 +434,15 @@ bool Server_Game::containsUser(const QString &userName) const return false; } -void Server_Game::addPlayer(Server_AbstractUserInterface *userInterface, ResponseContainer &rc, bool spectator, bool broadcastUpdate) +void Server_Game::addPlayer(Server_AbstractUserInterface *userInterface, + ResponseContainer &rc, + bool spectator, + bool broadcastUpdate) { QMutexLocker locker(&gameMutex); - Server_Player *newPlayer = new Server_Player(this, nextPlayerId++, userInterface->copyUserInfo(true, true, true), spectator, userInterface); + Server_Player *newPlayer = new Server_Player(this, nextPlayerId++, userInterface->copyUserInfo(true, true, true), + spectator, userInterface); newPlayer->moveToThread(thread()); Event_Join joinEvent; @@ -473,7 +479,8 @@ void Server_Game::addPlayer(Server_AbstractUserInterface *userInterface, Respons void Server_Game::removePlayer(Server_Player *player, Event_Leave::LeaveReason reason) { - room->getServer()->removePersistentPlayer(QString::fromStdString(player->getUserInfo()->name()), room->getId(), gameId, player->getPlayerId()); + room->getServer()->removePersistentPlayer(QString::fromStdString(player->getUserInfo()->name()), room->getId(), + gameId, player->getPlayerId()); players.remove(player->getPlayerId()); GameEventStorage ges; @@ -675,12 +682,15 @@ void Server_Game::createGameJoinedEvent(Server_Player *player, ResponseContainer QMapIterator playerIterator(players); while (playerIterator.hasNext()) - playerIterator.next().value()->getInfo(event2.add_player_list(), player, player->getSpectator() && spectatorsSeeEverything, true); + playerIterator.next().value()->getInfo(event2.add_player_list(), player, + player->getSpectator() && spectatorsSeeEverything, true); rc.enqueuePostResponseItem(ServerMessage::GAME_EVENT_CONTAINER, prepareGameEvent(event2, -1)); } -void Server_Game::sendGameEventContainer(GameEventContainer *cont, GameEventStorageItem::EventRecipients recipients, int privatePlayerId) +void Server_Game::sendGameEventContainer(GameEventContainer *cont, + GameEventStorageItem::EventRecipients recipients, + int privatePlayerId) { QMutexLocker locker(&gameMutex); @@ -688,8 +698,10 @@ void Server_Game::sendGameEventContainer(GameEventContainer *cont, GameEventStor QMapIterator playerIterator(players); while (playerIterator.hasNext()) { Server_Player *p = playerIterator.next().value(); - const bool playerPrivate = (p->getPlayerId() == privatePlayerId) || (p->getSpectator() && spectatorsSeeEverything); - if ((recipients.testFlag(GameEventStorageItem::SendToPrivate) && playerPrivate) || (recipients.testFlag(GameEventStorageItem::SendToOthers) && !playerPrivate)) + const bool playerPrivate = + (p->getPlayerId() == privatePlayerId) || (p->getSpectator() && spectatorsSeeEverything); + if ((recipients.testFlag(GameEventStorageItem::SendToPrivate) && playerPrivate) || + (recipients.testFlag(GameEventStorageItem::SendToOthers) && !playerPrivate)) p->sendGameEvent(*cont); } if (recipients.testFlag(GameEventStorageItem::SendToPrivate)) { @@ -701,7 +713,8 @@ void Server_Game::sendGameEventContainer(GameEventContainer *cont, GameEventStor delete cont; } -GameEventContainer *Server_Game::prepareGameEvent(const ::google::protobuf::Message &gameEvent, int playerId, GameEventContext *context) +GameEventContainer * +Server_Game::prepareGameEvent(const ::google::protobuf::Message &gameEvent, int playerId, GameEventContext *context) { GameEventContainer *cont = new GameEventContainer; cont->set_game_id(gameId); @@ -710,7 +723,9 @@ GameEventContainer *Server_Game::prepareGameEvent(const ::google::protobuf::Mess GameEvent *event = cont->add_event_list(); if (playerId != -1) event->set_player_id(playerId); - event->GetReflection()->MutableMessage(event, gameEvent.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(gameEvent); + event->GetReflection() + ->MutableMessage(event, gameEvent.GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(gameEvent); return cont; } diff --git a/common/server_game.h b/common/server_game.h index 606f2df2..ca704a87 100644 --- a/common/server_game.h +++ b/common/server_game.h @@ -20,16 +20,16 @@ #ifndef SERVERGAME_H #define SERVERGAME_H -#include -#include -#include -#include -#include -#include -#include "server_response_containers.h" +#include "pb/event_leave.pb.h" #include "pb/response.pb.h" #include "pb/serverinfo_game.pb.h" -#include "pb/event_leave.pb.h" +#include "server_response_containers.h" +#include +#include +#include +#include +#include +#include class QTimer; class GameEventContainer; @@ -42,7 +42,8 @@ class ServerInfo_Game; class Server_AbstractUserInterface; class Event_GameStateChanged; -class Server_Game : public QObject { +class Server_Game : public QObject +{ Q_OBJECT private: Server_Room *room; @@ -71,8 +72,11 @@ private: QTimer *pingClock; QList replayList; GameReplay *currentReplay; - - void createGameStateChangedEvent(Event_GameStateChanged *event, Server_Player *playerWhosAsking, bool omniscient, bool withUserInfo); + + void createGameStateChangedEvent(Event_GameStateChanged *event, + Server_Player *playerWhosAsking, + bool omniscient, + bool withUserInfo); void sendGameStateToPlayers(); void storeGameInformation(); signals: @@ -81,48 +85,117 @@ signals: private slots: void pingClockTimeout(); void doStartGameIfReady(); + public: mutable QMutex gameMutex; - Server_Game(const ServerInfo_User &_creatorInfo, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, const QList &_gameTypes, bool _onlyBuddies, bool _onlyRegistered, bool _spectatorsAllowed, bool _spectatorsNeedPassword, bool _spectatorsCanTalk, bool _spectatorsSeeEverything, Server_Room *parent); + Server_Game(const ServerInfo_User &_creatorInfo, + int _gameId, + const QString &_description, + const QString &_password, + int _maxPlayers, + const QList &_gameTypes, + bool _onlyBuddies, + bool _onlyRegistered, + bool _spectatorsAllowed, + bool _spectatorsNeedPassword, + bool _spectatorsCanTalk, + bool _spectatorsSeeEverything, + Server_Room *parent); ~Server_Game(); - Server_Room *getRoom() const { return room; } + Server_Room *getRoom() const + { + return room; + } void getInfo(ServerInfo_Game &result) const; - int getHostId() const { return hostId; } - ServerInfo_User *getCreatorInfo() const { return creatorInfo; } - bool getGameStarted() const { return gameStarted; } + int getHostId() const + { + return hostId; + } + ServerInfo_User *getCreatorInfo() const + { + return creatorInfo; + } + bool getGameStarted() const + { + return gameStarted; + } int getPlayerCount() const; int getSpectatorCount() const; - const QMap &getPlayers() const { return players; } - int getGameId() const { return gameId; } - QString getDescription() const { return description; } - QString getPassword() const { return password; } - int getMaxPlayers() const { return maxPlayers; } - bool getSpectatorsAllowed() const { return spectatorsAllowed; } - bool getSpectatorsNeedPassword() const { return spectatorsNeedPassword; } - bool getSpectatorsCanTalk() const { return spectatorsCanTalk; } - bool getSpectatorsSeeEverything() const { return spectatorsSeeEverything; } - Response::ResponseCode checkJoin(ServerInfo_User *user, const QString &_password, bool spectator, bool overrideRestrictions); + const QMap &getPlayers() const + { + return players; + } + int getGameId() const + { + return gameId; + } + QString getDescription() const + { + return description; + } + QString getPassword() const + { + return password; + } + int getMaxPlayers() const + { + return maxPlayers; + } + bool getSpectatorsAllowed() const + { + return spectatorsAllowed; + } + bool getSpectatorsNeedPassword() const + { + return spectatorsNeedPassword; + } + bool getSpectatorsCanTalk() const + { + return spectatorsCanTalk; + } + bool getSpectatorsSeeEverything() const + { + return spectatorsSeeEverything; + } + Response::ResponseCode + checkJoin(ServerInfo_User *user, const QString &_password, bool spectator, bool overrideRestrictions); bool containsUser(const QString &userName) const; - void addPlayer(Server_AbstractUserInterface *userInterface, ResponseContainer &rc, bool spectator, bool broadcastUpdate = true); + void addPlayer(Server_AbstractUserInterface *userInterface, + ResponseContainer &rc, + bool spectator, + bool broadcastUpdate = true); void removePlayer(Server_Player *player, Event_Leave::LeaveReason reason); void removeArrowsRelatedToPlayer(GameEventStorage &ges, Server_Player *player); void unattachCards(GameEventStorage &ges, Server_Player *player); bool kickPlayer(int playerId); void startGameIfReady(); void stopGameIfFinished(); - int getActivePlayer() const { return activePlayer; } - int getActivePhase() const { return activePhase; } + int getActivePlayer() const + { + return activePlayer; + } + int getActivePhase() const + { + return activePhase; + } void setActivePlayer(int _activePlayer); void setActivePhase(int _activePhase); void nextTurn(); - int getSecondsElapsed() const { return secondsElapsed; } + int getSecondsElapsed() const + { + return secondsElapsed; + } void createGameJoinedEvent(Server_Player *player, ResponseContainer &rc, bool resuming); - - GameEventContainer *prepareGameEvent(const ::google::protobuf::Message &gameEvent, int playerId, GameEventContext *context = 0); + + GameEventContainer * + prepareGameEvent(const ::google::protobuf::Message &gameEvent, int playerId, GameEventContext *context = 0); GameEventContext prepareGameEventContext(const ::google::protobuf::Message &gameEventContext); - - void sendGameEventContainer(GameEventContainer *cont, GameEventStorageItem::EventRecipients recipients = GameEventStorageItem::SendToPrivate | GameEventStorageItem::SendToOthers, int privatePlayerId = -1); + + void sendGameEventContainer(GameEventContainer *cont, + GameEventStorageItem::EventRecipients recipients = GameEventStorageItem::SendToPrivate | + GameEventStorageItem::SendToOthers, + int privatePlayerId = -1); }; #endif diff --git a/common/server_metatypes.h b/common/server_metatypes.h index fb858c6c..0a52fd3e 100644 --- a/common/server_metatypes.h +++ b/common/server_metatypes.h @@ -3,15 +3,15 @@ #include -#include "pb/serverinfo_ban.pb.h" -#include "pb/serverinfo_user.pb.h" -#include "pb/serverinfo_room.pb.h" -#include "pb/serverinfo_game.pb.h" #include "pb/commands.pb.h" -#include "pb/response.pb.h" #include "pb/game_event_container.pb.h" #include "pb/isl_message.pb.h" +#include "pb/response.pb.h" #include "pb/room_commands.pb.h" +#include "pb/serverinfo_ban.pb.h" +#include "pb/serverinfo_game.pb.h" +#include "pb/serverinfo_room.pb.h" +#include "pb/serverinfo_user.pb.h" Q_DECLARE_METATYPE(ServerInfo_Ban) Q_DECLARE_METATYPE(ServerInfo_User) diff --git a/common/server_player.cpp b/common/server_player.cpp index e9683228..48ae920f 100644 --- a/common/server_player.cpp +++ b/common/server_player.cpp @@ -1,21 +1,18 @@ -#include "server.h" #include "server_player.h" -#include "server_card.h" -#include "server_counter.h" +#include "color.h" +#include "decklist.h" +#include "get_pb_extension.h" +#include "rng_abstract.h" +#include "server.h" +#include "server_abstractuserinterface.h" #include "server_arrow.h" +#include "server_card.h" #include "server_cardzone.h" +#include "server_counter.h" +#include "server_database_interface.h" #include "server_game.h" #include "server_room.h" -#include "server_abstractuserinterface.h" -#include "server_database_interface.h" -#include "decklist.h" -#include "color.h" -#include "rng_abstract.h" -#include "get_pb_extension.h" -#include "pb/response.pb.h" -#include "pb/response_deck_download.pb.h" -#include "pb/response_dump_zone.pb.h" #include "pb/command_attach_card.pb.h" #include "pb/command_change_zone_properties.pb.h" #include "pb/command_concede.pb.h" @@ -23,7 +20,6 @@ #include "pb/command_create_counter.pb.h" #include "pb/command_create_token.pb.h" #include "pb/command_deck_select.pb.h" -#include "pb/command_set_sideboard_lock.pb.h" #include "pb/command_del_counter.pb.h" #include "pb/command_delete_arrow.pb.h" #include "pb/command_draw_cards.pb.h" @@ -44,47 +40,57 @@ #include "pb/command_set_card_attr.pb.h" #include "pb/command_set_card_counter.pb.h" #include "pb/command_set_counter.pb.h" +#include "pb/command_set_sideboard_lock.pb.h" #include "pb/command_set_sideboard_plan.pb.h" #include "pb/command_shuffle.pb.h" #include "pb/command_stop_dump_zone.pb.h" #include "pb/command_undo_draw.pb.h" -#include "pb/serverinfo_user.pb.h" -#include "pb/serverinfo_player.pb.h" #include "pb/event_attach_card.pb.h" #include "pb/event_change_zone_properties.pb.h" #include "pb/event_create_arrow.pb.h" #include "pb/event_create_counter.pb.h" #include "pb/event_create_token.pb.h" -#include "pb/event_delete_arrow.pb.h" #include "pb/event_del_counter.pb.h" -#include "pb/event_draw_cards.pb.h" +#include "pb/event_delete_arrow.pb.h" #include "pb/event_destroy_card.pb.h" +#include "pb/event_draw_cards.pb.h" #include "pb/event_dump_zone.pb.h" #include "pb/event_flip_card.pb.h" #include "pb/event_game_say.pb.h" #include "pb/event_move_card.pb.h" #include "pb/event_player_properties_changed.pb.h" -#include "pb/event_set_card_attr.pb.h" -#include "pb/event_shuffle.pb.h" +#include "pb/event_reveal_cards.pb.h" #include "pb/event_roll_die.pb.h" +#include "pb/event_set_card_attr.pb.h" #include "pb/event_set_card_counter.pb.h" #include "pb/event_set_counter.pb.h" +#include "pb/event_shuffle.pb.h" #include "pb/event_stop_dump_zone.pb.h" -#include "pb/event_reveal_cards.pb.h" +#include "pb/response.pb.h" +#include "pb/response_deck_download.pb.h" +#include "pb/response_dump_zone.pb.h" +#include "pb/serverinfo_player.pb.h" +#include "pb/serverinfo_user.pb.h" -#include "pb/context_connection_state_changed.pb.h" #include "pb/context_concede.pb.h" +#include "pb/context_connection_state_changed.pb.h" #include "pb/context_deck_select.pb.h" -#include "pb/context_set_sideboard_lock.pb.h" #include "pb/context_move_card.pb.h" #include "pb/context_mulligan.pb.h" -#include "pb/context_undo_draw.pb.h" #include "pb/context_ready_start.pb.h" +#include "pb/context_set_sideboard_lock.pb.h" +#include "pb/context_undo_draw.pb.h" #include -Server_Player::Server_Player(Server_Game *_game, int _playerId, const ServerInfo_User &_userInfo, bool _spectator, Server_AbstractUserInterface *_userInterface) - : ServerInfo_User_Container(_userInfo), game(_game), userInterface(_userInterface), deck(0), pingTime(0), playerId(_playerId), spectator(_spectator), nextCardId(0), readyStart(false), conceded(false), sideboardLocked(true) +Server_Player::Server_Player(Server_Game *_game, + int _playerId, + const ServerInfo_User &_userInfo, + bool _spectator, + Server_AbstractUserInterface *_userInterface) + : ServerInfo_User_Container(_userInfo), game(_game), userInterface(_userInterface), deck(0), pingTime(0), + playerId(_playerId), spectator(_spectator), nextCardId(0), readyStart(false), conceded(false), + sideboardLocked(true) { } @@ -95,14 +101,14 @@ Server_Player::~Server_Player() void Server_Player::prepareDestroy() { delete deck; - + playerMutex.lock(); if (userInterface) userInterface->playerRemovedFromGame(game); playerMutex.unlock(); - + clearZones(); - + deleteLater(); } @@ -176,7 +182,7 @@ void Server_Player::setupZones() z = sbZone; else continue; - + for (int j = 0; j < currentZone->size(); ++j) { DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); if (!currentCard) @@ -185,13 +191,13 @@ void Server_Player::setupZones() z->insertCard(new Server_Card(currentCard->getName(), nextCardId++, 0, 0, z), -1, 0); } } - + const QList &sideboardPlan = deck->getCurrentSideboardPlan(); for (int i = 0; i < sideboardPlan.size(); ++i) { const MoveCard_ToZone &m = sideboardPlan[i]; const QString startZone = QString::fromStdString(m.start_zone()); const QString targetZone = QString::fromStdString(m.target_zone()); - + Server_CardZone *start, *target; if (startZone == DECK_ZONE_MAIN) start = deckZone; @@ -205,7 +211,7 @@ void Server_Player::setupZones() target = sbZone; else continue; - + for (int j = 0; j < start->getCards().size(); ++j) if (start->getCards()[j]->getName() == QString::fromStdString(m.card_name())) { Server_Card *card = start->getCard(j, NULL, true); @@ -213,7 +219,7 @@ void Server_Player::setupZones() break; } } - + deckZone->shuffle(); } @@ -228,7 +234,7 @@ void Server_Player::clearZones() while (counterIterator.hasNext()) delete counterIterator.next().value(); counters.clear(); - + QMapIterator arrowIterator(arrows); while (arrowIterator.hasNext()) delete arrowIterator.next().value(); @@ -284,41 +290,45 @@ Response::ResponseCode Server_Player::drawCards(GameEventStorage &ges, int numbe Server_CardZone *handZone = zones.value("hand"); if (deckZone->getCards().size() < number) number = deckZone->getCards().size(); - + Event_DrawCards eventOthers; eventOthers.set_number(number); Event_DrawCards eventPrivate(eventOthers); - + for (int i = 0; i < number; ++i) { Server_Card *card = deckZone->getCard(0, NULL, true); handZone->insertCard(card, -1, 0); lastDrawList.append(card->getId()); - + ServerInfo_Card *cardInfo = eventPrivate.add_cards(); cardInfo->set_id(card->getId()); cardInfo->set_name(card->getName().toStdString()); } - + ges.enqueueGameEvent(eventPrivate, playerId, GameEventStorageItem::SendToPrivate, playerId); ges.enqueueGameEvent(eventOthers, playerId, GameEventStorageItem::SendToOthers); - + if (deckZone->getAlwaysRevealTopCard() && !deckZone->getCards().isEmpty()) { Event_RevealCards revealEvent; revealEvent.set_zone_name(deckZone->getName().toStdString()); revealEvent.set_card_id(0); deckZone->getCards().first()->getInfo(revealEvent.add_cards()); - + ges.enqueueGameEvent(revealEvent, playerId); } - + return Response::RespOk; } -class Server_Player::MoveCardCompareFunctor { +class Server_Player::MoveCardCompareFunctor +{ private: int x; + public: - MoveCardCompareFunctor(int _x) : x(_x) { } + MoveCardCompareFunctor(int _x) : x(_x) + { + } inline bool operator()(QPair a, QPair b) { if (a.second < x) { @@ -335,16 +345,24 @@ public: } }; -Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_CardZone *startzone, const QList &_cards, Server_CardZone *targetzone, int x, int y, bool fixFreeSpaces, bool undoingDraw) +Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, + Server_CardZone *startzone, + const QList &_cards, + Server_CardZone *targetzone, + int x, + int y, + bool fixFreeSpaces, + bool undoingDraw) { // Disallow controller change to other zones than the table. - if (((targetzone->getType() != ServerInfo_Zone::PublicZone) || !targetzone->hasCoords()) && (startzone->getPlayer() != targetzone->getPlayer())) + if (((targetzone->getType() != ServerInfo_Zone::PublicZone) || !targetzone->hasCoords()) && + (startzone->getPlayer() != targetzone->getPlayer())) return Response::RespContextError; - + if (!targetzone->hasCoords() && (x <= -1)) x = targetzone->getCards().size(); - - QList > cardsToMove; + + QList> cardsToMove; QMap cardProperties; QSet cardIdsToMove; for (int i = 0; i < _cards.size(); ++i) { @@ -352,7 +370,7 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car if (cardIdsToMove.contains(_cards[i]->card_id())) continue; cardIdsToMove.insert(_cards[i]->card_id()); - + // Consistency checks. In case the command contains illegal moves, try to resolve the legal ones still. int position; Server_Card *card = startzone->getCard(_cards[i]->card_id(), &position); @@ -368,12 +386,12 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car // In case all moves were filtered out, abort. if (cardsToMove.isEmpty()) return Response::RespContextError; - + // 0 performs no sorting - // 1 reverses the sorting + // 1 reverses the sorting MoveCardCompareFunctor cmp(0); qSort(cardsToMove.begin(), cardsToMove.end(), cmp); - + bool secondHalf = false; int xIndex = -1; @@ -383,7 +401,7 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car bool faceDown = thisCardProperties->has_face_down() ? thisCardProperties->face_down() : card->getFaceDown(); if (!targetzone->hasCoords()) faceDown = false; - + int originalPosition = cardsToMove[cardIndex].second; int position = startzone->removeCard(card); if (startzone->getName() == "hand") { @@ -392,7 +410,7 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car else if (lastDrawList.contains(card->getId())) lastDrawList.clear(); } - + if ((startzone == targetzone) && !startzone->hasCoords()) { if (!secondHalf && (originalPosition < x)) { xIndex = -1; @@ -404,19 +422,19 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car } else ++xIndex; int newX = x + xIndex; - + // Attachment relationships can be retained when moving a card onto the opponent's table if (startzone->getName() != targetzone->getName()) { // Delete all attachment relationships if (card->getParentCard()) card->setParentCard(0); - + // Make a copy of the list because the original one gets modified during the loop QList attachedCards = card->getAttachedCards(); for (int i = 0; i < attachedCards.size(); ++i) attachedCards[i]->getZone()->getPlayer()->unattachCard(ges, attachedCards[i]); } - + if (startzone != targetzone) { // Delete all arrows from and to the card const QList &players = game->getPlayers().values(); @@ -432,14 +450,14 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car players[i]->deleteArrow(arrowsToDelete[j]); } } - + int publicNewX; if (card->getDestroyOnZoneChange() && (startzone->getName() != targetzone->getName())) { Event_DestroyCard event; event.set_zone_name(startzone->getName().toStdString()); event.set_card_id(card->getId()); ges.enqueueGameEvent(event, playerId); - + card->deleteLater(); } else { if (!targetzone->hasCoords()) { @@ -447,28 +465,32 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car card->resetState(); } else newX = targetzone->getFreeGridColumn(newX, y, card->getName(), faceDown); - + targetzone->insertCard(card, newX, y); - - bool targetBeingLookedAt = (targetzone->getType() != ServerInfo_Zone::HiddenZone) || (targetzone->getCardsBeingLookedAt() > newX) || (targetzone->getCardsBeingLookedAt() == -1); - bool sourceBeingLookedAt = (startzone->getType() != ServerInfo_Zone::HiddenZone) || (startzone->getCardsBeingLookedAt() > position) || (startzone->getCardsBeingLookedAt() == -1); - + + bool targetBeingLookedAt = (targetzone->getType() != ServerInfo_Zone::HiddenZone) || + (targetzone->getCardsBeingLookedAt() > newX) || + (targetzone->getCardsBeingLookedAt() == -1); + bool sourceBeingLookedAt = (startzone->getType() != ServerInfo_Zone::HiddenZone) || + (startzone->getCardsBeingLookedAt() > position) || + (startzone->getCardsBeingLookedAt() == -1); + bool targetHiddenToPlayer = faceDown || !targetBeingLookedAt; bool targetHiddenToOthers = faceDown || (targetzone->getType() != ServerInfo_Zone::PublicZone); bool sourceHiddenToPlayer = card->getFaceDown() || !sourceBeingLookedAt; bool sourceHiddenToOthers = card->getFaceDown() || (startzone->getType() != ServerInfo_Zone::PublicZone); - + QString privateCardName, publicCardName; if (!(sourceHiddenToPlayer && targetHiddenToPlayer)) privateCardName = card->getName(); if (!(sourceHiddenToOthers && targetHiddenToOthers)) publicCardName = card->getName(); - + int oldCardId = card->getId(); if ((faceDown && (startzone != targetzone)) || (targetzone->getPlayer() != startzone->getPlayer())) card->setId(targetzone->getPlayer()->newCardId()); card->setFaceDown(faceDown); - + // The player does not get to see which card he moved if it moves between two parts of hidden zones which // are not being looked at. int privateNewCardId = card->getId(); @@ -481,9 +503,9 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car int privatePosition = -1; if (startzone->getType() == ServerInfo_Zone::HiddenZone) privatePosition = position; - + publicNewX = newX; - + Event_MoveCard eventOthers; eventOthers.set_start_player_id(startzone->getPlayer()->getPlayerId()); eventOthers.set_start_zone(startzone->getName().toStdString()); @@ -492,7 +514,7 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car eventOthers.set_target_zone(targetzone->getName().toStdString()); eventOthers.set_y(y); eventOthers.set_face_down(faceDown); - + Event_MoveCard eventPrivate(eventOthers); eventPrivate.set_card_id(privateOldCardId); if (!privateCardName.isEmpty()) @@ -500,42 +522,45 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car eventPrivate.set_position(privatePosition); eventPrivate.set_new_card_id(privateNewCardId); eventPrivate.set_x(newX); - + // Other players do not get to see the start and/or target position of the card if the respective // part of the zone is being looked at. The information is not needed anyway because in hidden zones, // all cards are equal. - if ( - ((startzone->getType() == ServerInfo_Zone::HiddenZone) && ((startzone->getCardsBeingLookedAt() > position) || (startzone->getCardsBeingLookedAt() == -1))) - || (startzone->getType() == ServerInfo_Zone::PublicZone) - ) + if (((startzone->getType() == ServerInfo_Zone::HiddenZone) && + ((startzone->getCardsBeingLookedAt() > position) || (startzone->getCardsBeingLookedAt() == -1))) || + (startzone->getType() == ServerInfo_Zone::PublicZone)) position = -1; - if ((targetzone->getType() == ServerInfo_Zone::HiddenZone) && ((targetzone->getCardsBeingLookedAt() > newX) || (targetzone->getCardsBeingLookedAt() == -1))) + if ((targetzone->getType() == ServerInfo_Zone::HiddenZone) && + ((targetzone->getCardsBeingLookedAt() > newX) || (targetzone->getCardsBeingLookedAt() == -1))) publicNewX = -1; - + eventOthers.set_x(publicNewX); eventOthers.set_position(position); - if ((startzone->getType() == ServerInfo_Zone::PublicZone) || (targetzone->getType() == ServerInfo_Zone::PublicZone)) { + if ((startzone->getType() == ServerInfo_Zone::PublicZone) || + (targetzone->getType() == ServerInfo_Zone::PublicZone)) { eventOthers.set_card_id(oldCardId); if (!publicCardName.isEmpty()) eventOthers.set_card_name(publicCardName.toStdString()); eventOthers.set_new_card_id(card->getId()); } - + ges.enqueueGameEvent(eventPrivate, playerId, GameEventStorageItem::SendToPrivate, playerId); ges.enqueueGameEvent(eventOthers, playerId, GameEventStorageItem::SendToOthers); if (thisCardProperties->tapped()) - setCardAttrHelper(ges, targetzone->getPlayer()->getPlayerId(), targetzone->getName(), card->getId(), AttrTapped, "1"); + setCardAttrHelper(ges, targetzone->getPlayer()->getPlayerId(), targetzone->getName(), card->getId(), + AttrTapped, "1"); QString ptString = QString::fromStdString(thisCardProperties->pt()); if (!ptString.isEmpty() && !faceDown) - setCardAttrHelper(ges, targetzone->getPlayer()->getPlayerId(), targetzone->getName(), card->getId(), AttrPT, ptString); + setCardAttrHelper(ges, targetzone->getPlayer()->getPlayerId(), targetzone->getName(), card->getId(), + AttrPT, ptString); } if (startzone->getAlwaysRevealTopCard() && !startzone->getCards().isEmpty() && (originalPosition == 0)) { Event_RevealCards revealEvent; revealEvent.set_zone_name(startzone->getName().toStdString()); revealEvent.set_card_id(0); startzone->getCards().first()->getInfo(revealEvent.add_cards()); - + ges.enqueueGameEvent(revealEvent, playerId); } if (targetzone->getAlwaysRevealTopCard() && !targetzone->getCards().isEmpty() && (newX == 0)) { @@ -543,7 +568,7 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car revealEvent.set_zone_name(targetzone->getName().toStdString()); revealEvent.set_card_id(0); targetzone->getCards().first()->getInfo(revealEvent.add_cards()); - + ges.enqueueGameEvent(revealEvent, playerId); } } @@ -551,10 +576,10 @@ Response::ResponseCode Server_Player::moveCard(GameEventStorage &ges, Server_Car ges.setGameEventContext(Context_UndoDraw()); else ges.setGameEventContext(Context_MoveCard()); - + if (startzone->hasCoords() && fixFreeSpaces) startzone->fixFreeSpaces(ges); - + return Response::RespOk; } @@ -563,22 +588,27 @@ void Server_Player::unattachCard(GameEventStorage &ges, Server_Card *card) Server_CardZone *zone = card->getZone(); Server_Card *parentCard = card->getParentCard(); card->setParentCard(0); - + Event_AttachCard event; event.set_start_zone(zone->getName().toStdString()); event.set_card_id(card->getId()); ges.enqueueGameEvent(event, playerId); - + CardToMove *cardToMove = new CardToMove; cardToMove->set_card_id(card->getId()); moveCard(ges, zone, QList() << cardToMove, zone, -1, card->getY(), card->getFaceDown()); delete cardToMove; - + if (parentCard->getZone()) parentCard->getZone()->updateCardCoordinates(parentCard, parentCard->getX(), parentCard->getY()); } -Response::ResponseCode Server_Player::setCardAttrHelper(GameEventStorage &ges, int targetPlayerId, const QString &zoneName, int cardId, CardAttribute attribute, const QString &attrValue) +Response::ResponseCode Server_Player::setCardAttrHelper(GameEventStorage &ges, + int targetPlayerId, + const QString &zoneName, + int cardId, + CardAttribute attribute, + const QString &attrValue) { Server_CardZone *zone = getZones().value(zoneName); if (!zone) @@ -602,7 +632,7 @@ Response::ResponseCode Server_Player::setCardAttrHelper(GameEventStorage &ges, i if (result.isNull()) return Response::RespInvalidCommand; } - + Event_SetCardAttr event; event.set_zone_name(zone->getName().toStdString()); if (cardId != -1) @@ -610,67 +640,73 @@ Response::ResponseCode Server_Player::setCardAttrHelper(GameEventStorage &ges, i event.set_attribute(attribute); event.set_attr_value(result.toStdString()); ges.enqueueGameEvent(event, targetPlayerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdLeaveGame(const Command_LeaveGame & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) +Response::ResponseCode +Server_Player::cmdLeaveGame(const Command_LeaveGame & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) { game->removePlayer(this, Event_Leave::USER_LEFT); return Response::RespOk; } -Response::ResponseCode Server_Player::cmdKickFromGame(const Command_KickFromGame &cmd, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) +Response::ResponseCode +Server_Player::cmdKickFromGame(const Command_KickFromGame &cmd, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) { if ((game->getHostId() != playerId) && !(userInfo->user_level() & ServerInfo_User::IsModerator)) return Response::RespFunctionNotAllowed; - + if (!game->kickPlayer(cmd.player_id())) return Response::RespNameNotFound; - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdDeckSelect(const Command_DeckSelect &cmd, ResponseContainer &rc, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdDeckSelect(const Command_DeckSelect &cmd, ResponseContainer &rc, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + DeckList *newDeck; if (cmd.has_deck_id()) { try { - newDeck = game->getRoom()->getServer()->getDatabaseInterface()->getDeckFromDatabase(cmd.deck_id(), userInfo->id()); - } catch(Response::ResponseCode r) { + newDeck = game->getRoom()->getServer()->getDatabaseInterface()->getDeckFromDatabase(cmd.deck_id(), + userInfo->id()); + } catch (Response::ResponseCode r) { return r; } } else newDeck = new DeckList(QString::fromStdString(cmd.deck())); - + if (!newDeck) return Response::RespInternalError; - + delete deck; deck = newDeck; sideboardLocked = true; - + Event_PlayerPropertiesChanged event; event.mutable_player_properties()->set_sideboard_locked(true); event.mutable_player_properties()->set_deck_hash(deck->getDeckHash().toStdString()); ges.enqueueGameEvent(event, playerId); - + Context_DeckSelect context; context.set_deck_hash(deck->getDeckHash().toStdString()); context.set_sideboard_size(deck->getSideboardSize()); ges.setGameEventContext(context); - + Response_DeckDownload *re = new Response_DeckDownload; re->set_deck(deck->writeToString_Native().toStdString()); - + rc.setResponseExtension(re); return Response::RespOk; } -Response::ResponseCode Server_Player::cmdSetSideboardPlan(const Command_SetSideboardPlan &cmd, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) +Response::ResponseCode Server_Player::cmdSetSideboardPlan(const Command_SetSideboardPlan &cmd, + ResponseContainer & /*rc*/, + GameEventStorage & /*ges*/) { if (spectator) return Response::RespFunctionNotAllowed; @@ -680,16 +716,18 @@ Response::ResponseCode Server_Player::cmdSetSideboardPlan(const Command_SetSideb return Response::RespContextError; if (sideboardLocked) return Response::RespContextError; - + QList sideboardPlan; for (int i = 0; i < cmd.move_list_size(); ++i) sideboardPlan.append(cmd.move_list(i)); deck->setCurrentSideboardPlan(sideboardPlan); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdSetSideboardLock(const Command_SetSideboardLock &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode Server_Player::cmdSetSideboardLock(const Command_SetSideboardLock &cmd, + ResponseContainer & /*rc*/, + GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; @@ -699,20 +737,21 @@ Response::ResponseCode Server_Player::cmdSetSideboardLock(const Command_SetSideb return Response::RespContextError; if (sideboardLocked == cmd.locked()) return Response::RespContextError; - + sideboardLocked = cmd.locked(); if (sideboardLocked) deck->setCurrentSideboardPlan(QList()); - + Event_PlayerPropertiesChanged event; event.mutable_player_properties()->set_sideboard_locked(sideboardLocked); ges.enqueueGameEvent(event, playerId); ges.setGameEventContext(Context_SetSideboardLock()); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdConcede(const Command_Concede & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdConcede(const Command_Concede & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; @@ -720,104 +759,111 @@ Response::ResponseCode Server_Player::cmdConcede(const Command_Concede & /*cmd*/ return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + setConceded(true); game->removeArrowsRelatedToPlayer(ges, this); game->unattachCards(ges, this); clearZones(); - + Event_PlayerPropertiesChanged event; event.mutable_player_properties()->set_conceded(true); ges.enqueueGameEvent(event, playerId); ges.setGameEventContext(Context_Concede()); - + game->stopGameIfFinished(); if (game->getGameStarted() && (game->getActivePlayer() == playerId)) game->nextTurn(); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdReadyStart(const Command_ReadyStart &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdReadyStart(const Command_ReadyStart &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!deck || game->getGameStarted()) return Response::RespContextError; if (readyStart == cmd.ready()) return Response::RespContextError; - + setReadyStart(cmd.ready()); - + Event_PlayerPropertiesChanged event; event.mutable_player_properties()->set_ready_start(cmd.ready()); ges.enqueueGameEvent(event, playerId); ges.setGameEventContext(Context_ReadyStart()); - + if (cmd.ready()) game->startGameIfReady(); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdGameSay(const Command_GameSay &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdGameSay(const Command_GameSay &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator && !game->getSpectatorsCanTalk() && !(userInfo->user_level() & ServerInfo_User::IsModerator)) return Response::RespFunctionNotAllowed; - + Event_GameSay event; event.set_message(cmd.message()); ges.enqueueGameEvent(event, playerId); - game->getRoom()->getServer()->getDatabaseInterface()->logMessage(userInfo->id(), QString::fromStdString(userInfo->name()), QString::fromStdString(userInfo->address()), QString::fromStdString(cmd.message()), Server_DatabaseInterface::MessageTargetGame, game->getGameId(), game->getDescription()); - + game->getRoom()->getServer()->getDatabaseInterface()->logMessage( + userInfo->id(), QString::fromStdString(userInfo->name()), QString::fromStdString(userInfo->address()), + QString::fromStdString(cmd.message()), Server_DatabaseInterface::MessageTargetGame, game->getGameId(), + game->getDescription()); + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdShuffle(const Command_Shuffle & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdShuffle(const Command_Shuffle & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *deckZone = zones.value("deck"); deckZone->shuffle(); - + Event_Shuffle event; event.set_zone_name("deck"); ges.enqueueGameEvent(event, playerId); - + if (deckZone->getAlwaysRevealTopCard() && !deckZone->getCards().isEmpty()) { Event_RevealCards revealEvent; revealEvent.set_zone_name(deckZone->getName().toStdString()); revealEvent.set_card_id(0); deckZone->getCards().first()->getInfo(revealEvent.add_cards()); - + ges.enqueueGameEvent(revealEvent, playerId); } - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdMulligan(const Command_Mulligan & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdMulligan(const Command_Mulligan & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *hand = zones.value("hand"); int number = (hand->getCards().size() <= 1) ? initialCards : hand->getCards().size() - 1; - + Server_CardZone *deck = zones.value("deck"); while (!hand->getCards().isEmpty()) { CardToMove *cardToMove = new CardToMove; @@ -825,15 +871,15 @@ Response::ResponseCode Server_Player::cmdMulligan(const Command_Mulligan & /*cmd moveCard(ges, hand, QList() << cardToMove, deck, 0, 0, false); delete cardToMove; } - + deck->shuffle(); ges.enqueueGameEvent(Event_Shuffle(), playerId); drawCards(ges, number); - + if (number == initialCards) number = -1; - + Context_Mulligan context; context.set_number(number); ges.setGameEventContext(context); @@ -841,119 +887,125 @@ Response::ResponseCode Server_Player::cmdMulligan(const Command_Mulligan & /*cmd return Response::RespOk; } -Response::ResponseCode Server_Player::cmdRollDie(const Command_RollDie &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdRollDie(const Command_RollDie &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; if (conceded) return Response::RespContextError; - + Event_RollDie event; event.set_sides(cmd.sides()); event.set_value(rng->rand(1, cmd.sides())); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdDrawCards(const Command_DrawCards &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdDrawCards(const Command_DrawCards &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + return drawCards(ges, cmd.number()); } -Response::ResponseCode Server_Player::cmdUndoDraw(const Command_UndoDraw & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdUndoDraw(const Command_UndoDraw & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + if (lastDrawList.isEmpty()) return Response::RespContextError; - + Response::ResponseCode retVal; CardToMove *cardToMove = new CardToMove; cardToMove->set_card_id(lastDrawList.takeLast()); - retVal = moveCard(ges, zones.value("hand"), QList() << cardToMove, zones.value("deck"), 0, 0, false, true); + retVal = moveCard(ges, zones.value("hand"), QList() << cardToMove, zones.value("deck"), 0, 0, + false, true); delete cardToMove; - + return retVal; } -Response::ResponseCode Server_Player::cmdMoveCard(const Command_MoveCard &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdMoveCard(const Command_MoveCard &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_Player *startPlayer = game->getPlayers().value(cmd.has_start_player_id() ? cmd.start_player_id() : playerId); if (!startPlayer) return Response::RespNameNotFound; Server_CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(cmd.start_zone())); if (!startZone) return Response::RespNameNotFound; - + if ((startPlayer != this) && (!startZone->getPlayersWithWritePermission().contains(playerId))) return Response::RespContextError; - + Server_Player *targetPlayer = game->getPlayers().value(cmd.target_player_id()); if (!targetPlayer) return Response::RespNameNotFound; Server_CardZone *targetZone = targetPlayer->getZones().value(QString::fromStdString(cmd.target_zone())); if (!targetZone) return Response::RespNameNotFound; - + if ((startPlayer != this) && (targetPlayer != this)) return Response::RespContextError; - + QList cardsToMove; for (int i = 0; i < cmd.cards_to_move().card_size(); ++i) cardsToMove.append(&cmd.cards_to_move().card(i)); - + return moveCard(ges, startZone, cardsToMove, targetZone, cmd.x(), cmd.y()); } -Response::ResponseCode Server_Player::cmdFlipCard(const Command_FlipCard &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdFlipCard(const Command_FlipCard &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *zone = zones.value(QString::fromStdString(cmd.zone())); if (!zone) return Response::RespNameNotFound; if (!zone->hasCoords()) return Response::RespContextError; - + Server_Card *card = zone->getCard(cmd.card_id()); if (!card) return Response::RespNameNotFound; - + const bool faceDown = cmd.face_down(); if (faceDown == card->getFaceDown()) return Response::RespContextError; - + card->setFaceDown(faceDown); - + Event_FlipCard event; event.set_zone_name(zone->getName().toStdString()); event.set_card_id(card->getId()); @@ -961,24 +1013,25 @@ Response::ResponseCode Server_Player::cmdFlipCard(const Command_FlipCard &cmd, R event.set_card_name(card->getName().toStdString()); event.set_face_down(faceDown); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdAttachCard(const Command_AttachCard &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdAttachCard(const Command_AttachCard &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *startzone = zones.value(QString::fromStdString(cmd.start_zone())); if (!startzone) return Response::RespNameNotFound; - + Server_Card *card = startzone->getCard(cmd.card_id()); if (!card) return Response::RespNameNotFound; @@ -986,7 +1039,7 @@ Response::ResponseCode Server_Player::cmdAttachCard(const Command_AttachCard &cm Server_Player *targetPlayer = 0; Server_CardZone *targetzone = 0; Server_Card *targetCard = 0; - + if (cmd.has_target_player_id()) { targetPlayer = game->getPlayers().value(cmd.target_player_id()); if (!targetPlayer) @@ -1010,7 +1063,7 @@ Response::ResponseCode Server_Player::cmdAttachCard(const Command_AttachCard &cm } if (!startzone->hasCoords()) return Response::RespContextError; - + // Get all arrows pointing to or originating from the card being attached and delete them. QMapIterator playerIterator(game->getPlayers()); while (playerIterator.hasNext()) { @@ -1037,19 +1090,21 @@ Response::ResponseCode Server_Player::cmdAttachCard(const Command_AttachCard &cm QList attachedList = card->getAttachedCards(); for (int i = 0; i < attachedList.size(); ++i) attachedList[i]->getZone()->getPlayer()->unattachCard(ges, attachedList[i]); - + card->setParentCard(targetCard); const int oldX = card->getX(); card->setCoords(-1, card->getY()); startzone->updateCardCoordinates(card, oldX, card->getY()); - + if (targetzone->isColumnStacked(targetCard->getX(), targetCard->getY())) { CardToMove *cardToMove = new CardToMove; cardToMove->set_card_id(targetCard->getId()); - targetPlayer->moveCard(ges, targetzone, QList() << cardToMove, targetzone, targetzone->getFreeGridColumn(-2, targetCard->getY(), targetCard->getName(), false), targetCard->getY(), targetCard->getFaceDown()); + targetPlayer->moveCard(ges, targetzone, QList() << cardToMove, targetzone, + targetzone->getFreeGridColumn(-2, targetCard->getY(), targetCard->getName(), false), + targetCard->getY(), targetCard->getFaceDown()); delete cardToMove; } - + Event_AttachCard event; event.set_start_zone(startzone->getName().toStdString()); event.set_card_id(card->getId()); @@ -1057,24 +1112,25 @@ Response::ResponseCode Server_Player::cmdAttachCard(const Command_AttachCard &cm event.set_target_zone(targetzone->getName().toStdString()); event.set_target_card_id(targetCard->getId()); ges.enqueueGameEvent(event, playerId); - + startzone->fixFreeSpaces(ges); } else unattachCard(ges, card); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdCreateToken(const Command_CreateToken &cmd, ResponseContainer & rc, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdCreateToken(const Command_CreateToken &cmd, ResponseContainer &rc, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *zone = zones.value(QString::fromStdString(cmd.zone())); if (!zone) return Response::RespNameNotFound; @@ -1095,9 +1151,9 @@ Response::ResponseCode Server_Player::cmdCreateToken(const Command_CreateToken & card->setColor(QString::fromStdString(cmd.color())); card->setAnnotation(QString::fromStdString(cmd.annotation())); card->setDestroyOnZoneChange(cmd.destroy_on_zone_change()); - + zone->insertCard(card, x, y); - + Event_CreateToken event; event.set_zone_name(zone->getName().toStdString()); event.set_card_id(card->getId()); @@ -1109,9 +1165,9 @@ Response::ResponseCode Server_Player::cmdCreateToken(const Command_CreateToken & event.set_x(x); event.set_y(y); ges.enqueueGameEvent(event, playerId); - + // chck if the token is a replacement for an existing card - if(cmd.target_card_id() < 0) + if (cmd.target_card_id() < 0) return Response::RespOk; Command_AttachCard cmd2; @@ -1125,16 +1181,17 @@ Response::ResponseCode Server_Player::cmdCreateToken(const Command_CreateToken & return cmdAttachCard(cmd2, rc, ges); } -Response::ResponseCode Server_Player::cmdCreateArrow(const Command_CreateArrow &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdCreateArrow(const Command_CreateArrow &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_Player *startPlayer = game->getPlayers().value(cmd.start_player_id()); Server_Player *targetPlayer = game->getPlayers().value(cmd.target_player_id()); if (!startPlayer || !targetPlayer) @@ -1158,7 +1215,7 @@ Response::ResponseCode Server_Player::cmdCreateArrow(const Command_CreateArrow & return Response::RespContextError; targetCard = targetZone->getCard(cmd.target_card_id()); } - + Server_ArrowTarget *targetItem; if (playerTarget) targetItem = targetPlayer; @@ -1173,10 +1230,10 @@ Response::ResponseCode Server_Player::cmdCreateArrow(const Command_CreateArrow & if ((temp->getStartCard() == startCard) && (temp->getTargetItem() == targetItem)) return Response::RespContextError; } - + Server_Arrow *arrow = new Server_Arrow(newArrowId(), startCard, targetItem, cmd.arrow_color()); addArrow(arrow); - + Event_CreateArrow event; ServerInfo_Arrow *arrowInfo = event.mutable_arrow_info(); arrowInfo->set_id(arrow->getId()); @@ -1190,53 +1247,57 @@ Response::ResponseCode Server_Player::cmdCreateArrow(const Command_CreateArrow & } arrowInfo->mutable_arrow_color()->CopyFrom(cmd.arrow_color()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdDeleteArrow(const Command_DeleteArrow &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdDeleteArrow(const Command_DeleteArrow &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + if (!deleteArrow(cmd.arrow_id())) return Response::RespNameNotFound; - + Event_DeleteArrow event; event.set_arrow_id(cmd.arrow_id()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdSetCardAttr(const Command_SetCardAttr &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdSetCardAttr(const Command_SetCardAttr &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - - return setCardAttrHelper(ges, playerId, QString::fromStdString(cmd.zone()), cmd.card_id(), cmd.attribute(), QString::fromStdString(cmd.attr_value())); + + return setCardAttrHelper(ges, playerId, QString::fromStdString(cmd.zone()), cmd.card_id(), cmd.attribute(), + QString::fromStdString(cmd.attr_value())); } -Response::ResponseCode Server_Player::cmdSetCardCounter(const Command_SetCardCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdSetCardCounter(const Command_SetCardCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *zone = zones.value(QString::fromStdString(cmd.zone())); if (!zone) return Response::RespNameNotFound; @@ -1246,29 +1307,30 @@ Response::ResponseCode Server_Player::cmdSetCardCounter(const Command_SetCardCou Server_Card *card = zone->getCard(cmd.card_id()); if (!card) return Response::RespNameNotFound; - + card->setCounter(cmd.counter_id(), cmd.counter_value()); - + Event_SetCardCounter event; event.set_zone_name(zone->getName().toStdString()); event.set_card_id(card->getId()); event.set_counter_id(cmd.counter_id()); event.set_counter_value(cmd.counter_value()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdIncCardCounter(const Command_IncCardCounter &cmd, ResponseContainer &/*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdIncCardCounter(const Command_IncCardCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_CardZone *zone = zones.value(QString::fromStdString(cmd.zone())); if (!zone) return Response::RespNameNotFound; @@ -1278,57 +1340,60 @@ Response::ResponseCode Server_Player::cmdIncCardCounter(const Command_IncCardCou Server_Card *card = zone->getCard(cmd.card_id()); if (!card) return Response::RespNameNotFound; - + int newValue = card->getCounter(cmd.counter_id()) + cmd.counter_delta(); card->setCounter(cmd.counter_id(), newValue); - + Event_SetCardCounter event; event.set_zone_name(zone->getName().toStdString()); event.set_card_id(card->getId()); event.set_counter_id(cmd.counter_id()); event.set_counter_value(newValue); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdIncCounter(const Command_IncCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdIncCounter(const Command_IncCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_Counter *c = counters.value(cmd.counter_id(), 0); if (!c) return Response::RespNameNotFound; - + c->setCount(c->getCount() + cmd.delta()); - + Event_SetCounter event; event.set_counter_id(c->getId()); event.set_value(c->getCount()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdCreateCounter(const Command_CreateCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdCreateCounter(const Command_CreateCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - - Server_Counter *c = new Server_Counter(newCounterId(), QString::fromStdString(cmd.counter_name()), cmd.counter_color(), cmd.radius(), cmd.value()); + + Server_Counter *c = new Server_Counter(newCounterId(), QString::fromStdString(cmd.counter_name()), + cmd.counter_color(), cmd.radius(), cmd.value()); addCounter(c); - + Event_CreateCounter event; ServerInfo_Counter *counterInfo = event.mutable_counter_info(); counterInfo->set_id(c->getId()); @@ -1337,93 +1402,100 @@ Response::ResponseCode Server_Player::cmdCreateCounter(const Command_CreateCount counterInfo->set_radius(c->getRadius()); counterInfo->set_count(c->getCount()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdSetCounter(const Command_SetCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdSetCounter(const Command_SetCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - - Server_Counter *c = counters.value(cmd.counter_id(), 0);; + + Server_Counter *c = counters.value(cmd.counter_id(), 0); + ; if (!c) return Response::RespNameNotFound; - + c->setCount(cmd.value()); - + Event_SetCounter event; event.set_counter_id(c->getId()); event.set_value(c->getCount()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdDelCounter(const Command_DelCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdDelCounter(const Command_DelCounter &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_Counter *counter = counters.value(cmd.counter_id(), 0); if (!counter) return Response::RespNameNotFound; counters.remove(cmd.counter_id()); delete counter; - + Event_DelCounter event; event.set_counter_id(cmd.counter_id()); ges.enqueueGameEvent(event, playerId); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdNextTurn(const Command_NextTurn & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) +Response::ResponseCode +Server_Player::cmdNextTurn(const Command_NextTurn & /*cmd*/, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + game->nextTurn(); return Response::RespOk; } -Response::ResponseCode Server_Player::cmdSetActivePhase(const Command_SetActivePhase &cmd, ResponseContainer & /*rc*/, GameEventStorage & /*ges*/) +Response::ResponseCode Server_Player::cmdSetActivePhase(const Command_SetActivePhase &cmd, + ResponseContainer & /*rc*/, + GameEventStorage & /*ges*/) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + if (game->getActivePlayer() != playerId) return Response::RespContextError; game->setActivePhase(cmd.phase()); - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdDumpZone(const Command_DumpZone &cmd, ResponseContainer &rc, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdDumpZone(const Command_DumpZone &cmd, ResponseContainer &rc, GameEventStorage &ges) { if (!game->getGameStarted()) return Response::RespGameNotStarted; - + Server_Player *otherPlayer = game->getPlayers().value(cmd.player_id()); if (!otherPlayer) return Response::RespNameNotFound; @@ -1432,17 +1504,17 @@ Response::ResponseCode Server_Player::cmdDumpZone(const Command_DumpZone &cmd, R return Response::RespNameNotFound; if (!((zone->getType() == ServerInfo_Zone::PublicZone) || (this == otherPlayer))) return Response::RespContextError; - + int numberCards = cmd.number_cards(); const QList &cards = zone->getCards(); - + Response_DumpZone *re = new Response_DumpZone; ServerInfo_Zone *zoneInfo = re->mutable_zone_info(); zoneInfo->set_name(zone->getName().toStdString()); zoneInfo->set_type(zone->getType()); zoneInfo->set_with_coords(zone->hasCoords()); zoneInfo->set_card_count(numberCards < cards.size() ? cards.size() : numberCards); - + for (int i = 0; (i < cards.size()) && (i < numberCards || numberCards == -1); ++i) { Server_Card *card = cards[i]; QString displayedName = card->getFaceDown() ? QString() : card->getName(); @@ -1462,7 +1534,7 @@ Response::ResponseCode Server_Player::cmdDumpZone(const Command_DumpZone &cmd, R cardInfo->set_annotation(card->getAnnotation().toStdString()); cardInfo->set_destroy_on_zone_change(card->getDestroyOnZoneChange()); cardInfo->set_doesnt_untap(card->getDoesntUntap()); - + QMapIterator cardCounterIterator(card->getCounters()); while (cardCounterIterator.hasNext()) { cardCounterIterator.next(); @@ -1480,7 +1552,7 @@ Response::ResponseCode Server_Player::cmdDumpZone(const Command_DumpZone &cmd, R } if (zone->getType() == ServerInfo_Zone::HiddenZone) { zone->setCardsBeingLookedAt(numberCards); - + Event_DumpZone event; event.set_zone_owner_id(otherPlayer->getPlayerId()); event.set_zone_name(zone->getName().toStdString()); @@ -1491,23 +1563,24 @@ Response::ResponseCode Server_Player::cmdDumpZone(const Command_DumpZone &cmd, R return Response::RespOk; } -Response::ResponseCode Server_Player::cmdStopDumpZone(const Command_StopDumpZone &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdStopDumpZone(const Command_StopDumpZone &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_Player *otherPlayer = game->getPlayers().value(cmd.player_id()); if (!otherPlayer) return Response::RespNameNotFound; Server_CardZone *zone = otherPlayer->getZones().value(QString::fromStdString(cmd.zone_name())); if (!zone) return Response::RespNameNotFound; - + if (zone->getType() == ServerInfo_Zone::HiddenZone) { zone->setCardsBeingLookedAt(0); - + Event_StopDumpZone event; event.set_zone_owner_id(cmd.player_id()); event.set_zone_name(zone->getName().toStdString()); @@ -1516,16 +1589,17 @@ Response::ResponseCode Server_Player::cmdStopDumpZone(const Command_StopDumpZone return Response::RespOk; } -Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) +Response::ResponseCode +Server_Player::cmdRevealCards(const Command_RevealCards &cmd, ResponseContainer & /*rc*/, GameEventStorage &ges) { if (spectator) return Response::RespFunctionNotAllowed; - + if (!game->getGameStarted()) return Response::RespGameNotStarted; if (conceded) return Response::RespContextError; - + Server_Player *otherPlayer = 0; if (cmd.has_player_id()) { otherPlayer = game->getPlayers().value(cmd.player_id()); @@ -1535,7 +1609,7 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & Server_CardZone *zone = zones.value(QString::fromStdString(cmd.zone_name())); if (!zone) return Response::RespNameNotFound; - + QList cardsToReveal; if (cmd.top_cards() != -1) { for (int i = 0; i < cmd.top_cards(); i++) { @@ -1556,7 +1630,7 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & return Response::RespNameNotFound; cardsToReveal.append(card); } - + Event_RevealCards eventOthers; eventOthers.set_grant_write_access(cmd.grant_write_access()); eventOthers.set_zone_name(zone->getName().toStdString()); @@ -1564,9 +1638,9 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & eventOthers.set_card_id(cmd.card_id()); if (cmd.has_player_id()) eventOthers.set_other_player_id(cmd.player_id()); - + Event_RevealCards eventPrivate(eventOthers); - + for (int i = 0; i < cardsToReveal.size(); ++i) { Server_Card *card = cardsToReveal[i]; ServerInfo_Card *cardInfo = eventPrivate.add_cards(); @@ -1583,7 +1657,7 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & cardInfo->set_annotation(card->getAnnotation().toStdString()); cardInfo->set_destroy_on_zone_change(card->getDestroyOnZoneChange()); cardInfo->set_doesnt_untap(card->getDoesntUntap()); - + QMapIterator cardCounterIterator(card->getCounters()); while (cardCounterIterator.hasNext()) { cardCounterIterator.next(); @@ -1591,18 +1665,18 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & counterInfo->set_id(cardCounterIterator.key()); counterInfo->set_value(cardCounterIterator.value()); } - + if (card->getParentCard()) { cardInfo->set_attach_player_id(card->getParentCard()->getZone()->getPlayer()->getPlayerId()); cardInfo->set_attach_zone(card->getParentCard()->getZone()->getName().toStdString()); cardInfo->set_attach_card_id(card->getParentCard()->getId()); } } - + if (cmd.has_player_id()) { if (cmd.grant_write_access()) zone->addWritePermission(cmd.player_id()); - + ges.enqueueGameEvent(eventPrivate, playerId, GameEventStorageItem::SendToPrivate, cmd.player_id()); ges.enqueueGameEvent(eventOthers, playerId, GameEventStorageItem::SendToOthers); } else { @@ -1611,36 +1685,38 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & for (int i = 0; i < playerIds.size(); ++i) zone->addWritePermission(playerIds[i]); } - + ges.enqueueGameEvent(eventPrivate, playerId); } - + return Response::RespOk; } -Response::ResponseCode Server_Player::cmdChangeZoneProperties(const Command_ChangeZoneProperties &cmd, ResponseContainer & /* rc */, GameEventStorage &ges) +Response::ResponseCode Server_Player::cmdChangeZoneProperties(const Command_ChangeZoneProperties &cmd, + ResponseContainer & /* rc */, + GameEventStorage &ges) { Server_CardZone *zone = zones.value(QString::fromStdString(cmd.zone_name())); if (!zone) return Response::RespNameNotFound; - + Event_ChangeZoneProperties event; event.set_zone_name(cmd.zone_name()); - + if (cmd.has_always_reveal_top_card()) { if (zone->getAlwaysRevealTopCard() == cmd.always_reveal_top_card()) return Response::RespContextError; zone->setAlwaysRevealTopCard(cmd.always_reveal_top_card()); event.set_always_reveal_top_card(cmd.always_reveal_top_card()); - + ges.enqueueGameEvent(event, playerId); - + if (!zone->getCards().isEmpty() && cmd.always_reveal_top_card()) { Event_RevealCards revealEvent; revealEvent.set_zone_name(zone->getName().toStdString()); revealEvent.set_card_id(0); zone->getCards().first()->getInfo(revealEvent.add_cards()); - + ges.enqueueGameEvent(revealEvent, playerId); } return Response::RespOk; @@ -1648,49 +1724,115 @@ Response::ResponseCode Server_Player::cmdChangeZoneProperties(const Command_Chan return Response::RespContextError; } -Response::ResponseCode Server_Player::processGameCommand(const GameCommand &command, ResponseContainer &rc, GameEventStorage &ges) +Response::ResponseCode +Server_Player::processGameCommand(const GameCommand &command, ResponseContainer &rc, GameEventStorage &ges) { - switch ((GameCommand::GameCommandType) getPbExtension(command)) { - case GameCommand::KICK_FROM_GAME: return cmdKickFromGame(command.GetExtension(Command_KickFromGame::ext), rc, ges); break; - case GameCommand::LEAVE_GAME: return cmdLeaveGame(command.GetExtension(Command_LeaveGame::ext), rc, ges); break; - case GameCommand::GAME_SAY: return cmdGameSay(command.GetExtension(Command_GameSay::ext), rc, ges); break; - case GameCommand::SHUFFLE: return cmdShuffle(command.GetExtension(Command_Shuffle::ext), rc, ges); break; - case GameCommand::MULLIGAN: return cmdMulligan(command.GetExtension(Command_Mulligan::ext), rc, ges); break; - case GameCommand::ROLL_DIE: return cmdRollDie(command.GetExtension(Command_RollDie::ext), rc, ges); break; - case GameCommand::DRAW_CARDS: return cmdDrawCards(command.GetExtension(Command_DrawCards::ext), rc, ges); break; - case GameCommand::UNDO_DRAW: return cmdUndoDraw(command.GetExtension(Command_UndoDraw::ext), rc, ges); break; - case GameCommand::FLIP_CARD: return cmdFlipCard(command.GetExtension(Command_FlipCard::ext), rc, ges); break; - case GameCommand::ATTACH_CARD: return cmdAttachCard(command.GetExtension(Command_AttachCard::ext), rc, ges); break; - case GameCommand::CREATE_TOKEN: return cmdCreateToken(command.GetExtension(Command_CreateToken::ext), rc, ges); break; - case GameCommand::CREATE_ARROW: return cmdCreateArrow(command.GetExtension(Command_CreateArrow::ext), rc, ges); break; - case GameCommand::DELETE_ARROW: return cmdDeleteArrow(command.GetExtension(Command_DeleteArrow::ext), rc, ges); break; - case GameCommand::SET_CARD_ATTR: return cmdSetCardAttr(command.GetExtension(Command_SetCardAttr::ext), rc, ges); break; - case GameCommand::SET_CARD_COUNTER: return cmdSetCardCounter(command.GetExtension(Command_SetCardCounter::ext), rc, ges); break; - case GameCommand::INC_CARD_COUNTER: return cmdIncCardCounter(command.GetExtension(Command_IncCardCounter::ext), rc, ges); break; - case GameCommand::READY_START: return cmdReadyStart(command.GetExtension(Command_ReadyStart::ext), rc, ges); break; - case GameCommand::CONCEDE: return cmdConcede(command.GetExtension(Command_Concede::ext), rc, ges); break; - case GameCommand::INC_COUNTER: return cmdIncCounter(command.GetExtension(Command_IncCounter::ext), rc, ges); break; - case GameCommand::CREATE_COUNTER: return cmdCreateCounter(command.GetExtension(Command_CreateCounter::ext), rc, ges); break; - case GameCommand::SET_COUNTER: return cmdSetCounter(command.GetExtension(Command_SetCounter::ext), rc, ges); break; - case GameCommand::DEL_COUNTER: return cmdDelCounter(command.GetExtension(Command_DelCounter::ext), rc, ges); break; - case GameCommand::NEXT_TURN: return cmdNextTurn(command.GetExtension(Command_NextTurn::ext), rc, ges); break; - case GameCommand::SET_ACTIVE_PHASE: return cmdSetActivePhase(command.GetExtension(Command_SetActivePhase::ext), rc, ges); break; - case GameCommand::DUMP_ZONE: return cmdDumpZone(command.GetExtension(Command_DumpZone::ext), rc, ges); break; - case GameCommand::STOP_DUMP_ZONE: return cmdStopDumpZone(command.GetExtension(Command_StopDumpZone::ext), rc, ges); break; - case GameCommand::REVEAL_CARDS: return cmdRevealCards(command.GetExtension(Command_RevealCards::ext), rc, ges); break; - case GameCommand::MOVE_CARD: return cmdMoveCard(command.GetExtension(Command_MoveCard::ext), rc, ges); break; - case GameCommand::SET_SIDEBOARD_PLAN: return cmdSetSideboardPlan(command.GetExtension(Command_SetSideboardPlan::ext), rc, ges); break; - case GameCommand::DECK_SELECT: return cmdDeckSelect(command.GetExtension(Command_DeckSelect::ext), rc, ges); break; - case GameCommand::SET_SIDEBOARD_LOCK: return cmdSetSideboardLock(command.GetExtension(Command_SetSideboardLock::ext), rc, ges); break; - case GameCommand::CHANGE_ZONE_PROPERTIES: return cmdChangeZoneProperties(command.GetExtension(Command_ChangeZoneProperties::ext), rc, ges); break; - default: return Response::RespInvalidCommand; + switch ((GameCommand::GameCommandType)getPbExtension(command)) { + case GameCommand::KICK_FROM_GAME: + return cmdKickFromGame(command.GetExtension(Command_KickFromGame::ext), rc, ges); + break; + case GameCommand::LEAVE_GAME: + return cmdLeaveGame(command.GetExtension(Command_LeaveGame::ext), rc, ges); + break; + case GameCommand::GAME_SAY: + return cmdGameSay(command.GetExtension(Command_GameSay::ext), rc, ges); + break; + case GameCommand::SHUFFLE: + return cmdShuffle(command.GetExtension(Command_Shuffle::ext), rc, ges); + break; + case GameCommand::MULLIGAN: + return cmdMulligan(command.GetExtension(Command_Mulligan::ext), rc, ges); + break; + case GameCommand::ROLL_DIE: + return cmdRollDie(command.GetExtension(Command_RollDie::ext), rc, ges); + break; + case GameCommand::DRAW_CARDS: + return cmdDrawCards(command.GetExtension(Command_DrawCards::ext), rc, ges); + break; + case GameCommand::UNDO_DRAW: + return cmdUndoDraw(command.GetExtension(Command_UndoDraw::ext), rc, ges); + break; + case GameCommand::FLIP_CARD: + return cmdFlipCard(command.GetExtension(Command_FlipCard::ext), rc, ges); + break; + case GameCommand::ATTACH_CARD: + return cmdAttachCard(command.GetExtension(Command_AttachCard::ext), rc, ges); + break; + case GameCommand::CREATE_TOKEN: + return cmdCreateToken(command.GetExtension(Command_CreateToken::ext), rc, ges); + break; + case GameCommand::CREATE_ARROW: + return cmdCreateArrow(command.GetExtension(Command_CreateArrow::ext), rc, ges); + break; + case GameCommand::DELETE_ARROW: + return cmdDeleteArrow(command.GetExtension(Command_DeleteArrow::ext), rc, ges); + break; + case GameCommand::SET_CARD_ATTR: + return cmdSetCardAttr(command.GetExtension(Command_SetCardAttr::ext), rc, ges); + break; + case GameCommand::SET_CARD_COUNTER: + return cmdSetCardCounter(command.GetExtension(Command_SetCardCounter::ext), rc, ges); + break; + case GameCommand::INC_CARD_COUNTER: + return cmdIncCardCounter(command.GetExtension(Command_IncCardCounter::ext), rc, ges); + break; + case GameCommand::READY_START: + return cmdReadyStart(command.GetExtension(Command_ReadyStart::ext), rc, ges); + break; + case GameCommand::CONCEDE: + return cmdConcede(command.GetExtension(Command_Concede::ext), rc, ges); + break; + case GameCommand::INC_COUNTER: + return cmdIncCounter(command.GetExtension(Command_IncCounter::ext), rc, ges); + break; + case GameCommand::CREATE_COUNTER: + return cmdCreateCounter(command.GetExtension(Command_CreateCounter::ext), rc, ges); + break; + case GameCommand::SET_COUNTER: + return cmdSetCounter(command.GetExtension(Command_SetCounter::ext), rc, ges); + break; + case GameCommand::DEL_COUNTER: + return cmdDelCounter(command.GetExtension(Command_DelCounter::ext), rc, ges); + break; + case GameCommand::NEXT_TURN: + return cmdNextTurn(command.GetExtension(Command_NextTurn::ext), rc, ges); + break; + case GameCommand::SET_ACTIVE_PHASE: + return cmdSetActivePhase(command.GetExtension(Command_SetActivePhase::ext), rc, ges); + break; + case GameCommand::DUMP_ZONE: + return cmdDumpZone(command.GetExtension(Command_DumpZone::ext), rc, ges); + break; + case GameCommand::STOP_DUMP_ZONE: + return cmdStopDumpZone(command.GetExtension(Command_StopDumpZone::ext), rc, ges); + break; + case GameCommand::REVEAL_CARDS: + return cmdRevealCards(command.GetExtension(Command_RevealCards::ext), rc, ges); + break; + case GameCommand::MOVE_CARD: + return cmdMoveCard(command.GetExtension(Command_MoveCard::ext), rc, ges); + break; + case GameCommand::SET_SIDEBOARD_PLAN: + return cmdSetSideboardPlan(command.GetExtension(Command_SetSideboardPlan::ext), rc, ges); + break; + case GameCommand::DECK_SELECT: + return cmdDeckSelect(command.GetExtension(Command_DeckSelect::ext), rc, ges); + break; + case GameCommand::SET_SIDEBOARD_LOCK: + return cmdSetSideboardLock(command.GetExtension(Command_SetSideboardLock::ext), rc, ges); + break; + case GameCommand::CHANGE_ZONE_PROPERTIES: + return cmdChangeZoneProperties(command.GetExtension(Command_ChangeZoneProperties::ext), rc, ges); + break; + default: + return Response::RespInvalidCommand; } } void Server_Player::sendGameEvent(const GameEventContainer &cont) { QMutexLocker locker(&playerMutex); - + if (userInterface) userInterface->sendProtocolItem(cont); } @@ -1700,12 +1842,12 @@ void Server_Player::setUserInterface(Server_AbstractUserInterface *_userInterfac playerMutex.lock(); userInterface = _userInterface; playerMutex.unlock(); - + pingTime = _userInterface ? 0 : -1; - + Event_PlayerPropertiesChanged event; event.mutable_player_properties()->set_ping_seconds(pingTime); - + GameEventStorage ges; ges.setGameEventContext(Context_ConnectionStateChanged()); ges.enqueueGameEvent(event, playerId); @@ -1720,22 +1862,25 @@ void Server_Player::disconnectClient() setUserInterface(0); } -void Server_Player::getInfo(ServerInfo_Player *info, Server_Player *playerWhosAsking, bool omniscient, bool withUserInfo) +void Server_Player::getInfo(ServerInfo_Player *info, + Server_Player *playerWhosAsking, + bool omniscient, + bool withUserInfo) { getProperties(*info->mutable_properties(), withUserInfo); if (playerWhosAsking == this) if (deck) info->set_deck_list(deck->writeToString_Native().toStdString()); - + QMapIterator arrowIterator(arrows); while (arrowIterator.hasNext()) arrowIterator.next().value()->getInfo(info->add_arrow_list()); - + QMapIterator counterIterator(counters); while (counterIterator.hasNext()) counterIterator.next().value()->getInfo(info->add_counter_list()); - + QMapIterator zoneIterator(zones); while (zoneIterator.hasNext()) - zoneIterator.next().value()->getInfo(info->add_zone_list(), playerWhosAsking, omniscient); + zoneIterator.next().value()->getInfo(info->add_zone_list(), playerWhosAsking, omniscient); } diff --git a/common/server_player.h b/common/server_player.h index 8011bac4..68193402 100644 --- a/common/server_player.h +++ b/common/server_player.h @@ -3,13 +3,13 @@ #include "server_arrowtarget.h" #include "serverinfo_user_container.h" -#include #include #include #include +#include -#include "pb/response.pb.h" #include "pb/card_attributes.pb.h" +#include "pb/response.pb.h" class DeckList; class Server_Game; @@ -61,7 +61,8 @@ class Command_DeckSelect; class Command_SetSideboardLock; class Command_ChangeZoneProperties; -class Server_Player : public Server_ArrowTarget, public ServerInfo_User_Container { +class Server_Player : public Server_ArrowTarget, public ServerInfo_User_Container +{ Q_OBJECT private: class MoveCardCompareFunctor; @@ -80,56 +81,121 @@ private: bool readyStart; bool conceded; bool sideboardLocked; + public: mutable QMutex playerMutex; - Server_Player(Server_Game *_game, int _playerId, const ServerInfo_User &_userInfo, bool _spectator, Server_AbstractUserInterface *_handler); + Server_Player(Server_Game *_game, + int _playerId, + const ServerInfo_User &_userInfo, + bool _spectator, + Server_AbstractUserInterface *_handler); ~Server_Player(); void prepareDestroy(); - Server_AbstractUserInterface *getUserInterface() const { return userInterface; } + Server_AbstractUserInterface *getUserInterface() const + { + return userInterface; + } void setUserInterface(Server_AbstractUserInterface *_userInterface); void disconnectClient(); - - void setPlayerId(int _id) { playerId = _id; } - bool getReadyStart() const { return readyStart; } - void setReadyStart(bool _readyStart) { readyStart = _readyStart; } - int getPlayerId() const { return playerId; } - bool getSpectator() const { return spectator; } - bool getConceded() const { return conceded; } - void setConceded(bool _conceded) { conceded = _conceded; } - DeckList *getDeck() const { return deck; } - Server_Game *getGame() const { return game; } - const QMap &getZones() const { return zones; } - const QMap &getCounters() const { return counters; } - const QMap &getArrows() const { return arrows; } - - int getPingTime() const { return pingTime; } - void setPingTime(int _pingTime) { pingTime = _pingTime; } + + void setPlayerId(int _id) + { + playerId = _id; + } + bool getReadyStart() const + { + return readyStart; + } + void setReadyStart(bool _readyStart) + { + readyStart = _readyStart; + } + int getPlayerId() const + { + return playerId; + } + bool getSpectator() const + { + return spectator; + } + bool getConceded() const + { + return conceded; + } + void setConceded(bool _conceded) + { + conceded = _conceded; + } + DeckList *getDeck() const + { + return deck; + } + Server_Game *getGame() const + { + return game; + } + const QMap &getZones() const + { + return zones; + } + const QMap &getCounters() const + { + return counters; + } + const QMap &getArrows() const + { + return arrows; + } + + int getPingTime() const + { + return pingTime; + } + void setPingTime(int _pingTime) + { + pingTime = _pingTime; + } void getProperties(ServerInfo_PlayerProperties &result, bool withUserInfo); - + int newCardId(); int newCounterId() const; int newArrowId() const; - + void addZone(Server_CardZone *zone); void addArrow(Server_Arrow *arrow); bool deleteArrow(int arrowId); void addCounter(Server_Counter *counter); - + void clearZones(); void setupZones(); Response::ResponseCode drawCards(GameEventStorage &ges, int number); - Response::ResponseCode moveCard(GameEventStorage &ges, Server_CardZone *startzone, const QList &_cards, Server_CardZone *targetzone, int x, int y, bool fixFreeSpaces = true, bool undoingDraw = false); + Response::ResponseCode moveCard(GameEventStorage &ges, + Server_CardZone *startzone, + const QList &_cards, + Server_CardZone *targetzone, + int x, + int y, + bool fixFreeSpaces = true, + bool undoingDraw = false); void unattachCard(GameEventStorage &ges, Server_Card *card); - Response::ResponseCode setCardAttrHelper(GameEventStorage &ges, int targetPlayerId, const QString &zone, int cardId, CardAttribute attribute, const QString &attrValue); + Response::ResponseCode setCardAttrHelper(GameEventStorage &ges, + int targetPlayerId, + const QString &zone, + int cardId, + CardAttribute attribute, + const QString &attrValue); Response::ResponseCode cmdLeaveGame(const Command_LeaveGame &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdKickFromGame(const Command_KickFromGame &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdKickFromGame(const Command_KickFromGame &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdConcede(const Command_Concede &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdReadyStart(const Command_ReadyStart &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdDeckSelect(const Command_DeckSelect &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdSetSideboardPlan(const Command_SetSideboardPlan &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdSetSideboardLock(const Command_SetSideboardLock &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdSetSideboardPlan(const Command_SetSideboardPlan &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdSetSideboardLock(const Command_SetSideboardLock &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdGameSay(const Command_GameSay &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdShuffle(const Command_Shuffle &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdMulligan(const Command_Mulligan &cmd, ResponseContainer &rc, GameEventStorage &ges); @@ -143,22 +209,28 @@ public: Response::ResponseCode cmdCreateArrow(const Command_CreateArrow &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdDeleteArrow(const Command_DeleteArrow &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdSetCardAttr(const Command_SetCardAttr &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdSetCardCounter(const Command_SetCardCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdIncCardCounter(const Command_IncCardCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdSetCardCounter(const Command_SetCardCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdIncCardCounter(const Command_IncCardCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdIncCounter(const Command_IncCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdCreateCounter(const Command_CreateCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdCreateCounter(const Command_CreateCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdSetCounter(const Command_SetCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdDelCounter(const Command_DelCounter &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdNextTurn(const Command_NextTurn &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdSetActivePhase(const Command_SetActivePhase &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdSetActivePhase(const Command_SetActivePhase &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdDumpZone(const Command_DumpZone &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdStopDumpZone(const Command_StopDumpZone &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode + cmdStopDumpZone(const Command_StopDumpZone &cmd, ResponseContainer &rc, GameEventStorage &ges); Response::ResponseCode cmdRevealCards(const Command_RevealCards &cmd, ResponseContainer &rc, GameEventStorage &ges); - Response::ResponseCode cmdChangeZoneProperties(const Command_ChangeZoneProperties &cmd, ResponseContainer &rc, GameEventStorage &ges); - + Response::ResponseCode + cmdChangeZoneProperties(const Command_ChangeZoneProperties &cmd, ResponseContainer &rc, GameEventStorage &ges); + Response::ResponseCode processGameCommand(const GameCommand &command, ResponseContainer &rc, GameEventStorage &ges); void sendGameEvent(const GameEventContainer &event); - + void getInfo(ServerInfo_Player *info, Server_Player *playerWhosAsking, bool omniscient, bool withUserInfo); }; diff --git a/common/server_player_reference.h b/common/server_player_reference.h index 868b40b6..07b2d3d2 100644 --- a/common/server_player_reference.h +++ b/common/server_player_reference.h @@ -1,17 +1,33 @@ #ifndef SERVER_PLAYER_REFERENCE_H #define SERVER_PLAYER_REFERENCE_H -class PlayerReference { +class PlayerReference +{ private: int roomId; int gameId; int playerId; + public: - PlayerReference(int _roomId, int _gameId, int _playerId) : roomId(_roomId), gameId(_gameId), playerId(_playerId) { } - int getRoomId() const { return roomId; } - int getGameId() const { return gameId; } - int getPlayerId() const { return playerId; } - bool operator==(const PlayerReference &other) { return ((roomId == other.roomId) && (gameId == other.gameId) && (playerId == other.playerId)); } + PlayerReference(int _roomId, int _gameId, int _playerId) : roomId(_roomId), gameId(_gameId), playerId(_playerId) + { + } + int getRoomId() const + { + return roomId; + } + int getGameId() const + { + return gameId; + } + int getPlayerId() const + { + return playerId; + } + bool operator==(const PlayerReference &other) + { + return ((roomId == other.roomId) && (gameId == other.gameId) && (playerId == other.playerId)); + } }; #endif diff --git a/common/server_protocolhandler.cpp b/common/server_protocolhandler.cpp index 85d5f8dc..e27be317 100644 --- a/common/server_protocolhandler.cpp +++ b/common/server_protocolhandler.cpp @@ -1,43 +1,36 @@ -#include -#include -#include #include "server_protocolhandler.h" -#include "server_database_interface.h" -#include "server_room.h" -#include "server_game.h" -#include "server_player.h" +#include "featureset.h" #include "get_pb_extension.h" #include "pb/commands.pb.h" +#include "pb/event_game_joined.pb.h" +#include "pb/event_list_rooms.pb.h" +#include "pb/event_notify_user.pb.h" +#include "pb/event_room_say.pb.h" +#include "pb/event_server_message.pb.h" +#include "pb/event_user_message.pb.h" #include "pb/response.pb.h" -#include "pb/response_login.pb.h" -#include "pb/response_list_users.pb.h" #include "pb/response_get_games_of_user.pb.h" #include "pb/response_get_user_info.pb.h" #include "pb/response_join_room.pb.h" -#include "pb/event_list_rooms.pb.h" -#include "pb/event_server_message.pb.h" -#include "pb/event_user_message.pb.h" -#include "pb/event_game_joined.pb.h" -#include "pb/event_room_say.pb.h" +#include "pb/response_list_users.pb.h" +#include "pb/response_login.pb.h" #include "pb/serverinfo_user.pb.h" -#include "pb/event_notify_user.pb.h" +#include "server_database_interface.h" +#include "server_game.h" +#include "server_player.h" +#include "server_room.h" +#include +#include #include -#include "featureset.h" +#include +Server_ProtocolHandler::Server_ProtocolHandler(Server *_server, + Server_DatabaseInterface *_databaseInterface, + QObject *parent) + : QObject(parent), Server_AbstractUserInterface(_server), deleted(false), databaseInterface(_databaseInterface), + authState(NotLoggedIn), acceptsUserListChanges(false), acceptsRoomListChanges(false), + idleClientWarningSent(false), timeRunning(0), lastDataReceived(0), lastActionReceived(0) -Server_ProtocolHandler::Server_ProtocolHandler(Server *_server, Server_DatabaseInterface *_databaseInterface, QObject *parent) - : QObject(parent), - Server_AbstractUserInterface(_server), - deleted(false), - databaseInterface(_databaseInterface), - authState(NotLoggedIn), - acceptsUserListChanges(false), - acceptsRoomListChanges(false), - idleClientWarningSent(false), - timeRunning(0), - lastDataReceived(0), - lastActionReceived(0) - { connect(server, SIGNAL(pingClockTimeout()), this, SLOT(pingClockTimeout())); } @@ -58,10 +51,10 @@ void Server_ProtocolHandler::prepareDestroy() while (roomIterator.hasNext()) roomIterator.next().value()->removeClient(this); - QMap > tempGames(getGames()); + QMap> tempGames(getGames()); server->roomsLock.lockForRead(); - QMapIterator > gameIterator(tempGames); + QMapIterator> gameIterator(tempGames); while (gameIterator.hasNext()) { gameIterator.next(); @@ -130,14 +123,15 @@ void Server_ProtocolHandler::sendProtocolItem(const RoomEvent &item) transmitProtocolItem(msg); } -Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(const CommandContainer &cont, ResponseContainer &rc) +Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(const CommandContainer &cont, + ResponseContainer &rc) { Response::ResponseCode finalResponseCode = Response::RespOk; for (int i = cont.session_command_size() - 1; i >= 0; --i) { Response::ResponseCode resp = Response::RespInvalidCommand; const SessionCommand &sc = cont.session_command(i); const int num = getPbExtension(sc); - if (num != SessionCommand::PING) { // don't log ping commands + if (num != SessionCommand::PING) { // don't log ping commands if (num == SessionCommand::LOGIN) { // log login commands, but hide passwords SessionCommand debugSc(sc); debugSc.MutableExtension(Command_Login::ext)->clear_password(); @@ -149,16 +143,33 @@ Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(co } else logDebugMessage(QString::fromStdString(sc.ShortDebugString())); } - switch ((SessionCommand::SessionCommandType) num) { - case SessionCommand::PING: resp = cmdPing(sc.GetExtension(Command_Ping::ext), rc); break; - case SessionCommand::LOGIN: resp = cmdLogin(sc.GetExtension(Command_Login::ext), rc); break; - case SessionCommand::MESSAGE: resp = cmdMessage(sc.GetExtension(Command_Message::ext), rc); break; - case SessionCommand::GET_GAMES_OF_USER: resp = cmdGetGamesOfUser(sc.GetExtension(Command_GetGamesOfUser::ext), rc); break; - case SessionCommand::GET_USER_INFO: resp = cmdGetUserInfo(sc.GetExtension(Command_GetUserInfo::ext), rc); break; - case SessionCommand::LIST_ROOMS: resp = cmdListRooms(sc.GetExtension(Command_ListRooms::ext), rc); break; - case SessionCommand::JOIN_ROOM: resp = cmdJoinRoom(sc.GetExtension(Command_JoinRoom::ext), rc); break; - case SessionCommand::LIST_USERS: resp = cmdListUsers(sc.GetExtension(Command_ListUsers::ext), rc); break; - default: resp = processExtendedSessionCommand(num, sc, rc); + switch ((SessionCommand::SessionCommandType)num) { + case SessionCommand::PING: + resp = cmdPing(sc.GetExtension(Command_Ping::ext), rc); + break; + case SessionCommand::LOGIN: + resp = cmdLogin(sc.GetExtension(Command_Login::ext), rc); + break; + case SessionCommand::MESSAGE: + resp = cmdMessage(sc.GetExtension(Command_Message::ext), rc); + break; + case SessionCommand::GET_GAMES_OF_USER: + resp = cmdGetGamesOfUser(sc.GetExtension(Command_GetGamesOfUser::ext), rc); + break; + case SessionCommand::GET_USER_INFO: + resp = cmdGetUserInfo(sc.GetExtension(Command_GetUserInfo::ext), rc); + break; + case SessionCommand::LIST_ROOMS: + resp = cmdListRooms(sc.GetExtension(Command_ListRooms::ext), rc); + break; + case SessionCommand::JOIN_ROOM: + resp = cmdJoinRoom(sc.GetExtension(Command_JoinRoom::ext), rc); + break; + case SessionCommand::LIST_USERS: + resp = cmdListUsers(sc.GetExtension(Command_ListUsers::ext), rc); + break; + default: + resp = processExtendedSessionCommand(num, sc, rc); } if (resp != Response::RespOk) finalResponseCode = resp; @@ -166,7 +177,8 @@ Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(co return finalResponseCode; } -Response::ResponseCode Server_ProtocolHandler::processRoomCommandContainer(const CommandContainer &cont, ResponseContainer &rc) +Response::ResponseCode Server_ProtocolHandler::processRoomCommandContainer(const CommandContainer &cont, + ResponseContainer &rc) { if (authState == NotLoggedIn) return Response::RespLoginNeeded; @@ -184,11 +196,19 @@ Response::ResponseCode Server_ProtocolHandler::processRoomCommandContainer(const const RoomCommand &sc = cont.room_command(i); const int num = getPbExtension(sc); logDebugMessage(QString::fromStdString(sc.ShortDebugString())); - switch ((RoomCommand::RoomCommandType) num) { - case RoomCommand::LEAVE_ROOM: resp = cmdLeaveRoom(sc.GetExtension(Command_LeaveRoom::ext), room, rc); break; - case RoomCommand::ROOM_SAY: resp = cmdRoomSay(sc.GetExtension(Command_RoomSay::ext), room, rc); break; - case RoomCommand::CREATE_GAME: resp = cmdCreateGame(sc.GetExtension(Command_CreateGame::ext), room, rc); break; - case RoomCommand::JOIN_GAME: resp = cmdJoinGame(sc.GetExtension(Command_JoinGame::ext), room, rc); break; + switch ((RoomCommand::RoomCommandType)num) { + case RoomCommand::LEAVE_ROOM: + resp = cmdLeaveRoom(sc.GetExtension(Command_LeaveRoom::ext), room, rc); + break; + case RoomCommand::ROOM_SAY: + resp = cmdRoomSay(sc.GetExtension(Command_RoomSay::ext), room, rc); + break; + case RoomCommand::CREATE_GAME: + resp = cmdCreateGame(sc.GetExtension(Command_CreateGame::ext), room, rc); + break; + case RoomCommand::JOIN_GAME: + resp = cmdJoinGame(sc.GetExtension(Command_JoinGame::ext), room, rc); + break; } if (resp != Response::RespOk) finalResponseCode = resp; @@ -196,9 +216,11 @@ Response::ResponseCode Server_ProtocolHandler::processRoomCommandContainer(const return finalResponseCode; } -Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const CommandContainer &cont, ResponseContainer &rc) +Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const CommandContainer &cont, + ResponseContainer &rc) { - static QList antifloodCommandsWhiteList = QList() + static QList antifloodCommandsWhiteList = + QList() // draw/undo card draw (example: drawing 10 cards one by one from the deck) << GameCommand::DRAW_CARDS << GameCommand::UNDO_DRAW @@ -217,7 +239,7 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const if (authState == NotLoggedIn) return Response::RespLoginNeeded; - QMap > gameMap = getGames(); + QMap> gameMap = getGames(); if (!gameMap.contains(cont.game_id())) return Response::RespNotInRoom; const QPair roomIdAndPlayerId = gameMap.value(cont.game_id()); @@ -231,12 +253,8 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const Server_Game *game = room->getGames().value(cont.game_id()); if (!game) { if (room->getExternalGames().contains(cont.game_id())) { - server->sendIsl_GameCommand(cont, - room->getExternalGames().value(cont.game_id()).server_id(), - userInfo->session_id(), - roomIdAndPlayerId.first, - roomIdAndPlayerId.second - ); + server->sendIsl_GameCommand(cont, room->getExternalGames().value(cont.game_id()).server_id(), + userInfo->session_id(), roomIdAndPlayerId.first, roomIdAndPlayerId.second); return Response::RespNothing; } return Response::RespNotInRoom; @@ -255,14 +273,15 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const Response::ResponseCode finalResponseCode = Response::RespOk; for (int i = cont.game_command_size() - 1; i >= 0; --i) { const GameCommand &sc = cont.game_command(i); - logDebugMessage(QString("game %1 player %2: ").arg(cont.game_id()).arg(roomIdAndPlayerId.second) + QString::fromStdString(sc.ShortDebugString())); + logDebugMessage(QString("game %1 player %2: ").arg(cont.game_id()).arg(roomIdAndPlayerId.second) + + QString::fromStdString(sc.ShortDebugString())); if (commandCountingInterval > 0) { int totalCount = 0; if (commandCountOverTime.isEmpty()) commandCountOverTime.prepend(0); - if(!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType) getPbExtension(sc))) + if (!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType)getPbExtension(sc))) ++commandCountOverTime[0]; for (int i = 0; i < commandCountOverTime.size(); ++i) @@ -282,7 +301,8 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const return finalResponseCode; } -Response::ResponseCode Server_ProtocolHandler::processModeratorCommandContainer(const CommandContainer &cont, ResponseContainer &rc) +Response::ResponseCode Server_ProtocolHandler::processModeratorCommandContainer(const CommandContainer &cont, + ResponseContainer &rc) { if (!userInfo) return Response::RespLoginNeeded; @@ -305,7 +325,8 @@ Response::ResponseCode Server_ProtocolHandler::processModeratorCommandContainer( return finalResponseCode; } -Response::ResponseCode Server_ProtocolHandler::processAdminCommandContainer(const CommandContainer &cont, ResponseContainer &rc) +Response::ResponseCode Server_ProtocolHandler::processAdminCommandContainer(const CommandContainer &cont, + ResponseContainer &rc) { if (!userInfo) return Response::RespLoginNeeded; @@ -365,7 +386,7 @@ void Server_ProtocolHandler::pingClockTimeout() int interval = server->getMessageCountingInterval(); if (interval > 0) { - if(pingclockinterval > 0) { + if (pingclockinterval > 0) { messageSizeOverTime.prepend(0); if (messageSizeOverTime.size() > (msgcountinterval / pingclockinterval)) messageSizeOverTime.removeLast(); @@ -394,7 +415,8 @@ void Server_ProtocolHandler::pingClockTimeout() } } - if (((timeRunning - lastActionReceived) >= ceil(server->getIdleClientTimeout() *.9)) && (!idleClientWarningSent) && (server->getIdleClientTimeout() > 0)) { + if (((timeRunning - lastActionReceived) >= ceil(server->getIdleClientTimeout() * .9)) && + (!idleClientWarningSent) && (server->getIdleClientTimeout() > 0)) { Event_NotifyUser event; event.set_type(Event_NotifyUser::IDLEWARNING); SessionEvent *se = prepareSessionEvent(event); @@ -414,7 +436,7 @@ Response::ResponseCode Server_ProtocolHandler::cmdPing(const Command_Ping & /*cm Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd, ResponseContainer &rc) { - + QString userName = QString::fromStdString(cmd.user_name()).simplified(); QString clientId = QString::fromStdString(cmd.clientid()).simplified(); QString clientVersion = QString::fromStdString(cmd.clientver()).simplified(); @@ -430,7 +452,8 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd for (int i = 0; i < cmd.clientfeatures().size(); ++i) receivedClientFeatures.insert(QString::fromStdString(cmd.clientfeatures(i)).simplified(), false); - missingClientFeatures = features.identifyMissingFeatures(receivedClientFeatures, server->getServerRequiredFeatureList()); + missingClientFeatures = + features.identifyMissingFeatures(receivedClientFeatures, server->getServerRequiredFeatureList()); if (!missingClientFeatures.isEmpty()) { if (features.isRequiredFeaturesMissing(missingClientFeatures, server->getServerRequiredFeatureList())) { @@ -447,7 +470,8 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd QString reasonStr; int banSecondsLeft = 0; QString connectionType = getConnectionType(); - AuthenticationResult res = server->loginUser(this, userName, QString::fromStdString(cmd.password()), reasonStr, banSecondsLeft, clientId, clientVersion, connectionType); + AuthenticationResult res = server->loginUser(this, userName, QString::fromStdString(cmd.password()), reasonStr, + banSecondsLeft, clientId, clientVersion, connectionType); switch (res) { case UserIsBanned: { Response_Login *re = new Response_Login; @@ -457,18 +481,24 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd rc.setResponseExtension(re); return Response::RespUserIsBanned; } - case NotLoggedIn: return Response::RespWrongPassword; - case WouldOverwriteOldSession: return Response::RespWouldOverwriteOldSession; + case NotLoggedIn: + return Response::RespWrongPassword; + case WouldOverwriteOldSession: + return Response::RespWouldOverwriteOldSession; case UsernameInvalid: { Response_Login *re = new Response_Login; re->set_denied_reason_str(reasonStr.toStdString()); rc.setResponseExtension(re); return Response::RespUsernameInvalid; } - case RegistrationRequired: return Response::RespRegistrationRequired; - case ClientIdRequired: return Response::RespClientIdRequired; - case UserIsInactive: return Response::RespAccountNotActivated; - default: authState = res; + case RegistrationRequired: + return Response::RespRegistrationRequired; + case ClientIdRequired: + return Response::RespClientIdRequired; + case UserIsInactive: + return Response::RespAccountNotActivated; + default: + authState = res; } // limit the number of non-privileged users that can connect to the server based on configuration settings @@ -535,12 +565,16 @@ Response::ResponseCode Server_ProtocolHandler::cmdMessage(const Command_Message userInterface->sendProtocolItem(*se); rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, se); - databaseInterface->logMessage(userInfo->id(), QString::fromStdString(userInfo->name()), QString::fromStdString(userInfo->address()), QString::fromStdString(cmd.message()), Server_DatabaseInterface::MessageTargetChat, userInterface->getUserInfo()->id(), receiver); + databaseInterface->logMessage(userInfo->id(), QString::fromStdString(userInfo->name()), + QString::fromStdString(userInfo->address()), QString::fromStdString(cmd.message()), + Server_DatabaseInterface::MessageTargetChat, userInterface->getUserInfo()->id(), + receiver); resetIdleTimer(); return Response::RespOk; } -Response::ResponseCode Server_ProtocolHandler::cmdGetGamesOfUser(const Command_GetGamesOfUser &cmd, ResponseContainer &rc) +Response::ResponseCode Server_ProtocolHandler::cmdGetGamesOfUser(const Command_GetGamesOfUser &cmd, + ResponseContainer &rc) { if (authState == NotLoggedIn) return Response::RespLoginNeeded; @@ -581,13 +615,13 @@ Response::ResponseCode Server_ProtocolHandler::cmdGetUserInfo(const Command_GetU ServerInfo_User_Container *infoSource = server->findUser(userName); if (!infoSource) { - re->mutable_user_info()->CopyFrom(databaseInterface->getUserData(userName,true)); + re->mutable_user_info()->CopyFrom(databaseInterface->getUserData(userName, true)); } else { - re->mutable_user_info()->CopyFrom(infoSource->copyUserInfo(true, false, userInfo->user_level() & ServerInfo_User::IsModerator)); + re->mutable_user_info()->CopyFrom( + infoSource->copyUserInfo(true, false, userInfo->user_level() & ServerInfo_User::IsModerator)); } } - rc.setResponseExtension(re); return Response::RespOk; } @@ -640,7 +674,8 @@ Response::ResponseCode Server_ProtocolHandler::cmdJoinRoom(const Command_JoinRoo Event_RoomSay roomChatHistory; roomChatHistory.set_message(chatMessage.sender_name() + ": " + chatMessage.message()); roomChatHistory.set_message_type(Event_RoomSay::ChatHistory); - roomChatHistory.set_time_of(QDateTime::fromString(QString::fromStdString(chatMessage.time())).toMSecsSinceEpoch()); + roomChatHistory.set_time_of( + QDateTime::fromString(QString::fromStdString(chatMessage.time())).toMSecsSinceEpoch()); rc.enqueuePostResponseItem(ServerMessage::ROOM_EVENT, r->prepareRoomEvent(roomChatHistory)); } @@ -672,14 +707,16 @@ Response::ResponseCode Server_ProtocolHandler::cmdListUsers(const Command_ListUs return Response::RespOk; } -Response::ResponseCode Server_ProtocolHandler::cmdLeaveRoom(const Command_LeaveRoom & /*cmd*/, Server_Room *room, ResponseContainer & /*rc*/) +Response::ResponseCode +Server_ProtocolHandler::cmdLeaveRoom(const Command_LeaveRoom & /*cmd*/, Server_Room *room, ResponseContainer & /*rc*/) { rooms.remove(room->getId()); room->removeClient(this); return Response::RespOk; } -Response::ResponseCode Server_ProtocolHandler::cmdRoomSay(const Command_RoomSay &cmd, Server_Room *room, ResponseContainer & /*rc*/) +Response::ResponseCode +Server_ProtocolHandler::cmdRoomSay(const Command_RoomSay &cmd, Server_Room *room, ResponseContainer & /*rc*/) { QString msg = QString::fromStdString(cmd.message()); @@ -697,19 +734,23 @@ Response::ResponseCode Server_ProtocolHandler::cmdRoomSay(const Command_RoomSay for (int i = 0; i < messageCountOverTime.size(); ++i) totalCount += messageCountOverTime[i]; - if ((totalSize > server->getMaxMessageSizePerInterval()) || (totalCount > server->getMaxMessageCountPerInterval())) + if ((totalSize > server->getMaxMessageSizePerInterval()) || + (totalCount > server->getMaxMessageCountPerInterval())) return Response::RespChatFlood; } msg.replace(QChar('\n'), QChar(' ')); room->say(QString::fromStdString(userInfo->name()), msg); - databaseInterface->logMessage(userInfo->id(), QString::fromStdString(userInfo->name()), QString::fromStdString(userInfo->address()), msg, Server_DatabaseInterface::MessageTargetRoom, room->getId(), room->getName()); + databaseInterface->logMessage(userInfo->id(), QString::fromStdString(userInfo->name()), + QString::fromStdString(userInfo->address()), msg, + Server_DatabaseInterface::MessageTargetRoom, room->getId(), room->getName()); return Response::RespOk; } -Response::ResponseCode Server_ProtocolHandler::cmdCreateGame(const Command_CreateGame &cmd, Server_Room *room, ResponseContainer &rc) +Response::ResponseCode +Server_ProtocolHandler::cmdCreateGame(const Command_CreateGame &cmd, Server_Room *room, ResponseContainer &rc) { if (authState == NotLoggedIn) return Response::RespLoginNeeded; @@ -731,14 +772,18 @@ Response::ResponseCode Server_ProtocolHandler::cmdCreateGame(const Command_Creat // When server doesn't permit registered users to exist, do not honor only-reg setting bool onlyRegisteredUsers = cmd.only_registered() && (server->permitUnregisteredUsers()); - Server_Game *game = new Server_Game(copyUserInfo(false), gameId, description, QString::fromStdString(cmd.password()), cmd.max_players(), gameTypes, cmd.only_buddies(), onlyRegisteredUsers, cmd.spectators_allowed(), cmd.spectators_need_password(), cmd.spectators_can_talk(), cmd.spectators_see_everything(), room); + Server_Game *game = new Server_Game( + copyUserInfo(false), gameId, description, QString::fromStdString(cmd.password()), cmd.max_players(), gameTypes, + cmd.only_buddies(), onlyRegisteredUsers, cmd.spectators_allowed(), cmd.spectators_need_password(), + cmd.spectators_can_talk(), cmd.spectators_see_everything(), room); game->addPlayer(this, rc, false, false); room->addGame(game); return Response::RespOk; } -Response::ResponseCode Server_ProtocolHandler::cmdJoinGame(const Command_JoinGame &cmd, Server_Room *room, ResponseContainer &rc) +Response::ResponseCode +Server_ProtocolHandler::cmdJoinGame(const Command_JoinGame &cmd, Server_Room *room, ResponseContainer &rc) { if (authState == NotLoggedIn) return Response::RespLoginNeeded; diff --git a/common/server_protocolhandler.h b/common/server_protocolhandler.h index 8dae20bb..f3d82a27 100644 --- a/common/server_protocolhandler.h +++ b/common/server_protocolhandler.h @@ -1,12 +1,12 @@ #ifndef SERVER_PROTOCOLHANDLER_H #define SERVER_PROTOCOLHANDLER_H -#include -#include -#include "server.h" -#include "server_abstractuserinterface.h" #include "pb/response.pb.h" #include "pb/server_message.pb.h" +#include "server.h" +#include "server_abstractuserinterface.h" +#include +#include class Features; class Server_DatabaseInterface; @@ -42,25 +42,29 @@ class Command_RoomSay; class Command_CreateGame; class Command_JoinGame; -class Server_ProtocolHandler : public QObject, public Server_AbstractUserInterface { +class Server_ProtocolHandler : public QObject, public Server_AbstractUserInterface +{ Q_OBJECT protected: QMap rooms; - + bool deleted; Server_DatabaseInterface *databaseInterface; AuthenticationResult authState; bool acceptsUserListChanges; bool acceptsRoomListChanges; bool idleClientWarningSent; - virtual void logDebugMessage(const QString & /* message */) { } + virtual void logDebugMessage(const QString & /* message */) + { + } + private: QList messageSizeOverTime, messageCountOverTime, commandCountOverTime; int timeRunning, lastDataReceived, lastActionReceived; QTimer *pingClock; virtual void transmitProtocolItem(const ServerMessage &item) = 0; - + Response::ResponseCode cmdPing(const Command_Ping &cmd, ResponseContainer &rc); Response::ResponseCode cmdLogin(const Command_Login &cmd, ResponseContainer &rc); Response::ResponseCode cmdMessage(const Command_Message &cmd, ResponseContainer &rc); @@ -73,39 +77,63 @@ private: Response::ResponseCode cmdRoomSay(const Command_RoomSay &cmd, Server_Room *room, ResponseContainer &rc); Response::ResponseCode cmdCreateGame(const Command_CreateGame &cmd, Server_Room *room, ResponseContainer &rc); Response::ResponseCode cmdJoinGame(const Command_JoinGame &cmd, Server_Room *room, ResponseContainer &rc); - + Response::ResponseCode processSessionCommandContainer(const CommandContainer &cont, ResponseContainer &rc); - virtual Response::ResponseCode processExtendedSessionCommand(int /* cmdType */, const SessionCommand & /* cmd */, ResponseContainer & /* rc */) { return Response::RespFunctionNotAllowed; } + virtual Response::ResponseCode + processExtendedSessionCommand(int /* cmdType */, const SessionCommand & /* cmd */, ResponseContainer & /* rc */) + { + return Response::RespFunctionNotAllowed; + } Response::ResponseCode processRoomCommandContainer(const CommandContainer &cont, ResponseContainer &rc); Response::ResponseCode processGameCommandContainer(const CommandContainer &cont, ResponseContainer &rc); Response::ResponseCode processModeratorCommandContainer(const CommandContainer &cont, ResponseContainer &rc); - virtual Response::ResponseCode processExtendedModeratorCommand(int /* cmdType */, const ModeratorCommand & /* cmd */, ResponseContainer & /* rc */) { return Response::RespFunctionNotAllowed; } + virtual Response::ResponseCode + processExtendedModeratorCommand(int /* cmdType */, const ModeratorCommand & /* cmd */, ResponseContainer & /* rc */) + { + return Response::RespFunctionNotAllowed; + } Response::ResponseCode processAdminCommandContainer(const CommandContainer &cont, ResponseContainer &rc); - virtual Response::ResponseCode processExtendedAdminCommand(int /* cmdType */, const AdminCommand & /* cmd */, ResponseContainer & /* rc */) { return Response::RespFunctionNotAllowed; } + virtual Response::ResponseCode + processExtendedAdminCommand(int /* cmdType */, const AdminCommand & /* cmd */, ResponseContainer & /* rc */) + { + return Response::RespFunctionNotAllowed; + } void resetIdleTimer(); private slots: void pingClockTimeout(); public slots: void prepareDestroy(); + public: Server_ProtocolHandler(Server *_server, Server_DatabaseInterface *_databaseInterface, QObject *parent = 0); ~Server_ProtocolHandler(); - - bool getAcceptsUserListChanges() const { return acceptsUserListChanges; } - bool getAcceptsRoomListChanges() const { return acceptsRoomListChanges; } + + bool getAcceptsUserListChanges() const + { + return acceptsUserListChanges; + } + bool getAcceptsRoomListChanges() const + { + return acceptsRoomListChanges; + } virtual QString getAddress() const = 0; virtual QString getConnectionType() const = 0; - Server_DatabaseInterface *getDatabaseInterface() const { return databaseInterface; } + Server_DatabaseInterface *getDatabaseInterface() const + { + return databaseInterface; + } - int getLastCommandTime() const { return timeRunning - lastDataReceived; } + int getLastCommandTime() const + { + return timeRunning - lastDataReceived; + } void processCommandContainer(const CommandContainer &cont); - + void sendProtocolItem(const Response &item); void sendProtocolItem(const SessionEvent &item); void sendProtocolItem(const GameEventContainer &item); void sendProtocolItem(const RoomEvent &item); - }; #endif diff --git a/common/server_remoteuserinterface.cpp b/common/server_remoteuserinterface.cpp index 7bbcf963..ca0fc7dc 100644 --- a/common/server_remoteuserinterface.cpp +++ b/common/server_remoteuserinterface.cpp @@ -1,6 +1,6 @@ #include "server_remoteuserinterface.h" -#include "server.h" #include "pb/serverinfo_user.pb.h" +#include "server.h" void Server_RemoteUserInterface::sendProtocolItem(const Response &item) { diff --git a/common/server_remoteuserinterface.h b/common/server_remoteuserinterface.h index 311f0516..bf412d64 100644 --- a/common/server_remoteuserinterface.h +++ b/common/server_remoteuserinterface.h @@ -3,12 +3,19 @@ #include "server_abstractuserinterface.h" -class Server_RemoteUserInterface : public Server_AbstractUserInterface { +class Server_RemoteUserInterface : public Server_AbstractUserInterface +{ public: - Server_RemoteUserInterface(Server *_server, const ServerInfo_User_Container &_userInfoContainer) : Server_AbstractUserInterface(_server, _userInfoContainer) { } - - int getLastCommandTime() const { return 0; } - + Server_RemoteUserInterface(Server *_server, const ServerInfo_User_Container &_userInfoContainer) + : Server_AbstractUserInterface(_server, _userInfoContainer) + { + } + + int getLastCommandTime() const + { + return 0; + } + void sendProtocolItem(const Response &item); void sendProtocolItem(const SessionEvent &item); void sendProtocolItem(const GameEventContainer &item); diff --git a/common/server_response_containers.cpp b/common/server_response_containers.cpp index e327ee9d..a9b38a01 100644 --- a/common/server_response_containers.cpp +++ b/common/server_response_containers.cpp @@ -1,8 +1,10 @@ #include "server_response_containers.h" -#include #include "server_game.h" +#include -GameEventStorageItem::GameEventStorageItem(const ::google::protobuf::Message &_event, int _playerId, EventRecipients _recipients) +GameEventStorageItem::GameEventStorageItem(const ::google::protobuf::Message &_event, + int _playerId, + EventRecipients _recipients) : event(new GameEvent), recipients(_recipients) { event->GetReflection()->MutableMessage(event, _event.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(_event); @@ -14,8 +16,7 @@ GameEventStorageItem::~GameEventStorageItem() delete event; } -GameEventStorage::GameEventStorage() - : gameEventContext(0), privatePlayerId(0) +GameEventStorage::GameEventStorage() : gameEventContext(0), privatePlayerId(0) { } @@ -30,10 +31,15 @@ void GameEventStorage::setGameEventContext(const ::google::protobuf::Message &_g { delete gameEventContext; gameEventContext = new GameEventContext; - gameEventContext->GetReflection()->MutableMessage(gameEventContext, _gameEventContext.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(_gameEventContext); + gameEventContext->GetReflection() + ->MutableMessage(gameEventContext, _gameEventContext.GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(_gameEventContext); } -void GameEventStorage::enqueueGameEvent(const ::google::protobuf::Message &event, int playerId, GameEventStorageItem::EventRecipients recipients, int _privatePlayerId) +void GameEventStorage::enqueueGameEvent(const ::google::protobuf::Message &event, + int playerId, + GameEventStorageItem::EventRecipients recipients, + int _privatePlayerId) { gameEventList.append(new GameEventStorageItem(event, playerId, recipients)); if (_privatePlayerId != -1) @@ -44,7 +50,7 @@ void GameEventStorage::sendToGame(Server_Game *game) { if (gameEventList.isEmpty()) return; - + GameEventContainer *contPrivate = new GameEventContainer; GameEventContainer *contOthers = new GameEventContainer; for (int i = 0; i < gameEventList.size(); ++i) { @@ -63,8 +69,7 @@ void GameEventStorage::sendToGame(Server_Game *game) game->sendGameEventContainer(contOthers, GameEventStorageItem::SendToOthers, privatePlayerId); } -ResponseContainer::ResponseContainer(int _cmdId) - : cmdId(_cmdId), responseExtension(0) +ResponseContainer::ResponseContainer(int _cmdId) : cmdId(_cmdId), responseExtension(0) { } diff --git a/common/server_response_containers.h b/common/server_response_containers.h index 5363f802..b2e77755 100644 --- a/common/server_response_containers.h +++ b/common/server_response_containers.h @@ -1,63 +1,119 @@ #ifndef SERVER_RESPONSE_CONTAINERS_H #define SERVER_RESPONSE_CONTAINERS_H -#include -#include #include "pb/server_message.pb.h" +#include +#include -namespace google { namespace protobuf { class Message; } } +namespace google +{ +namespace protobuf +{ +class Message; +} +} // namespace google class Server_Game; -class GameEventStorageItem { +class GameEventStorageItem +{ public: - enum EventRecipient { SendToPrivate = 0x01, SendToOthers = 0x02}; + enum EventRecipient + { + SendToPrivate = 0x01, + SendToOthers = 0x02 + }; Q_DECLARE_FLAGS(EventRecipients, EventRecipient) private: GameEvent *event; EventRecipients recipients; + public: GameEventStorageItem(const ::google::protobuf::Message &_event, int _playerId, EventRecipients _recipients); ~GameEventStorageItem(); - - const GameEvent &getGameEvent() const { return *event; } - EventRecipients getRecipients() const { return recipients; } + + const GameEvent &getGameEvent() const + { + return *event; + } + EventRecipients getRecipients() const + { + return recipients; + } }; Q_DECLARE_OPERATORS_FOR_FLAGS(GameEventStorageItem::EventRecipients) -class GameEventStorage { +class GameEventStorage +{ private: ::google::protobuf::Message *gameEventContext; QList gameEventList; int privatePlayerId; + public: GameEventStorage(); ~GameEventStorage(); - + void setGameEventContext(const ::google::protobuf::Message &_gameEventContext); - ::google::protobuf::Message *getGameEventContext() const { return gameEventContext; } - const QList &getGameEventList() const { return gameEventList; } - int getPrivatePlayerId() const { return privatePlayerId; } - - void enqueueGameEvent(const ::google::protobuf::Message &event, int playerId, GameEventStorageItem::EventRecipients recipients = GameEventStorageItem::SendToPrivate | GameEventStorageItem::SendToOthers, int _privatePlayerId = -1); + ::google::protobuf::Message *getGameEventContext() const + { + return gameEventContext; + } + const QList &getGameEventList() const + { + return gameEventList; + } + int getPrivatePlayerId() const + { + return privatePlayerId; + } + + void enqueueGameEvent(const ::google::protobuf::Message &event, + int playerId, + GameEventStorageItem::EventRecipients recipients = GameEventStorageItem::SendToPrivate | + GameEventStorageItem::SendToOthers, + int _privatePlayerId = -1); void sendToGame(Server_Game *game); }; -class ResponseContainer { +class ResponseContainer +{ private: int cmdId; ::google::protobuf::Message *responseExtension; - QList > preResponseQueue, postResponseQueue; + QList> preResponseQueue, postResponseQueue; + public: ResponseContainer(int _cmdId); ~ResponseContainer(); - - int getCmdId() const { return cmdId; } - void setResponseExtension(::google::protobuf::Message *_responseExtension) { responseExtension = _responseExtension; } - ::google::protobuf::Message *getResponseExtension() const { return responseExtension; } - void enqueuePreResponseItem(ServerMessage::MessageType type, ::google::protobuf::Message *item) { preResponseQueue.append(qMakePair(type, item)); } - void enqueuePostResponseItem(ServerMessage::MessageType type, ::google::protobuf::Message *item) { postResponseQueue.append(qMakePair(type, item)); } - const QList > &getPreResponseQueue() const { return preResponseQueue; } - const QList > &getPostResponseQueue() const { return postResponseQueue; } + + int getCmdId() const + { + return cmdId; + } + void setResponseExtension(::google::protobuf::Message *_responseExtension) + { + responseExtension = _responseExtension; + } + ::google::protobuf::Message *getResponseExtension() const + { + return responseExtension; + } + void enqueuePreResponseItem(ServerMessage::MessageType type, ::google::protobuf::Message *item) + { + preResponseQueue.append(qMakePair(type, item)); + } + void enqueuePostResponseItem(ServerMessage::MessageType type, ::google::protobuf::Message *item) + { + postResponseQueue.append(qMakePair(type, item)); + } + const QList> &getPreResponseQueue() const + { + return preResponseQueue; + } + const QList> &getPostResponseQueue() const + { + return postResponseQueue; + } }; #endif diff --git a/common/server_room.cpp b/common/server_room.cpp index 752b5fee..5f1ccd3c 100644 --- a/common/server_room.cpp +++ b/common/server_room.cpp @@ -1,42 +1,54 @@ #include "server_room.h" -#include "server_protocolhandler.h" #include "server_game.h" -#include +#include "server_protocolhandler.h" #include +#include #include "pb/commands.pb.h" -#include "pb/room_commands.pb.h" #include "pb/event_join_room.pb.h" #include "pb/event_leave_room.pb.h" #include "pb/event_list_games.pb.h" #include "pb/event_room_say.pb.h" -#include "pb/serverinfo_room.pb.h" +#include "pb/room_commands.pb.h" #include "pb/serverinfo_chat_message.pb.h" +#include "pb/serverinfo_room.pb.h" #include -Server_Room::Server_Room(int _id, int _chatHistorySize, const QString &_name, const QString &_description, const QString &_permissionLevel, const QString &_privilegeLevel, bool _autoJoin, const QString &_joinMessage, const QStringList &_gameTypes, Server *parent) - : QObject(parent), id(_id), chatHistorySize(_chatHistorySize), name(_name), description(_description), permissionLevel(_permissionLevel), privilegeLevel(_privilegeLevel), autoJoin(_autoJoin), joinMessage(_joinMessage), gameTypes(_gameTypes), gamesLock(QReadWriteLock::Recursive) +Server_Room::Server_Room(int _id, + int _chatHistorySize, + const QString &_name, + const QString &_description, + const QString &_permissionLevel, + const QString &_privilegeLevel, + bool _autoJoin, + const QString &_joinMessage, + const QStringList &_gameTypes, + Server *parent) + : QObject(parent), id(_id), chatHistorySize(_chatHistorySize), name(_name), description(_description), + permissionLevel(_permissionLevel), privilegeLevel(_privilegeLevel), autoJoin(_autoJoin), + joinMessage(_joinMessage), gameTypes(_gameTypes), gamesLock(QReadWriteLock::Recursive) { - connect(this, SIGNAL(gameListChanged(ServerInfo_Game)), this, SLOT(broadcastGameListUpdate(ServerInfo_Game)), Qt::QueuedConnection); + connect(this, SIGNAL(gameListChanged(ServerInfo_Game)), this, SLOT(broadcastGameListUpdate(ServerInfo_Game)), + Qt::QueuedConnection); } Server_Room::~Server_Room() { qDebug("Server_Room destructor"); - + gamesLock.lockForWrite(); const QList gameList = games.values(); for (int i = 0; i < gameList.size(); ++i) delete gameList[i]; games.clear(); gamesLock.unlock(); - + usersLock.lockForWrite(); users.clear(); usersLock.unlock(); } -bool Server_Room::userMayJoin(const ServerInfo_User & userInfo) +bool Server_Room::userMayJoin(const ServerInfo_User &userInfo) { if (permissionLevel.toLower() == "administrator" || permissionLevel.toLower() == "moderator") @@ -45,15 +57,11 @@ bool Server_Room::userMayJoin(const ServerInfo_User & userInfo) if (permissionLevel.toLower() == "registered" && !(userInfo.user_level() & ServerInfo_User::IsRegistered)) return false; - if (privilegeLevel.toLower() != "none") - { - if (privilegeLevel.toLower() == "privileged") - { + if (privilegeLevel.toLower() != "none") { + if (privilegeLevel.toLower() == "privileged") { if (privilegeLevel.toLower() == "none") return false; - } - else - { + } else { if (privilegeLevel.toLower() != QString::fromStdString(userInfo.privlevel()).toLower()) return false; } @@ -66,7 +74,8 @@ Server *Server_Room::getServer() const return static_cast(parent()); } -const ServerInfo_Room &Server_Room::getInfo(ServerInfo_Room &result, bool complete, bool showGameTypes, bool includeExternalData) const +const ServerInfo_Room & +Server_Room::getInfo(ServerInfo_Room &result, bool complete, bool showGameTypes, bool includeExternalData) const { result.set_room_id(id); result.set_name(name.toStdString()); @@ -74,7 +83,7 @@ const ServerInfo_Room &Server_Room::getInfo(ServerInfo_Room &result, bool comple result.set_auto_join(autoJoin); result.set_permissionlevel(permissionLevel.toStdString()); result.set_privilegelevel(privilegeLevel.toStdString()); - + gamesLock.lockForRead(); result.set_game_count(games.size() + externalGames.size()); if (complete) { @@ -88,7 +97,7 @@ const ServerInfo_Room &Server_Room::getInfo(ServerInfo_Room &result, bool comple } } gamesLock.unlock(); - + usersLock.lockForRead(); result.set_player_count(users.size() + externalUsers.size()); if (complete) { @@ -102,14 +111,14 @@ const ServerInfo_Room &Server_Room::getInfo(ServerInfo_Room &result, bool comple } } usersLock.unlock(); - + if (complete || showGameTypes) for (int i = 0; i < gameTypes.size(); ++i) { ServerInfo_GameType *gameTypeInfo = result.add_gametype_list(); gameTypeInfo->set_game_type_id(i); gameTypeInfo->set_description(gameTypes[i].toStdString()); } - + return result; } @@ -117,7 +126,9 @@ RoomEvent *Server_Room::prepareRoomEvent(const ::google::protobuf::Message &room { RoomEvent *event = new RoomEvent; event->set_room_id(id); - event->GetReflection()->MutableMessage(event, roomEvent.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(roomEvent); + event->GetReflection() + ->MutableMessage(event, roomEvent.GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(roomEvent); return event; } @@ -126,21 +137,21 @@ void Server_Room::addClient(Server_ProtocolHandler *client) Event_JoinRoom event; event.mutable_user_info()->CopyFrom(client->copyUserInfo(false)); sendRoomEvent(prepareRoomEvent(event)); - + ServerInfo_Room roomInfo; roomInfo.set_room_id(id); - + usersLock.lockForWrite(); users.insert(QString::fromStdString(client->getUserInfo()->name()), client); roomInfo.set_player_count(users.size() + externalUsers.size()); usersLock.unlock(); - + // XXX This can be removed during the next client update. gamesLock.lockForRead(); roomInfo.set_game_count(games.size() + externalGames.size()); gamesLock.unlock(); // ----------- - + emit roomInfoChanged(roomInfo); } @@ -148,22 +159,22 @@ void Server_Room::removeClient(Server_ProtocolHandler *client) { usersLock.lockForWrite(); users.remove(QString::fromStdString(client->getUserInfo()->name())); - + ServerInfo_Room roomInfo; roomInfo.set_room_id(id); roomInfo.set_player_count(users.size() + externalUsers.size()); usersLock.unlock(); - + Event_LeaveRoom event; event.set_name(client->getUserInfo()->name()); sendRoomEvent(prepareRoomEvent(event)); - + // XXX This can be removed during the next client update. gamesLock.lockForRead(); roomInfo.set_game_count(games.size() + externalGames.size()); gamesLock.unlock(); // ----------- - + emit roomInfoChanged(roomInfo); } @@ -174,7 +185,7 @@ void Server_Room::addExternalUser(const ServerInfo_User &userInfo) Event_JoinRoom event; event.mutable_user_info()->CopyFrom(userInfoContainer.copyUserInfo(false)); sendRoomEvent(prepareRoomEvent(event), false); - + ServerInfo_Room roomInfo; roomInfo.set_room_id(id); @@ -182,7 +193,7 @@ void Server_Room::addExternalUser(const ServerInfo_User &userInfo) externalUsers.insert(QString::fromStdString(userInfo.name()), userInfoContainer); roomInfo.set_player_count(users.size() + externalUsers.size()); usersLock.unlock(); - + emit roomInfoChanged(roomInfo); } @@ -191,17 +202,17 @@ void Server_Room::removeExternalUser(const QString &name) // This function is always called from the Server thread with server->roomsMutex locked. ServerInfo_Room roomInfo; roomInfo.set_room_id(id); - + usersLock.lockForWrite(); if (externalUsers.contains(name)) externalUsers.remove(name); roomInfo.set_player_count(users.size() + externalUsers.size()); usersLock.unlock(); - + Event_LeaveRoom event; event.set_name(name.toStdString()); sendRoomEvent(prepareRoomEvent(event), false); - + emit roomInfoChanged(roomInfo); } @@ -210,7 +221,7 @@ void Server_Room::updateExternalGameList(const ServerInfo_Game &gameInfo) // This function is always called from the Server thread with server->roomsMutex locked. ServerInfo_Room roomInfo; roomInfo.set_room_id(id); - + gamesLock.lockForWrite(); if (!gameInfo.has_player_count() && externalGames.contains(gameInfo.game_id())) externalGames.remove(gameInfo.game_id()); @@ -218,16 +229,18 @@ void Server_Room::updateExternalGameList(const ServerInfo_Game &gameInfo) externalGames.insert(gameInfo.game_id(), gameInfo); roomInfo.set_game_count(games.size() + externalGames.size()); gamesLock.unlock(); - + broadcastGameListUpdate(gameInfo, false); emit roomInfoChanged(roomInfo); } -Response::ResponseCode Server_Room::processJoinGameCommand(const Command_JoinGame &cmd, ResponseContainer &rc, Server_AbstractUserInterface *userInterface) +Response::ResponseCode Server_Room::processJoinGameCommand(const Command_JoinGame &cmd, + ResponseContainer &rc, + Server_AbstractUserInterface *userInterface) { // This function is called from the Server thread and from the S_PH thread. // server->roomsMutex is always locked. - + QReadLocker roomGamesLocker(&gamesLock); Server_Game *g = games.value(cmd.game_id()); if (!g) { @@ -235,31 +248,34 @@ Response::ResponseCode Server_Room::processJoinGameCommand(const Command_JoinGam CommandContainer cont; cont.set_cmd_id(rc.getCmdId()); RoomCommand *roomCommand = cont.add_room_command(); - roomCommand->GetReflection()->MutableMessage(roomCommand, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - getServer()->sendIsl_RoomCommand(cont, externalGames.value(cmd.game_id()).server_id(), userInterface->getUserInfo()->session_id(), id); - + roomCommand->GetReflection() + ->MutableMessage(roomCommand, cmd.GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(cmd); + getServer()->sendIsl_RoomCommand(cont, externalGames.value(cmd.game_id()).server_id(), + userInterface->getUserInfo()->session_id(), id); + return Response::RespNothing; } else return Response::RespNameNotFound; } - + QMutexLocker gameLocker(&g->gameMutex); - - Response::ResponseCode result = g->checkJoin(userInterface->getUserInfo(), QString::fromStdString(cmd.password()), cmd.spectator(), cmd.override_restrictions()); + + Response::ResponseCode result = g->checkJoin(userInterface->getUserInfo(), QString::fromStdString(cmd.password()), + cmd.spectator(), cmd.override_restrictions()); if (result == Response::RespOk) g->addPlayer(userInterface, rc, cmd.spectator()); - + return result; } - void Server_Room::say(const QString &userName, const QString &s, bool sendToIsl) { Event_RoomSay event; event.set_name(userName.toStdString()); event.set_message(s.toStdString()); sendRoomEvent(prepareRoomEvent(event), sendToIsl); - + if (chatHistorySize != 0) { ServerInfo_ChatMessage chatMessage; QDateTime dateTime = dateTime.currentDateTimeUtc(); @@ -275,7 +291,6 @@ void Server_Room::say(const QString &userName, const QString &s, bool sendToIsl) chatHistory << chatMessage; historyLock.unlock(); } - } void Server_Room::sendRoomEvent(RoomEvent *event, bool sendToIsl) @@ -287,10 +302,10 @@ void Server_Room::sendRoomEvent(RoomEvent *event, bool sendToIsl) userIterator.next().value()->sendProtocolItem(*event); } usersLock.unlock(); - + if (sendToIsl) static_cast(parent())->sendIsl_RoomEvent(*event); - + delete event; } @@ -305,10 +320,10 @@ void Server_Room::addGame(Server_Game *game) { ServerInfo_Room roomInfo; roomInfo.set_room_id(id); - + gamesLock.lockForWrite(); connect(game, SIGNAL(gameInfoChanged(ServerInfo_Game)), this, SLOT(broadcastGameListUpdate(ServerInfo_Game))); - + game->gameMutex.lock(); games.insert(game->getGameId(), game); ServerInfo_Game gameInfo; @@ -316,7 +331,7 @@ void Server_Room::addGame(Server_Game *game) roomInfo.set_game_count(games.size() + externalGames.size()); game->gameMutex.unlock(); gamesLock.unlock(); - + // XXX This can be removed during the next client update. usersLock.lockForRead(); roomInfo.set_player_count(users.size() + externalUsers.size()); @@ -331,32 +346,32 @@ void Server_Room::removeGame(Server_Game *game) { // No need to lock gamesLock or gameMutex. This method is only // called from ~Server_Game, which locks both mutexes anyway beforehand. - + disconnect(game, 0, this, 0); - + ServerInfo_Game gameInfo; game->getInfo(gameInfo); emit gameListChanged(gameInfo); - + games.remove(game->getGameId()); - + ServerInfo_Room roomInfo; roomInfo.set_room_id(id); roomInfo.set_game_count(games.size() + externalGames.size()); - + // XXX This can be removed during the next client update. usersLock.lockForRead(); roomInfo.set_player_count(users.size() + externalUsers.size()); usersLock.unlock(); // ----------- - + emit roomInfoChanged(roomInfo); } int Server_Room::getGamesCreatedByUser(const QString &userName) const { QReadLocker locker(&gamesLock); - + QMapIterator gamesIterator(games); int result = 0; while (gamesIterator.hasNext()) @@ -368,7 +383,7 @@ int Server_Room::getGamesCreatedByUser(const QString &userName) const QList Server_Room::getGamesOfUser(const QString &userName) const { QReadLocker locker(&gamesLock); - + QList result; QMapIterator gamesIterator(games); while (gamesIterator.hasNext()) { diff --git a/common/server_room.h b/common/server_room.h index edf2d3fd..ec4b82b9 100644 --- a/common/server_room.h +++ b/common/server_room.h @@ -1,15 +1,15 @@ #ifndef SERVER_ROOM_H #define SERVER_ROOM_H -#include -#include -#include -#include -#include -#include -#include "serverinfo_user_container.h" #include "pb/response.pb.h" #include "pb/serverinfo_chat_message.pb.h" +#include "serverinfo_user_container.h" +#include +#include +#include +#include +#include +#include class Server_DatabaseInterface; class Server_ProtocolHandler; @@ -24,11 +24,13 @@ class Command_JoinGame; class ResponseContainer; class Server_AbstractUserInterface; -class Server_Room : public QObject { +class Server_Room : public QObject +{ Q_OBJECT signals: void roomInfoChanged(const ServerInfo_Room &roomInfo); void gameListChanged(const ServerInfo_Game &gameInfo); + private: int id; int chatHistorySize; @@ -46,44 +48,93 @@ private: QList chatHistory; private slots: void broadcastGameListUpdate(const ServerInfo_Game &gameInfo, bool sendToIsl = true); + public: mutable QReadWriteLock usersLock; mutable QReadWriteLock gamesLock; mutable QReadWriteLock historyLock; - Server_Room(int _id, int _chatHistorySize, const QString &_name, const QString &_description, const QString &_permissionLevel, const QString &_privilegeLevel, bool _autoJoin, const QString &_joinMessage, const QStringList &_gameTypes, Server *parent ); + Server_Room(int _id, + int _chatHistorySize, + const QString &_name, + const QString &_description, + const QString &_permissionLevel, + const QString &_privilegeLevel, + bool _autoJoin, + const QString &_joinMessage, + const QStringList &_gameTypes, + Server *parent); ~Server_Room(); - int getId() const { return id; } - QString getName() const { return name; } - QString getDescription() const { return description; } - QString getRoomPermission() const { return permissionLevel; } - QString getRoomPrivilege() const { return privilegeLevel; } - bool getAutoJoin() const { return autoJoin; } + int getId() const + { + return id; + } + QString getName() const + { + return name; + } + QString getDescription() const + { + return description; + } + QString getRoomPermission() const + { + return permissionLevel; + } + QString getRoomPrivilege() const + { + return privilegeLevel; + } + bool getAutoJoin() const + { + return autoJoin; + } bool userMayJoin(const ServerInfo_User &userInfo); - QString getJoinMessage() const { return joinMessage; } - const QStringList &getGameTypes() const { return gameTypes; } - const QMap &getGames() const { return games; } - const QMap &getExternalGames() const { return externalGames; } + QString getJoinMessage() const + { + return joinMessage; + } + const QStringList &getGameTypes() const + { + return gameTypes; + } + const QMap &getGames() const + { + return games; + } + const QMap &getExternalGames() const + { + return externalGames; + } Server *getServer() const; - const ServerInfo_Room &getInfo(ServerInfo_Room &result, bool complete, bool showGameTypes = false, bool includeExternalData = true) const; + const ServerInfo_Room & + getInfo(ServerInfo_Room &result, bool complete, bool showGameTypes = false, bool includeExternalData = true) const; int getGamesCreatedByUser(const QString &name) const; QList getGamesOfUser(const QString &name) const; - QList & getChatHistory() { return chatHistory; } - + QList &getChatHistory() + { + return chatHistory; + } + void addClient(Server_ProtocolHandler *client); void removeClient(Server_ProtocolHandler *client); - + void addExternalUser(const ServerInfo_User &userInfo); void removeExternalUser(const QString &name); - const QMap &getExternalUsers() const { return externalUsers; } + const QMap &getExternalUsers() const + { + return externalUsers; + } void updateExternalGameList(const ServerInfo_Game &gameInfo); - - Response::ResponseCode processJoinGameCommand(const Command_JoinGame &cmd, ResponseContainer &rc, Server_AbstractUserInterface *userInterface); - + + Response::ResponseCode processJoinGameCommand(const Command_JoinGame &cmd, + ResponseContainer &rc, + Server_AbstractUserInterface *userInterface); + void say(const QString &userName, const QString &s, bool sendToIsl = true); - + void addGame(Server_Game *game); void removeGame(Server_Game *game); - + void sendRoomEvent(RoomEvent *event, bool sendToIsl = true); RoomEvent *prepareRoomEvent(const ::google::protobuf::Message &roomEvent); }; diff --git a/common/serverinfo_user_container.cpp b/common/serverinfo_user_container.cpp index a0fd05c9..cf8c9888 100644 --- a/common/serverinfo_user_container.cpp +++ b/common/serverinfo_user_container.cpp @@ -1,8 +1,7 @@ #include "serverinfo_user_container.h" #include "pb/serverinfo_user.pb.h" -ServerInfo_User_Container::ServerInfo_User_Container(ServerInfo_User *_userInfo) - : userInfo(_userInfo) +ServerInfo_User_Container::ServerInfo_User_Container(ServerInfo_User *_userInfo) : userInfo(_userInfo) { } @@ -29,7 +28,10 @@ void ServerInfo_User_Container::setUserInfo(const ServerInfo_User &_userInfo) userInfo = new ServerInfo_User(_userInfo); } -ServerInfo_User &ServerInfo_User_Container::copyUserInfo(ServerInfo_User &result, bool complete, bool internalInfo, bool sessionInfo) const +ServerInfo_User &ServerInfo_User_Container::copyUserInfo(ServerInfo_User &result, + bool complete, + bool internalInfo, + bool sessionInfo) const { if (userInfo) { result.CopyFrom(*userInfo); @@ -38,15 +40,14 @@ ServerInfo_User &ServerInfo_User_Container::copyUserInfo(ServerInfo_User &result result.clear_address(); result.clear_clientid(); } - if (!internalInfo) - { + if (!internalInfo) { result.clear_id(); result.clear_email(); } if (!complete) result.clear_avatar_bmp(); } - return result; + return result; } ServerInfo_User ServerInfo_User_Container::copyUserInfo(bool complete, bool internalInfo, bool sessionInfo) const diff --git a/common/serverinfo_user_container.h b/common/serverinfo_user_container.h index d7fb76f8..908babea 100644 --- a/common/serverinfo_user_container.h +++ b/common/serverinfo_user_container.h @@ -3,17 +3,23 @@ class ServerInfo_User; -class ServerInfo_User_Container { +class ServerInfo_User_Container +{ protected: ServerInfo_User *userInfo; + public: ServerInfo_User_Container(ServerInfo_User *_userInfo = 0); ServerInfo_User_Container(const ServerInfo_User &_userInfo); ServerInfo_User_Container(const ServerInfo_User_Container &other); virtual ~ServerInfo_User_Container(); - ServerInfo_User *getUserInfo() const { return userInfo; } + ServerInfo_User *getUserInfo() const + { + return userInfo; + } void setUserInfo(const ServerInfo_User &_userInfo); - ServerInfo_User ©UserInfo(ServerInfo_User &result, bool complete, bool internalInfo = false, bool sessionInfo = false) const; + ServerInfo_User & + copyUserInfo(ServerInfo_User &result, bool complete, bool internalInfo = false, bool sessionInfo = false) const; ServerInfo_User copyUserInfo(bool complete, bool internalInfo = false, bool sessionInfo = false) const; }; diff --git a/oracle/src/main.cpp b/oracle/src/main.cpp index 697f8cb3..0005e077 100644 --- a/oracle/src/main.cpp +++ b/oracle/src/main.cpp @@ -1,9 +1,9 @@ #include -#include -#include -#include -#include #include +#include +#include +#include +#include #include "main.h" #include "oraclewizard.h" @@ -30,12 +30,12 @@ void installNewTranslator() int main(int argc, char *argv[]) { - QApplication app(argc, argv); + QApplication app(argc, argv); - QCoreApplication::setOrganizationName("Cockatrice"); - QCoreApplication::setOrganizationDomain("cockatrice"); - // this can't be changed, as it influences the default savepath for cards.xml - QCoreApplication::setApplicationName("Cockatrice"); + QCoreApplication::setOrganizationName("Cockatrice"); + QCoreApplication::setOrganizationDomain("cockatrice"); + // this can't be changed, as it influences the default savepath for cards.xml + QCoreApplication::setApplicationName("Cockatrice"); // If the program is opened with the -s flag, it will only do spoilers. Otherwise it will do MTGJSON/Tokens QCommandLineParser parser; @@ -52,19 +52,19 @@ int main(int argc, char *argv[]) translationPath = qApp->applicationDirPath() + "/../share/cockatrice/translations"; #endif - settingsCache = new SettingsCache; + settingsCache = new SettingsCache; themeManager = new ThemeManager; qtTranslator = new QTranslator; translator = new QTranslator; installNewTranslator(); - OracleWizard wizard; + OracleWizard wizard; QIcon icon("theme:appicon.svg"); wizard.setWindowIcon(icon); - wizard.show(); + wizard.show(); - return app.exec(); + return app.exec(); } diff --git a/oracle/src/oracleimporter.cpp b/oracle/src/oracleimporter.cpp index c3931bc7..16c45e69 100644 --- a/oracle/src/oracleimporter.cpp +++ b/oracle/src/oracleimporter.cpp @@ -1,26 +1,25 @@ #include "oracleimporter.h" -#include #include +#include #include "qt-json/json.h" -OracleImporter::OracleImporter(const QString &_dataDir, QObject *parent) - : CardDatabase(parent), dataDir(_dataDir) +OracleImporter::OracleImporter(const QString &_dataDir, QObject *parent) : CardDatabase(parent), dataDir(_dataDir) { } bool OracleImporter::readSetsFromByteArray(const QByteArray &data) { QList newSetList; - + bool ok; setsMap = QtJson::Json::parse(QString(data), ok).toMap(); if (!ok) { qDebug() << "error: QtJson::Json::parse()"; return 0; } - + QListIterator it(setsMap.values()); QVariantMap map; @@ -37,7 +36,7 @@ bool OracleImporter::readSetsFromByteArray(const QByteArray &data) editionCards = map.value("cards"); setType = map.value("type").toString(); // capitalize set type - if(setType.length() > 0) + if (setType.length() > 0) setType[0] = setType[0].toUpper(); releaseDate = map.value("releaseDate").toDate(); @@ -63,12 +62,11 @@ CardInfo *OracleImporter::addCard(const QString &setName, const QString &cardPT, int cardLoyalty, const QString &cardText, - const QStringList & colors, - const QList & relatedCards, - const QList & reverseRelatedCards, + const QStringList &colors, + const QList &relatedCards, + const QList &reverseRelatedCards, bool upsideDown, - QString &rarity - ) + QString &rarity) { QStringList cardTextRows = cardText.split("\n"); @@ -76,7 +74,7 @@ CardInfo *OracleImporter::addCard(const QString &setName, cardName = cardName.replace("Æ", "AE"); cardName = cardName.replace("’", "'"); - CardInfo * card; + CardInfo *card; if (cards.contains(cardName)) { card = cards.value(cardName); } else { @@ -92,10 +90,13 @@ CardInfo *OracleImporter::addCard(const QString &setName, mArtifact = true; // detect cards that enter the field tapped - bool cipt = cardText.contains("Hideaway") || (cardText.contains(cardName + " enters the battlefield tapped") && !cardText.contains(cardName + " enters the battlefield tapped unless")); - + bool cipt = + cardText.contains("Hideaway") || (cardText.contains(cardName + " enters the battlefield tapped") && + !cardText.contains(cardName + " enters the battlefield tapped unless")); + // insert the card and its properties - card = new CardInfo(cardName, isToken, cardCost, cmc, cardType, cardPT, cardText, colors, relatedCards, reverseRelatedCards, upsideDown, cardLoyalty, cipt); + card = new CardInfo(cardName, isToken, cardCost, cmc, cardType, cardPT, cardText, colors, relatedCards, + reverseRelatedCards, upsideDown, cardLoyalty, cipt); int tableRow = 1; QString mainCardType = card->getMainCardType(); if ((mainCardType == "Land") || mArtifact) @@ -105,7 +106,7 @@ CardInfo *OracleImporter::addCard(const QString &setName, else if (mainCardType == "Creature") tableRow = 2; card->setTableRow(tableRow); - + cards.insert(cardName, card); } card->setMuId(setName, cardId); @@ -115,10 +116,9 @@ CardInfo *OracleImporter::addCard(const QString &setName, return card; } -void OracleImporter::extractColors(const QStringList & in, QStringList & out) +void OracleImporter::extractColors(const QStringList &in, QStringList &out) { - foreach(QString c, in) - { + foreach (QString c, in) { if (c == "White") out << "W"; else if (c == "Blue") @@ -137,7 +137,7 @@ void OracleImporter::extractColors(const QStringList & in, QStringList & out) int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) { int cards = 0; - + QListIterator it(data.toList()); QVariantMap map; QString cardName; @@ -156,21 +156,19 @@ int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) bool upsideDown = false; QMap splitCards; - while (it.hasNext()) - { + while (it.hasNext()) { map = it.next().toMap(); QString layout = map.value("layout").toString(); - if(layout == "token") + if (layout == "token") continue; - if(layout == "split" || layout == "aftermath") - { + if (layout == "split" || layout == "aftermath") { // Enqueue split card for later handling cardId = map.contains("multiverseid") ? map.value("multiverseid").toInt() : 0; if (cardId) - splitCards.insertMulti(cardId, map); + splitCards.insertMulti(cardId, map); continue; } @@ -179,21 +177,22 @@ int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) cardCost = map.contains("manaCost") ? map.value("manaCost").toString() : QString(""); cmc = map.contains("cmc") ? map.value("cmc").toString() : QString("0"); cardType = map.contains("type") ? map.value("type").toString() : QString(""); - cardPT = map.contains("power") || map.contains("toughness") ? map.value("power").toString() + QString('/') + map.value("toughness").toString() : QString(""); + cardPT = map.contains("power") || map.contains("toughness") + ? map.value("power").toString() + QString('/') + map.value("toughness").toString() + : QString(""); cardText = map.contains("text") ? map.value("text").toString() : QString(""); cardId = map.contains("multiverseid") ? map.value("multiverseid").toInt() : 0; setNumber = map.contains("number") ? map.value("number").toString() : QString(""); rarity = map.contains("rarity") ? map.value("rarity").toString() : QString(""); cardLoyalty = map.contains("loyalty") ? map.value("loyalty").toInt() : 0; relatedCards = QList(); - if(map.contains("names")) - foreach(const QString & name, map.value("names").toStringList()) { - if(name != cardName) + if (map.contains("names")) + foreach (const QString &name, map.value("names").toStringList()) { + if (name != cardName) relatedCards.append(new CardRelation(name, true)); } - if(0 == QString::compare(map.value("layout").toString(), QString("flip"), Qt::CaseInsensitive)) - { + if (0 == QString::compare(map.value("layout").toString(), QString("flip"), Qt::CaseInsensitive)) { QStringList cardNames = map.contains("names") ? map.value("names").toStringList() : QStringList(); upsideDown = (cardNames.indexOf(cardName) > 0); } else { @@ -203,26 +202,26 @@ int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) colors.clear(); extractColors(map.value("colors").toStringList(), colors); - CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, setNumber, cardCost, cmc, cardType, cardPT, cardLoyalty, cardText, colors, relatedCards, reverseRelatedCards, upsideDown, rarity); + CardInfo *card = + addCard(set->getShortName(), cardName, false, cardId, setNumber, cardCost, cmc, cardType, cardPT, + cardLoyalty, cardText, colors, relatedCards, reverseRelatedCards, upsideDown, rarity); if (!set->contains(card)) { card->addToSet(set); cards++; } } - + // split cards handling - get all unique card muids QList muids = splitCards.uniqueKeys(); - foreach(int muid, muids) - { + foreach (int muid, muids) { // get all cards for this specific muid QList maps = splitCards.values(muid); QStringList names; // now, reorder the cards using the ordered list of names QMap orderedMaps; - foreach(QVariantMap map, maps) - { - if(names.isEmpty()) + foreach (QVariantMap map, maps) { + if (names.isEmpty()) names = map.contains("names") ? map.value("names").toStringList() : QStringList(); QString name = map.value("name").toString(); int index = names.indexOf(name); @@ -236,7 +235,7 @@ int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) cardType = ""; cardPT = ""; cardText = ""; - setNumber = ""; + setNumber = ""; rarity = ""; colors.clear(); // this is currently an integer; can't accept 2 values @@ -245,47 +244,39 @@ int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) // loop cards and merge their contents QString prefix = QString(" // "); QString prefix2 = QString("\n\n---\n\n"); - foreach(QVariantMap map, orderedMaps.values()) - { - if(map.contains("name")) - { - if(!cardName.isEmpty()) - cardName += (orderedMaps.count() > 2) ? QString("/") : prefix; + foreach (QVariantMap map, orderedMaps.values()) { + if (map.contains("name")) { + if (!cardName.isEmpty()) + cardName += (orderedMaps.count() > 2) ? QString("/") : prefix; cardName += map.value("name").toString(); } - if(map.contains("manaCost")) - { - if(!cardCost.isEmpty()) + if (map.contains("manaCost")) { + if (!cardCost.isEmpty()) cardCost += prefix; cardCost += map.value("manaCost").toString(); } - if(map.contains("cmc")) - { - if(!cmc.isEmpty()) + if (map.contains("cmc")) { + if (!cmc.isEmpty()) cmc += prefix; cmc += map.value("cmc").toString(); } - if(map.contains("type")) - { - if(!cardType.isEmpty()) + if (map.contains("type")) { + if (!cardType.isEmpty()) cardType += prefix; cardType += map.value("type").toString(); } - if(map.contains("power") || map.contains("toughness")) - { - if(!cardPT.isEmpty()) + if (map.contains("power") || map.contains("toughness")) { + if (!cardPT.isEmpty()) cardPT += prefix; cardPT += map.value("power").toString() + QString('/') + map.value("toughness").toString(); } - if(map.contains("text")) - { - if(!cardText.isEmpty()) + if (map.contains("text")) { + if (!cardText.isEmpty()) cardText += prefix2; cardText += map.value("text").toString(); } - if(map.contains("number")) - { - if(setNumber.isEmpty()) + if (map.contains("number")) { + if (setNumber.isEmpty()) setNumber = map.value("number").toString(); } @@ -293,19 +284,19 @@ int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data) } colors.removeDuplicates(); - //Fortunately, there are no split cards that flip, transform or meld. + // Fortunately, there are no split cards that flip, transform or meld. relatedCards = QList(); reverseRelatedCards = QList(); upsideDown = false; // add the card - CardInfo *card = addCard(set->getShortName(), cardName, false, muid, setNumber, cardCost, cmc, cardType, cardPT, cardLoyalty, cardText, colors, relatedCards, reverseRelatedCards, upsideDown, rarity); + CardInfo *card = addCard(set->getShortName(), cardName, false, muid, setNumber, cardCost, cmc, cardType, cardPT, + cardLoyalty, cardText, colors, relatedCards, reverseRelatedCards, upsideDown, rarity); if (!set->contains(card)) { card->addToSet(set); cards++; } - } return cards; @@ -315,28 +306,28 @@ int OracleImporter::startImport() { clear(); - int setCards = 0, setIndex= 0; + int setCards = 0, setIndex = 0; QListIterator it(allSets); - const SetToDownload * curSet; + const SetToDownload *curSet; // add an empty set for tokens CardSet *tokenSet = new CardSet(TOKENS_SETNAME, tr("Dummy set containing tokens"), "Tokens"); sets.insert(TOKENS_SETNAME, tokenSet); - while (it.hasNext()) - { - curSet = & it.next(); - CardSet *set = new CardSet(curSet->getShortName(), curSet->getLongName(), curSet->getSetType(), curSet->getReleaseDate()); + while (it.hasNext()) { + curSet = &it.next(); + CardSet *set = + new CardSet(curSet->getShortName(), curSet->getLongName(), curSet->getSetType(), curSet->getReleaseDate()); if (!sets.contains(set->getShortName())) sets.insert(set->getShortName(), set); int setCards = importTextSpoiler(set, curSet->getCards()); ++setIndex; - + emit setIndexChanged(setCards, setIndex, curSet->getLongName()); } - + emit setIndexChanged(setCards, setIndex, QString()); // total number of sets diff --git a/oracle/src/oracleimporter.h b/oracle/src/oracleimporter.h index 3a7db78a..4c9e4637 100644 --- a/oracle/src/oracleimporter.h +++ b/oracle/src/oracleimporter.h @@ -6,60 +6,93 @@ #include -class SetToDownload { +class SetToDownload +{ private: QString shortName, longName; QVariant cards; QDate releaseDate; QString setType; + public: - const QString &getShortName() const { return shortName; } - const QString &getLongName() const { return longName; } - const QVariant &getCards() const { return cards; } - const QString &getSetType() const { return setType; } - const QDate &getReleaseDate() const { return releaseDate; } - SetToDownload(const QString &_shortName, const QString &_longName, const QVariant &_cards, const QString &_setType = QString(), const QDate &_releaseDate = QDate()) - : shortName(_shortName), longName(_longName), cards(_cards), releaseDate(_releaseDate), setType(_setType) { } - bool operator<(const SetToDownload &set) const { return longName.compare(set.longName, Qt::CaseInsensitive) < 0; } + const QString &getShortName() const + { + return shortName; + } + const QString &getLongName() const + { + return longName; + } + const QVariant &getCards() const + { + return cards; + } + const QString &getSetType() const + { + return setType; + } + const QDate &getReleaseDate() const + { + return releaseDate; + } + SetToDownload(const QString &_shortName, + const QString &_longName, + const QVariant &_cards, + const QString &_setType = QString(), + const QDate &_releaseDate = QDate()) + : shortName(_shortName), longName(_longName), cards(_cards), releaseDate(_releaseDate), setType(_setType) + { + } + bool operator<(const SetToDownload &set) const + { + return longName.compare(set.longName, Qt::CaseInsensitive) < 0; + } }; -class OracleImporter : public CardDatabase { +class OracleImporter : public CardDatabase +{ Q_OBJECT private: QList allSets; QVariantMap setsMap; QString dataDir; - - CardInfo *addCard( - const QString &setName, - QString cardName, - bool isToken, - int cardId, - QString &setNumber, - QString &cardCost, - QString &cmc, - const QString &cardType, - const QString &cardPT, - int cardLoyalty, - const QString &cardText, - const QStringList & colors, - const QList & relatedCards, - const QList & reverseRelatedCards, - bool upsideDown, - QString &rarity - ); + + CardInfo *addCard(const QString &setName, + QString cardName, + bool isToken, + int cardId, + QString &setNumber, + QString &cardCost, + QString &cmc, + const QString &cardType, + const QString &cardPT, + int cardLoyalty, + const QString &cardText, + const QStringList &colors, + const QList &relatedCards, + const QList &reverseRelatedCards, + bool upsideDown, + QString &rarity); signals: void setIndexChanged(int cardsImported, int setIndex, const QString &setName); void dataReadProgress(int bytesRead, int totalBytes); + public: OracleImporter(const QString &_dataDir, QObject *parent = 0); bool readSetsFromByteArray(const QByteArray &data); int startImport(); int importTextSpoiler(CardSet *set, const QVariant &data); - QList &getSets() { return allSets; } - const QString &getDataDir() const { return dataDir; } + QList &getSets() + { + return allSets; + } + const QString &getDataDir() const + { + return dataDir; + } + protected: - void extractColors(const QStringList & in, QStringList & out); + void extractColors(const QStringList &in, QStringList &out); }; #endif diff --git a/oracle/src/oraclewizard.cpp b/oracle/src/oraclewizard.cpp index f6d66746..33d9b78f 100644 --- a/oracle/src/oraclewizard.cpp +++ b/oracle/src/oraclewizard.cpp @@ -1,14 +1,11 @@ -#include -#include -#include #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -18,11 +15,14 @@ #include #include #include +#include #include +#include +#include -#include "oraclewizard.h" -#include "oracleimporter.h" #include "main.h" +#include "oracleimporter.h" +#include "oraclewizard.h" #include "settingscache.h" #include "version_string.h" @@ -30,10 +30,10 @@ #define ALLSETS_URL_FALLBACK "https://mtgjson.com/json/AllSets.json" #ifdef HAS_ZLIB - #include "zip/unzip.h" - #define ALLSETS_URL "https://mtgjson.com/json/AllSets.json.zip" +#include "zip/unzip.h" +#define ALLSETS_URL "https://mtgjson.com/json/AllSets.json.zip" #else - #define ALLSETS_URL "https://mtgjson.com/json/AllSets.json" +#define ALLSETS_URL "https://mtgjson.com/json/AllSets.json" #endif #define TOKENS_URL "https://raw.githubusercontent.com/Cockatrice/Magic-Token/master/tokens.xml" @@ -41,21 +41,18 @@ OracleWizard::OracleWizard(QWidget *parent) : QWizard(parent) { - settings = new QSettings(settingsCache->getSettingsPath()+"global.ini",QSettings::IniFormat, this); + settings = new QSettings(settingsCache->getSettingsPath() + "global.ini", QSettings::IniFormat, this); connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage())); importer = new OracleImporter(settingsCache->getDataPath(), this); - if (! isSpoilersOnly) - { + if (!isSpoilersOnly) { addPage(new IntroPage); addPage(new LoadSetsPage); addPage(new SaveSetsPage); addPage(new LoadTokensPage); addPage(new SaveTokensPage); - } - else - { + } else { addPage(new LoadSpoilersPage); addPage(new SaveSpoilersPage); } @@ -71,8 +68,7 @@ void OracleWizard::updateLanguage() void OracleWizard::changeEvent(QEvent *event) { - if (event->type() == QEvent::LanguageChange) - { + if (event->type() == QEvent::LanguageChange) { retranslateUi(); } @@ -83,9 +79,8 @@ void OracleWizard::retranslateUi() { setWindowTitle(tr("Oracle Importer")); QWizard::setButtonText(QWizard::FinishButton, tr("Save")); - - for (int i = 0; i < pageIds().count(); i++) - { + + for (int i = 0; i < pageIds().count(); i++) { dynamic_cast(page(i))->retranslateUi(); } } @@ -107,17 +102,15 @@ void OracleWizard::disableButtons() button(QWizard::BackButton)->setDisabled(true); } -bool OracleWizard::saveTokensToFile(const QString & fileName) +bool OracleWizard::saveTokensToFile(const QString &fileName) { QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) - { + if (!file.open(QIODevice::WriteOnly)) { qDebug() << "File open (w) failed for" << fileName; return false; } - if (file.write(tokensData) == -1) - { + if (file.write(tokensData) == -1) { qDebug() << "File write (w) failed for" << fileName; return false; } @@ -137,12 +130,11 @@ IntroPage::IntroPage(QWidget *parent) : OracleWizardPage(parent) QString setLanguage = settingsCache->getLang(); QStringList qmFiles = findQmFiles(); - for (int i = 0; i < qmFiles.size(); i++) - { + 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 == QCoreApplication::translate("i18n", DEFAULT_LANG_NAME))) - { + if ((qmFiles[i] == setLanguage) || + (setLanguage.isEmpty() && langName == QCoreApplication::translate("i18n", DEFAULT_LANG_NAME))) { languageBox->setCurrentIndex(i); } } @@ -168,14 +160,13 @@ QStringList IntroPage::findQmFiles() QString IntroPage::languageName(const QString &qmFile) { - if (qmFile == DEFAULT_LANG_CODE) - { + if (qmFile == DEFAULT_LANG_CODE) { return DEFAULT_LANG_NAME; } QTranslator translator; translator.load(translationPrefix + "_" + qmFile + ".qm", translationPath); - + return translator.translate("i18n", DEFAULT_LANG_NAME); } @@ -257,20 +248,18 @@ void LoadSetsPage::actLoadSetsFile() { QFileDialog dialog(this, tr("Load sets file")); dialog.setFileMode(QFileDialog::ExistingFile); - + #ifdef HAS_ZLIB dialog.setNameFilter(tr("Sets JSON file (*.json *.zip)")); #else dialog.setNameFilter(tr("Sets JSON file (*.json)")); #endif - if (!fileLineEdit->text().isEmpty() && QFile::exists(fileLineEdit->text())) - { + if (!fileLineEdit->text().isEmpty() && QFile::exists(fileLineEdit->text())) { dialog.selectFile(fileLineEdit->text()); } - if (!dialog.exec()) - { + if (!dialog.exec()) { return; } @@ -280,17 +269,14 @@ void LoadSetsPage::actLoadSetsFile() bool LoadSetsPage::validatePage() { // once the import is finished, we call next(); skip validation - if (wizard()->importer->getSets().count() > 0) - { + if (wizard()->importer->getSets().count() > 0) { return true; } // else, try to import sets - if (urlRadioButton->isChecked()) - { + if (urlRadioButton->isChecked()) { QUrl url = QUrl::fromUserInput(urlLineEdit->text()); - if (!url.isValid()) - { + if (!url.isValid()) { QMessageBox::critical(this, tr("Error"), tr("The provided URL is not valid.")); return false; } @@ -307,18 +293,14 @@ bool LoadSetsPage::validatePage() setEnabled(false); downloadSetsFile(url); - } - else if (fileRadioButton->isChecked()) - { + } else if (fileRadioButton->isChecked()) { QFile setsFile(fileLineEdit->text()); - if (!setsFile.exists()) - { + if (!setsFile.exists()) { QMessageBox::critical(this, tr("Error"), tr("Please choose a file.")); return false; } - if (!setsFile.open(QIODevice::ReadOnly)) - { + if (!setsFile.open(QIODevice::ReadOnly)) { QMessageBox::critical(nullptr, tr("Error"), tr("Cannot open file '%1'.").arg(fileLineEdit->text())); return false; } @@ -327,7 +309,6 @@ bool LoadSetsPage::validatePage() setEnabled(false); readSetsFromByteArray(setsFile.readAll()); - } return false; @@ -335,8 +316,7 @@ bool LoadSetsPage::validatePage() void LoadSetsPage::downloadSetsFile(QUrl url) { - if (!nam) - { + if (!nam) { nam = new QNetworkAccessManager(this); } QNetworkReply *reply = nam->get(QNetworkRequest(url)); @@ -347,12 +327,11 @@ void LoadSetsPage::downloadSetsFile(QUrl url) void LoadSetsPage::actDownloadProgressSetsFile(qint64 received, qint64 total) { - if (total > 0) - { + if (total > 0) { progressBar->setMaximum(static_cast(total)); progressBar->setValue(static_cast(received)); } - progressLabel->setText(tr("Downloading (%1MB)").arg((int) received / (1024 * 1024))); + progressLabel->setText(tr("Downloading (%1MB)").arg((int)received / (1024 * 1024))); } void LoadSetsPage::actDownloadFinishedSetsFile() @@ -360,8 +339,7 @@ void LoadSetsPage::actDownloadFinishedSetsFile() // check for a reply auto *reply = dynamic_cast(sender()); QNetworkReply::NetworkError errorCode = reply->error(); - if (errorCode != QNetworkReply::NoError) - { + if (errorCode != QNetworkReply::NoError) { QMessageBox::critical(this, tr("Error"), tr("Network error: %1.").arg(reply->errorString())); wizard()->enableButtons(); @@ -372,8 +350,7 @@ void LoadSetsPage::actDownloadFinishedSetsFile() } int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if (statusCode == 301 || statusCode == 302) - { + if (statusCode == 301 || statusCode == 302) { QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); qDebug() << "following redirect url:" << redirectUrl.toString(); downloadSetsFile(redirectUrl); @@ -385,12 +362,9 @@ void LoadSetsPage::actDownloadFinishedSetsFile() progressBar->hide(); // save allsets.json url, but only if the user customized it and download was successfull - if (urlLineEdit->text() != QString(ALLSETS_URL)) - { + if (urlLineEdit->text() != QString(ALLSETS_URL)) { wizard()->settings->setValue("allsetsurl", urlLineEdit->text()); - } - else - { + } else { wizard()->settings->remove("allsetsurl"); } @@ -409,8 +383,7 @@ void LoadSetsPage::readSetsFromByteArray(QByteArray data) progressBar->show(); // unzip the file if needed - if(data.startsWith(ZIP_SIGNATURE)) - { + if (data.startsWith(ZIP_SIGNATURE)) { #ifdef HAS_ZLIB // zipped file auto *inBuffer = new QBuffer(&data); @@ -420,23 +393,20 @@ void LoadSetsPage::readSetsFromByteArray(QByteArray data) UnZip uz; ec = uz.openArchive(inBuffer); - if (ec != UnZip::Ok) - { + if (ec != UnZip::Ok) { zipDownloadFailed(tr("Failed to open Zip archive: %1.").arg(uz.formatError(ec))); return; } - if (uz.fileList().size() != 1) - { + if (uz.fileList().size() != 1) { zipDownloadFailed(tr("Zip extraction failed: the Zip archive doesn't contain exactly one file.")); - return; + return; } fileName = uz.fileList().at(0); outBuffer->open(QBuffer::ReadWrite); ec = uz.extractFile(fileName, outBuffer); - if (ec != UnZip::Ok) - { + if (ec != UnZip::Ok) { zipDownloadFailed(tr("Zip extraction failed: %1.").arg(uz.formatError(ec))); uz.closeArchive(); return; @@ -454,7 +424,7 @@ void LoadSetsPage::readSetsFromByteArray(QByteArray data) progressBar->hide(); return; #endif - } + } // Start the computation. future = QtConcurrent::run(wizard()->importer, &OracleImporter::readSetsFromByteArray, data); watcher.setFuture(future); @@ -468,10 +438,12 @@ void LoadSetsPage::zipDownloadFailed(const QString &message) progressBar->hide(); QMessageBox::StandardButton reply; - reply = static_cast(QMessageBox::question(this, tr("Error"), message + "
    " + tr("Do you want to try to download a fresh copy of the uncompressed file instead?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)); + reply = static_cast(QMessageBox::question( + this, tr("Error"), + message + "
    " + tr("Do you want to try to download a fresh copy of the uncompressed file instead?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)); - if (reply == QMessageBox::Yes) - { + if (reply == QMessageBox::Yes) { urlRadioButton->setChecked(true); urlLineEdit->setText(ALLSETS_URL_FALLBACK); @@ -486,13 +458,11 @@ void LoadSetsPage::importFinished() progressLabel->hide(); progressBar->hide(); - if (watcher.future().result()) - { + if (watcher.future().result()) { wizard()->next(); - } - else - { - QMessageBox::critical(this, tr("Error"), tr("The file was retrieved successfully, but it does not contain any sets data.")); + } else { + QMessageBox::critical(this, tr("Error"), + tr("The file was retrieved successfully, but it does not contain any sets data.")); } } @@ -520,10 +490,10 @@ void SaveSetsPage::initializePage() { messageLog->clear(); - connect(wizard()->importer, SIGNAL(setIndexChanged(int, int, const QString &)), this, SLOT(updateTotalProgress(int, int, const QString &))); + connect(wizard()->importer, SIGNAL(setIndexChanged(int, int, const QString &)), this, + SLOT(updateTotalProgress(int, int, const QString &))); - if (!wizard()->importer->startImport()) - { + if (!wizard()->importer->startImport()) { QMessageBox::critical(this, tr("Error"), tr("No set has been imported.")); } } @@ -539,13 +509,11 @@ void SaveSetsPage::retranslateUi() void SaveSetsPage::updateTotalProgress(int cardsImported, int /* setIndex */, const QString &setName) { - if (setName.isEmpty()) - { - messageLog->append("" + tr("Import finished: %1 cards.").arg(wizard()->importer->getCardList().size()) + ""); - } - else - { - messageLog->append(tr("%1: %2 cards imported").arg(setName).arg(cardsImported)); + if (setName.isEmpty()) { + messageLog->append("" + tr("Import finished: %1 cards.").arg(wizard()->importer->getCardList().size()) + + ""); + } else { + messageLog->append(tr("%1: %2 cards imported").arg(setName).arg(cardsImported)); } messageLog->verticalScrollBar()->setValue(messageLog->verticalScrollBar()->maximum()); @@ -558,42 +526,32 @@ bool SaveSetsPage::validatePage() QString windowName = tr("Save card database"); QString fileType = tr("XML; card database (*.xml)"); - do - { + do { QString fileName; - if (defaultPathCheckBox->isChecked()) - { + if (defaultPathCheckBox->isChecked()) { fileName = defaultPath; - } - else - { + } else { fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType); } - if (fileName.isEmpty()) - { + if (fileName.isEmpty()) { return false; } QFileInfo fi(fileName); QDir fileDir(fi.path()); - if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) - { + if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { return false; } - if (wizard()->importer->saveToFile(fileName)) - { + if (wizard()->importer->saveToFile(fileName)) { ok = true; - QMessageBox::information(this, - tr("Success"), - tr("The card database has been saved successfully to\n%1").arg(fileName)); - } - else - { - QMessageBox::critical(this, tr("Error"), tr("The file could not be saved to %1").arg(fileName));; - if (defaultPathCheckBox->isChecked()) - { + QMessageBox::information(this, tr("Success"), + tr("The card database has been saved successfully to\n%1").arg(fileName)); + } else { + QMessageBox::critical(this, tr("Error"), tr("The file could not be saved to %1").arg(fileName)); + ; + if (defaultPathCheckBox->isChecked()) { defaultPathCheckBox->setChecked(false); } } @@ -636,13 +594,12 @@ void LoadSpoilersPage::initializePage() void LoadSpoilersPage::actDownloadProgressSpoilersFile(qint64 received, qint64 total) { - if (total > 0) - { + if (total > 0) { progressBar->setMaximum(static_cast(total)); progressBar->setValue(static_cast(received)); } - progressLabel->setText(tr("Downloading (%1MB)").arg((int) received / (1024 * 1024))); + progressLabel->setText(tr("Downloading (%1MB)").arg((int)received / (1024 * 1024))); } void LoadSpoilersPage::actDownloadFinishedSpoilersFile() @@ -651,8 +608,7 @@ void LoadSpoilersPage::actDownloadFinishedSpoilersFile() auto *reply = dynamic_cast(sender()); QNetworkReply::NetworkError errorCode = reply->error(); - if (errorCode != QNetworkReply::NoError) - { + if (errorCode != QNetworkReply::NoError) { QMessageBox::critical(this, tr("Error"), tr("Network error: %1.").arg(reply->errorString())); wizard()->enableButtons(); @@ -663,8 +619,7 @@ void LoadSpoilersPage::actDownloadFinishedSpoilersFile() } int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if (statusCode == 301 || statusCode == 302) - { + if (statusCode == 301 || statusCode == 302) { QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); qDebug() << "following redirect url:" << redirectUrl.toString(); downloadSpoilersFile(redirectUrl); @@ -676,12 +631,9 @@ void LoadSpoilersPage::actDownloadFinishedSpoilersFile() progressBar->hide(); // save spoiler.xml url, but only if the user customized it and download was successful - if (urlLineEdit->text() != QString(SPOILERS_URL)) - { + if (urlLineEdit->text() != QString(SPOILERS_URL)) { wizard()->settings->setValue("spoilersurl", urlLineEdit->text()); - } - else - { + } else { wizard()->settings->remove("spoilersurl"); } @@ -698,27 +650,25 @@ void LoadSpoilersPage::actDownloadFinishedSpoilersFile() void LoadSpoilersPage::downloadSpoilersFile(QUrl url) { - if (!nam) - { + if (!nam) { nam = new QNetworkAccessManager(this); } QNetworkReply *reply = nam->get(QNetworkRequest(url)); connect(reply, SIGNAL(finished()), this, SLOT(actDownloadFinishedSpoilersFile())); - connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(actDownloadProgressSpoilersFile(qint64, qint64))); + connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, + SLOT(actDownloadProgressSpoilersFile(qint64, qint64))); } bool LoadSpoilersPage::validatePage() { // once the import is finished, we call next(); skip validation - if (wizard()->hasTokensData()) - { + if (wizard()->hasTokensData()) { return true; } QUrl url = QUrl::fromUserInput(urlLineEdit->text()); - if (!url.isValid()) - { + if (!url.isValid()) { QMessageBox::critical(this, tr("Error"), tr("The provided URL is not valid.")); return false; } @@ -793,14 +743,12 @@ void LoadTokensPage::actRestoreDefaultUrl() bool LoadTokensPage::validatePage() { // once the import is finished, we call next(); skip validation - if (wizard()->hasTokensData()) - { + if (wizard()->hasTokensData()) { return true; } QUrl url = QUrl::fromUserInput(urlLineEdit->text()); - if (!url.isValid()) - { + if (!url.isValid()) { QMessageBox::critical(this, tr("Error"), tr("The provided URL is not valid.")); return false; } @@ -822,8 +770,7 @@ bool LoadTokensPage::validatePage() void LoadTokensPage::downloadTokensFile(QUrl url) { - if (!nam) - { + if (!nam) { nam = new QNetworkAccessManager(this); } QNetworkReply *reply = nam->get(QNetworkRequest(url)); @@ -834,12 +781,11 @@ void LoadTokensPage::downloadTokensFile(QUrl url) void LoadTokensPage::actDownloadProgressTokensFile(qint64 received, qint64 total) { - if (total > 0) - { + if (total > 0) { progressBar->setMaximum(static_cast(total)); progressBar->setValue(static_cast(received)); } - progressLabel->setText(tr("Downloading (%1MB)").arg((int) received / (1024 * 1024))); + progressLabel->setText(tr("Downloading (%1MB)").arg((int)received / (1024 * 1024))); } void LoadTokensPage::actDownloadFinishedTokensFile() @@ -847,8 +793,7 @@ void LoadTokensPage::actDownloadFinishedTokensFile() // check for a reply auto *reply = dynamic_cast(sender()); QNetworkReply::NetworkError errorCode = reply->error(); - if (errorCode != QNetworkReply::NoError) - { + if (errorCode != QNetworkReply::NoError) { QMessageBox::critical(this, tr("Error"), tr("Network error: %1.").arg(reply->errorString())); wizard()->enableButtons(); @@ -859,8 +804,7 @@ void LoadTokensPage::actDownloadFinishedTokensFile() } int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if (statusCode == 301 || statusCode == 302) - { + if (statusCode == 301 || statusCode == 302) { QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); qDebug() << "following redirect url:" << redirectUrl.toString(); downloadTokensFile(redirectUrl); @@ -872,12 +816,9 @@ void LoadTokensPage::actDownloadFinishedTokensFile() progressBar->hide(); // save tokens.xml url, but only if the user customized it and download was successfull - if (urlLineEdit->text() != QString(TOKENS_URL)) - { + if (urlLineEdit->text() != QString(TOKENS_URL)) { wizard()->settings->setValue("tokensurl", urlLineEdit->text()); - } - else - { + } else { wizard()->settings->remove("tokensurl"); } @@ -901,14 +842,13 @@ SaveSpoilersPage::SaveSpoilersPage(QWidget *parent) : OracleWizardPage(parent) layout->addWidget(defaultPathCheckBox, 0, 0); setLayout(layout); - } void SaveSpoilersPage::retranslateUi() { setTitle(tr("Spoilers imported")); setSubTitle(tr("The spoilers file has been imported. " - "Press \"Save\" to save the imported spoilers to the Cockatrice card database.")); + "Press \"Save\" to save the imported spoilers to the Cockatrice card database.")); defaultPathCheckBox->setText(tr("Save to the default path (recommended)")); } @@ -920,39 +860,30 @@ bool SaveSpoilersPage::validatePage() QString windowName = tr("Save spoiler database"); QString fileType = tr("XML; card database (*.xml)"); - do - { + do { QString fileName; - if (defaultPathCheckBox->isChecked()) - { + if (defaultPathCheckBox->isChecked()) { fileName = defaultPath; - } - else - { + } else { fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType); } - if (fileName.isEmpty()) - { + if (fileName.isEmpty()) { return false; } QFileInfo fi(fileName); QDir fileDir(fi.path()); - if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) - { + if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { return false; } - if (wizard()->saveTokensToFile(fileName)) - { + if (wizard()->saveTokensToFile(fileName)) { ok = true; - } - else - { - QMessageBox::critical(this, tr("Error"), tr("The file could not be saved to %1").arg(fileName));; - if (defaultPathCheckBox->isChecked()) - { + } else { + QMessageBox::critical(this, tr("Error"), tr("The file could not be saved to %1").arg(fileName)); + ; + if (defaultPathCheckBox->isChecked()) { defaultPathCheckBox->setChecked(false); } } @@ -988,43 +919,32 @@ bool SaveTokensPage::validatePage() QString windowName = tr("Save token database"); QString fileType = tr("XML; token database (*.xml)"); - do - { + do { QString fileName; - if (defaultPathCheckBox->isChecked()) - { + if (defaultPathCheckBox->isChecked()) { fileName = defaultPath; - } - else - { + } else { fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType); } - if (fileName.isEmpty()) - { + if (fileName.isEmpty()) { return false; } - QFileInfo fi(fileName); QDir fileDir(fi.path()); - if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) - { + if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { return false; } - if (wizard()->saveTokensToFile(fileName)) - { + if (wizard()->saveTokensToFile(fileName)) { ok = true; - QMessageBox::information(this, - tr("Success"), - tr("The token database has been saved successfully to\n%1").arg(fileName)); - } - else - { - QMessageBox::critical(this, tr("Error"), tr("The file could not be saved to %1").arg(fileName));; - if (defaultPathCheckBox->isChecked()) - { + QMessageBox::information(this, tr("Success"), + tr("The token database has been saved successfully to\n%1").arg(fileName)); + } else { + QMessageBox::critical(this, tr("Error"), tr("The file could not be saved to %1").arg(fileName)); + ; + if (defaultPathCheckBox->isChecked()) { defaultPathCheckBox->setChecked(false); } } diff --git a/oracle/src/oraclewizard.h b/oracle/src/oraclewizard.h index d7e812f6..f3275998 100644 --- a/oracle/src/oraclewizard.h +++ b/oracle/src/oraclewizard.h @@ -1,9 +1,9 @@ #ifndef ORACLEWIZARD_H #define ORACLEWIZARD_H -#include -#include #include +#include +#include #include class QCheckBox; @@ -22,194 +22,203 @@ class QSettings; class OracleWizard : public QWizard { Q_OBJECT - public: - explicit OracleWizard(QWidget *parent = nullptr); - void accept() override; - void enableButtons(); - void disableButtons(); - void retranslateUi(); - void setTokensData(QByteArray _tokensData) { tokensData = std::move(_tokensData); } - bool hasTokensData() { return !tokensData.isEmpty(); } - bool saveTokensToFile(const QString & fileName); +public: + explicit OracleWizard(QWidget *parent = nullptr); + void accept() override; + void enableButtons(); + void disableButtons(); + void retranslateUi(); + void setTokensData(QByteArray _tokensData) + { + tokensData = std::move(_tokensData); + } + bool hasTokensData() + { + return !tokensData.isEmpty(); + } + bool saveTokensToFile(const QString &fileName); - public: - OracleImporter *importer; - QSettings *settings; +public: + OracleImporter *importer; + QSettings *settings; - private slots: - void updateLanguage(); +private slots: + void updateLanguage(); - private: - QByteArray tokensData; +private: + QByteArray tokensData; - protected: - void changeEvent(QEvent *event) override; +protected: + void changeEvent(QEvent *event) override; }; class OracleWizardPage : public QWizardPage { Q_OBJECT - public: - explicit OracleWizardPage(QWidget *parent = nullptr): QWizardPage(parent) {}; - virtual void retranslateUi() = 0; +public: + explicit OracleWizardPage(QWidget *parent = nullptr) : QWizardPage(parent){}; + virtual void retranslateUi() = 0; - protected: - inline OracleWizard *wizard() { return (OracleWizard*) QWizardPage::wizard(); }; +protected: + inline OracleWizard *wizard() + { + return (OracleWizard *)QWizardPage::wizard(); + }; }; class IntroPage : public OracleWizardPage { Q_OBJECT - public: - explicit IntroPage(QWidget *parent = nullptr); - void retranslateUi() override; +public: + explicit IntroPage(QWidget *parent = nullptr); + void retranslateUi() override; - private: - QStringList findQmFiles(); - QString languageName(const QString &qmFile); +private: + QStringList findQmFiles(); + QString languageName(const QString &qmFile); - private: - QLabel *label, *languageLabel, *versionLabel; - QComboBox *languageBox; +private: + QLabel *label, *languageLabel, *versionLabel; + QComboBox *languageBox; - private slots: - void languageBoxChanged(int index); +private slots: + void languageBoxChanged(int index); }; class LoadSetsPage : public OracleWizardPage { - Q_OBJECT - public: - explicit LoadSetsPage(QWidget *parent = nullptr); - void retranslateUi() override; + Q_OBJECT +public: + explicit LoadSetsPage(QWidget *parent = nullptr); + void retranslateUi() override; - protected: - void initializePage() override; - bool validatePage() override; - void readSetsFromByteArray(QByteArray data); - void downloadSetsFile(QUrl url); +protected: + void initializePage() override; + bool validatePage() override; + void readSetsFromByteArray(QByteArray data); + void downloadSetsFile(QUrl url); - private: - QRadioButton *urlRadioButton; - QRadioButton *fileRadioButton; - QLineEdit *urlLineEdit; - QLineEdit *fileLineEdit; - QPushButton *urlButton; - QPushButton *fileButton; - QLabel *progressLabel; - QProgressBar *progressBar; +private: + QRadioButton *urlRadioButton; + QRadioButton *fileRadioButton; + QLineEdit *urlLineEdit; + QLineEdit *fileLineEdit; + QPushButton *urlButton; + QPushButton *fileButton; + QLabel *progressLabel; + QProgressBar *progressBar; - QNetworkAccessManager *nam; - QFutureWatcher watcher; - QFuture future; + QNetworkAccessManager *nam; + QFutureWatcher watcher; + QFuture future; - private slots: - void actLoadSetsFile(); - void actRestoreDefaultUrl(); - void actDownloadProgressSetsFile(qint64 received, qint64 total); - void actDownloadFinishedSetsFile(); - void importFinished(); - void zipDownloadFailed(const QString &message); +private slots: + void actLoadSetsFile(); + void actRestoreDefaultUrl(); + void actDownloadProgressSetsFile(qint64 received, qint64 total); + void actDownloadFinishedSetsFile(); + void importFinished(); + void zipDownloadFailed(const QString &message); }; class SaveSetsPage : public OracleWizardPage { Q_OBJECT - public: - explicit SaveSetsPage(QWidget *parent = nullptr); - void retranslateUi() override; +public: + explicit SaveSetsPage(QWidget *parent = nullptr); + void retranslateUi() override; - private: - QTextEdit *messageLog; - QCheckBox *defaultPathCheckBox; +private: + QTextEdit *messageLog; + QCheckBox *defaultPathCheckBox; - protected: - void initializePage() override; - void cleanupPage() override; - bool validatePage() override; +protected: + void initializePage() override; + void cleanupPage() override; + bool validatePage() override; - private slots: - void updateTotalProgress(int cardsImported, int setIndex, const QString &setName); +private slots: + void updateTotalProgress(int cardsImported, int setIndex, const QString &setName); }; class LoadSpoilersPage : public OracleWizardPage { Q_OBJECT - public: - explicit LoadSpoilersPage(QWidget *parent = nullptr); - void retranslateUi() override; +public: + explicit LoadSpoilersPage(QWidget *parent = nullptr); + void retranslateUi() override; - private: - QLabel *urlLabel; - QLineEdit *urlLineEdit; - QPushButton *urlButton; - QLabel *progressLabel; - QProgressBar *progressBar; - QNetworkAccessManager *nam; +private: + QLabel *urlLabel; + QLineEdit *urlLineEdit; + QPushButton *urlButton; + QLabel *progressLabel; + QProgressBar *progressBar; + QNetworkAccessManager *nam; - private slots: - void actRestoreDefaultUrl(); - void actDownloadProgressSpoilersFile(qint64 received, qint64 total); - void actDownloadFinishedSpoilersFile(); +private slots: + void actRestoreDefaultUrl(); + void actDownloadProgressSpoilersFile(qint64 received, qint64 total); + void actDownloadFinishedSpoilersFile(); - protected: - void initializePage() override; - bool validatePage() override; - void downloadSpoilersFile(QUrl url); +protected: + void initializePage() override; + bool validatePage() override; + void downloadSpoilersFile(QUrl url); }; class SaveSpoilersPage : public OracleWizardPage { Q_OBJECT - public: - explicit SaveSpoilersPage(QWidget *parent = nullptr); - void retranslateUi() override; +public: + explicit SaveSpoilersPage(QWidget *parent = nullptr); + void retranslateUi() override; - private: - QCheckBox *defaultPathCheckBox; +private: + QCheckBox *defaultPathCheckBox; - protected: - bool validatePage() override; +protected: + bool validatePage() override; }; class LoadTokensPage : public OracleWizardPage { Q_OBJECT - public: - explicit LoadTokensPage(QWidget *parent = nullptr); - void retranslateUi() override; +public: + explicit LoadTokensPage(QWidget *parent = nullptr); + void retranslateUi() override; - protected: - void initializePage() override; - bool validatePage() override; - void downloadTokensFile(QUrl url); +protected: + void initializePage() override; + bool validatePage() override; + void downloadTokensFile(QUrl url); - private: - QLabel *urlLabel; - QLineEdit *urlLineEdit; - QPushButton *urlButton; - QLabel *progressLabel; - QProgressBar *progressBar; - QNetworkAccessManager *nam; +private: + QLabel *urlLabel; + QLineEdit *urlLineEdit; + QPushButton *urlButton; + QLabel *progressLabel; + QProgressBar *progressBar; + QNetworkAccessManager *nam; - private slots: - void actRestoreDefaultUrl(); - void actDownloadProgressTokensFile(qint64 received, qint64 total); - void actDownloadFinishedTokensFile(); +private slots: + void actRestoreDefaultUrl(); + void actDownloadProgressTokensFile(qint64 received, qint64 total); + void actDownloadFinishedTokensFile(); }; class SaveTokensPage : public OracleWizardPage { Q_OBJECT - public: - explicit SaveTokensPage(QWidget *parent = nullptr); - void retranslateUi() override; +public: + explicit SaveTokensPage(QWidget *parent = nullptr); + void retranslateUi() override; - private: - QCheckBox *defaultPathCheckBox; +private: + QCheckBox *defaultPathCheckBox; - protected: - bool validatePage() override; +protected: + bool validatePage() override; }; #endif \ No newline at end of file diff --git a/servatrice/src/isl_interface.cpp b/servatrice/src/isl_interface.cpp index 3d75a7e9..d2ce7f05 100644 --- a/servatrice/src/isl_interface.cpp +++ b/servatrice/src/isl_interface.cpp @@ -1,415 +1,447 @@ #include "isl_interface.h" -#include -#include "server_logger.h" #include "main.h" +#include "server_logger.h" #include "server_protocolhandler.h" #include "server_room.h" +#include #include "get_pb_extension.h" -#include "pb/isl_message.pb.h" #include "pb/event_game_joined.pb.h" -#include "pb/event_server_complete_list.pb.h" -#include "pb/event_user_message.pb.h" -#include "pb/event_user_joined.pb.h" -#include "pb/event_user_left.pb.h" #include "pb/event_join_room.pb.h" #include "pb/event_leave_room.pb.h" -#include "pb/event_room_say.pb.h" #include "pb/event_list_games.pb.h" +#include "pb/event_room_say.pb.h" +#include "pb/event_server_complete_list.pb.h" +#include "pb/event_user_joined.pb.h" +#include "pb/event_user_left.pb.h" +#include "pb/event_user_message.pb.h" +#include "pb/isl_message.pb.h" #include void IslInterface::sharedCtor(const QSslCertificate &cert, const QSslKey &privateKey) { - socket = new QSslSocket(this); - socket->setLocalCertificate(cert); - socket->setPrivateKey(privateKey); - - connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()), Qt::QueuedConnection); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); - connect(this, SIGNAL(outputBufferChanged()), this, SLOT(flushOutputBuffer()), Qt::QueuedConnection); + socket = new QSslSocket(this); + socket->setLocalCertificate(cert); + socket->setPrivateKey(privateKey); + + connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()), Qt::QueuedConnection); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, + SLOT(catchSocketError(QAbstractSocket::SocketError))); + connect(this, SIGNAL(outputBufferChanged()), this, SLOT(flushOutputBuffer()), Qt::QueuedConnection); } -IslInterface::IslInterface(int _socketDescriptor, const QSslCertificate &cert, const QSslKey &privateKey, Servatrice *_server) - : QObject(), socketDescriptor(_socketDescriptor), server(_server), messageInProgress(false) +IslInterface::IslInterface(int _socketDescriptor, + const QSslCertificate &cert, + const QSslKey &privateKey, + Servatrice *_server) + : QObject(), socketDescriptor(_socketDescriptor), server(_server), messageInProgress(false) { - sharedCtor(cert, privateKey); + sharedCtor(cert, privateKey); } -IslInterface::IslInterface(int _serverId, const QString &_peerHostName, const QString &_peerAddress, int _peerPort, const QSslCertificate &_peerCert, const QSslCertificate &cert, const QSslKey &privateKey, Servatrice *_server) - : QObject(), serverId(_serverId), peerHostName(_peerHostName), peerAddress(_peerAddress), peerPort(_peerPort), peerCert(_peerCert), server(_server), messageInProgress(false) +IslInterface::IslInterface(int _serverId, + const QString &_peerHostName, + const QString &_peerAddress, + int _peerPort, + const QSslCertificate &_peerCert, + const QSslCertificate &cert, + const QSslKey &privateKey, + Servatrice *_server) + : QObject(), serverId(_serverId), peerHostName(_peerHostName), peerAddress(_peerAddress), peerPort(_peerPort), + peerCert(_peerCert), server(_server), messageInProgress(false) { - sharedCtor(cert, privateKey); + sharedCtor(cert, privateKey); } IslInterface::~IslInterface() { - logger->logMessage("[ISL] session ended", this); - - flushOutputBuffer(); - - // As these signals are connected with Qt::QueuedConnection implicitly, - // we don't need to worry about them modifying the lists while we're iterating. - - server->roomsLock.lockForRead(); - QMapIterator roomIterator(server->getRooms()); - while (roomIterator.hasNext()) { - Server_Room *room = roomIterator.next().value(); - room->usersLock.lockForRead(); - QMapIterator roomUsers(room->getExternalUsers()); - while (roomUsers.hasNext()) { - roomUsers.next(); - if (roomUsers.value().getUserInfo()->server_id() == serverId) - emit externalRoomUserLeft(room->getId(), roomUsers.key()); - } - room->usersLock.unlock(); - } - server->roomsLock.unlock(); - - server->clientsLock.lockForRead(); - QMapIterator extUsers(server->getExternalUsers()); - while (extUsers.hasNext()) { - extUsers.next(); - if (extUsers.value()->getUserInfo()->server_id() == serverId) - emit externalUserLeft(extUsers.key()); - } - server->clientsLock.unlock(); + logger->logMessage("[ISL] session ended", this); + + flushOutputBuffer(); + + // As these signals are connected with Qt::QueuedConnection implicitly, + // we don't need to worry about them modifying the lists while we're iterating. + + server->roomsLock.lockForRead(); + QMapIterator roomIterator(server->getRooms()); + while (roomIterator.hasNext()) { + Server_Room *room = roomIterator.next().value(); + room->usersLock.lockForRead(); + QMapIterator roomUsers(room->getExternalUsers()); + while (roomUsers.hasNext()) { + roomUsers.next(); + if (roomUsers.value().getUserInfo()->server_id() == serverId) + emit externalRoomUserLeft(room->getId(), roomUsers.key()); + } + room->usersLock.unlock(); + } + server->roomsLock.unlock(); + + server->clientsLock.lockForRead(); + QMapIterator extUsers(server->getExternalUsers()); + while (extUsers.hasNext()) { + extUsers.next(); + if (extUsers.value()->getUserInfo()->server_id() == serverId) + emit externalUserLeft(extUsers.key()); + } + server->clientsLock.unlock(); } void IslInterface::initServer() { - socket->setSocketDescriptor(socketDescriptor); - - logger->logMessage(QString("[ISL] incoming connection: %1").arg(socket->peerAddress().toString())); - - QList serverList = server->getServerList(); - int listIndex = -1; - for (int i = 0; i < serverList.size(); ++i) - if (serverList[i].address == socket->peerAddress()) { - listIndex = i; - break; - } - if (listIndex == -1) { - logger->logMessage(QString("[ISL] address %1 unknown, terminating connection").arg(socket->peerAddress().toString())); - deleteLater(); - return; - } - - socket->startServerEncryption(); - if (!socket->waitForEncrypted(5000)) { - QList sslErrors(socket->sslErrors()); - if (sslErrors.isEmpty()) - qDebug() << "[ISL] SSL handshake timeout, terminating connection"; - else - qDebug() << "[ISL] SSL errors:" << sslErrors; - deleteLater(); - return; - } - - if (serverList[listIndex].cert == socket->peerCertificate()) - logger->logMessage(QString("[ISL] Peer authenticated as " + serverList[listIndex].hostname)); - else { - logger->logMessage(QString("[ISL] Authentication failed, terminating connection")); - deleteLater(); - return; - } - serverId = serverList[listIndex].id; - - Event_ServerCompleteList event; - event.set_server_id(server->getServerID()); - - server->clientsLock.lockForRead(); - QMapIterator userIterator(server->getUsers()); - while (userIterator.hasNext()) - event.add_user_list()->CopyFrom(userIterator.next().value()->copyUserInfo(true, true)); - server->clientsLock.unlock(); - - server->roomsLock.lockForRead(); - QMapIterator roomIterator(server->getRooms()); - while (roomIterator.hasNext()) { - Server_Room *room = roomIterator.next().value(); - room->usersLock.lockForRead(); - room->gamesLock.lockForRead(); - room->getInfo(*event.add_room_list(), true, true, false); - } - - IslMessage message; - message.set_message_type(IslMessage::SESSION_EVENT); - SessionEvent *sessionEvent = message.mutable_session_event(); - sessionEvent->GetReflection()->MutableMessage(sessionEvent, event.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(event); - - server->islLock.lockForWrite(); - if (server->islConnectionExists(serverId)) { - qDebug() << "[ISL] Duplicate connection to #" << serverId << "terminating connection"; - deleteLater(); - } else { - transmitMessage(message); - server->addIslInterface(serverId, this); - } - server->islLock.unlock(); - - roomIterator.toFront(); - while (roomIterator.hasNext()) { - roomIterator.next(); - roomIterator.value()->gamesLock.unlock(); - roomIterator.value()->usersLock.unlock(); - } - server->roomsLock.unlock(); + socket->setSocketDescriptor(socketDescriptor); + + logger->logMessage(QString("[ISL] incoming connection: %1").arg(socket->peerAddress().toString())); + + QList serverList = server->getServerList(); + int listIndex = -1; + for (int i = 0; i < serverList.size(); ++i) + if (serverList[i].address == socket->peerAddress()) { + listIndex = i; + break; + } + if (listIndex == -1) { + logger->logMessage( + QString("[ISL] address %1 unknown, terminating connection").arg(socket->peerAddress().toString())); + deleteLater(); + return; + } + + socket->startServerEncryption(); + if (!socket->waitForEncrypted(5000)) { + QList sslErrors(socket->sslErrors()); + if (sslErrors.isEmpty()) + qDebug() << "[ISL] SSL handshake timeout, terminating connection"; + else + qDebug() << "[ISL] SSL errors:" << sslErrors; + deleteLater(); + return; + } + + if (serverList[listIndex].cert == socket->peerCertificate()) + logger->logMessage(QString("[ISL] Peer authenticated as " + serverList[listIndex].hostname)); + else { + logger->logMessage(QString("[ISL] Authentication failed, terminating connection")); + deleteLater(); + return; + } + serverId = serverList[listIndex].id; + + Event_ServerCompleteList event; + event.set_server_id(server->getServerID()); + + server->clientsLock.lockForRead(); + QMapIterator userIterator(server->getUsers()); + while (userIterator.hasNext()) + event.add_user_list()->CopyFrom(userIterator.next().value()->copyUserInfo(true, true)); + server->clientsLock.unlock(); + + server->roomsLock.lockForRead(); + QMapIterator roomIterator(server->getRooms()); + while (roomIterator.hasNext()) { + Server_Room *room = roomIterator.next().value(); + room->usersLock.lockForRead(); + room->gamesLock.lockForRead(); + room->getInfo(*event.add_room_list(), true, true, false); + } + + IslMessage message; + message.set_message_type(IslMessage::SESSION_EVENT); + SessionEvent *sessionEvent = message.mutable_session_event(); + sessionEvent->GetReflection() + ->MutableMessage(sessionEvent, event.GetDescriptor()->FindExtensionByName("ext")) + ->CopyFrom(event); + + server->islLock.lockForWrite(); + if (server->islConnectionExists(serverId)) { + qDebug() << "[ISL] Duplicate connection to #" << serverId << "terminating connection"; + deleteLater(); + } else { + transmitMessage(message); + server->addIslInterface(serverId, this); + } + server->islLock.unlock(); + + roomIterator.toFront(); + while (roomIterator.hasNext()) { + roomIterator.next(); + roomIterator.value()->gamesLock.unlock(); + roomIterator.value()->usersLock.unlock(); + } + server->roomsLock.unlock(); } void IslInterface::initClient() { - QList expectedErrors; - expectedErrors.append(QSslError(QSslError::SelfSignedCertificate, peerCert)); - socket->ignoreSslErrors(expectedErrors); - - qDebug() << "[ISL] Connecting to #" << serverId << ":" << peerAddress << ":" << peerPort; + QList expectedErrors; + expectedErrors.append(QSslError(QSslError::SelfSignedCertificate, peerCert)); + socket->ignoreSslErrors(expectedErrors); - socket->connectToHostEncrypted(peerAddress, peerPort, peerHostName); - if (!socket->waitForConnected(5000)) { - qDebug() << "[ISL] Socket error:" << socket->errorString(); - deleteLater(); - return; - } - if (!socket->waitForEncrypted(5000)) { - QList sslErrors(socket->sslErrors()); - if (sslErrors.isEmpty()) - qDebug() << "[ISL] SSL handshake timeout, terminating connection"; - else - qDebug() << "[ISL] SSL errors:" << sslErrors; - deleteLater(); - return; - } - - server->islLock.lockForWrite(); - if (server->islConnectionExists(serverId)) { - qDebug() << "[ISL] Duplicate connection to #" << serverId << "terminating connection"; - deleteLater(); - return; - } - - server->addIslInterface(serverId, this); - server->islLock.unlock(); + qDebug() << "[ISL] Connecting to #" << serverId << ":" << peerAddress << ":" << peerPort; + + socket->connectToHostEncrypted(peerAddress, peerPort, peerHostName); + if (!socket->waitForConnected(5000)) { + qDebug() << "[ISL] Socket error:" << socket->errorString(); + deleteLater(); + return; + } + if (!socket->waitForEncrypted(5000)) { + QList sslErrors(socket->sslErrors()); + if (sslErrors.isEmpty()) + qDebug() << "[ISL] SSL handshake timeout, terminating connection"; + else + qDebug() << "[ISL] SSL errors:" << sslErrors; + deleteLater(); + return; + } + + server->islLock.lockForWrite(); + if (server->islConnectionExists(serverId)) { + qDebug() << "[ISL] Duplicate connection to #" << serverId << "terminating connection"; + deleteLater(); + return; + } + + server->addIslInterface(serverId, this); + server->islLock.unlock(); } void IslInterface::flushOutputBuffer() { - QMutexLocker locker(&outputBufferMutex); - if (outputBuffer.isEmpty()) - return; - server->incTxBytes(outputBuffer.size()); - socket->write(outputBuffer); - socket->flush(); - outputBuffer.clear(); + QMutexLocker locker(&outputBufferMutex); + if (outputBuffer.isEmpty()) + return; + server->incTxBytes(outputBuffer.size()); + socket->write(outputBuffer); + socket->flush(); + outputBuffer.clear(); } void IslInterface::readClient() { - QByteArray data = socket->readAll(); - server->incRxBytes(data.size()); - inputBuffer.append(data); - - do { - if (!messageInProgress) { - if (inputBuffer.size() >= 4) { - messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24) - + (((quint32) (unsigned char) inputBuffer[1]) << 16) - + (((quint32) (unsigned char) inputBuffer[2]) << 8) - + ((quint32) (unsigned char) inputBuffer[3]); - inputBuffer.remove(0, 4); - messageInProgress = true; - } else - return; - } - if (inputBuffer.size() < messageLength) - return; - - IslMessage newMessage; - newMessage.ParseFromArray(inputBuffer.data(), messageLength); - inputBuffer.remove(0, messageLength); - messageInProgress = false; - - processMessage(newMessage); - } while (!inputBuffer.isEmpty()); + QByteArray data = socket->readAll(); + server->incRxBytes(data.size()); + inputBuffer.append(data); + + do { + if (!messageInProgress) { + if (inputBuffer.size() >= 4) { + messageLength = (((quint32)(unsigned char)inputBuffer[0]) << 24) + + (((quint32)(unsigned char)inputBuffer[1]) << 16) + + (((quint32)(unsigned char)inputBuffer[2]) << 8) + + ((quint32)(unsigned char)inputBuffer[3]); + inputBuffer.remove(0, 4); + messageInProgress = true; + } else + return; + } + if (inputBuffer.size() < messageLength) + return; + + IslMessage newMessage; + newMessage.ParseFromArray(inputBuffer.data(), messageLength); + inputBuffer.remove(0, messageLength); + messageInProgress = false; + + processMessage(newMessage); + } while (!inputBuffer.isEmpty()); } void IslInterface::catchSocketError(QAbstractSocket::SocketError socketError) { - qDebug() << "[ISL] Socket error:" << socketError; - - server->islLock.lockForWrite(); - server->removeIslInterface(serverId); - server->islLock.unlock(); - - deleteLater(); + qDebug() << "[ISL] Socket error:" << socketError; + + server->islLock.lockForWrite(); + server->removeIslInterface(serverId); + server->islLock.unlock(); + + deleteLater(); } void IslInterface::transmitMessage(const IslMessage &item) { - QByteArray buf; - unsigned int size = item.ByteSize(); - buf.resize(size + 4); - item.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); - - outputBufferMutex.lock(); - outputBuffer.append(buf); - outputBufferMutex.unlock(); - emit outputBufferChanged(); + QByteArray buf; + unsigned int size = item.ByteSize(); + buf.resize(size + 4); + item.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); + + outputBufferMutex.lock(); + outputBuffer.append(buf); + outputBufferMutex.unlock(); + emit outputBufferChanged(); } void IslInterface::sessionEvent_ServerCompleteList(const Event_ServerCompleteList &event) { - for (int i = 0; i < event.user_list_size(); ++i) { - ServerInfo_User temp(event.user_list(i)); - temp.set_server_id(serverId); - emit externalUserJoined(temp); - } - for (int i = 0; i < event.room_list_size(); ++i) { - const ServerInfo_Room &room = event.room_list(i); - for (int j = 0; j < room.user_list_size(); ++j) { - ServerInfo_User userInfo(room.user_list(j)); - userInfo.set_server_id(serverId); - emit externalRoomUserJoined(room.room_id(), userInfo); - } - for (int j = 0; j < room.game_list_size(); ++j) { - ServerInfo_Game gameInfo(room.game_list(j)); - gameInfo.set_server_id(serverId); - emit externalRoomGameListChanged(room.room_id(), gameInfo); - } - } + for (int i = 0; i < event.user_list_size(); ++i) { + ServerInfo_User temp(event.user_list(i)); + temp.set_server_id(serverId); + emit externalUserJoined(temp); + } + for (int i = 0; i < event.room_list_size(); ++i) { + const ServerInfo_Room &room = event.room_list(i); + for (int j = 0; j < room.user_list_size(); ++j) { + ServerInfo_User userInfo(room.user_list(j)); + userInfo.set_server_id(serverId); + emit externalRoomUserJoined(room.room_id(), userInfo); + } + for (int j = 0; j < room.game_list_size(); ++j) { + ServerInfo_Game gameInfo(room.game_list(j)); + gameInfo.set_server_id(serverId); + emit externalRoomGameListChanged(room.room_id(), gameInfo); + } + } } void IslInterface::sessionEvent_UserJoined(const Event_UserJoined &event) { - ServerInfo_User userInfo(event.user_info()); - userInfo.set_server_id(serverId); - emit externalUserJoined(userInfo); + ServerInfo_User userInfo(event.user_info()); + userInfo.set_server_id(serverId); + emit externalUserJoined(userInfo); } void IslInterface::sessionEvent_UserLeft(const Event_UserLeft &event) { - emit externalUserLeft(QString::fromStdString(event.name())); + emit externalUserLeft(QString::fromStdString(event.name())); } void IslInterface::roomEvent_UserJoined(int roomId, const Event_JoinRoom &event) { - ServerInfo_User userInfo(event.user_info()); - userInfo.set_server_id(serverId); - emit externalRoomUserJoined(roomId, userInfo); + ServerInfo_User userInfo(event.user_info()); + userInfo.set_server_id(serverId); + emit externalRoomUserJoined(roomId, userInfo); } void IslInterface::roomEvent_UserLeft(int roomId, const Event_LeaveRoom &event) { - emit externalRoomUserLeft(roomId, QString::fromStdString(event.name())); + emit externalRoomUserLeft(roomId, QString::fromStdString(event.name())); } void IslInterface::roomEvent_Say(int roomId, const Event_RoomSay &event) { - emit externalRoomSay(roomId, QString::fromStdString(event.name()), QString::fromStdString(event.message())); + emit externalRoomSay(roomId, QString::fromStdString(event.name()), QString::fromStdString(event.message())); } void IslInterface::roomEvent_ListGames(int roomId, const Event_ListGames &event) { - for (int i = 0; i < event.game_list_size(); ++i) { - ServerInfo_Game gameInfo(event.game_list(i)); - gameInfo.set_server_id(serverId); - emit externalRoomGameListChanged(roomId, gameInfo); - } + for (int i = 0; i < event.game_list_size(); ++i) { + ServerInfo_Game gameInfo(event.game_list(i)); + gameInfo.set_server_id(serverId); + emit externalRoomGameListChanged(roomId, gameInfo); + } } void IslInterface::roomCommand_JoinGame(const Command_JoinGame &cmd, int cmdId, int roomId, qint64 sessionId) { - emit joinGameCommandReceived(cmd, cmdId, roomId, serverId, sessionId); + emit joinGameCommandReceived(cmd, cmdId, roomId, serverId, sessionId); } void IslInterface::processSessionEvent(const SessionEvent &event, qint64 sessionId) { - switch (getPbExtension(event)) { - case SessionEvent::SERVER_COMPLETE_LIST: sessionEvent_ServerCompleteList(event.GetExtension(Event_ServerCompleteList::ext)); break; - case SessionEvent::USER_JOINED: sessionEvent_UserJoined(event.GetExtension(Event_UserJoined::ext)); break; - case SessionEvent::USER_LEFT: sessionEvent_UserLeft(event.GetExtension(Event_UserLeft::ext)); break; - case SessionEvent::GAME_JOINED: { - QReadLocker clientsLocker(&server->clientsLock); - Server_AbstractUserInterface *client = server->getUsersBySessionId().value(sessionId); - if (!client) { - qDebug() << "IslInterface::processSessionEvent: session id" << sessionId << "not found"; - break; - } - const Event_GameJoined &gameJoined = event.GetExtension(Event_GameJoined::ext); - client->playerAddedToGame(gameJoined.game_info().game_id(), gameJoined.game_info().room_id(), gameJoined.player_id()); - client->sendProtocolItem(event); - break; - } - case SessionEvent::USER_MESSAGE: - case SessionEvent::REPLAY_ADDED: { - QReadLocker clientsLocker(&server->clientsLock); - Server_AbstractUserInterface *client = server->getUsersBySessionId().value(sessionId); - if (!client) { - qDebug() << "IslInterface::processSessionEvent: session id" << sessionId << "not found"; - break; - } - - client->sendProtocolItem(event); - break; - } - default: ; - } + switch (getPbExtension(event)) { + case SessionEvent::SERVER_COMPLETE_LIST: + sessionEvent_ServerCompleteList(event.GetExtension(Event_ServerCompleteList::ext)); + break; + case SessionEvent::USER_JOINED: + sessionEvent_UserJoined(event.GetExtension(Event_UserJoined::ext)); + break; + case SessionEvent::USER_LEFT: + sessionEvent_UserLeft(event.GetExtension(Event_UserLeft::ext)); + break; + case SessionEvent::GAME_JOINED: { + QReadLocker clientsLocker(&server->clientsLock); + Server_AbstractUserInterface *client = server->getUsersBySessionId().value(sessionId); + if (!client) { + qDebug() << "IslInterface::processSessionEvent: session id" << sessionId << "not found"; + break; + } + const Event_GameJoined &gameJoined = event.GetExtension(Event_GameJoined::ext); + client->playerAddedToGame(gameJoined.game_info().game_id(), gameJoined.game_info().room_id(), + gameJoined.player_id()); + client->sendProtocolItem(event); + break; + } + case SessionEvent::USER_MESSAGE: + case SessionEvent::REPLAY_ADDED: { + QReadLocker clientsLocker(&server->clientsLock); + Server_AbstractUserInterface *client = server->getUsersBySessionId().value(sessionId); + if (!client) { + qDebug() << "IslInterface::processSessionEvent: session id" << sessionId << "not found"; + break; + } + + client->sendProtocolItem(event); + break; + } + default:; + } } void IslInterface::processRoomEvent(const RoomEvent &event) { - switch (getPbExtension(event)) { - case RoomEvent::JOIN_ROOM: roomEvent_UserJoined(event.room_id(), event.GetExtension(Event_JoinRoom::ext)); break; - case RoomEvent::LEAVE_ROOM: roomEvent_UserLeft(event.room_id(), event.GetExtension(Event_LeaveRoom::ext)); break; - case RoomEvent::ROOM_SAY: roomEvent_Say(event.room_id(), event.GetExtension(Event_RoomSay::ext)); break; - case RoomEvent::LIST_GAMES: roomEvent_ListGames(event.room_id(), event.GetExtension(Event_ListGames::ext)); break; - default: ; - } + switch (getPbExtension(event)) { + case RoomEvent::JOIN_ROOM: + roomEvent_UserJoined(event.room_id(), event.GetExtension(Event_JoinRoom::ext)); + break; + case RoomEvent::LEAVE_ROOM: + roomEvent_UserLeft(event.room_id(), event.GetExtension(Event_LeaveRoom::ext)); + break; + case RoomEvent::ROOM_SAY: + roomEvent_Say(event.room_id(), event.GetExtension(Event_RoomSay::ext)); + break; + case RoomEvent::LIST_GAMES: + roomEvent_ListGames(event.room_id(), event.GetExtension(Event_ListGames::ext)); + break; + default:; + } } void IslInterface::processRoomCommand(const CommandContainer &cont, qint64 sessionId) { - for (int i = 0; i < cont.room_command_size(); ++i) { - const RoomCommand &roomCommand = cont.room_command(i); - switch (static_cast(getPbExtension(roomCommand))) { - case RoomCommand::JOIN_GAME: roomCommand_JoinGame(roomCommand.GetExtension(Command_JoinGame::ext), cont.cmd_id(), cont.room_id(), sessionId); - default: ; - } - } + for (int i = 0; i < cont.room_command_size(); ++i) { + const RoomCommand &roomCommand = cont.room_command(i); + switch (static_cast(getPbExtension(roomCommand))) { + case RoomCommand::JOIN_GAME: + roomCommand_JoinGame(roomCommand.GetExtension(Command_JoinGame::ext), cont.cmd_id(), cont.room_id(), + sessionId); + default:; + } + } } void IslInterface::processMessage(const IslMessage &item) { - qDebug() << QString::fromStdString(item.DebugString()); - - switch (item.message_type()) { - case IslMessage::ROOM_COMMAND_CONTAINER: { - processRoomCommand(item.room_command(), item.session_id()); - break; - } - case IslMessage::GAME_COMMAND_CONTAINER: { - emit gameCommandContainerReceived(item.game_command(), item.player_id(), serverId, item.session_id()); - break; - } - case IslMessage::SESSION_EVENT: { - processSessionEvent(item.session_event(), item.session_id()); - break; - } - case IslMessage::RESPONSE: { - emit responseReceived(item.response(), item.session_id()); - break; - } - case IslMessage::GAME_EVENT_CONTAINER: { - emit gameEventContainerReceived(item.game_event_container(), item.session_id()); - break; - } - case IslMessage::ROOM_EVENT: { - processRoomEvent(item.room_event()); - break; - } - default: ; - } + qDebug() << QString::fromStdString(item.DebugString()); + + switch (item.message_type()) { + case IslMessage::ROOM_COMMAND_CONTAINER: { + processRoomCommand(item.room_command(), item.session_id()); + break; + } + case IslMessage::GAME_COMMAND_CONTAINER: { + emit gameCommandContainerReceived(item.game_command(), item.player_id(), serverId, item.session_id()); + break; + } + case IslMessage::SESSION_EVENT: { + processSessionEvent(item.session_event(), item.session_id()); + break; + } + case IslMessage::RESPONSE: { + emit responseReceived(item.response(), item.session_id()); + break; + } + case IslMessage::GAME_EVENT_CONTAINER: { + emit gameEventContainerReceived(item.game_event_container(), item.session_id()); + break; + } + case IslMessage::ROOM_EVENT: { + processRoomEvent(item.room_event()); + break; + } + default:; + } } diff --git a/servatrice/src/isl_interface.h b/servatrice/src/isl_interface.h index cd1787ff..7296d0a4 100644 --- a/servatrice/src/isl_interface.h +++ b/servatrice/src/isl_interface.h @@ -1,12 +1,12 @@ #ifndef ISL_INTERFACE_H #define ISL_INTERFACE_H +#include "pb/serverinfo_game.pb.h" +#include "pb/serverinfo_room.pb.h" +#include "pb/serverinfo_user.pb.h" #include "servatrice.h" #include #include -#include "pb/serverinfo_user.pb.h" -#include "pb/serverinfo_room.pb.h" -#include "pb/serverinfo_game.pb.h" class Servatrice; class QSslSocket; @@ -23,66 +23,76 @@ class Event_RoomSay; class Event_ListGames; class Command_JoinGame; -class IslInterface : public QObject { - Q_OBJECT +class IslInterface : public QObject +{ + Q_OBJECT private slots: - void readClient(); - void catchSocketError(QAbstractSocket::SocketError socketError); - void flushOutputBuffer(); + void readClient(); + void catchSocketError(QAbstractSocket::SocketError socketError); + void flushOutputBuffer(); signals: - void outputBufferChanged(); - - void externalUserJoined(ServerInfo_User userInfo); - void externalUserLeft(QString userName); - void externalRoomUserJoined(int roomId, ServerInfo_User userInfo); - void externalRoomUserLeft(int roomId, QString userName); - void externalRoomSay(int roomId, QString userName, QString message); - void externalRoomGameListChanged(int roomId, ServerInfo_Game gameInfo); - void joinGameCommandReceived(const Command_JoinGame &cmd, int cmdId, int roomId, int serverId, qint64 sessionId); - void gameCommandContainerReceived(const CommandContainer &cont, int playerId, int serverId, qint64 sessionId); - void responseReceived(const Response &resp, qint64 sessionId); - void gameEventContainerReceived(const GameEventContainer &cont, qint64 sessionId); + void outputBufferChanged(); + + void externalUserJoined(ServerInfo_User userInfo); + void externalUserLeft(QString userName); + void externalRoomUserJoined(int roomId, ServerInfo_User userInfo); + void externalRoomUserLeft(int roomId, QString userName); + void externalRoomSay(int roomId, QString userName, QString message); + void externalRoomGameListChanged(int roomId, ServerInfo_Game gameInfo); + void joinGameCommandReceived(const Command_JoinGame &cmd, int cmdId, int roomId, int serverId, qint64 sessionId); + void gameCommandContainerReceived(const CommandContainer &cont, int playerId, int serverId, qint64 sessionId); + void responseReceived(const Response &resp, qint64 sessionId); + void gameEventContainerReceived(const GameEventContainer &cont, qint64 sessionId); + private: - int serverId; - int socketDescriptor; - QString peerHostName, peerAddress; - int peerPort; - QSslCertificate peerCert; - - QMutex outputBufferMutex; - Servatrice *server; - QSslSocket *socket; - - QByteArray inputBuffer, outputBuffer; - bool messageInProgress; - int messageLength; - - void sessionEvent_ServerCompleteList(const Event_ServerCompleteList &event); - void sessionEvent_UserJoined(const Event_UserJoined &event); - void sessionEvent_UserLeft(const Event_UserLeft &event); - - void roomEvent_UserJoined(int roomId, const Event_JoinRoom &event); - void roomEvent_UserLeft(int roomId, const Event_LeaveRoom &event); - void roomEvent_Say(int roomId, const Event_RoomSay &event); - void roomEvent_ListGames(int roomId, const Event_ListGames &event); - - void roomCommand_JoinGame(const Command_JoinGame &cmd, int cmdId, int roomId, qint64 sessionId); - - void processSessionEvent(const SessionEvent &event, qint64 sessionId); - void processRoomEvent(const RoomEvent &event); - void processRoomCommand(const CommandContainer &cont, qint64 sessionId); - - void processMessage(const IslMessage &item); - void sharedCtor(const QSslCertificate &cert, const QSslKey &privateKey); + int serverId; + int socketDescriptor; + QString peerHostName, peerAddress; + int peerPort; + QSslCertificate peerCert; + + QMutex outputBufferMutex; + Servatrice *server; + QSslSocket *socket; + + QByteArray inputBuffer, outputBuffer; + bool messageInProgress; + int messageLength; + + void sessionEvent_ServerCompleteList(const Event_ServerCompleteList &event); + void sessionEvent_UserJoined(const Event_UserJoined &event); + void sessionEvent_UserLeft(const Event_UserLeft &event); + + void roomEvent_UserJoined(int roomId, const Event_JoinRoom &event); + void roomEvent_UserLeft(int roomId, const Event_LeaveRoom &event); + void roomEvent_Say(int roomId, const Event_RoomSay &event); + void roomEvent_ListGames(int roomId, const Event_ListGames &event); + + void roomCommand_JoinGame(const Command_JoinGame &cmd, int cmdId, int roomId, qint64 sessionId); + + void processSessionEvent(const SessionEvent &event, qint64 sessionId); + void processRoomEvent(const RoomEvent &event); + void processRoomCommand(const CommandContainer &cont, qint64 sessionId); + + void processMessage(const IslMessage &item); + void sharedCtor(const QSslCertificate &cert, const QSslKey &privateKey); public slots: - void initServer(); - void initClient(); + void initServer(); + void initClient(); + public: - IslInterface(int socketDescriptor, const QSslCertificate &cert, const QSslKey &privateKey, Servatrice *_server); - IslInterface(int _serverId, const QString &peerHostName, const QString &peerAddress, int peerPort, const QSslCertificate &peerCert, const QSslCertificate &cert, const QSslKey &privateKey, Servatrice *_server); - ~IslInterface(); - - void transmitMessage(const IslMessage &item); + IslInterface(int socketDescriptor, const QSslCertificate &cert, const QSslKey &privateKey, Servatrice *_server); + IslInterface(int _serverId, + const QString &peerHostName, + const QString &peerAddress, + int peerPort, + const QSslCertificate &peerCert, + const QSslCertificate &cert, + const QSslKey &privateKey, + Servatrice *_server); + ~IslInterface(); + + void transmitMessage(const IslMessage &item); }; #endif diff --git a/servatrice/src/main.cpp b/servatrice/src/main.cpp index 8a11a63e..af1ad98a 100644 --- a/servatrice/src/main.cpp +++ b/servatrice/src/main.cpp @@ -18,25 +18,24 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ +#include #include +#include +#include #include #include #include -#include -#include -#include - + #include "passwordhasher.h" +#include "rng_sfmt.h" #include "servatrice.h" #include "server_logger.h" #include "settingscache.h" #include "signalhandler.h" #include "smtpclient.h" -#include "rng_sfmt.h" #include "version_string.h" #include - RNG_Abstract *rng; ServerLogger *logger; QThread *loggerThread; @@ -55,157 +54,157 @@ void myMessageOutput2(QtMsgType type, const QMessageLogContext &, const QString void testRNG() { - const int n = 500000; - std::cerr << "Testing random number generator (n = " << n << " * bins)..." << std::endl; - - const int min = 1; - const int minMax = 2; - const int maxMax = 10; - - QVector > numbers(maxMax - minMax + 1); - QVector chisq(maxMax - minMax + 1); - for (int max = minMax; max <= maxMax; ++max) { - numbers[max - minMax] = rng->makeNumbersVector(n * (max - min + 1), min, max); - chisq[max - minMax] = rng->testRandom(numbers[max - minMax]); - } - for (int i = 0; i <= maxMax - min; ++i) { - std::cerr << (min + i); - for (int j = 0; j < numbers.size(); ++j) { - if (i < numbers[j].size()) - std::cerr << "\t" << numbers[j][i]; - else - std::cerr << "\t"; - } - std::cerr << std::endl; - } - std::cerr << std::endl << "Chi^2 ="; - for (int j = 0; j < chisq.size(); ++j) - std::cerr << "\t" << QString::number(chisq[j], 'f', 3).toStdString(); - std::cerr << std::endl << "k ="; - for (int j = 0; j < chisq.size(); ++j) - std::cerr << "\t" << (j - min + minMax); - std::cerr << std::endl << std::endl; + const int n = 500000; + std::cerr << "Testing random number generator (n = " << n << " * bins)..." << std::endl; + + const int min = 1; + const int minMax = 2; + const int maxMax = 10; + + QVector> numbers(maxMax - minMax + 1); + QVector chisq(maxMax - minMax + 1); + for (int max = minMax; max <= maxMax; ++max) { + numbers[max - minMax] = rng->makeNumbersVector(n * (max - min + 1), min, max); + chisq[max - minMax] = rng->testRandom(numbers[max - minMax]); + } + for (int i = 0; i <= maxMax - min; ++i) { + std::cerr << (min + i); + for (int j = 0; j < numbers.size(); ++j) { + if (i < numbers[j].size()) + std::cerr << "\t" << numbers[j][i]; + else + std::cerr << "\t"; + } + std::cerr << std::endl; + } + std::cerr << std::endl << "Chi^2 ="; + for (int j = 0; j < chisq.size(); ++j) + std::cerr << "\t" << QString::number(chisq[j], 'f', 3).toStdString(); + std::cerr << std::endl << "k ="; + for (int j = 0; j < chisq.size(); ++j) + std::cerr << "\t" << (j - min + minMax); + std::cerr << std::endl << std::endl; } void testHash() { - const int n = 5000; - std::cerr << "Benchmarking password hash function (n =" << n << ")..." << std::endl; - QDateTime startTime = QDateTime::currentDateTime(); - for (int i = 0; i < n; ++i) - PasswordHasher::computeHash("aaaaaa", "aaaaaaaaaaaaaaaa"); - QDateTime endTime = QDateTime::currentDateTime(); - std::cerr << startTime.secsTo(endTime) << "secs" << std::endl; + const int n = 5000; + std::cerr << "Benchmarking password hash function (n =" << n << ")..." << std::endl; + QDateTime startTime = QDateTime::currentDateTime(); + for (int i = 0; i < n; ++i) + PasswordHasher::computeHash("aaaaaa", "aaaaaaaaaaaaaaaa"); + QDateTime endTime = QDateTime::currentDateTime(); + std::cerr << startTime.secsTo(endTime) << "secs" << std::endl; } void myMessageOutput(QtMsgType /*type*/, const QMessageLogContext &, const QString &msg) { - logger->logMessage(msg); + logger->logMessage(msg); } void myMessageOutput2(QtMsgType /*type*/, const QMessageLogContext &, const QString &msg) { - logger->logMessage(msg); - std::cerr << msg.toStdString() << std::endl; + logger->logMessage(msg); + std::cerr << msg.toStdString() << std::endl; } int main(int argc, char *argv[]) { - QCoreApplication app(argc, argv); - app.setOrganizationName("Cockatrice"); - app.setApplicationName("Servatrice"); - app.setApplicationVersion(VERSION_STRING); + QCoreApplication app(argc, argv); + app.setOrganizationName("Cockatrice"); + app.setApplicationName("Servatrice"); + app.setApplicationVersion(VERSION_STRING); - bool testRandom = false; - bool testHashFunction = false; - bool logToConsole = false; - QString configPath; + bool testRandom = false; + bool testHashFunction = false; + bool logToConsole = false; + QString configPath; - QCommandLineParser parser; - parser.addHelpOption(); - parser.addVersionOption(); + QCommandLineParser parser; + parser.addHelpOption(); + parser.addVersionOption(); - QCommandLineOption testRandomOpt("test-random", "Test PRNG (chi^2)"); - parser.addOption(testRandomOpt); + QCommandLineOption testRandomOpt("test-random", "Test PRNG (chi^2)"); + parser.addOption(testRandomOpt); - QCommandLineOption testHashFunctionOpt("test-hash", "Test password hash function"); - parser.addOption(testHashFunctionOpt); + QCommandLineOption testHashFunctionOpt("test-hash", "Test password hash function"); + parser.addOption(testHashFunctionOpt); - QCommandLineOption logToConsoleOpt("log-to-console", "Write server logs to console"); - parser.addOption(logToConsoleOpt); + QCommandLineOption logToConsoleOpt("log-to-console", "Write server logs to console"); + parser.addOption(logToConsoleOpt); - QCommandLineOption configPathOpt("config", "Read server configuration from ", "file", ""); - parser.addOption(configPathOpt); + QCommandLineOption configPathOpt("config", "Read server configuration from ", "file", ""); + parser.addOption(configPathOpt); - parser.process(app); + parser.process(app); - testRandom = parser.isSet(testRandomOpt); - testHashFunction = parser.isSet(testHashFunctionOpt); - logToConsole = parser.isSet(logToConsoleOpt); - configPath = parser.value(configPathOpt); + testRandom = parser.isSet(testRandomOpt); + testHashFunction = parser.isSet(testHashFunctionOpt); + logToConsole = parser.isSet(logToConsoleOpt); + configPath = parser.value(configPathOpt); - - qRegisterMetaType >("QList"); + qRegisterMetaType>("QList"); - configPath = SettingsCache::guessConfigurationPath(configPath); - qWarning() << "Using configuration file: " << configPath; - settingsCache = new SettingsCache(configPath); - - loggerThread = new QThread; - loggerThread->setObjectName("logger"); - logger = new ServerLogger(logToConsole); - logger->moveToThread(loggerThread); - - loggerThread->start(); - QMetaObject::invokeMethod(logger, "startLog", Qt::BlockingQueuedConnection, Q_ARG(QString, settingsCache->value("server/logfile", QString("server.log")).toString())); + configPath = SettingsCache::guessConfigurationPath(configPath); + qWarning() << "Using configuration file: " << configPath; + settingsCache = new SettingsCache(configPath); - if (logToConsole) - qInstallMessageHandler(myMessageOutput); - else - qInstallMessageHandler(myMessageOutput2); + loggerThread = new QThread; + loggerThread->setObjectName("logger"); + logger = new ServerLogger(logToConsole); + logger->moveToThread(loggerThread); - signalhandler = new SignalHandler(); + loggerThread->start(); + QMetaObject::invokeMethod(logger, "startLog", Qt::BlockingQueuedConnection, + Q_ARG(QString, settingsCache->value("server/logfile", QString("server.log")).toString())); - rng = new RNG_SFMT; - - std::cerr << "Servatrice " << VERSION_STRING << " starting." << std::endl; - std::cerr << "-------------------------" << std::endl; - - PasswordHasher::initialize(); - - if (testRandom) - testRNG(); - if (testHashFunction) - testHash(); + if (logToConsole) + qInstallMessageHandler(myMessageOutput); + else + qInstallMessageHandler(myMessageOutput2); - smtpClient = new SmtpClient(); - - Servatrice *server = new Servatrice(); - QObject::connect(server, SIGNAL(destroyed()), &app, SLOT(quit()), Qt::QueuedConnection); - int retval = 0; - if (server->initServer()) { - std::cerr << "-------------------------" << std::endl; - std::cerr << "Server initialized." << std::endl; + signalhandler = new SignalHandler(); - qInstallMessageHandler(myMessageOutput); + rng = new RNG_SFMT; - retval = app.exec(); - - std::cerr << "Server quit." << std::endl; - std::cerr << "-------------------------" << std::endl; - } - - delete smtpClient; - delete rng; - delete signalhandler; - delete settingsCache; - - logger->deleteLater(); - loggerThread->wait(); - delete loggerThread; + std::cerr << "Servatrice " << VERSION_STRING << " starting." << std::endl; + std::cerr << "-------------------------" << std::endl; - // Delete all global objects allocated by libprotobuf. - google::protobuf::ShutdownProtobufLibrary(); + PasswordHasher::initialize(); - return retval; + if (testRandom) + testRNG(); + if (testHashFunction) + testHash(); + + smtpClient = new SmtpClient(); + + Servatrice *server = new Servatrice(); + QObject::connect(server, SIGNAL(destroyed()), &app, SLOT(quit()), Qt::QueuedConnection); + int retval = 0; + if (server->initServer()) { + std::cerr << "-------------------------" << std::endl; + std::cerr << "Server initialized." << std::endl; + + qInstallMessageHandler(myMessageOutput); + + retval = app.exec(); + + std::cerr << "Server quit." << std::endl; + std::cerr << "-------------------------" << std::endl; + } + + delete smtpClient; + delete rng; + delete signalhandler; + delete settingsCache; + + logger->deleteLater(); + loggerThread->wait(); + delete loggerThread; + + // Delete all global objects allocated by libprotobuf. + google::protobuf::ShutdownProtobufLibrary(); + + return retval; } diff --git a/servatrice/src/passwordhasher.cpp b/servatrice/src/passwordhasher.cpp index ff9536e5..32c5ea89 100644 --- a/servatrice/src/passwordhasher.cpp +++ b/servatrice/src/passwordhasher.cpp @@ -1,7 +1,7 @@ #include "passwordhasher.h" -#include #include "rng_sfmt.h" +#include void PasswordHasher::initialize() { @@ -23,10 +23,9 @@ QString PasswordHasher::computeHash(const QString &password, const QString &salt QString PasswordHasher::generateRandomSalt(const int len) { - static const char alphanum[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; + static const char alphanum[] = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; QString ret; int size = sizeof(alphanum) - 1; diff --git a/servatrice/src/passwordhasher.h b/servatrice/src/passwordhasher.h index 4160cb0f..07557975 100644 --- a/servatrice/src/passwordhasher.h +++ b/servatrice/src/passwordhasher.h @@ -3,12 +3,13 @@ #include -class PasswordHasher { +class PasswordHasher +{ public: - static void initialize(); - static QString computeHash(const QString &password, const QString &salt); - static QString generateRandomSalt(const int len = 16); - static QString generateActivationToken(); + static void initialize(); + static QString computeHash(const QString &password, const QString &salt); + static QString generateRandomSalt(const int len = 16); + static QString generateActivationToken(); }; #endif diff --git a/servatrice/src/servatrice.cpp b/servatrice/src/servatrice.cpp index fcae32b1..18b64262 100644 --- a/servatrice/src/servatrice.cpp +++ b/servatrice/src/servatrice.cpp @@ -17,32 +17,34 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include -#include -#include -#include -#include -#include -#include #include "servatrice.h" -#include "servatrice_database_interface.h" -#include "servatrice_connection_pool.h" -#include "server_room.h" -#include "settingscache.h" -#include "serversocketinterface.h" -#include "isl_interface.h" -#include "server_logger.h" -#include "main.h" #include "decklist.h" -#include "smtpclient.h" +#include "featureset.h" +#include "isl_interface.h" +#include "main.h" +#include "pb/event_connection_closed.pb.h" #include "pb/event_server_message.pb.h" #include "pb/event_server_shutdown.pb.h" -#include "pb/event_connection_closed.pb.h" -#include "featureset.h" +#include "servatrice_connection_pool.h" +#include "servatrice_database_interface.h" +#include "server_logger.h" +#include "server_room.h" +#include "serversocketinterface.h" +#include "settingscache.h" +#include "smtpclient.h" +#include +#include +#include +#include +#include +#include +#include -Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent) - : QTcpServer(parent), - server(_server) +Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, + int _numberPools, + const QSqlDatabase &_sqlDatabase, + QObject *parent) + : QTcpServer(parent), server(_server) { for (int i = 0; i < _numberPools; ++i) { Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(i, server); @@ -55,7 +57,8 @@ Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPoo server->addDatabaseInterface(newThread, newDatabaseInterface); newThread->start(); - QMetaObject::invokeMethod(newDatabaseInterface, "initDatabase", Qt::BlockingQueuedConnection, Q_ARG(QSqlDatabase, _sqlDatabase)); + QMetaObject::invokeMethod(newDatabaseInterface, "initDatabase", Qt::BlockingQueuedConnection, + Q_ARG(QSqlDatabase, _sqlDatabase)); connectionPools.append(newPool); } @@ -103,12 +106,15 @@ Servatrice_ConnectionPool *Servatrice_GameServer::findLeastUsedConnectionPool() #if QT_VERSION > 0x050300 #define WEBSOCKET_POOL_NUMBER 999 -Servatrice_WebsocketGameServer::Servatrice_WebsocketGameServer(Servatrice *_server, int /* _numberPools */, const QSqlDatabase &_sqlDatabase, QObject *parent) - : QWebSocketServer("Servatrice", QWebSocketServer::NonSecureMode, parent), - server(_server) +Servatrice_WebsocketGameServer::Servatrice_WebsocketGameServer(Servatrice *_server, + int /* _numberPools */, + const QSqlDatabase &_sqlDatabase, + QObject *parent) + : QWebSocketServer("Servatrice", QWebSocketServer::NonSecureMode, parent), server(_server) { // Qt limitation: websockets can't be moved to another thread - Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(WEBSOCKET_POOL_NUMBER, server); + Servatrice_DatabaseInterface *newDatabaseInterface = + new Servatrice_DatabaseInterface(WEBSOCKET_POOL_NUMBER, server); Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface); server->addDatabaseInterface(thread(), newDatabaseInterface); @@ -134,7 +140,7 @@ void Servatrice_WebsocketGameServer::onNewConnection() Servatrice_ConnectionPool *pool = findLeastUsedConnectionPool(); WebsocketServerSocketInterface *ssi = new WebsocketServerSocketInterface(server, pool->getDatabaseInterface()); -// ssi->moveToThread(pool->thread()); + // ssi->moveToThread(pool->thread()); pool->addClient(); connect(ssi, SIGNAL(destroyed()), pool, SLOT(removeClient())); @@ -172,8 +178,7 @@ void Servatrice_IslServer::incomingConnection(qintptr socketDescriptor) QMetaObject::invokeMethod(interface, "initServer", Qt::QueuedConnection); } -Servatrice::Servatrice(QObject *parent) - : Server(parent), uptime(0), shutdownTimer(0), isFirstShutdownMessage(true) +Servatrice::Servatrice(QObject *parent) : Server(parent), uptime(0), shutdownTimer(0), isFirstShutdownMessage(true) { qRegisterMetaType("QSqlDatabase"); } @@ -182,7 +187,7 @@ Servatrice::~Servatrice() { gameServer->close(); - // clients live in other threads, we need to lock them + // clients live in other threads, we need to lock them clientsLock.lockForRead(); for (int i = 0; i < clients.size(); ++i) QMetaObject::invokeMethod(clients.at(i), "prepareDestroy", Qt::QueuedConnection); @@ -194,7 +199,10 @@ Servatrice::~Servatrice() class SleeperThread : public QThread { public: - static void msleep(unsigned long msecs) { QThread::usleep(msecs); } + static void msleep(unsigned long msecs) + { + QThread::usleep(msecs); + } }; do { @@ -210,12 +218,12 @@ Servatrice::~Servatrice() bool Servatrice::initServer() { - + serverId = getServerID(); if (getAuthenticationMethodString() == "sql") { qDebug() << "Authenticating method: sql"; authenticationMethod = AuthenticationSql; - } else if(getAuthenticationMethodString() == "password") { + } else if (getAuthenticationMethodString() == "password") { qDebug() << "Authenticating method: password"; authenticationMethod = AuthenticationPassword; } else { @@ -244,11 +252,15 @@ bool Servatrice::initServer() qDebug() << "Email blacklist: " << emailBlackListFilters; qDebug() << "Require email address to register: " << getRequireEmailForRegistrationEnabled(); qDebug() << "Require email activation via token: " << getRequireEmailActivationEnabled(); - if (getMaxAccountsPerEmail()) { qDebug() << "Maximum number of accounts per email: " << getMaxAccountsPerEmail(); } else { qDebug() << "Maximum number of accounts per email: unlimited"; } + if (getMaxAccountsPerEmail()) { + qDebug() << "Maximum number of accounts per email: " << getMaxAccountsPerEmail(); + } else { + qDebug() << "Maximum number of accounts per email: unlimited"; + } qDebug() << "Enable Internal SMTP Client: " << getEnableInternalSMTPClient(); - if (!getEnableInternalSMTPClient()) - { - qDebug() << "WARNING: Registrations are enabled but internal SMTP client is disabled. Users activation emails will not be automatically mailed to users!"; + if (!getEnableInternalSMTPClient()) { + qDebug() << "WARNING: Registrations are enabled but internal SMTP client is disabled. Users activation " + "emails will not be automatically mailed to users!"; } } @@ -274,7 +286,8 @@ bool Servatrice::initServer() if (databaseType != DatabaseNone) { dbPrefix = getDBPrefixString(); - bool dbOpened = servatriceDatabaseInterface->initDatabase("QMYSQL",getDBHostNameString(),getDBDatabaseNameString(),getDBUserNameString(),getDBPasswordString()); + bool dbOpened = servatriceDatabaseInterface->initDatabase( + "QMYSQL", getDBHostNameString(), getDBDatabaseNameString(), getDBUserNameString(), getDBPasswordString()); if (!dbOpened) { qDebug() << "Failed to open database"; return false; @@ -285,27 +298,24 @@ bool Servatrice::initServer() } if (getRoomsMethodString() == "sql") { - QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, name, descr, permissionlevel, privlevel, auto_join, join_message, chat_history_size from {prefix}_rooms where id_server = :id_server order by id asc"); + QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( + "select id, name, descr, permissionlevel, privlevel, auto_join, join_message, chat_history_size from " + "{prefix}_rooms where id_server = :id_server order by id asc"); query->bindValue(":id_server", serverId); servatriceDatabaseInterface->execSqlQuery(query); while (query->next()) { - QSqlQuery *query2 = servatriceDatabaseInterface->prepareQuery("select name from {prefix}_rooms_gametypes where id_room = :id_room AND id_server = :id_server"); + QSqlQuery *query2 = servatriceDatabaseInterface->prepareQuery( + "select name from {prefix}_rooms_gametypes where id_room = :id_room AND id_server = :id_server"); query2->bindValue(":id_server", serverId); query2->bindValue(":id_room", query->value(0).toInt()); servatriceDatabaseInterface->execSqlQuery(query2); QStringList gameTypes; while (query2->next()) gameTypes.append(query2->value(0).toString()); - addRoom(new Server_Room(query->value(0).toInt(), - query->value(7).toInt(), - query->value(1).toString(), - query->value(2).toString(), - query->value(3).toString().toLower(), - query->value(4).toString().toLower(), - query->value(5).toInt(), - query->value(6).toString(), - gameTypes, - this)); + addRoom(new Server_Room(query->value(0).toInt(), query->value(7).toInt(), query->value(1).toString(), + query->value(2).toString(), query->value(3).toString().toLower(), + query->value(4).toString().toLower(), query->value(5).toInt(), + query->value(6).toString(), gameTypes, this)); } } else { int size = settingsCache->beginReadArray("rooms/roomlist"); @@ -313,18 +323,24 @@ bool Servatrice::initServer() settingsCache->setArrayIndex(i); QStringList gameTypes; int size2 = settingsCache->beginReadArray("game_types"); - for (int j = 0; j < size2; ++j) { + for (int j = 0; j < size2; ++j) { settingsCache->setArrayIndex(j); gameTypes.append(settingsCache->value("name").toString()); } settingsCache->endArray(); - Server_Room *newRoom = new Server_Room(i,settingsCache->value("chathistorysize").toInt(),settingsCache->value("name").toString(),settingsCache->value("description").toString(),settingsCache->value("permissionlevel").toString().toLower(),settingsCache->value("privilegelevel").toString().toLower(),settingsCache->value("autojoin").toBool(),settingsCache->value("joinmessage").toString(),gameTypes,this); + Server_Room *newRoom = new Server_Room( + i, settingsCache->value("chathistorysize").toInt(), settingsCache->value("name").toString(), + settingsCache->value("description").toString(), + settingsCache->value("permissionlevel").toString().toLower(), + settingsCache->value("privilegelevel").toString().toLower(), settingsCache->value("autojoin").toBool(), + settingsCache->value("joinmessage").toString(), gameTypes, this); addRoom(newRoom); } - if(size==0) { + if (size == 0) { // no room defined in config, add a dummy one - Server_Room *newRoom = new Server_Room(0,100,"General room","Play anything here.","none","none",true,"",QStringList("Standard"),this); + Server_Room *newRoom = new Server_Room(0, 100, "General room", "Play anything here.", "none", "none", true, + "", QStringList("Standard"), this); addRoom(newRoom); } @@ -333,55 +349,56 @@ bool Servatrice::initServer() updateLoginMessage(); - try { if (getISLNetworkEnabled()) { - qDebug() << "Connecting to ISL network."; - qDebug() << "Loading certificate..."; - QFile certFile(getISLNetworkSSLCertFile()); - if (!certFile.open(QIODevice::ReadOnly)) - throw QString("Error opening certificate file: %1").arg(getISLNetworkSSLCertFile()); - QSslCertificate cert(&certFile); + try { + if (getISLNetworkEnabled()) { + qDebug() << "Connecting to ISL network."; + qDebug() << "Loading certificate..."; + QFile certFile(getISLNetworkSSLCertFile()); + if (!certFile.open(QIODevice::ReadOnly)) + throw QString("Error opening certificate file: %1").arg(getISLNetworkSSLCertFile()); + QSslCertificate cert(&certFile); - const QDateTime currentTime = QDateTime::currentDateTime(); - if(currentTime < cert.effectiveDate() || - currentTime > cert.expiryDate() || - cert.isBlacklisted()) - throw(QString("Invalid certificate.")); + const QDateTime currentTime = QDateTime::currentDateTime(); + if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate() || cert.isBlacklisted()) + throw(QString("Invalid certificate.")); - qDebug() << "Loading private key..."; - QFile keyFile(getISLNetworkSSLKeyFile()); - if (!keyFile.open(QIODevice::ReadOnly)) - throw QString("Error opening private key file: %1").arg(getISLNetworkSSLKeyFile()); - QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey); - if (key.isNull()) - throw QString("Invalid private key."); + qDebug() << "Loading private key..."; + QFile keyFile(getISLNetworkSSLKeyFile()); + if (!keyFile.open(QIODevice::ReadOnly)) + throw QString("Error opening private key file: %1").arg(getISLNetworkSSLKeyFile()); + QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey); + if (key.isNull()) + throw QString("Invalid private key."); - QMutableListIterator serverIterator(serverList); - while (serverIterator.hasNext()) { - const ServerProperties &prop = serverIterator.next(); - if (prop.cert == cert) { - serverIterator.remove(); - continue; + QMutableListIterator serverIterator(serverList); + while (serverIterator.hasNext()) { + const ServerProperties &prop = serverIterator.next(); + if (prop.cert == cert) { + serverIterator.remove(); + continue; + } + + QThread *thread = new QThread; + thread->setObjectName("isl_" + QString::number(prop.id)); + connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); + + IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), + prop.controlPort, prop.cert, cert, key, this); + interface->moveToThread(thread); + connect(interface, SIGNAL(destroyed()), thread, SLOT(quit())); + + thread->start(); + QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection); } - QThread *thread = new QThread; - thread->setObjectName("isl_" + QString::number(prop.id)); - connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); - - IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), prop.controlPort, prop.cert, cert, key, this); - interface->moveToThread(thread); - connect(interface, SIGNAL(destroyed()), thread, SLOT(quit())); - - thread->start(); - QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection); + qDebug() << "Starting ISL server on port" << getISLNetworkPort(); + islServer = new Servatrice_IslServer(this, cert, key, this); + if (islServer->listen(QHostAddress::Any, getISLNetworkPort())) + qDebug() << "ISL server listening."; + else + throw QString("islServer->listen()"); } - - qDebug() << "Starting ISL server on port" << getISLNetworkPort(); - islServer = new Servatrice_IslServer(this, cert, key, this); - if (islServer->listen(QHostAddress::Any, getISLNetworkPort())) - qDebug() << "ISL server listening."; - else - throw QString("islServer->listen()"); - } } catch (QString error) { + } catch (QString error) { qDebug() << "ERROR --" << error; return false; } @@ -398,9 +415,9 @@ bool Servatrice::initServer() } // SOCKET SERVER - if(getNumberOfTCPPools() > 0) - { - gameServer = new Servatrice_GameServer(this, getNumberOfTCPPools(), servatriceDatabaseInterface->getDatabase(), this); + if (getNumberOfTCPPools() > 0) { + gameServer = + new Servatrice_GameServer(this, getNumberOfTCPPools(), servatriceDatabaseInterface->getDatabase(), this); gameServer->setMaxPendingConnections(1000); qDebug() << "Starting server on port" << getServerTCPPort(); if (gameServer->listen(QHostAddress::Any, getServerTCPPort())) @@ -413,9 +430,9 @@ bool Servatrice::initServer() #if QT_VERSION > 0x050300 // WEBSOCKET SERVER - if(getNumberOfWebSocketPools() > 0) - { - websocketGameServer = new Servatrice_WebsocketGameServer(this, getNumberOfWebSocketPools(), servatriceDatabaseInterface->getDatabase(), this); + if (getNumberOfWebSocketPools() > 0) { + websocketGameServer = new Servatrice_WebsocketGameServer(this, getNumberOfWebSocketPools(), + servatriceDatabaseInterface->getDatabase(), this); websocketGameServer->setMaxPendingConnections(1000); qDebug() << "Starting websocket server on port" << getServerWebSocketPort(); if (websocketGameServer->listen(QHostAddress::Any, getServerWebSocketPort())) @@ -430,7 +447,10 @@ bool Servatrice::initServer() if (getIdleClientTimeout() > 0) { qDebug() << "Idle client timeout value: " << getIdleClientTimeout(); if (getIdleClientTimeout() < 300) - qDebug() << "WARNING: It is not recommended to set the IdleClientTimeout value very low. Doing so will cause clients to very quickly be disconnected. Many players when connected may be searching for card details outside the client in the middle of matches or possibly drafting outside the client and short time out values will remove these players."; + qDebug() << "WARNING: It is not recommended to set the IdleClientTimeout value very low. Doing so will " + "cause clients to very quickly be disconnected. Many players when connected may be searching " + "for card details outside the client in the middle of matches or possibly drafting outside the " + "client and short time out values will remove these players."; } setRequiredFeatures(getRequiredFeatures()); @@ -449,12 +469,21 @@ void Servatrice::updateServerList() serverListMutex.lock(); serverList.clear(); - QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, ssl_cert, hostname, address, game_port, control_port from {prefix}_servers order by id asc"); + QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( + "select id, ssl_cert, hostname, address, game_port, control_port from {prefix}_servers order by id asc"); servatriceDatabaseInterface->execSqlQuery(query); while (query->next()) { - ServerProperties prop(query->value(0).toInt(), QSslCertificate(query->value(1).toString().toUtf8()), query->value(2).toString(), QHostAddress(query->value(3).toString()), query->value(4).toInt(), query->value(5).toInt()); + ServerProperties prop(query->value(0).toInt(), QSslCertificate(query->value(1).toString().toUtf8()), + query->value(2).toString(), QHostAddress(query->value(3).toString()), + query->value(4).toInt(), query->value(5).toInt()); serverList.append(prop); - qDebug() << QString("#%1 CERT=%2 NAME=%3 IP=%4:%5 CPORT=%6").arg(prop.id).arg(QString(prop.cert.digest().toHex())).arg(prop.hostname).arg(prop.address.toString()).arg(prop.gamePort).arg(prop.controlPort); + qDebug() << QString("#%1 CERT=%2 NAME=%3 IP=%4:%5 CPORT=%6") + .arg(prop.id) + .arg(QString(prop.cert.digest().toHex())) + .arg(prop.hostname) + .arg(prop.address.toString()) + .arg(prop.gamePort) + .arg(prop.controlPort); } serverListMutex.unlock(); @@ -474,8 +503,8 @@ int Servatrice::getUsersWithAddress(const QHostAddress &address) const int result = 0; QReadLocker locker(&clientsLock); for (int i = 0; i < clients.size(); ++i) - if (static_cast(clients[i])->getPeerAddress() == address) - ++result; + if (static_cast(clients[i])->getPeerAddress() == address) + ++result; return result; } @@ -495,7 +524,8 @@ void Servatrice::updateLoginMessage() if (!servatriceDatabaseInterface->checkSql()) return; - QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select message from {prefix}_servermessages where id_server = :id_server order by timest desc limit 1"); + QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( + "select message from {prefix}_servermessages where id_server = :id_server order by timest desc limit 1"); query->bindValue(":id_server", serverId); if (servatriceDatabaseInterface->execSqlQuery(query)) if (query->next()) { @@ -515,14 +545,15 @@ void Servatrice::updateLoginMessage() } } -void Servatrice::setRequiredFeatures(const QString featureList) { +void Servatrice::setRequiredFeatures(const QString featureList) +{ FeatureSet features; serverRequiredFeatureList.clear(); features.initalizeFeatureList(serverRequiredFeatureList); QStringList listReqFeatures = featureList.split(",", QString::SkipEmptyParts); if (!listReqFeatures.isEmpty()) - foreach(QString reqFeature, listReqFeatures) - features.enableRequiredFeature(serverRequiredFeatureList, reqFeature); + foreach (QString reqFeature, listReqFeatures) + features.enableRequiredFeature(serverRequiredFeatureList, reqFeature); qDebug() << "Set required client features to: " << serverRequiredFeatureList; } @@ -546,7 +577,9 @@ void Servatrice::statusUpdate() rxBytes = 0; rxBytesMutex.unlock(); - QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("insert into {prefix}_uptime (id_server, timest, uptime, users_count, games_count, tx_bytes, rx_bytes) values(:id, NOW(), :uptime, :users_count, :games_count, :tx, :rx)"); + QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( + "insert into {prefix}_uptime (id_server, timest, uptime, users_count, games_count, tx_bytes, rx_bytes) " + "values(:id, NOW(), :uptime, :users_count, :games_count, :tx, :rx)"); query->bindValue(":id", serverId); query->bindValue(":uptime", uptime); query->bindValue(":users_count", uc); @@ -555,44 +588,45 @@ void Servatrice::statusUpdate() query->bindValue(":rx", rx); servatriceDatabaseInterface->execSqlQuery(query); - if (getRegistrationEnabled() && getEnableInternalSMTPClient()) - { - if (getRequireEmailActivationEnabled()) - { - QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select a.name, b.email, b.token from {prefix}_activation_emails a left join {prefix}_users b on a.name = b.name"); + if (getRegistrationEnabled() && getEnableInternalSMTPClient()) { + if (getRequireEmailActivationEnabled()) { + QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select a.name, b.email, b.token from " + "{prefix}_activation_emails a left join " + "{prefix}_users b on a.name = b.name"); if (!servatriceDatabaseInterface->execSqlQuery(query)) return; - QSqlQuery *queryDelete = servatriceDatabaseInterface->prepareQuery("delete from {prefix}_activation_emails where name = :name"); + QSqlQuery *queryDelete = + servatriceDatabaseInterface->prepareQuery("delete from {prefix}_activation_emails where name = :name"); while (query->next()) { const QString userName = query->value(0).toString(); const QString emailAddress = query->value(1).toString(); const QString token = query->value(2).toString(); - if (smtpClient->enqueueActivationTokenMail(userName, emailAddress, token)) - { + if (smtpClient->enqueueActivationTokenMail(userName, emailAddress, token)) { queryDelete->bindValue(":name", userName); servatriceDatabaseInterface->execSqlQuery(queryDelete); } } } - if (getEnableForgotPassword()) - { - QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select a.name, b.email, b.token from {prefix}_forgot_password a left join {prefix}_users b on a.name = b.name where a.emailed = 0"); + if (getEnableForgotPassword()) { + QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( + "select a.name, b.email, b.token from {prefix}_forgot_password a left join {prefix}_users b on a.name " + "= b.name where a.emailed = 0"); if (!servatriceDatabaseInterface->execSqlQuery(query)) return; - QSqlQuery *queryDelete = servatriceDatabaseInterface->prepareQuery("update {prefix}_forgot_password set emailed = 1 where name = :name"); + QSqlQuery *queryDelete = servatriceDatabaseInterface->prepareQuery( + "update {prefix}_forgot_password set emailed = 1 where name = :name"); while (query->next()) { const QString userName = query->value(0).toString(); const QString emailAddress = query->value(1).toString(); const QString token = query->value(2).toString(); - if (smtpClient->enqueueForgotPasswordTokenMail(userName, emailAddress, token)) - { + if (smtpClient->enqueueForgotPasswordTokenMail(userName, emailAddress, token)) { queryDelete->bindValue(":name", userName); servatriceDatabaseInterface->execSqlQuery(queryDelete); } @@ -673,20 +707,28 @@ void Servatrice::addIslInterface(int serverId, IslInterface *interface) islInterfaces.insert(serverId, interface); connect(interface, SIGNAL(externalUserJoined(ServerInfo_User)), this, SLOT(externalUserJoined(ServerInfo_User))); connect(interface, SIGNAL(externalUserLeft(QString)), this, SLOT(externalUserLeft(QString))); - connect(interface, SIGNAL(externalRoomUserJoined(int, ServerInfo_User)), this, SLOT(externalRoomUserJoined(int, ServerInfo_User))); + connect(interface, SIGNAL(externalRoomUserJoined(int, ServerInfo_User)), this, + SLOT(externalRoomUserJoined(int, ServerInfo_User))); connect(interface, SIGNAL(externalRoomUserLeft(int, QString)), this, SLOT(externalRoomUserLeft(int, QString))); - connect(interface, SIGNAL(externalRoomSay(int, QString, QString)), this, SLOT(externalRoomSay(int, QString, QString))); - connect(interface, SIGNAL(externalRoomGameListChanged(int, ServerInfo_Game)), this, SLOT(externalRoomGameListChanged(int, ServerInfo_Game))); - connect(interface, SIGNAL(joinGameCommandReceived(Command_JoinGame, int, int, int, qint64)), this, SLOT(externalJoinGameCommandReceived(Command_JoinGame, int, int, int, qint64))); - connect(interface, SIGNAL(gameCommandContainerReceived(CommandContainer, int, int, qint64)), this, SLOT(externalGameCommandContainerReceived(CommandContainer, int, int, qint64))); - connect(interface, SIGNAL(responseReceived(Response, qint64)), this, SLOT(externalResponseReceived(Response, qint64))); - connect(interface, SIGNAL(gameEventContainerReceived(GameEventContainer, qint64)), this, SLOT(externalGameEventContainerReceived(GameEventContainer, qint64))); + connect(interface, SIGNAL(externalRoomSay(int, QString, QString)), this, + SLOT(externalRoomSay(int, QString, QString))); + connect(interface, SIGNAL(externalRoomGameListChanged(int, ServerInfo_Game)), this, + SLOT(externalRoomGameListChanged(int, ServerInfo_Game))); + connect(interface, SIGNAL(joinGameCommandReceived(Command_JoinGame, int, int, int, qint64)), this, + SLOT(externalJoinGameCommandReceived(Command_JoinGame, int, int, int, qint64))); + connect(interface, SIGNAL(gameCommandContainerReceived(CommandContainer, int, int, qint64)), this, + SLOT(externalGameCommandContainerReceived(CommandContainer, int, int, qint64))); + connect(interface, SIGNAL(responseReceived(Response, qint64)), this, + SLOT(externalResponseReceived(Response, qint64))); + connect(interface, SIGNAL(gameEventContainerReceived(GameEventContainer, qint64)), this, + SLOT(externalGameEventContainerReceived(GameEventContainer, qint64))); } void Servatrice::removeIslInterface(int serverId) { // Only call with islLock locked for writing - // XXX we probably need to delete everything that belonged to it... <-- THIS SHOULD BE FIXED FOR ISL FUNCTIONALITY TO WORK COMPLETLY! + // XXX we probably need to delete everything that belonged to it... <-- THIS SHOULD BE FIXED FOR ISL FUNCTIONALITY + // TO WORK COMPLETLY! islInterfaces.remove(serverId); } @@ -707,206 +749,257 @@ void Servatrice::doSendIslMessage(const IslMessage &msg, int serverId) // start helper functions -int Servatrice::getMaxUserTotal() const { +int Servatrice::getMaxUserTotal() const +{ return settingsCache->value("security/max_users_total", 500).toInt(); } -bool Servatrice::getMaxUserLimitEnabled() const { +bool Servatrice::getMaxUserLimitEnabled() const +{ return settingsCache->value("security/enable_max_user_limit", false).toBool(); } -QString Servatrice::getServerName() const { +QString Servatrice::getServerName() const +{ return settingsCache->value("server/name", "My Cockatrice server").toString(); } -int Servatrice::getServerID() const { +int Servatrice::getServerID() const +{ return settingsCache->value("server/id", 0).toInt(); } -bool Servatrice::getClientIDRequiredEnabled() const { +bool Servatrice::getClientIDRequiredEnabled() const +{ return settingsCache->value("server/requireclientid", 0).toBool(); } -bool Servatrice::getRegOnlyServerEnabled() const { +bool Servatrice::getRegOnlyServerEnabled() const +{ return settingsCache->value("authentication/regonly", 0).toBool(); } -QString Servatrice::getAuthenticationMethodString() const { +QString Servatrice::getAuthenticationMethodString() const +{ return settingsCache->value("authentication/method").toString(); } -bool Servatrice::getStoreReplaysEnabled() const { +bool Servatrice::getStoreReplaysEnabled() const +{ return settingsCache->value("game/store_replays", true).toBool(); } -int Servatrice::getMaxTcpUserLimit() const { +int Servatrice::getMaxTcpUserLimit() const +{ return settingsCache->value("security/max_users_tcp", 500).toInt(); } -int Servatrice::getMaxWebSocketUserLimit() const { +int Servatrice::getMaxWebSocketUserLimit() const +{ return settingsCache->value("security/max_users_websocket", 500).toInt(); } -bool Servatrice::getRegistrationEnabled() const { +bool Servatrice::getRegistrationEnabled() const +{ return settingsCache->value("registration/enabled", false).toBool(); } -bool Servatrice::getRequireEmailForRegistrationEnabled() const { +bool Servatrice::getRequireEmailForRegistrationEnabled() const +{ return settingsCache->value("registration/requireemail", true).toBool(); } -bool Servatrice::getRequireEmailActivationEnabled() const { +bool Servatrice::getRequireEmailActivationEnabled() const +{ return settingsCache->value("registration/requireemailactivation", true).toBool(); } -QString Servatrice::getRequiredFeatures() const { +QString Servatrice::getRequiredFeatures() const +{ return settingsCache->value("server/requiredfeatures", "").toString(); } -QString Servatrice::getDBTypeString() const { +QString Servatrice::getDBTypeString() const +{ return settingsCache->value("database/type").toString(); } -QString Servatrice::getDBPrefixString() const { +QString Servatrice::getDBPrefixString() const +{ return settingsCache->value("database/prefix").toString(); } -QString Servatrice::getDBHostNameString() const { +QString Servatrice::getDBHostNameString() const +{ return settingsCache->value("database/hostname").toString(); } -QString Servatrice::getDBDatabaseNameString() const { +QString Servatrice::getDBDatabaseNameString() const +{ return settingsCache->value("database/database").toString(); } -QString Servatrice::getDBUserNameString() const { +QString Servatrice::getDBUserNameString() const +{ return settingsCache->value("database/user").toString(); } -QString Servatrice::getDBPasswordString() const { +QString Servatrice::getDBPasswordString() const +{ return settingsCache->value("database/password").toString(); } -QString Servatrice::getRoomsMethodString() const { +QString Servatrice::getRoomsMethodString() const +{ return settingsCache->value("rooms/method").toString(); } -int Servatrice::getMaxGameInactivityTime() const { +int Servatrice::getMaxGameInactivityTime() const +{ return settingsCache->value("game/max_game_inactivity_time", 120).toInt(); } -int Servatrice::getMaxPlayerInactivityTime() const { +int Servatrice::getMaxPlayerInactivityTime() const +{ return settingsCache->value("server/max_player_inactivity_time", 15).toInt(); } -int Servatrice::getClientKeepAlive() const { +int Servatrice::getClientKeepAlive() const +{ return settingsCache->value("server/clientkeepalive", 1).toInt(); } -int Servatrice::getMaxUsersPerAddress() const { +int Servatrice::getMaxUsersPerAddress() const +{ return settingsCache->value("security/max_users_per_address", 4).toInt(); } -int Servatrice::getMessageCountingInterval() const { +int Servatrice::getMessageCountingInterval() const +{ return settingsCache->value("security/message_counting_interval", 10).toInt(); } -int Servatrice::getMaxMessageCountPerInterval() const { +int Servatrice::getMaxMessageCountPerInterval() const +{ return settingsCache->value("security/max_message_count_per_interval", 15).toInt(); } -int Servatrice::getMaxMessageSizePerInterval() const { +int Servatrice::getMaxMessageSizePerInterval() const +{ return settingsCache->value("security/max_message_size_per_interval", 1000).toInt(); } -int Servatrice::getMaxGamesPerUser() const { +int Servatrice::getMaxGamesPerUser() const +{ return settingsCache->value("security/max_games_per_user", 5).toInt(); } -int Servatrice::getCommandCountingInterval() const { +int Servatrice::getCommandCountingInterval() const +{ return settingsCache->value("game/command_counting_interval", 10).toInt(); } -int Servatrice::getMaxCommandCountPerInterval() const { +int Servatrice::getMaxCommandCountPerInterval() const +{ return settingsCache->value("game/max_command_count_per_interval", 20).toInt(); } -int Servatrice::getServerStatusUpdateTime() const { +int Servatrice::getServerStatusUpdateTime() const +{ return settingsCache->value("server/statusupdate", 15000).toInt(); } -int Servatrice::getNumberOfTCPPools() const { +int Servatrice::getNumberOfTCPPools() const +{ return settingsCache->value("server/number_pools", 1).toInt(); } -int Servatrice::getServerTCPPort() const { +int Servatrice::getServerTCPPort() const +{ return settingsCache->value("server/port", 4747).toInt(); } -int Servatrice::getNumberOfWebSocketPools() const { +int Servatrice::getNumberOfWebSocketPools() const +{ return settingsCache->value("server/websocket_number_pools", 1).toInt(); } -int Servatrice::getServerWebSocketPort() const { +int Servatrice::getServerWebSocketPort() const +{ return settingsCache->value("server/websocket_port", 4748).toInt(); } -bool Servatrice::getISLNetworkEnabled() const { +bool Servatrice::getISLNetworkEnabled() const +{ return settingsCache->value("servernetwork/active", false).toBool(); } -QString Servatrice::getISLNetworkSSLCertFile() const { +QString Servatrice::getISLNetworkSSLCertFile() const +{ return settingsCache->value("servernetwork/ssl_cert").toString(); } -QString Servatrice::getISLNetworkSSLKeyFile() const { +QString Servatrice::getISLNetworkSSLKeyFile() const +{ return settingsCache->value("servernetwork/ssl_key").toString(); } -int Servatrice::getISLNetworkPort() const { +int Servatrice::getISLNetworkPort() const +{ return settingsCache->value("servernetwork/port", 14747).toInt(); } -int Servatrice::getIdleClientTimeout() const { +int Servatrice::getIdleClientTimeout() const +{ return settingsCache->value("server/idleclienttimeout", 3600).toInt(); } -bool Servatrice::getEnableLogQuery() const { +bool Servatrice::getEnableLogQuery() const +{ return settingsCache->value("logging/enablelogquery", false).toBool(); } -int Servatrice::getMaxAccountsPerEmail() const { +int Servatrice::getMaxAccountsPerEmail() const +{ return settingsCache->value("registration/maxaccountsperemail", 0).toInt(); } -bool Servatrice::getEnableInternalSMTPClient() const { +bool Servatrice::getEnableInternalSMTPClient() const +{ return settingsCache->value("smtp/enableinternalsmtpclient", true).toBool(); } -bool Servatrice::getEnableForgotPassword() const { +bool Servatrice::getEnableForgotPassword() const +{ return settingsCache->value("forgotpassword/enable", false).toBool(); } -int Servatrice::getForgotPasswordTokenLife() const { +int Servatrice::getForgotPasswordTokenLife() const +{ return settingsCache->value("forgotpassword/tokenlife", 60).toInt(); } -bool Servatrice::getEnableForgotPasswordChallenge() const { +bool Servatrice::getEnableForgotPasswordChallenge() const +{ return settingsCache->value("forgotpassword/enablechallenge", false).toBool(); } - -QString Servatrice::getEmailBlackList() const { + +QString Servatrice::getEmailBlackList() const +{ return settingsCache->value("registration/emailproviderblacklist").toString(); } -bool Servatrice::getEnableAudit() const { +bool Servatrice::getEnableAudit() const +{ return settingsCache->value("audit/enable_audit", true).toBool(); } -bool Servatrice::getEnableRegistrationAudit() const { +bool Servatrice::getEnableRegistrationAudit() const +{ return settingsCache->value("audit/enable_registration_audit", true).toBool(); } -bool Servatrice::getEnableForgotPasswordAudit() const { +bool Servatrice::getEnableForgotPasswordAudit() const +{ return settingsCache->value("audit/enable_forgotpassword_audit", true).toBool(); } diff --git a/servatrice/src/servatrice.h b/servatrice/src/servatrice.h index 97c4ddba..76619697 100644 --- a/servatrice/src/servatrice.h +++ b/servatrice/src/servatrice.h @@ -22,17 +22,16 @@ #include #if QT_VERSION > 0x050300 - #include +#include #endif -#include -#include -#include +#include "server.h" #include +#include +#include #include #include -#include -#include "server.h" - +#include +#include Q_DECLARE_METATYPE(QSqlDatabase) @@ -47,28 +46,37 @@ class AbstractServerSocketInterface; class IslInterface; class FeatureSet; -class Servatrice_GameServer : public QTcpServer { +class Servatrice_GameServer : public QTcpServer +{ Q_OBJECT private: Servatrice *server; QList connectionPools; + public: Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent = 0); ~Servatrice_GameServer(); + protected: void incomingConnection(qintptr socketDescriptor); Servatrice_ConnectionPool *findLeastUsedConnectionPool(); }; #if QT_VERSION > 0x050300 -class Servatrice_WebsocketGameServer : public QWebSocketServer { +class Servatrice_WebsocketGameServer : public QWebSocketServer +{ Q_OBJECT private: Servatrice *server; QList connectionPools; + public: - Servatrice_WebsocketGameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent = 0); + Servatrice_WebsocketGameServer(Servatrice *_server, + int _numberPools, + const QSqlDatabase &_sqlDatabase, + QObject *parent = 0); ~Servatrice_WebsocketGameServer(); + protected: Servatrice_ConnectionPool *findLeastUsedConnectionPool(); protected slots: @@ -76,20 +84,29 @@ protected slots: }; #endif -class Servatrice_IslServer : public QTcpServer { +class Servatrice_IslServer : public QTcpServer +{ Q_OBJECT private: Servatrice *server; QSslCertificate cert; QSslKey privateKey; + public: - Servatrice_IslServer(Servatrice *_server, const QSslCertificate &_cert, const QSslKey &_privateKey, QObject *parent = 0) - : QTcpServer(parent), server(_server), cert(_cert), privateKey(_privateKey) { } + Servatrice_IslServer(Servatrice *_server, + const QSslCertificate &_cert, + const QSslKey &_privateKey, + QObject *parent = 0) + : QTcpServer(parent), server(_server), cert(_cert), privateKey(_privateKey) + { + } + protected: void incomingConnection(qintptr socketDescriptor); }; -class ServerProperties { +class ServerProperties +{ public: int id; QSslCertificate cert; @@ -98,22 +115,40 @@ public: int gamePort; int controlPort; - ServerProperties(int _id, const QSslCertificate &_cert, const QString &_hostname, const QHostAddress &_address, int _gamePort, int _controlPort) - : id(_id), cert(_cert), hostname(_hostname), address(_address), gamePort(_gamePort), controlPort(_controlPort) { } + ServerProperties(int _id, + const QSslCertificate &_cert, + const QString &_hostname, + const QHostAddress &_address, + int _gamePort, + int _controlPort) + : id(_id), cert(_cert), hostname(_hostname), address(_address), gamePort(_gamePort), controlPort(_controlPort) + { + } }; class Servatrice : public Server { Q_OBJECT public: - enum AuthenticationMethod { AuthenticationNone, AuthenticationSql, AuthenticationPassword }; + enum AuthenticationMethod + { + AuthenticationNone, + AuthenticationSql, + AuthenticationPassword + }; private slots: void statusUpdate(); void shutdownTimeout(); + protected: void doSendIslMessage(const IslMessage &msg, int serverId); + private: - enum DatabaseType { DatabaseNone, DatabaseMySql }; + enum DatabaseType + { + DatabaseNone, + DatabaseMySql + }; AuthenticationMethod authenticationMethod; DatabaseType databaseType; QTimer *pingClock, *statusUpdateClock; @@ -167,22 +202,45 @@ public slots: void scheduleShutdown(const QString &reason, int minutes); void updateLoginMessage(); void setRequiredFeatures(const QString featureList); + public: Servatrice(QObject *parent = 0); ~Servatrice(); bool initServer(); - QMap getServerRequiredFeatureList() const { return serverRequiredFeatureList; } - QString getOfficialWarningsList() const { return officialWarnings; } + QMap getServerRequiredFeatureList() const + { + return serverRequiredFeatureList; + } + QString getOfficialWarningsList() const + { + return officialWarnings; + } QString getServerName() const; - QString getLoginMessage() const { QMutexLocker locker(&loginMessageMutex); return loginMessage; } + QString getLoginMessage() const + { + QMutexLocker locker(&loginMessageMutex); + return loginMessage; + } QString getRequiredFeatures() const; QString getAuthenticationMethodString() const; QString getDBTypeString() const; - QString getDbPrefix() const { return dbPrefix; } + QString getDbPrefix() const + { + return dbPrefix; + } QString getEmailBlackList() const; - AuthenticationMethod getAuthenticationMethod() const { return authenticationMethod; } - bool permitUnregisteredUsers() const { return authenticationMethod != AuthenticationNone; } - bool getGameShouldPing() const { return true; } + AuthenticationMethod getAuthenticationMethod() const + { + return authenticationMethod; + } + bool permitUnregisteredUsers() const + { + return authenticationMethod != AuthenticationNone; + } + bool getGameShouldPing() const + { + return true; + } bool getClientIDRequiredEnabled() const; bool getRegOnlyServerEnabled() const; bool getMaxUserLimitEnabled() const; diff --git a/servatrice/src/servatrice_connection_pool.cpp b/servatrice/src/servatrice_connection_pool.cpp index a2f849be..b1b36071 100644 --- a/servatrice/src/servatrice_connection_pool.cpp +++ b/servatrice/src/servatrice_connection_pool.cpp @@ -3,13 +3,12 @@ #include Servatrice_ConnectionPool::Servatrice_ConnectionPool(Servatrice_DatabaseInterface *_databaseInterface) - : databaseInterface(_databaseInterface), - clientCount(0) + : databaseInterface(_databaseInterface), clientCount(0) { } Servatrice_ConnectionPool::~Servatrice_ConnectionPool() { - delete databaseInterface; - thread()->quit(); + delete databaseInterface; + thread()->quit(); } diff --git a/servatrice/src/servatrice_connection_pool.h b/servatrice/src/servatrice_connection_pool.h index f1bbc26f..2814089e 100644 --- a/servatrice/src/servatrice_connection_pool.h +++ b/servatrice/src/servatrice_connection_pool.h @@ -1,29 +1,46 @@ #ifndef SERVATRICE_CONNECTION_POOL_H #define SERVATRICE_CONNECTION_POOL_H -#include #include #include +#include class Servatrice_DatabaseInterface; -class Servatrice_ConnectionPool : public QObject { - Q_OBJECT +class Servatrice_ConnectionPool : public QObject +{ + Q_OBJECT private: - Servatrice_DatabaseInterface *databaseInterface; - bool threaded; - mutable QMutex clientCountMutex; - int clientCount; + Servatrice_DatabaseInterface *databaseInterface; + bool threaded; + mutable QMutex clientCountMutex; + int clientCount; + public: - Servatrice_ConnectionPool(Servatrice_DatabaseInterface *_databaseInterface); - ~Servatrice_ConnectionPool(); - - Servatrice_DatabaseInterface *getDatabaseInterface() const { return databaseInterface; } - - int getClientCount() const { QMutexLocker locker(&clientCountMutex); return clientCount; } - void addClient() { QMutexLocker locker(&clientCountMutex); ++clientCount; } + Servatrice_ConnectionPool(Servatrice_DatabaseInterface *_databaseInterface); + ~Servatrice_ConnectionPool(); + + Servatrice_DatabaseInterface *getDatabaseInterface() const + { + return databaseInterface; + } + + int getClientCount() const + { + QMutexLocker locker(&clientCountMutex); + return clientCount; + } + void addClient() + { + QMutexLocker locker(&clientCountMutex); + ++clientCount; + } public slots: - void removeClient() { QMutexLocker locker(&clientCountMutex); --clientCount; } + void removeClient() + { + QMutexLocker locker(&clientCountMutex); + --clientCount; + } }; #endif diff --git a/servatrice/src/servatrice_database_interface.cpp b/servatrice/src/servatrice_database_interface.cpp index e742b3a0..2ce5fff7 100644 --- a/servatrice/src/servatrice_database_interface.cpp +++ b/servatrice/src/servatrice_database_interface.cpp @@ -1,20 +1,18 @@ -#include "servatrice.h" #include "servatrice_database_interface.h" +#include "decklist.h" #include "passwordhasher.h" +#include "pb/game_replay.pb.h" +#include "servatrice.h" #include "serversocketinterface.h" #include "settingscache.h" -#include "decklist.h" -#include "pb/game_replay.pb.h" +#include +#include #include #include #include -#include -#include Servatrice_DatabaseInterface::Servatrice_DatabaseInterface(int _instanceId, Servatrice *_server) - : instanceId(_instanceId), - sqlDatabase(QSqlDatabase()), - server(_server) + : instanceId(_instanceId), sqlDatabase(QSqlDatabase()), server(_server) { } @@ -35,8 +33,10 @@ void Servatrice_DatabaseInterface::initDatabase(const QSqlDatabase &_sqlDatabase } } -bool Servatrice_DatabaseInterface::initDatabase(const QString &type, const QString &hostName, - const QString &databaseName, const QString &userName, +bool Servatrice_DatabaseInterface::initDatabase(const QString &type, + const QString &hostName, + const QString &databaseName, + const QString &userName, const QString &password) { sqlDatabase = QSqlDatabase::addDatabase(type, "main"); @@ -62,23 +62,34 @@ bool Servatrice_DatabaseInterface::openDatabase() QSqlQuery *versionQuery = prepareQuery("select version from {prefix}_schema_version limit 1"); if (!execSqlQuery(versionQuery)) { - qCritical() << QString("[%1] Error opening database: unable to load database schema version (hint: ensure the cockatrice_schema_version exists)").arg(poolStr); + qCritical() << QString("[%1] Error opening database: unable to load database schema version (hint: ensure the " + "cockatrice_schema_version exists)") + .arg(poolStr); return false; } if (versionQuery->next()) { const int dbversion = versionQuery->value(0).toInt(); const int expectedversion = DATABASE_SCHEMA_VERSION; - if(dbversion < expectedversion) - { - qCritical() << QString("[%1] Error opening database: the database schema version is too old, you need to run the migrations to update it from version %2 to version %3").arg(poolStr).arg(dbversion).arg(expectedversion); + if (dbversion < expectedversion) { + qCritical() << QString("[%1] Error opening database: the database schema version is too old, you need to " + "run the migrations to update it from version %2 to version %3") + .arg(poolStr) + .arg(dbversion) + .arg(expectedversion); return false; - } else if(dbversion > expectedversion) { - qCritical() << QString("[%1] Error opening database: the database schema version %2 is too new, you need to update servatrice (this servatrice actually uses version %3)").arg(poolStr).arg(dbversion).arg(expectedversion); + } else if (dbversion > expectedversion) { + qCritical() << QString("[%1] Error opening database: the database schema version %2 is too new, you need " + "to update servatrice (this servatrice actually uses version %3)") + .arg(poolStr) + .arg(dbversion) + .arg(expectedversion); return false; } } else { - qCritical() << QString("[%1] Error opening database: unable to load database schema version (hint: ensure the cockatrice_schema_version contains a single record)").arg(poolStr); + qCritical() << QString("[%1] Error opening database: unable to load database schema version (hint: ensure the " + "cockatrice_schema_version contains a single record)") + .arg(poolStr); return false; } @@ -98,14 +109,14 @@ bool Servatrice_DatabaseInterface::checkSql() return true; } -QSqlQuery * Servatrice_DatabaseInterface::prepareQuery(const QString &queryText) +QSqlQuery *Servatrice_DatabaseInterface::prepareQuery(const QString &queryText) { - if(preparedStatements.contains(queryText)) + if (preparedStatements.contains(queryText)) return preparedStatements.value(queryText); QString prefixedQueryText = queryText; prefixedQueryText.replace("{prefix}", server->getDbPrefix()); - QSqlQuery * query = new QSqlQuery(sqlDatabase); + QSqlQuery *query = new QSqlQuery(sqlDatabase); query->prepare(prefixedQueryText); preparedStatements.insert(queryText, query); @@ -121,10 +132,10 @@ bool Servatrice_DatabaseInterface::execSqlQuery(QSqlQuery *query) return false; } -bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString & error) +bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString &error) { int minNameLength = settingsCache->value("users/minnamelength", 6).toInt(); - if(minNameLength < 1) + if (minNameLength < 1) minNameLength = 1; int maxNameLength = settingsCache->value("users/maxnamelength", 12).toInt(); bool allowLowercase = settingsCache->value("users/allowlowercase", true).toBool(); @@ -137,7 +148,16 @@ bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString disallowedWords.removeDuplicates(); QString disallowedRegExpStr = settingsCache->value("users/disallowedregexp", "").toString(); - error = QString("%1|%2|%3|%4|%5|%6|%7|%8|%9").arg(minNameLength).arg(maxNameLength).arg(allowLowercase).arg(allowUppercase).arg(allowNumerics).arg(allowPunctuationPrefix).arg(allowedPunctuation).arg(disallowedWordsStr).arg(disallowedRegExpStr); + error = QString("%1|%2|%3|%4|%5|%6|%7|%8|%9") + .arg(minNameLength) + .arg(maxNameLength) + .arg(allowLowercase) + .arg(allowUppercase) + .arg(allowNumerics) + .arg(allowPunctuationPrefix) + .arg(allowedPunctuation) + .arg(disallowedWordsStr) + .arg(disallowedRegExpStr); if (user.length() < minNameLength || user.length() > maxNameLength) return false; @@ -146,11 +166,13 @@ bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString return false; for (const QString &word : disallowedWords) { - if (user.contains(word, Qt::CaseInsensitive)) return false; + if (user.contains(word, Qt::CaseInsensitive)) + return false; } for (const QRegExp ®Exp : settingsCache->disallowedRegExp) { - if (regExp.exactMatch(user)) return false; + if (regExp.exactMatch(user)) + return false; } QString regEx("["); @@ -158,7 +180,7 @@ bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString regEx.append("a-z"); if (allowUppercase) regEx.append("A-Z"); - if(allowNumerics) + if (allowNumerics) regEx.append("0-9"); regEx.append(QRegExp::escape(allowedPunctuation)); regEx.append("]+"); @@ -167,7 +189,14 @@ bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString return re.exactMatch(user); } -bool Servatrice_DatabaseInterface::registerUser(const QString &userName, const QString &realName, ServerInfo_User_Gender const &gender, const QString &password, const QString &emailAddress, const QString &country, QString &token, bool active) +bool Servatrice_DatabaseInterface::registerUser(const QString &userName, + const QString &realName, + ServerInfo_User_Gender const &gender, + const QString &password, + const QString &emailAddress, + const QString &country, + QString &token, + bool active) { if (!checkSql()) return false; @@ -175,10 +204,13 @@ bool Servatrice_DatabaseInterface::registerUser(const QString &userName, const Q QString passwordSha512 = PasswordHasher::computeHash(password, PasswordHasher::generateRandomSalt()); token = active ? QString() : PasswordHasher::generateActivationToken(); - QSqlQuery *query = prepareQuery("insert into {prefix}_users " - "(name, realname, gender, password_sha512, email, country, registrationDate, active, token, admin, avatar_bmp, clientid, privlevel, privlevelStartDate, privlevelEndDate) " - "values " - "(:userName, :realName, :gender, :password_sha512, :email, :country, UTC_TIMESTAMP(), :active, :token, 0, '', '', 'NONE', UTC_TIMESTAMP(), UTC_TIMESTAMP())"); + QSqlQuery *query = + prepareQuery("insert into {prefix}_users " + "(name, realname, gender, password_sha512, email, country, registrationDate, active, token, " + "admin, avatar_bmp, clientid, privlevel, privlevelStartDate, privlevelEndDate) " + "values " + "(:userName, :realName, :gender, :password_sha512, :email, :country, UTC_TIMESTAMP(), :active, " + ":token, 0, '', '', 'NONE', UTC_TIMESTAMP(), UTC_TIMESTAMP())"); query->bindValue(":userName", userName); query->bindValue(":realName", realName); query->bindValue(":gender", getGenderChar(gender)); @@ -201,20 +233,21 @@ bool Servatrice_DatabaseInterface::activateUser(const QString &userName, const Q if (!checkSql()) return false; - QSqlQuery *activateQuery = prepareQuery("select name from {prefix}_users where active=0 and name=:username and token=:token"); + QSqlQuery *activateQuery = + prepareQuery("select name from {prefix}_users where active=0 and name=:username and token=:token"); activateQuery->bindValue(":username", userName); activateQuery->bindValue(":token", token); if (!execSqlQuery(activateQuery)) { - qDebug() << "Account activation failed: SQL error." << activateQuery->lastError()<< " sql: " << activateQuery->lastQuery(); + qDebug() << "Account activation failed: SQL error." << activateQuery->lastError() + << " sql: " << activateQuery->lastQuery(); return false; } if (activateQuery->next()) { const QString name = activateQuery->value(0).toString(); // redundant check - if(name == userName) - { + if (name == userName) { QSqlQuery *query = prepareQuery("update {prefix}_users set active=1 where name = :userName"); query->bindValue(":userName", userName); @@ -244,58 +277,69 @@ QChar Servatrice_DatabaseInterface::getGenderChar(ServerInfo_User_Gender const & } } -AuthenticationResult Servatrice_DatabaseInterface::checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, const QString &clientId, QString &reasonStr, int &banSecondsLeft) +AuthenticationResult Servatrice_DatabaseInterface::checkUserPassword(Server_ProtocolHandler *handler, + const QString &user, + const QString &password, + const QString &clientId, + QString &reasonStr, + int &banSecondsLeft) { switch (server->getAuthenticationMethod()) { - case Servatrice::AuthenticationNone: return UnknownUser; - case Servatrice::AuthenticationPassword: { - QString configPassword = settingsCache->value("authentication/password").toString(); - if (configPassword == password) - return PasswordRight; - - return NotLoggedIn; - } - case Servatrice::AuthenticationSql: { - if (!checkSql()) + case Servatrice::AuthenticationNone: return UnknownUser; + case Servatrice::AuthenticationPassword: { + QString configPassword = settingsCache->value("authentication/password").toString(); + if (configPassword == password) + return PasswordRight; - if (!usernameIsValid(user, reasonStr)) - return UsernameInvalid; - - if (checkUserIsBanned(handler->getAddress(), user, clientId, reasonStr, banSecondsLeft)) - return UserIsBanned; - - QSqlQuery *passwordQuery = prepareQuery("select password_sha512, active from {prefix}_users where name = :name"); - passwordQuery->bindValue(":name", user); - if (!execSqlQuery(passwordQuery)) { - qDebug("Login denied: SQL error"); return NotLoggedIn; } + case Servatrice::AuthenticationSql: { + if (!checkSql()) + return UnknownUser; - if (passwordQuery->next()) { - const QString correctPassword = passwordQuery->value(0).toString(); - const bool userIsActive = passwordQuery->value(1).toBool(); - if(!userIsActive) { - qDebug("Login denied: user not active"); - return UserIsInactive; - } - if (correctPassword == PasswordHasher::computeHash(password, correctPassword.left(16))) { - qDebug("Login accepted: password right"); - return PasswordRight; - } else { - qDebug("Login denied: password wrong"); + if (!usernameIsValid(user, reasonStr)) + return UsernameInvalid; + + if (checkUserIsBanned(handler->getAddress(), user, clientId, reasonStr, banSecondsLeft)) + return UserIsBanned; + + QSqlQuery *passwordQuery = + prepareQuery("select password_sha512, active from {prefix}_users where name = :name"); + passwordQuery->bindValue(":name", user); + if (!execSqlQuery(passwordQuery)) { + qDebug("Login denied: SQL error"); return NotLoggedIn; } - } else { - qDebug("Login accepted: unknown user"); - return UnknownUser; + + if (passwordQuery->next()) { + const QString correctPassword = passwordQuery->value(0).toString(); + const bool userIsActive = passwordQuery->value(1).toBool(); + if (!userIsActive) { + qDebug("Login denied: user not active"); + return UserIsInactive; + } + if (correctPassword == PasswordHasher::computeHash(password, correctPassword.left(16))) { + qDebug("Login accepted: password right"); + return PasswordRight; + } else { + qDebug("Login denied: password wrong"); + return NotLoggedIn; + } + } else { + qDebug("Login accepted: unknown user"); + return UnknownUser; + } } } - } return UnknownUser; } -bool Servatrice_DatabaseInterface::checkUserIsBanned(const QString &ipAddress, const QString &userName, const QString &clientId, QString &banReason, int &banSecondsRemaining) +bool Servatrice_DatabaseInterface::checkUserIsBanned(const QString &ipAddress, + const QString &userName, + const QString &clientId, + QString &banReason, + int &banSecondsRemaining) { if (server->getAuthenticationMethod() != Servatrice::AuthenticationSql) return false; @@ -305,27 +349,29 @@ bool Servatrice_DatabaseInterface::checkUserIsBanned(const QString &ipAddress, c return false; } - return - checkUserIsIpBanned(ipAddress, banReason, banSecondsRemaining) || checkUserIsNameBanned(userName, banReason, banSecondsRemaining) || checkUserIsIdBanned(clientId, banReason, banSecondsRemaining); - + return checkUserIsIpBanned(ipAddress, banReason, banSecondsRemaining) || + checkUserIsNameBanned(userName, banReason, banSecondsRemaining) || + checkUserIsIdBanned(clientId, banReason, banSecondsRemaining); } -bool Servatrice_DatabaseInterface::checkUserIsIdBanned(const QString &clientId, QString &banReason, int &banSecondsRemaining) +bool Servatrice_DatabaseInterface::checkUserIsIdBanned(const QString &clientId, + QString &banReason, + int &banSecondsRemaining) { if (clientId.isEmpty()) return false; - QSqlQuery *idBanQuery = prepareQuery( - "select" - " timestampdiff(second, now(), date_add(b.time_from, interval b.minutes minute))," - " b.minutes <=> 0," - " b.visible_reason" - " from {prefix}_bans b" - " where" - " b.time_from = (select max(c.time_from)" - " from {prefix}_bans c" - " where c.clientid = :id)" - " and b.clientid = :id2"); + QSqlQuery *idBanQuery = + prepareQuery("select" + " timestampdiff(second, now(), date_add(b.time_from, interval b.minutes minute))," + " b.minutes <=> 0," + " b.visible_reason" + " from {prefix}_bans b" + " where" + " b.time_from = (select max(c.time_from)" + " from {prefix}_bans c" + " where c.clientid = :id)" + " and b.clientid = :id2"); idBanQuery->bindValue(":id", clientId); idBanQuery->bindValue(":id2", clientId); @@ -347,10 +393,14 @@ bool Servatrice_DatabaseInterface::checkUserIsIdBanned(const QString &clientId, return false; } - -bool Servatrice_DatabaseInterface::checkUserIsNameBanned(const QString &userName, QString &banReason, int &banSecondsRemaining) +bool Servatrice_DatabaseInterface::checkUserIsNameBanned(const QString &userName, + QString &banReason, + int &banSecondsRemaining) { - QSqlQuery *nameBanQuery = prepareQuery("select timestampdiff(second, now(), date_add(b.time_from, interval b.minutes minute)), b.minutes <=> 0, b.visible_reason from {prefix}_bans b where b.time_from = (select max(c.time_from) from {prefix}_bans c where c.user_name = :name2) and b.user_name = :name1"); + QSqlQuery *nameBanQuery = + prepareQuery("select timestampdiff(second, now(), date_add(b.time_from, interval b.minutes minute)), b.minutes " + "<=> 0, b.visible_reason from {prefix}_bans b where b.time_from = (select max(c.time_from) from " + "{prefix}_bans c where c.user_name = :name2) and b.user_name = :name1"); nameBanQuery->bindValue(":name1", userName); nameBanQuery->bindValue(":name2", userName); if (!execSqlQuery(nameBanQuery)) { @@ -371,19 +421,21 @@ bool Servatrice_DatabaseInterface::checkUserIsNameBanned(const QString &userName return false; } -bool Servatrice_DatabaseInterface::checkUserIsIpBanned(const QString &ipAddress, QString &banReason, int &banSecondsRemaining) +bool Servatrice_DatabaseInterface::checkUserIsIpBanned(const QString &ipAddress, + QString &banReason, + int &banSecondsRemaining) { - QSqlQuery *ipBanQuery = prepareQuery( - "select" - " timestampdiff(second, now(), date_add(b.time_from, interval b.minutes minute))," - " b.minutes <=> 0," - " b.visible_reason" - " from {prefix}_bans b" - " where" - " b.time_from = (select max(c.time_from)" - " from {prefix}_bans c" - " where c.ip_address = :address)" - " and b.ip_address = :address2"); + QSqlQuery *ipBanQuery = + prepareQuery("select" + " timestampdiff(second, now(), date_add(b.time_from, interval b.minutes minute))," + " b.minutes <=> 0," + " b.visible_reason" + " from {prefix}_bans b" + " where" + " b.time_from = (select max(c.time_from)" + " from {prefix}_bans c" + " where c.ip_address = :address)" + " and b.ip_address = :address2"); ipBanQuery->bindValue(":address", ipAddress); ipBanQuery->bindValue(":address2", ipAddress); @@ -458,7 +510,8 @@ bool Servatrice_DatabaseInterface::isInBuddyList(const QString &whoseList, const int id1 = getUserIdInDB(whoseList); int id2 = getUserIdInDB(who); - QSqlQuery *query = prepareQuery("select 1 from {prefix}_buddylist where id_user1 = :id_user1 and id_user2 = :id_user2"); + QSqlQuery *query = + prepareQuery("select 1 from {prefix}_buddylist where id_user1 = :id_user1 and id_user2 = :id_user2"); query->bindValue(":id_user1", id1); query->bindValue(":id_user2", id2); if (!execSqlQuery(query)) @@ -477,7 +530,8 @@ bool Servatrice_DatabaseInterface::isInIgnoreList(const QString &whoseList, cons int id1 = getUserIdInDB(whoseList); int id2 = getUserIdInDB(who); - QSqlQuery *query = prepareQuery("select 1 from {prefix}_ignorelist where id_user1 = :id_user1 and id_user2 = :id_user2"); + QSqlQuery *query = + prepareQuery("select 1 from {prefix}_ignorelist where id_user1 = :id_user1 and id_user2 = :id_user2"); query->bindValue(":id_user1", id1); query->bindValue(":id_user2", id2); if (!execSqlQuery(query)) @@ -551,7 +605,9 @@ ServerInfo_User Servatrice_DatabaseInterface::getUserData(const QString &name, b if (!checkSql()) return result; - QSqlQuery *query = prepareQuery("select id, name, admin, country, privlevel, gender, realname, avatar_bmp, registrationDate, email, clientid from {prefix}_users where name = :name and active = 1"); + QSqlQuery *query = + prepareQuery("select id, name, admin, country, privlevel, gender, realname, avatar_bmp, registrationDate, " + "email, clientid from {prefix}_users where name = :name and active = 1"); query->bindValue(":name", name); if (!execSqlQuery(query)) return result; @@ -560,15 +616,15 @@ ServerInfo_User Servatrice_DatabaseInterface::getUserData(const QString &name, b return evalUserQueryResult(query, true, withId); else return result; - } - else + } else return result; } void Servatrice_DatabaseInterface::clearSessionTables() { lockSessionTables(); - QSqlQuery *query = prepareQuery("update {prefix}_sessions set end_time=now() where end_time is null and id_server = :id_server"); + QSqlQuery *query = + prepareQuery("update {prefix}_sessions set end_time=now() where end_time is null and id_server = :id_server"); query->bindValue(":id_server", server->getServerID()); execSqlQuery(query); unlockSessionTables(); @@ -590,14 +646,18 @@ bool Servatrice_DatabaseInterface::userSessionExists(const QString &userName) { // Call only after lockSessionTables(). - QSqlQuery *query = prepareQuery("select 1 from {prefix}_sessions where user_name = :user_name and id_server = :id_server and end_time is null"); + QSqlQuery *query = prepareQuery( + "select 1 from {prefix}_sessions where user_name = :user_name and id_server = :id_server and end_time is null"); query->bindValue(":id_server", server->getServerID()); query->bindValue(":user_name", userName); execSqlQuery(query); return query->next(); } -qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const QString &address, const QString &clientId, const QString & connectionType) +qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, + const QString &address, + const QString &clientId, + const QString &connectionType) { if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone) return -1; @@ -605,7 +665,9 @@ qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const if (!checkSql()) return -1; - QSqlQuery *query = prepareQuery("insert into {prefix}_sessions (user_name, id_server, ip_address, start_time, clientid, connection_type) values(:user_name, :id_server, :ip_address, NOW(), :client_id, :connection_type)"); + QSqlQuery *query = prepareQuery("insert into {prefix}_sessions (user_name, id_server, ip_address, start_time, " + "clientid, connection_type) values(:user_name, :id_server, :ip_address, NOW(), " + ":client_id, :connection_type)"); query->bindValue(":user_name", userName); query->bindValue(":id_server", server->getServerID()); query->bindValue(":ip_address", address); @@ -642,7 +704,9 @@ QMap Servatrice_DatabaseInterface::getBuddyList(const if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) { checkSql(); - QSqlQuery *query = prepareQuery("select a.id, a.name, a.admin, a.country, a.privlevel from {prefix}_users a left join {prefix}_buddylist b on a.id = b.id_user2 left join {prefix}_users c on b.id_user1 = c.id where c.name = :name"); + QSqlQuery *query = prepareQuery("select a.id, a.name, a.admin, a.country, a.privlevel from {prefix}_users a " + "left join {prefix}_buddylist b on a.id = b.id_user2 left join {prefix}_users " + "c on b.id_user1 = c.id where c.name = :name"); query->bindValue(":name", name); if (!execSqlQuery(query)) return result; @@ -662,7 +726,9 @@ QMap Servatrice_DatabaseInterface::getIgnoreList(const if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) { checkSql(); - QSqlQuery *query = prepareQuery("select a.id, a.name, a.admin, a.country, a.privlevel from {prefix}_users a left join {prefix}_ignorelist b on a.id = b.id_user2 left join {prefix}_users c on b.id_user1 = c.id where c.name = :name"); + QSqlQuery *query = prepareQuery("select a.id, a.name, a.admin, a.country, a.privlevel from {prefix}_users a " + "left join {prefix}_ignorelist b on a.id = b.id_user2 left join {prefix}_users " + "c on b.id_user1 = c.id where c.name = :name"); query->bindValue(":name", name); if (!execSqlQuery(query)) return result; @@ -700,12 +766,17 @@ int Servatrice_DatabaseInterface::getNextReplayId() return query->lastInsertId().toInt(); } -void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName, const QStringList &roomGameTypes, const ServerInfo_Game &gameInfo, const QSet &allPlayersEver, const QSet &allSpectatorsEver, const QList &replayList) +void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName, + const QStringList &roomGameTypes, + const ServerInfo_Game &gameInfo, + const QSet &allPlayersEver, + const QSet &allSpectatorsEver, + const QList &replayList) { if (!checkSql()) return; - if (!settingsCache->value("game/store_replays", 1).toBool() ) + if (!settingsCache->value("game/store_replays", 1).toBool()) return; QVariantList gameIds1, playerNames, gameIds2, userIds, replayNames; @@ -733,14 +804,16 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName, blob.resize(size); replayList[i]->SerializeToArray(blob.data(), size); - replayIds.append(QVariant((qulonglong) replayList[i]->replay_id())); + replayIds.append(QVariant((qulonglong)replayList[i]->replay_id())); replayGameIds.append(gameInfo.game_id()); replayDurations.append(replayList[i]->duration_seconds()); replayBlobs.append(blob); } { - QSqlQuery *query = prepareQuery("update {prefix}_games set room_name=:room_name, descr=:descr, creator_name=:creator_name, password=:password, game_types=:game_types, player_count=:player_count, time_finished=now() where id=:id_game"); + QSqlQuery *query = prepareQuery("update {prefix}_games set room_name=:room_name, descr=:descr, " + "creator_name=:creator_name, password=:password, game_types=:game_types, " + "player_count=:player_count, time_finished=now() where id=:id_game"); query->bindValue(":room_name", roomName); query->bindValue(":id_game", gameInfo.game_id()); query->bindValue(":descr", QString::fromStdString(gameInfo.description())); @@ -752,13 +825,15 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName, return; } { - QSqlQuery *query = prepareQuery("insert into {prefix}_games_players (id_game, player_name) values (:id_game, :player_name)"); + QSqlQuery *query = + prepareQuery("insert into {prefix}_games_players (id_game, player_name) values (:id_game, :player_name)"); query->bindValue(":id_game", gameIds1); query->bindValue(":player_name", playerNames); query->execBatch(); } { - QSqlQuery *query = prepareQuery("update {prefix}_replays set id_game=:id_game, duration=:duration, replay=:replay where id=:id_replay"); + QSqlQuery *query = prepareQuery( + "update {prefix}_replays set id_game=:id_game, duration=:duration, replay=:replay where id=:id_replay"); query->bindValue(":id_replay", replayIds); query->bindValue(":id_game", replayGameIds); query->bindValue(":duration", replayDurations); @@ -766,7 +841,8 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName, query->execBatch(); } { - QSqlQuery *query = prepareQuery("insert into {prefix}_replays_access (id_game, id_player, replay_name) values (:id_game, :id_player, :replay_name)"); + QSqlQuery *query = prepareQuery("insert into {prefix}_replays_access (id_game, id_player, replay_name) values " + "(:id_game, :id_player, :replay_name)"); query->bindValue(":id_game", gameIds2); query->bindValue(":id_player", userIds); query->bindValue(":replay_name", replayNames); @@ -778,7 +854,8 @@ DeckList *Servatrice_DatabaseInterface::getDeckFromDatabase(int deckId, int user { checkSql(); - QSqlQuery *query = prepareQuery("select content from {prefix}_decklist_files where id = :id and id_user = :id_user"); + QSqlQuery *query = + prepareQuery("select content from {prefix}_decklist_files where id = :id and id_user = :id_user"); query->bindValue(":id", deckId); query->bindValue(":id_user", userId); execSqlQuery(query); @@ -791,28 +868,33 @@ DeckList *Servatrice_DatabaseInterface::getDeckFromDatabase(int deckId, int user return deck; } -void Servatrice_DatabaseInterface::logMessage(const int senderId, const QString &senderName, const QString &senderIp, const QString &logMessage, LogMessage_TargetType targetType, const int targetId, const QString &targetName) +void Servatrice_DatabaseInterface::logMessage(const int senderId, + const QString &senderName, + const QString &senderIp, + const QString &logMessage, + LogMessage_TargetType targetType, + const int targetId, + const QString &targetName) { QString targetTypeString; - switch(targetType) - { + switch (targetType) { case MessageTargetRoom: - if(!settingsCache->value("logging/log_user_msg_room", 0).toBool()) + if (!settingsCache->value("logging/log_user_msg_room", 0).toBool()) return; targetTypeString = "room"; break; case MessageTargetGame: - if(!settingsCache->value("logging/log_user_msg_game", 0).toBool()) + if (!settingsCache->value("logging/log_user_msg_game", 0).toBool()) return; targetTypeString = "game"; break; case MessageTargetChat: - if(!settingsCache->value("logging/log_user_msg_chat", 0).toBool()) + if (!settingsCache->value("logging/log_user_msg_chat", 0).toBool()) return; targetTypeString = "chat"; break; case MessageTargetIslRoom: - if(!settingsCache->value("logging/log_user_msg_isl", 0).toBool()) + if (!settingsCache->value("logging/log_user_msg_isl", 0).toBool()) return; targetTypeString = "room"; break; @@ -820,7 +902,9 @@ void Servatrice_DatabaseInterface::logMessage(const int senderId, const QString return; } - QSqlQuery *query = prepareQuery("insert into {prefix}_log (log_time, sender_id, sender_name, sender_ip, log_message, target_type, target_id, target_name) values (now(), :sender_id, :sender_name, :sender_ip, :log_message, :target_type, :target_id, :target_name)"); + QSqlQuery *query = prepareQuery("insert into {prefix}_log (log_time, sender_id, sender_name, sender_ip, " + "log_message, target_type, target_id, target_name) values (now(), :sender_id, " + ":sender_name, :sender_ip, :log_message, :target_type, :target_id, :target_name)"); query->bindValue(":sender_id", senderId < 1 ? QVariant() : senderId); query->bindValue(":sender_name", senderName); query->bindValue(":sender_ip", senderIp); @@ -831,9 +915,12 @@ void Servatrice_DatabaseInterface::logMessage(const int senderId, const QString execSqlQuery(query); } -bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user, const QString &oldPassword, const QString &newPassword, const bool &force = false) +bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user, + const QString &oldPassword, + const QString &newPassword, + const bool &force = false) { - if(server->getAuthenticationMethod() != Servatrice::AuthenticationSql) + if (server->getAuthenticationMethod() != Servatrice::AuthenticationSql) return false; if (!checkSql()) @@ -879,12 +966,12 @@ int Servatrice_DatabaseInterface::getActiveUserCount(QString connectionType) return userCount; QString text = "select count(*) from {prefix}_sessions where id_server = :serverid AND end_time is NULL"; - if(!connectionType.isEmpty()) - text +=" AND connection_type = :connection_type"; + if (!connectionType.isEmpty()) + text += " AND connection_type = :connection_type"; QSqlQuery *query = prepareQuery(text); query->bindValue(":serverid", server->getServerID()); - if(!connectionType.isEmpty()) + if (!connectionType.isEmpty()) query->bindValue(":connection_type", connectionType); if (!execSqlQuery(query)) @@ -906,15 +993,15 @@ void Servatrice_DatabaseInterface::updateUsersClientID(const QString &userName, query->bindValue(":clientid", userClientID); query->bindValue(":username", userName); execSqlQuery(query); - } -void Servatrice_DatabaseInterface::updateUsersLastLoginData(const QString &userName, const QString &clientVersion) { +void Servatrice_DatabaseInterface::updateUsersLastLoginData(const QString &userName, const QString &clientVersion) +{ if (!checkSql()) return; - int usersID=0; + int usersID = 0; QSqlQuery *query = prepareQuery("select id from {prefix}_users where name = :user_name"); query->bindValue(":user_name", userName); @@ -939,12 +1026,14 @@ void Servatrice_DatabaseInterface::updateUsersLastLoginData(const QString &userN } if (!userCount) { - query = prepareQuery("insert into {prefix}_user_analytics (id,client_ver,last_login) values (:user_id,:client_ver,NOW())"); + query = prepareQuery( + "insert into {prefix}_user_analytics (id,client_ver,last_login) values (:user_id,:client_ver,NOW())"); query->bindValue(":user_id", usersID); query->bindValue(":client_ver", clientVersion); execSqlQuery(query); } else { - query = prepareQuery("update {prefix}_user_analytics set last_login = NOW(), client_ver = :client_ver where id = :user_id"); + query = prepareQuery( + "update {prefix}_user_analytics set last_login = NOW(), client_ver = :client_ver where id = :user_id"); query->bindValue(":client_ver", clientVersion); query->bindValue(":user_id", usersID); execSqlQuery(query); @@ -960,7 +1049,9 @@ QList Servatrice_DatabaseInterface::getUserBanHistory(const QStr if (!checkSql()) return results; - QSqlQuery *query = prepareQuery("SELECT A.id_admin, A.time_from, A.minutes, A.reason, A.visible_reason, B.name AS name_admin FROM {prefix}_bans A LEFT JOIN {prefix}_users B ON A.id_admin=B.id WHERE A.user_name = :user_name"); + QSqlQuery *query = + prepareQuery("SELECT A.id_admin, A.time_from, A.minutes, A.reason, A.visible_reason, B.name AS name_admin FROM " + "{prefix}_bans A LEFT JOIN {prefix}_users B ON A.id_admin=B.id WHERE A.user_name = :user_name"); query->bindValue(":user_name", userName); if (!execSqlQuery(query)) { @@ -968,7 +1059,7 @@ QList Servatrice_DatabaseInterface::getUserBanHistory(const QStr return results; } - while (query->next()){ + while (query->next()) { banDetails.set_admin_id(QString(query->value(0).toString()).toStdString()); banDetails.set_admin_name(QString(query->value(5).toString()).toStdString()); banDetails.set_ban_time(QString(query->value(1).toString()).toStdString()); @@ -981,13 +1072,18 @@ QList Servatrice_DatabaseInterface::getUserBanHistory(const QStr return results; } -bool Servatrice_DatabaseInterface::addWarning(const QString userName, const QString adminName, const QString warningReason, const QString clientID) +bool Servatrice_DatabaseInterface::addWarning(const QString userName, + const QString adminName, + const QString warningReason, + const QString clientID) { if (!checkSql()) return false; int userID = getUserIdInDB(userName); - QSqlQuery *query = prepareQuery("insert into {prefix}_warnings (user_id,user_name,mod_name,reason,time_of,clientid) values (:user_id,:user_name,:mod_name,:warn_reason,NOW(),:client_id)"); + QSqlQuery *query = + prepareQuery("insert into {prefix}_warnings (user_id,user_name,mod_name,reason,time_of,clientid) values " + "(:user_id,:user_name,:mod_name,:warn_reason,NOW(),:client_id)"); query->bindValue(":user_id", userID); query->bindValue(":user_name", userName); query->bindValue(":mod_name", adminName); @@ -1010,7 +1106,8 @@ QList Servatrice_DatabaseInterface::getUserWarnHistory(const return results; int userID = getUserIdInDB(userName); - QSqlQuery *query = prepareQuery("SELECT user_name, mod_name, reason, time_of FROM {prefix}_warnings WHERE user_id = :user_id"); + QSqlQuery *query = + prepareQuery("SELECT user_name, mod_name, reason, time_of FROM {prefix}_warnings WHERE user_id = :user_id"); query->bindValue(":user_id", userID); if (!execSqlQuery(query)) { @@ -1018,7 +1115,7 @@ QList Servatrice_DatabaseInterface::getUserWarnHistory(const return results; } - while (query->next()){ + while (query->next()) { warnDetails.set_user_name(QString(query->value(0).toString()).toStdString()); warnDetails.set_admin_name(QString(query->value(1).toString()).toStdString()); warnDetails.set_reason(QString(query->value(2).toString()).toStdString()); @@ -1029,7 +1126,16 @@ QList Servatrice_DatabaseInterface::getUserWarnHistory(const return results; } -QList Servatrice_DatabaseInterface::getMessageLogHistory(const QString &user, const QString &ipaddress, const QString &gamename, const QString &gameid, const QString &message, bool &chat, bool &game, bool &room, int &range, int &maxresults) +QList Servatrice_DatabaseInterface::getMessageLogHistory(const QString &user, + const QString &ipaddress, + const QString &gamename, + const QString &gameid, + const QString &message, + bool &chat, + bool &game, + bool &room, + int &range, + int &maxresults) { QList results; @@ -1084,13 +1190,27 @@ QList Servatrice_DatabaseInterface::getMessageLogHistory queryString.append(" LIMIT :limit_size"); QSqlQuery *query = prepareQuery(queryString); - if (!user.isEmpty()) { query->bindValue(":user_name", user); } - if (!ipaddress.isEmpty()) { query->bindValue(":ip_to_find", ipaddress); } - if (!gameid.isEmpty()) { query->bindValue(":game_id", gameid); } - if (!gamename.isEmpty()) { query->bindValue(":game_name", gamename); } - if (!message.isEmpty()) { query->bindValue(":log_message", message); } - if (range) { query->bindValue(":range_time", range); } - if (maxresults) { query->bindValue(":limit_size", maxresults); } + if (!user.isEmpty()) { + query->bindValue(":user_name", user); + } + if (!ipaddress.isEmpty()) { + query->bindValue(":ip_to_find", ipaddress); + } + if (!gameid.isEmpty()) { + query->bindValue(":game_id", gameid); + } + if (!gamename.isEmpty()) { + query->bindValue(":game_name", gamename); + } + if (!message.isEmpty()) { + query->bindValue(":log_message", message); + } + if (range) { + query->bindValue(":range_time", range); + } + if (maxresults) { + query->bindValue(":limit_size", maxresults); + } if (!execSqlQuery(query)) { qDebug("Failed to collect log history information: SQL Error"); @@ -1165,7 +1285,8 @@ bool Servatrice_DatabaseInterface::doesForgotPasswordExist(const QString &user) if (!checkSql()) return false; - QSqlQuery *query = prepareQuery("select count(name) from {prefix}_forgot_password where name = :user_name AND requestDate > (now() - interval :minutes minute)"); + QSqlQuery *query = prepareQuery("select count(name) from {prefix}_forgot_password where name = :user_name AND " + "requestDate > (now() - interval :minutes minute)"); query->bindValue(":user_name", user); query->bindValue(":minutes", QString::number(server->getForgotPasswordTokenLife())); @@ -1179,7 +1300,7 @@ bool Servatrice_DatabaseInterface::doesForgotPasswordExist(const QString &user) return false; } -bool Servatrice_DatabaseInterface::updateUserToken(const QString & token, const QString &user) +bool Servatrice_DatabaseInterface::updateUserToken(const QString &token, const QString &user) { if (!checkSql()) return false; @@ -1197,12 +1318,15 @@ bool Servatrice_DatabaseInterface::updateUserToken(const QString & token, const return false; } -bool Servatrice_DatabaseInterface::validateTableColumnStringData(const QString &table, const QString &column, const QString &_user, const QString &_datatocheck) +bool Servatrice_DatabaseInterface::validateTableColumnStringData(const QString &table, + const QString &column, + const QString &_user, + const QString &_datatocheck) { if (!checkSql()) return false; - if (table.isEmpty() || column.isEmpty() ||_user.isEmpty() || _datatocheck.isEmpty()) + if (table.isEmpty() || column.isEmpty() || _user.isEmpty() || _datatocheck.isEmpty()) return false; QString formatedQuery = QString("select %1 from %2 where name = :user_name").arg(column).arg(table); @@ -1219,18 +1343,25 @@ bool Servatrice_DatabaseInterface::validateTableColumnStringData(const QString & return false; } -void Servatrice_DatabaseInterface::addAuditRecord(const QString &user, const QString &ipaddress, const QString &clientid, const QString &action, const QString &details, const bool &results = false) +void Servatrice_DatabaseInterface::addAuditRecord(const QString &user, + const QString &ipaddress, + const QString &clientid, + const QString &action, + const QString &details, + const bool &results = false) { if (!checkSql()) return; - + if (!server->getEnableAudit()) return; - + if (user.isEmpty() || ipaddress.isEmpty() || clientid.isEmpty() || action.isEmpty()) return; - - QSqlQuery *query = prepareQuery("insert into {prefix}_audit (id_server,name,ip_address,clientid,incidentDate,action,results,details) values (:idserver,:username,:ipaddress,:clientid,NOW(),:action,:results,:details)"); + + QSqlQuery *query = prepareQuery("insert into {prefix}_audit " + "(id_server,name,ip_address,clientid,incidentDate,action,results,details) values " + "(:idserver,:username,:ipaddress,:clientid,NOW(),:action,:results,:details)"); query->bindValue(":idserver", server->getServerID()); query->bindValue(":username", user); query->bindValue(":ipaddress", ipaddress); diff --git a/servatrice/src/servatrice_database_interface.h b/servatrice/src/servatrice_database_interface.h index f5382ea5..8e1b9c04 100644 --- a/servatrice/src/servatrice_database_interface.h +++ b/servatrice/src/servatrice_database_interface.h @@ -1,10 +1,10 @@ #ifndef SERVATRICE_DATABASE_INTERFACE_H #define SERVATRICE_DATABASE_INTERFACE_H +#include +#include #include #include -#include -#include #include "server.h" #include "server_database_interface.h" @@ -13,7 +13,8 @@ class Servatrice; -class Servatrice_DatabaseInterface : public Server_DatabaseInterface { +class Servatrice_DatabaseInterface : public Server_DatabaseInterface +{ Q_OBJECT private: int instanceId; @@ -29,7 +30,12 @@ private: bool checkUserIsNameBanned(QString const &userName, QString &banReason, int &banSecondsRemaining); protected: - AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, const QString &clientId, QString &reasonStr, int &secondsLeft); + AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, + const QString &user, + const QString &password, + const QString &clientId, + QString &reasonStr, + int &secondsLeft); public slots: void initDatabase(const QSqlDatabase &_sqlDatabase); @@ -37,13 +43,19 @@ public slots: public: Servatrice_DatabaseInterface(int _instanceId, Servatrice *_server); ~Servatrice_DatabaseInterface(); - bool initDatabase(const QString &type, const QString &hostName, const QString &databaseName, - const QString &userName, const QString &password); + bool initDatabase(const QString &type, + const QString &hostName, + const QString &databaseName, + const QString &userName, + const QString &password); bool openDatabase(); bool checkSql(); - QSqlQuery * prepareQuery(const QString &queryText); + QSqlQuery *prepareQuery(const QString &queryText); bool execSqlQuery(QSqlQuery *query); - const QSqlDatabase &getDatabase() { return sqlDatabase; } + const QSqlDatabase &getDatabase() + { + return sqlDatabase; + } bool activeUserExists(const QString &user); bool userExists(const QString &user); @@ -53,40 +65,83 @@ public: bool isInBuddyList(const QString &whoseList, const QString &who); bool isInIgnoreList(const QString &whoseList, const QString &who); ServerInfo_User getUserData(const QString &name, bool withId = false); - void storeGameInformation(const QString &roomName, const QStringList &roomGameTypes, const ServerInfo_Game &gameInfo, - const QSet &allPlayersEver, const QSet&allSpectatorsEver, const QList &replayList); + void storeGameInformation(const QString &roomName, + const QStringList &roomGameTypes, + const ServerInfo_Game &gameInfo, + const QSet &allPlayersEver, + const QSet &allSpectatorsEver, + const QList &replayList); DeckList *getDeckFromDatabase(int deckId, int userId); int getNextGameId(); int getNextReplayId(); int getActiveUserCount(QString connectionType = QString()); - qint64 startSession(const QString &userName, const QString &address, const QString &clientId, const QString & connectionType); + qint64 startSession(const QString &userName, + const QString &address, + const QString &clientId, + const QString &connectionType); void endSession(qint64 sessionId); void clearSessionTables(); void lockSessionTables(); void unlockSessionTables(); bool userSessionExists(const QString &userName); - bool usernameIsValid(const QString &user, QString & error); - bool checkUserIsBanned(const QString &ipAddress, const QString &userName, const QString &clientId, QString &banReason, int &banSecondsRemaining); + bool usernameIsValid(const QString &user, QString &error); + bool checkUserIsBanned(const QString &ipAddress, + const QString &userName, + const QString &clientId, + QString &banReason, + int &banSecondsRemaining); int checkNumberOfUserAccounts(const QString &email); - bool registerUser(const QString &userName, const QString &realName, ServerInfo_User_Gender const &gender, const QString &password, const QString &emailAddress, const QString &country, QString &token, bool active = false); + bool registerUser(const QString &userName, + const QString &realName, + ServerInfo_User_Gender const &gender, + const QString &password, + const QString &emailAddress, + const QString &country, + QString &token, + bool active = false); bool activateUser(const QString &userName, const QString &token); void updateUsersClientID(const QString &userName, const QString &userClientID); void updateUsersLastLoginData(const QString &userName, const QString &clientVersion); - void logMessage(const int senderId, const QString &senderName, const QString &senderIp, const QString &logMessage, LogMessage_TargetType targetType, const int targetId, const QString &targetName); - bool changeUserPassword(const QString &user, const QString &oldPassword, const QString &newPassword, const bool &force); + void logMessage(const int senderId, + const QString &senderName, + const QString &senderIp, + const QString &logMessage, + LogMessage_TargetType targetType, + const int targetId, + const QString &targetName); + bool + changeUserPassword(const QString &user, const QString &oldPassword, const QString &newPassword, const bool &force); QChar getGenderChar(ServerInfo_User_Gender const &gender); QList getUserBanHistory(const QString userName); - bool addWarning(const QString userName, const QString adminName, const QString warningReason, const QString clientID); + bool + addWarning(const QString userName, const QString adminName, const QString warningReason, const QString clientID); QList getUserWarnHistory(const QString userName); - QList getMessageLogHistory(const QString &user, const QString &ipaddress, const QString &gamename, const QString &gameid, const QString &message, bool &chat, bool &game, bool &room, int &range, int &maxresults); + QList getMessageLogHistory(const QString &user, + const QString &ipaddress, + const QString &gamename, + const QString &gameid, + const QString &message, + bool &chat, + bool &game, + bool &room, + int &range, + int &maxresults); bool addForgotPassword(const QString &user); bool removeForgotPassword(const QString &user); bool doesForgotPasswordExist(const QString &user); bool updateUserToken(const QString &token, const QString &user); - bool validateTableColumnStringData(const QString &table, const QString &column, const QString &_user, const QString &_datatocheck); - void addAuditRecord(const QString &user, const QString &ipaddress, const QString &clientid, const QString &action, const QString &details, const bool &results); + bool validateTableColumnStringData(const QString &table, + const QString &column, + const QString &_user, + const QString &_datatocheck); + void addAuditRecord(const QString &user, + const QString &ipaddress, + const QString &clientid, + const QString &action, + const QString &details, + const bool &results); }; #endif diff --git a/servatrice/src/server_logger.cpp b/servatrice/src/server_logger.cpp index 2b841ace..99d78060 100644 --- a/servatrice/src/server_logger.cpp +++ b/servatrice/src/server_logger.cpp @@ -1,10 +1,10 @@ #include "server_logger.h" #include "settingscache.h" +#include +#include #include #include -#include #include -#include #include ServerLogger::ServerLogger(bool _logToConsole, QObject *parent) @@ -30,9 +30,8 @@ void ServerLogger::startLog(const QString &logFileName) return; } - logFile = new QFile(logFileName, this); - if(!logFile->open(QIODevice::Append)) { + if (!logFile->open(QIODevice::Append)) { std::cerr << "ERROR: can't open() logfile." << std::endl; delete logFile; logFile = 0; @@ -40,7 +39,7 @@ void ServerLogger::startLog(const QString &logFileName) } } else logFile = 0; - + connect(this, SIGNAL(sigFlushBuffer()), this, SLOT(flushBuffer()), Qt::QueuedConnection); } @@ -48,24 +47,24 @@ void ServerLogger::logMessage(QString message, void *caller) { if (!logFile) return; - + QString callerString; if (caller) - callerString = QString::number((qulonglong) caller, 16) + " "; - - //filter out all log entries based on values in configuration file - bool shouldWeWriteLog = settingsCache->value("server/writelog",1).toBool(); + callerString = QString::number((qulonglong)caller, 16) + " "; + + // filter out all log entries based on values in configuration file + bool shouldWeWriteLog = settingsCache->value("server/writelog", 1).toBool(); QString logFilters = settingsCache->value("server/logfilters").toString(); - QStringList listlogFilters = logFilters.split(",", QString::SkipEmptyParts); - bool shouldWeSkipLine = false; - + QStringList listlogFilters = logFilters.split(",", QString::SkipEmptyParts); + bool shouldWeSkipLine = false; + if (!shouldWeWriteLog) return; - if (!logFilters.trimmed().isEmpty()){ + if (!logFilters.trimmed().isEmpty()) { shouldWeSkipLine = true; - foreach(QString logFilter, listlogFilters){ - if (message.contains(logFilter, Qt::CaseInsensitive)){ + foreach (QString logFilter, listlogFilters) { + if (message.contains(logFilter, Qt::CaseInsensitive)) { shouldWeSkipLine = false; break; } @@ -85,10 +84,11 @@ void ServerLogger::flushBuffer() { if (flushRunning) return; - + flushRunning = true; QTextStream stream(logFile); - forever { + forever + { bufferMutex.lock(); if (buffer.isEmpty()) { bufferMutex.unlock(); @@ -97,10 +97,10 @@ void ServerLogger::flushBuffer() } QString message = buffer.takeFirst(); bufferMutex.unlock(); - + stream << message << "\n"; stream.flush(); - + if (logToConsole) std::cout << message.toStdString() << std::endl; } @@ -112,7 +112,7 @@ void ServerLogger::rotateLogs() return; flushBuffer(); - + logFile->close(); logFile->open(QIODevice::Append); } diff --git a/servatrice/src/server_logger.h b/servatrice/src/server_logger.h index 478d0460..0e11d23f 100644 --- a/servatrice/src/server_logger.h +++ b/servatrice/src/server_logger.h @@ -1,34 +1,36 @@ #ifndef SERVER_LOGGER_H #define SERVER_LOGGER_H -#include -#include #include -#include +#include #include +#include +#include class QFile; class Server_ProtocolHandler; -class ServerLogger : public QObject { - Q_OBJECT +class ServerLogger : public QObject +{ + Q_OBJECT public: - ServerLogger(bool _logToConsole, QObject *parent = 0); - ~ServerLogger(); + ServerLogger(bool _logToConsole, QObject *parent = 0); + ~ServerLogger(); public slots: - void startLog(const QString &logFileName); - void logMessage(QString message, void *caller = 0); - void rotateLogs(); + void startLog(const QString &logFileName); + void logMessage(QString message, void *caller = 0); + void rotateLogs(); private slots: - void flushBuffer(); + void flushBuffer(); signals: - void sigFlushBuffer(); + void sigFlushBuffer(); + private: - bool logToConsole; - static QFile *logFile; - bool flushRunning; - QStringList buffer; - QMutex bufferMutex; + bool logToConsole; + static QFile *logFile; + bool flushRunning; + QStringList buffer; + QMutex bufferMutex; }; #endif diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index 1227182b..81ee3c90 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -18,70 +18,72 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include "settingscache.h" #include "serversocketinterface.h" -#include "servatrice.h" -#include "servatrice_database_interface.h" #include "decklist.h" -#include "server_player.h" #include "main.h" -#include "server_logger.h" -#include "server_response_containers.h" -#include "pb/commands.pb.h" -#include "pb/command_deck_list.pb.h" -#include "pb/command_deck_upload.pb.h" -#include "pb/command_deck_download.pb.h" -#include "pb/command_deck_new_dir.pb.h" -#include "pb/command_deck_del_dir.pb.h" #include "pb/command_deck_del.pb.h" -#include "pb/command_replay_list.pb.h" -#include "pb/command_replay_download.pb.h" -#include "pb/command_replay_modify_match.pb.h" +#include "pb/command_deck_del_dir.pb.h" +#include "pb/command_deck_download.pb.h" +#include "pb/command_deck_list.pb.h" +#include "pb/command_deck_new_dir.pb.h" +#include "pb/command_deck_upload.pb.h" #include "pb/command_replay_delete_match.pb.h" -#include "pb/event_connection_closed.pb.h" -#include "pb/event_server_message.pb.h" -#include "pb/event_server_identification.pb.h" +#include "pb/command_replay_download.pb.h" +#include "pb/command_replay_list.pb.h" +#include "pb/command_replay_modify_match.pb.h" +#include "pb/commands.pb.h" #include "pb/event_add_to_list.pb.h" -#include "pb/event_remove_from_list.pb.h" +#include "pb/event_connection_closed.pb.h" #include "pb/event_notify_user.pb.h" +#include "pb/event_remove_from_list.pb.h" +#include "pb/event_server_identification.pb.h" +#include "pb/event_server_message.pb.h" #include "pb/event_user_message.pb.h" #include "pb/response_ban_history.pb.h" -#include "pb/response_deck_list.pb.h" #include "pb/response_deck_download.pb.h" +#include "pb/response_deck_list.pb.h" #include "pb/response_deck_upload.pb.h" +#include "pb/response_forgotpasswordrequest.pb.h" #include "pb/response_register.pb.h" -#include "pb/response_replay_list.pb.h" #include "pb/response_replay_download.pb.h" +#include "pb/response_replay_list.pb.h" +#include "pb/response_viewlog_history.pb.h" #include "pb/response_warn_history.pb.h" #include "pb/response_warn_list.pb.h" -#include "pb/response_viewlog_history.pb.h" -#include "pb/response_forgotpasswordrequest.pb.h" -#include "pb/serverinfo_replay.pb.h" -#include "pb/serverinfo_user.pb.h" -#include "pb/serverinfo_deckstorage.pb.h" #include "pb/serverinfo_ban.pb.h" #include "pb/serverinfo_chat_message.pb.h" +#include "pb/serverinfo_deckstorage.pb.h" +#include "pb/serverinfo_replay.pb.h" +#include "pb/serverinfo_user.pb.h" +#include "servatrice.h" +#include "servatrice_database_interface.h" +#include "server_logger.h" +#include "server_player.h" +#include "server_response_containers.h" +#include "settingscache.h" +#include +#include +#include +#include +#include +#include +#include #include "version_string.h" -#include #include +#include static const int protocolVersion = 14; -AbstractServerSocketInterface::AbstractServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent) - : Server_ProtocolHandler(_server, _databaseInterface, parent), - servatrice(_server), +AbstractServerSocketInterface::AbstractServerSocketInterface(Servatrice *_server, + Servatrice_DatabaseInterface *_databaseInterface, + QObject *parent) + : Server_ProtocolHandler(_server, _databaseInterface, parent), servatrice(_server), sqlInterface(reinterpret_cast(databaseInterface)) { // Never call flushOutputQueue directly from outputQueueChanged. In case of a socket error, - // it could lead to this object being destroyed while another function is still on the call stack. -> mutex deadlocks etc. + // it could lead to this object being destroyed while another function is still on the call stack. -> mutex + // deadlocks etc. connect(this, SIGNAL(outputQueueChanged()), this, SLOT(flushOutputQueue()), Qt::QueuedConnection); } @@ -95,11 +97,11 @@ bool AbstractServerSocketInterface::initSession() sendProtocolItem(*identSe); delete identSe; - //allow unlimited number of connections from the trusted sources - QString trustedSources = settingsCache->value("security/trusted_sources","127.0.0.1,::1").toString(); - if (trustedSources.contains(getAddress(),Qt::CaseInsensitive)) + // allow unlimited number of connections from the trusted sources + QString trustedSources = settingsCache->value("security/trusted_sources", "127.0.0.1,::1").toString(); + if (trustedSources.contains(getAddress(), Qt::CaseInsensitive)) return true; - + int maxUsers = servatrice->getMaxUsersPerAddress(); if ((maxUsers > 0) && (servatrice->getUsersWithAddress(getPeerAddress()) >= maxUsers)) { Event_ConnectionClosed event; @@ -134,54 +136,97 @@ void AbstractServerSocketInterface::logDebugMessage(const QString &message) logger->logMessage(message, this); } -Response::ResponseCode AbstractServerSocketInterface::processExtendedSessionCommand(int cmdType, const SessionCommand &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::processExtendedSessionCommand(int cmdType, + const SessionCommand &cmd, + ResponseContainer &rc) { - switch ((SessionCommand::SessionCommandType) cmdType) { - case SessionCommand::ADD_TO_LIST: return cmdAddToList(cmd.GetExtension(Command_AddToList::ext), rc); - case SessionCommand::REMOVE_FROM_LIST: return cmdRemoveFromList(cmd.GetExtension(Command_RemoveFromList::ext), rc); - case SessionCommand::DECK_LIST: return cmdDeckList(cmd.GetExtension(Command_DeckList::ext), rc); - case SessionCommand::DECK_NEW_DIR: return cmdDeckNewDir(cmd.GetExtension(Command_DeckNewDir::ext), rc); - case SessionCommand::DECK_DEL_DIR: return cmdDeckDelDir(cmd.GetExtension(Command_DeckDelDir::ext), rc); - case SessionCommand::DECK_DEL: return cmdDeckDel(cmd.GetExtension(Command_DeckDel::ext), rc); - case SessionCommand::DECK_UPLOAD: return cmdDeckUpload(cmd.GetExtension(Command_DeckUpload::ext), rc); - case SessionCommand::DECK_DOWNLOAD: return cmdDeckDownload(cmd.GetExtension(Command_DeckDownload::ext), rc); - case SessionCommand::REPLAY_LIST: return cmdReplayList(cmd.GetExtension(Command_ReplayList::ext), rc); - case SessionCommand::REPLAY_DOWNLOAD: return cmdReplayDownload(cmd.GetExtension(Command_ReplayDownload::ext), rc); - case SessionCommand::REPLAY_MODIFY_MATCH: return cmdReplayModifyMatch(cmd.GetExtension(Command_ReplayModifyMatch::ext), rc); - case SessionCommand::REPLAY_DELETE_MATCH: return cmdReplayDeleteMatch(cmd.GetExtension(Command_ReplayDeleteMatch::ext), rc); - case SessionCommand::REGISTER: return cmdRegisterAccount(cmd.GetExtension(Command_Register::ext), rc); break; - case SessionCommand::ACTIVATE: return cmdActivateAccount(cmd.GetExtension(Command_Activate::ext), rc); break; - case SessionCommand::FORGOT_PASSWORD_REQUEST: return cmdForgotPasswordRequest(cmd.GetExtension(Command_ForgotPasswordRequest::ext), rc); break; - case SessionCommand::FORGOT_PASSWORD_RESET: return cmdForgotPasswordReset(cmd.GetExtension(Command_ForgotPasswordReset::ext), rc); break; - case SessionCommand::FORGOT_PASSWORD_CHALLENGE: return cmdForgotPasswordChallenge(cmd.GetExtension(Command_ForgotPasswordChallenge::ext), rc); break; - case SessionCommand::ACCOUNT_EDIT: return cmdAccountEdit(cmd.GetExtension(Command_AccountEdit::ext), rc); - case SessionCommand::ACCOUNT_IMAGE: return cmdAccountImage(cmd.GetExtension(Command_AccountImage::ext), rc); - case SessionCommand::ACCOUNT_PASSWORD: return cmdAccountPassword(cmd.GetExtension(Command_AccountPassword::ext), rc); - default: return Response::RespFunctionNotAllowed; + switch ((SessionCommand::SessionCommandType)cmdType) { + case SessionCommand::ADD_TO_LIST: + return cmdAddToList(cmd.GetExtension(Command_AddToList::ext), rc); + case SessionCommand::REMOVE_FROM_LIST: + return cmdRemoveFromList(cmd.GetExtension(Command_RemoveFromList::ext), rc); + case SessionCommand::DECK_LIST: + return cmdDeckList(cmd.GetExtension(Command_DeckList::ext), rc); + case SessionCommand::DECK_NEW_DIR: + return cmdDeckNewDir(cmd.GetExtension(Command_DeckNewDir::ext), rc); + case SessionCommand::DECK_DEL_DIR: + return cmdDeckDelDir(cmd.GetExtension(Command_DeckDelDir::ext), rc); + case SessionCommand::DECK_DEL: + return cmdDeckDel(cmd.GetExtension(Command_DeckDel::ext), rc); + case SessionCommand::DECK_UPLOAD: + return cmdDeckUpload(cmd.GetExtension(Command_DeckUpload::ext), rc); + case SessionCommand::DECK_DOWNLOAD: + return cmdDeckDownload(cmd.GetExtension(Command_DeckDownload::ext), rc); + case SessionCommand::REPLAY_LIST: + return cmdReplayList(cmd.GetExtension(Command_ReplayList::ext), rc); + case SessionCommand::REPLAY_DOWNLOAD: + return cmdReplayDownload(cmd.GetExtension(Command_ReplayDownload::ext), rc); + case SessionCommand::REPLAY_MODIFY_MATCH: + return cmdReplayModifyMatch(cmd.GetExtension(Command_ReplayModifyMatch::ext), rc); + case SessionCommand::REPLAY_DELETE_MATCH: + return cmdReplayDeleteMatch(cmd.GetExtension(Command_ReplayDeleteMatch::ext), rc); + case SessionCommand::REGISTER: + return cmdRegisterAccount(cmd.GetExtension(Command_Register::ext), rc); + break; + case SessionCommand::ACTIVATE: + return cmdActivateAccount(cmd.GetExtension(Command_Activate::ext), rc); + break; + case SessionCommand::FORGOT_PASSWORD_REQUEST: + return cmdForgotPasswordRequest(cmd.GetExtension(Command_ForgotPasswordRequest::ext), rc); + break; + case SessionCommand::FORGOT_PASSWORD_RESET: + return cmdForgotPasswordReset(cmd.GetExtension(Command_ForgotPasswordReset::ext), rc); + break; + case SessionCommand::FORGOT_PASSWORD_CHALLENGE: + return cmdForgotPasswordChallenge(cmd.GetExtension(Command_ForgotPasswordChallenge::ext), rc); + break; + case SessionCommand::ACCOUNT_EDIT: + return cmdAccountEdit(cmd.GetExtension(Command_AccountEdit::ext), rc); + case SessionCommand::ACCOUNT_IMAGE: + return cmdAccountImage(cmd.GetExtension(Command_AccountImage::ext), rc); + case SessionCommand::ACCOUNT_PASSWORD: + return cmdAccountPassword(cmd.GetExtension(Command_AccountPassword::ext), rc); + default: + return Response::RespFunctionNotAllowed; } } -Response::ResponseCode AbstractServerSocketInterface::processExtendedModeratorCommand(int cmdType, const ModeratorCommand &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::processExtendedModeratorCommand(int cmdType, + const ModeratorCommand &cmd, + ResponseContainer &rc) { - switch ((ModeratorCommand::ModeratorCommandType) cmdType) { - case ModeratorCommand::BAN_FROM_SERVER: return cmdBanFromServer(cmd.GetExtension(Command_BanFromServer::ext), rc); - case ModeratorCommand::BAN_HISTORY: return cmdGetBanHistory(cmd.GetExtension(Command_GetBanHistory::ext), rc); - case ModeratorCommand::WARN_USER: return cmdWarnUser(cmd.GetExtension(Command_WarnUser::ext), rc); - case ModeratorCommand::WARN_HISTORY: return cmdGetWarnHistory(cmd.GetExtension(Command_GetWarnHistory::ext), rc); - case ModeratorCommand::WARN_LIST: return cmdGetWarnList(cmd.GetExtension(Command_GetWarnList::ext), rc); - case ModeratorCommand::VIEWLOG_HISTORY: return cmdGetLogHistory(cmd.GetExtension(Command_ViewLogHistory::ext), rc); - default: return Response::RespFunctionNotAllowed; + switch ((ModeratorCommand::ModeratorCommandType)cmdType) { + case ModeratorCommand::BAN_FROM_SERVER: + return cmdBanFromServer(cmd.GetExtension(Command_BanFromServer::ext), rc); + case ModeratorCommand::BAN_HISTORY: + return cmdGetBanHistory(cmd.GetExtension(Command_GetBanHistory::ext), rc); + case ModeratorCommand::WARN_USER: + return cmdWarnUser(cmd.GetExtension(Command_WarnUser::ext), rc); + case ModeratorCommand::WARN_HISTORY: + return cmdGetWarnHistory(cmd.GetExtension(Command_GetWarnHistory::ext), rc); + case ModeratorCommand::WARN_LIST: + return cmdGetWarnList(cmd.GetExtension(Command_GetWarnList::ext), rc); + case ModeratorCommand::VIEWLOG_HISTORY: + return cmdGetLogHistory(cmd.GetExtension(Command_ViewLogHistory::ext), rc); + default: + return Response::RespFunctionNotAllowed; } } -Response::ResponseCode AbstractServerSocketInterface::processExtendedAdminCommand(int cmdType, const AdminCommand &cmd, ResponseContainer &rc) +Response::ResponseCode +AbstractServerSocketInterface::processExtendedAdminCommand(int cmdType, const AdminCommand &cmd, ResponseContainer &rc) { - switch ((AdminCommand::AdminCommandType) cmdType) { - case AdminCommand::SHUTDOWN_SERVER: return cmdShutdownServer(cmd.GetExtension(Command_ShutdownServer::ext), rc); - case AdminCommand::UPDATE_SERVER_MESSAGE: return cmdUpdateServerMessage(cmd.GetExtension(Command_UpdateServerMessage::ext), rc); - case AdminCommand::RELOAD_CONFIG: return cmdReloadConfig(cmd.GetExtension(Command_ReloadConfig::ext), rc); - case AdminCommand::ADJUST_MOD: return cmdAdjustMod(cmd.GetExtension(Command_AdjustMod::ext), rc); - default: return Response::RespFunctionNotAllowed; + switch ((AdminCommand::AdminCommandType)cmdType) { + case AdminCommand::SHUTDOWN_SERVER: + return cmdShutdownServer(cmd.GetExtension(Command_ShutdownServer::ext), rc); + case AdminCommand::UPDATE_SERVER_MESSAGE: + return cmdUpdateServerMessage(cmd.GetExtension(Command_UpdateServerMessage::ext), rc); + case AdminCommand::RELOAD_CONFIG: + return cmdReloadConfig(cmd.GetExtension(Command_ReloadConfig::ext), rc); + case AdminCommand::ADJUST_MOD: + return cmdAdjustMod(cmd.GetExtension(Command_AdjustMod::ext), rc); + default: + return Response::RespFunctionNotAllowed; } } @@ -210,7 +255,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAddToList(const Command if (id1 == id2) return Response::RespContextError; - QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_" + list + "list (id_user1, id_user2) values(:id1, :id2)"); + QSqlQuery *query = + sqlInterface->prepareQuery("insert into {prefix}_" + list + "list (id_user1, id_user2) values(:id1, :id2)"); query->bindValue(":id1", id1); query->bindValue(":id2", id2); if (!sqlInterface->execSqlQuery(query)) @@ -224,7 +270,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAddToList(const Command return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdRemoveFromList(const Command_RemoveFromList &cmd, + ResponseContainer &rc) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -247,7 +294,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRemoveFromList(const Co if (id2 < 0) return Response::RespNameNotFound; - QSqlQuery *query = sqlInterface->prepareQuery("delete from {prefix}_" + list + "list where id_user1 = :id1 and id_user2 = :id2"); + QSqlQuery *query = + sqlInterface->prepareQuery("delete from {prefix}_" + list + "list where id_user1 = :id1 and id_user2 = :id2"); query->bindValue(":id1", id1); query->bindValue(":id2", id2); if (!sqlInterface->execSqlQuery(query)) @@ -268,7 +316,8 @@ int AbstractServerSocketInterface::getDeckPathId(int basePathId, QStringList pat if (path[0].isEmpty()) return 0; - QSqlQuery *query = sqlInterface->prepareQuery("select id from {prefix}_decklist_folders where id_parent = :id_parent and name = :name and id_user = :id_user"); + QSqlQuery *query = sqlInterface->prepareQuery("select id from {prefix}_decklist_folders where id_parent = " + ":id_parent and name = :name and id_user = :id_user"); query->bindValue(":id_parent", basePathId); query->bindValue(":name", path.takeFirst()); query->bindValue(":id_user", userInfo->id()); @@ -290,18 +339,18 @@ int AbstractServerSocketInterface::getDeckPathId(const QString &path) bool AbstractServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_Folder *folder) { - QSqlQuery *query = sqlInterface->prepareQuery("select id, name from {prefix}_decklist_folders where id_parent = :id_parent and id_user = :id_user"); + QSqlQuery *query = sqlInterface->prepareQuery( + "select id, name from {prefix}_decklist_folders where id_parent = :id_parent and id_user = :id_user"); query->bindValue(":id_parent", folderId); query->bindValue(":id_user", userInfo->id()); if (!sqlInterface->execSqlQuery(query)) return false; QMap results; - while(query->next()) + while (query->next()) results[query->value(0).toInt()] = query->value(1).toString(); - foreach(int key, results.keys()) - { + foreach (int key, results.keys()) { ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); newItem->set_id(key); newItem->set_name(results.value(key).toStdString()); @@ -310,7 +359,8 @@ bool AbstractServerSocketInterface::deckListHelper(int folderId, ServerInfo_Deck return false; } - query = sqlInterface->prepareQuery("select id, name, upload_time from {prefix}_decklist_files where id_folder = :id_folder and id_user = :id_user"); + query = sqlInterface->prepareQuery("select id, name, upload_time from {prefix}_decklist_files where id_folder = " + ":id_folder and id_user = :id_user"); query->bindValue(":id_folder", folderId); query->bindValue(":id_user", userInfo->id()); if (!sqlInterface->execSqlQuery(query)) @@ -331,7 +381,8 @@ bool AbstractServerSocketInterface::deckListHelper(int folderId, ServerInfo_Deck // CHECK AUTHENTICATION! // Also check for every function that data belonging to other users cannot be accessed. -Response::ResponseCode AbstractServerSocketInterface::cmdDeckList(const Command_DeckList & /*cmd*/, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdDeckList(const Command_DeckList & /*cmd*/, + ResponseContainer &rc) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -348,7 +399,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckList(const Command_ return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdDeckNewDir(const Command_DeckNewDir &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdDeckNewDir(const Command_DeckNewDir &cmd, + ResponseContainer & /*rc*/) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -359,7 +411,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckNewDir(const Comman if (folderId == -1) return Response::RespNameNotFound; - QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_decklist_folders (id_parent, id_user, name) values(:id_parent, :id_user, :name)"); + QSqlQuery *query = sqlInterface->prepareQuery( + "insert into {prefix}_decklist_folders (id_parent, id_user, name) values(:id_parent, :id_user, :name)"); query->bindValue(":id_parent", folderId); query->bindValue(":id_user", userInfo->id()); query->bindValue(":name", QString::fromStdString(cmd.dir_name())); @@ -371,7 +424,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckNewDir(const Comman void AbstractServerSocketInterface::deckDelDirHelper(int basePathId) { sqlInterface->checkSql(); - QSqlQuery *query = sqlInterface->prepareQuery("select id from {prefix}_decklist_folders where id_parent = :id_parent"); + QSqlQuery *query = + sqlInterface->prepareQuery("select id from {prefix}_decklist_folders where id_parent = :id_parent"); query->bindValue(":id_parent", basePathId); sqlInterface->execSqlQuery(query); while (query->next()) @@ -388,7 +442,8 @@ void AbstractServerSocketInterface::deckDelDirHelper(int basePathId) void AbstractServerSocketInterface::sendServerMessage(const QString userName, const QString message) { - AbstractServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + AbstractServerSocketInterface *user = + static_cast(server->getUsers().value(userName)); if (!user) return; @@ -401,7 +456,8 @@ void AbstractServerSocketInterface::sendServerMessage(const QString userName, co delete se; } -Response::ResponseCode AbstractServerSocketInterface::cmdDeckDelDir(const Command_DeckDelDir &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdDeckDelDir(const Command_DeckDelDir &cmd, + ResponseContainer & /*rc*/) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -421,7 +477,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckDel(const Command_D return Response::RespFunctionNotAllowed; sqlInterface->checkSql(); - QSqlQuery *query = sqlInterface->prepareQuery("select id from {prefix}_decklist_files where id = :id and id_user = :id_user"); + QSqlQuery *query = + sqlInterface->prepareQuery("select id from {prefix}_decklist_files where id = :id and id_user = :id_user"); query->bindValue(":id", cmd.deck_id()); query->bindValue(":id_user", userInfo->id()); sqlInterface->execSqlQuery(query); @@ -435,7 +492,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckDel(const Command_D return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdDeckUpload(const Command_DeckUpload &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdDeckUpload(const Command_DeckUpload &cmd, + ResponseContainer &rc) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -457,7 +515,9 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckUpload(const Comman if (folderId == -1) return Response::RespNameNotFound; - QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_decklist_files (id_folder, id_user, name, upload_time, content) values(:id_folder, :id_user, :name, NOW(), :content)"); + QSqlQuery *query = + sqlInterface->prepareQuery("insert into {prefix}_decklist_files (id_folder, id_user, name, upload_time, " + "content) values(:id_folder, :id_user, :name, NOW(), :content)"); query->bindValue(":id_folder", folderId); query->bindValue(":id_user", userInfo->id()); query->bindValue(":name", deckName); @@ -471,7 +531,9 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckUpload(const Comman fileInfo->mutable_file()->set_creation_time(QDateTime::currentDateTime().toTime_t()); rc.setResponseExtension(re); } else if (cmd.has_deck_id()) { - QSqlQuery *query = sqlInterface->prepareQuery("update {prefix}_decklist_files set name=:name, upload_time=NOW(), content=:content where id = :id_deck and id_user = :id_user"); + QSqlQuery *query = + sqlInterface->prepareQuery("update {prefix}_decklist_files set name=:name, upload_time=NOW(), " + "content=:content where id = :id_deck and id_user = :id_user"); query->bindValue(":id_deck", cmd.deck_id()); query->bindValue(":id_user", userInfo->id()); query->bindValue(":name", deckName); @@ -493,7 +555,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckUpload(const Comman return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdDeckDownload(const Command_DeckDownload &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdDeckDownload(const Command_DeckDownload &cmd, + ResponseContainer &rc) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -501,7 +564,7 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckDownload(const Comm DeckList *deck; try { deck = sqlInterface->getDeckFromDatabase(cmd.deck_id(), userInfo->id()); - } catch(Response::ResponseCode r) { + } catch (Response::ResponseCode r) { return r; } @@ -513,14 +576,18 @@ Response::ResponseCode AbstractServerSocketInterface::cmdDeckDownload(const Comm return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdReplayList(const Command_ReplayList & /*cmd*/, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdReplayList(const Command_ReplayList & /*cmd*/, + ResponseContainer &rc) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; Response_ReplayList *re = new Response_ReplayList; - QSqlQuery *query1 = sqlInterface->prepareQuery("select a.id_game, a.replay_name, b.room_name, b.time_started, b.time_finished, b.descr, a.do_not_hide from {prefix}_replays_access a left join {prefix}_games b on b.id = a.id_game where a.id_player = :id_player and (a.do_not_hide = 1 or date_add(b.time_started, interval 7 day) > now())"); + QSqlQuery *query1 = sqlInterface->prepareQuery( + "select a.id_game, a.replay_name, b.room_name, b.time_started, b.time_finished, b.descr, a.do_not_hide from " + "{prefix}_replays_access a left join {prefix}_games b on b.id = a.id_game where a.id_player = :id_player and " + "(a.do_not_hide = 1 or date_add(b.time_started, interval 7 day) > now())"); query1->bindValue(":id_player", userInfo->id()); sqlInterface->execSqlQuery(query1); while (query1->next()) { @@ -538,14 +605,16 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayList(const Comman matchInfo->set_do_not_hide(query1->value(6).toBool()); { - QSqlQuery *query2 = sqlInterface->prepareQuery("select player_name from {prefix}_games_players where id_game = :id_game"); + QSqlQuery *query2 = + sqlInterface->prepareQuery("select player_name from {prefix}_games_players where id_game = :id_game"); query2->bindValue(":id_game", gameId); sqlInterface->execSqlQuery(query2); while (query2->next()) matchInfo->add_player_names(query2->value(0).toString().toStdString()); } { - QSqlQuery *query3 = sqlInterface->prepareQuery("select id, duration from {prefix}_replays where id_game = :id_game"); + QSqlQuery *query3 = + sqlInterface->prepareQuery("select id, duration from {prefix}_replays where id_game = :id_game"); query3->bindValue(":id_game", gameId); sqlInterface->execSqlQuery(query3); while (query3->next()) { @@ -561,13 +630,16 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayList(const Comman return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdReplayDownload(const Command_ReplayDownload &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdReplayDownload(const Command_ReplayDownload &cmd, + ResponseContainer &rc) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; { - QSqlQuery *query = sqlInterface->prepareQuery("select 1 from {prefix}_replays_access a left join {prefix}_replays b on a.id_game = b.id_game where b.id = :id_replay and a.id_player = :id_player"); + QSqlQuery *query = + sqlInterface->prepareQuery("select 1 from {prefix}_replays_access a left join {prefix}_replays b on " + "a.id_game = b.id_game where b.id = :id_replay and a.id_player = :id_player"); query->bindValue(":id_replay", cmd.replay_id()); query->bindValue(":id_player", userInfo->id()); if (!sqlInterface->execSqlQuery(query)) @@ -592,7 +664,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayDownload(const Co return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdReplayModifyMatch(const Command_ReplayModifyMatch &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdReplayModifyMatch(const Command_ReplayModifyMatch &cmd, + ResponseContainer & /*rc*/) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -600,7 +673,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayModifyMatch(const if (!sqlInterface->checkSql()) return Response::RespInternalError; - QSqlQuery *query = sqlInterface->prepareQuery("update {prefix}_replays_access set do_not_hide=:do_not_hide where id_player = :id_player and id_game = :id_game"); + QSqlQuery *query = sqlInterface->prepareQuery("update {prefix}_replays_access set do_not_hide=:do_not_hide where " + "id_player = :id_player and id_game = :id_game"); query->bindValue(":id_player", userInfo->id()); query->bindValue(":id_game", cmd.game_id()); query->bindValue(":do_not_hide", cmd.do_not_hide()); @@ -610,7 +684,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayModifyMatch(const return query->numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; } -Response::ResponseCode AbstractServerSocketInterface::cmdReplayDeleteMatch(const Command_ReplayDeleteMatch &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdReplayDeleteMatch(const Command_ReplayDeleteMatch &cmd, + ResponseContainer & /*rc*/) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -618,7 +693,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayDeleteMatch(const if (!sqlInterface->checkSql()) return Response::RespInternalError; - QSqlQuery *query = sqlInterface->prepareQuery("delete from {prefix}_replays_access where id_player = :id_player and id_game = :id_game"); + QSqlQuery *query = sqlInterface->prepareQuery( + "delete from {prefix}_replays_access where id_player = :id_player and id_game = :id_game"); query->bindValue(":id_player", userInfo->id()); query->bindValue(":id_game", cmd.game_id()); @@ -627,10 +703,10 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReplayDeleteMatch(const return query->numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; } - // MODERATOR FUNCTIONS. // May be called by admins and moderators. Permission is checked by the calling function. -Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Command_ViewLogHistory &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Command_ViewLogHistory &cmd, + ResponseContainer &rc) { QList messageList; @@ -656,15 +732,16 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Com int maximumResults = cmd.maximum_results(); Response_ViewLogHistory *re = new Response_ViewLogHistory; - + if (servatrice->getEnableLogQuery()) { - QListIterator messageIterator(sqlInterface->getMessageLogHistory(userName, ipAddress, gameName, gameID, message, chatType, gameType, roomType, dateRange, maximumResults)); + QListIterator messageIterator(sqlInterface->getMessageLogHistory( + userName, ipAddress, gameName, gameID, message, chatType, gameType, roomType, dateRange, maximumResults)); while (messageIterator.hasNext()) re->add_log_message()->CopyFrom(messageIterator.next()); } else { ServerInfo_ChatMessage chatMessage; - //create dummy chat message for room tab in the event the query is for room messages (and possibly not others) + // create dummy chat message for room tab in the event the query is for room messages (and possibly not others) chatMessage.set_time(QString(tr("Log query disabled, please contact server owner for details.")).toStdString()); chatMessage.set_sender_id(QString("").toStdString()); chatMessage.set_sender_name(QString("").toStdString()); @@ -675,7 +752,7 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Com chatMessage.set_target_name(QString("").toStdString()); messageList << chatMessage; - //create dummy chat message for room tab in the event the query is for game messages (and possibly not others) + // create dummy chat message for room tab in the event the query is for game messages (and possibly not others) chatMessage.set_time(QString(tr("Log query disabled, please contact server owner for details.")).toStdString()); chatMessage.set_sender_id(QString("").toStdString()); chatMessage.set_sender_name(QString("").toStdString()); @@ -686,7 +763,7 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Com chatMessage.set_target_name(QString("").toStdString()); messageList << chatMessage; - //create dummy chat message for room tab in the event the query is for chat messages (and possibly not others) + // create dummy chat message for room tab in the event the query is for chat messages (and possibly not others) chatMessage.set_time(QString(tr("Log query disabled, please contact server owner for details.")).toStdString()); chatMessage.set_sender_id(QString("").toStdString()); chatMessage.set_sender_name(QString("").toStdString()); @@ -706,7 +783,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Com return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdGetBanHistory(const Command_GetBanHistory &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdGetBanHistory(const Command_GetBanHistory &cmd, + ResponseContainer &rc) { QList banList; QString userName = QString::fromStdString(cmd.user_name()); @@ -719,13 +797,14 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetBanHistory(const Com return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnList(const Command_GetWarnList &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnList(const Command_GetWarnList &cmd, + ResponseContainer &rc) { Response_WarnList *re = new Response_WarnList; QString officialWarnings = settingsCache->value("server/officialwarnings").toString(); QStringList warningsList = officialWarnings.split(",", QString::SkipEmptyParts); - foreach(QString warning, warningsList){ + foreach (QString warning, warningsList) { re->add_warning(warning.toStdString()); } re->set_user_name(cmd.user_name()); @@ -734,7 +813,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnList(const Comma return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnHistory(const Command_GetWarnHistory &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnHistory(const Command_GetWarnHistory &cmd, + ResponseContainer &rc) { QList warnList; QString userName = QString::fromStdString(cmd.user_name()); @@ -747,7 +827,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnHistory(const Co return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdWarnUser(const Command_WarnUser &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdWarnUser(const Command_WarnUser &cmd, + ResponseContainer & /*rc*/) { if (!sqlInterface->checkSql()) return Response::RespInternalError; @@ -759,7 +840,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdWarnUser(const Command_ if (sqlInterface->addWarning(userName, sendingModerator, warningReason, clientID)) { servatrice->clientsLock.lockForRead(); - AbstractServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + AbstractServerSocketInterface *user = + static_cast(server->getUsers().value(userName)); QList moderatorList = server->getOnlineModeratorList(); servatrice->clientsLock.unlock(); @@ -773,7 +855,7 @@ Response::ResponseCode AbstractServerSocketInterface::cmdWarnUser(const Command_ } QListIterator modIterator(moderatorList); - foreach(QString moderator, moderatorList) { + foreach (QString moderator, moderatorList) { QString notificationMessage = sendingModerator + " has sent a warning with the following information"; notificationMessage.append("\n Username: " + userName); notificationMessage.append("\n Reason: " + warningReason); @@ -786,7 +868,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdWarnUser(const Command_ } } -Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, + ResponseContainer & /*rc*/) { if (!sqlInterface->checkSql()) return Response::RespInternalError; @@ -798,12 +881,14 @@ Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Com if (userName.isEmpty() && address.isEmpty() && clientID.isEmpty()) return Response::RespOk; - QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); + QString trustedSources = settingsCache->value("server/trusted_sources", "127.0.0.1,::1").toString(); int minutes = cmd.minutes(); - if (trustedSources.contains(address,Qt::CaseInsensitive)) + if (trustedSources.contains(address, Qt::CaseInsensitive)) address = ""; - QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason, clientid) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason, :client_id)"); + QSqlQuery *query = sqlInterface->prepareQuery( + "insert into {prefix}_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason, " + "clientid) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason, :client_id)"); query->bindValue(":user_name", userName); query->bindValue(":ip_address", address); query->bindValue(":id_admin", userInfo->id()); @@ -818,7 +903,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Com QList userList = servatrice->getUsersWithAddressAsList(QHostAddress(address)); if (!userName.isEmpty()) { - AbstractServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + AbstractServerSocketInterface *user = + static_cast(server->getUsers().value(userName)); if (user && !userList.contains(user)) userList.append(user); } @@ -827,14 +913,15 @@ Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Com QSqlQuery *query = sqlInterface->prepareQuery("select name from {prefix}_users where clientid = :client_id"); query->bindValue(":client_id", QString::fromStdString(cmd.clientid())); sqlInterface->execSqlQuery(query); - if (!sqlInterface->execSqlQuery(query)){ + if (!sqlInterface->execSqlQuery(query)) { qDebug("ClientID username ban lookup failed: SQL Error"); } else { while (query->next()) { userName = query->value(0).toString(); - AbstractServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + AbstractServerSocketInterface *user = + static_cast(server->getUsers().value(userName)); if (user && !userList.contains(user)) - userList.append(user); + userList.append(user); } } } @@ -856,8 +943,9 @@ Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Com } QListIterator modIterator(moderatorList); - foreach(QString moderator, moderatorList) { - QString notificationMessage = QString::fromStdString(userInfo->name()).simplified() + " has placed a ban with the following information"; + foreach (QString moderator, moderatorList) { + QString notificationMessage = + QString::fromStdString(userInfo->name()).simplified() + " has placed a ban with the following information"; if (!userName.isEmpty()) notificationMessage.append("\n Username: " + userName); if (!address.isEmpty()) @@ -874,7 +962,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Com return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const Command_Register &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const Command_Register &cmd, + ResponseContainer &rc) { QString userName = QString::fromStdString(cmd.user_name()); QString clientId = QString::fromStdString(cmd.clientid()); @@ -883,7 +972,9 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool(); if (!registrationEnabled) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Server functionality disabled", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Server functionality disabled", false); return Response::RespRegistrationDisabled; } @@ -894,10 +985,13 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C // verify that users email/provider is not blacklisted if (!emailBlackList.trimmed().isEmpty()) { - foreach(QString blackListEmailAddress, emailBlackListFilters) { + foreach (QString blackListEmailAddress, emailBlackListFilters) { if (emailAddress.contains(blackListEmailAddress, Qt::CaseInsensitive)) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Email used is blacklisted", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), + this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), + "REGISTER_ACCOUNT", "Email used is blacklisted", false); return Response::RespEmailBlackListed; } @@ -905,19 +999,19 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C } bool requireEmailForRegistration = settingsCache->value("registration/requireemail", true).toBool(); - if (requireEmailForRegistration) - { + if (requireEmailForRegistration) { QRegExp rx("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b"); - if(emailAddress.isEmpty() || !rx.exactMatch(emailAddress)) + if (emailAddress.isEmpty() || !rx.exactMatch(emailAddress)) return Response::RespEmailRequiredToRegister; } // TODO: Move this method outside of the db interface QString errorString; - if (!sqlInterface->usernameIsValid(userName, errorString)) - { + if (!sqlInterface->usernameIsValid(userName, errorString)) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Username is invalid", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Username is invalid", false); Response_Register *re = new Response_Register; re->set_denied_reason_str(errorString.toStdString()); @@ -927,32 +1021,39 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C if (userName.toLower().simplified() == "servatrice") { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Username is invalid", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Username is invalid", false); return Response::RespUsernameInvalid; } if (sqlInterface->userExists(userName)) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Username already exists", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Username already exists", false); return Response::RespUserAlreadyExists; } - if (servatrice->getMaxAccountsPerEmail() && !(sqlInterface->checkNumberOfUserAccounts(emailAddress) < servatrice->getMaxAccountsPerEmail())) - { + if (servatrice->getMaxAccountsPerEmail() && + !(sqlInterface->checkNumberOfUserAccounts(emailAddress) < servatrice->getMaxAccountsPerEmail())) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Too many usernames registered with this email address", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Too many usernames registered with this email address", false); return Response::RespTooManyRequests; } QString banReason; int banSecondsRemaining; - if (sqlInterface->checkUserIsBanned(this->getAddress(), userName, clientId, banReason, banSecondsRemaining)) - { + if (sqlInterface->checkUserIsBanned(this->getAddress(), userName, clientId, banReason, banSecondsRemaining)) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "User is banned", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "User is banned", false); Response_Register *re = new Response_Register; re->set_denied_reason_str(banReason.toStdString()); @@ -964,7 +1065,9 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C if (tooManyRegistrationAttempts(this->getAddress())) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Too many registration attempts from this ip address", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Too many registration attempts from this ip address", false); return Response::RespTooManyRequests; } @@ -977,40 +1080,48 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C // TODO make this configurable? if (password.length() < 6) { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Password is too short", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Password is too short", false); return Response::RespPasswordTooShort; } QString token; bool requireEmailActivation = settingsCache->value("registration/requireemailactivation", true).toBool(); - bool regSucceeded = sqlInterface->registerUser(userName, realName, gender, password, emailAddress, country, token, !requireEmailActivation); + bool regSucceeded = sqlInterface->registerUser(userName, realName, gender, password, emailAddress, country, token, + !requireEmailActivation); - if(regSucceeded) - { + if (regSucceeded) { qDebug() << "Accepted register command for user: " << userName; - if(requireEmailActivation) - { - QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_activation_emails (name) values(:name)"); + if (requireEmailActivation) { + QSqlQuery *query = + sqlInterface->prepareQuery("insert into {prefix}_activation_emails (name) values(:name)"); query->bindValue(":name", userName); if (!sqlInterface->execSqlQuery(query)) return Response::RespRegistrationFailed; if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "", true); return Response::RespRegistrationAcceptedNeedsActivation; } else { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "", true); return Response::RespRegistrationAccepted; } } else { if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", "Unknown reason for failure", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "REGISTER_ACCOUNT", + "Unknown reason for failure", false); return Response::RespRegistrationFailed; } @@ -1019,38 +1130,42 @@ Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const C bool AbstractServerSocketInterface::tooManyRegistrationAttempts(const QString &ipAddress) { // TODO: implement - Q_UNUSED(ipAddress); + Q_UNUSED(ipAddress); return false; } -Response::ResponseCode AbstractServerSocketInterface::cmdActivateAccount(const Command_Activate &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdActivateAccount(const Command_Activate &cmd, + ResponseContainer & /*rc*/) { QString userName = QString::fromStdString(cmd.user_name()); QString token = QString::fromStdString(cmd.token()); QString clientID = QString::fromStdString(cmd.clientid()); - + if (clientID.isEmpty()) clientID = "UNKNOWN"; - - if(sqlInterface->activateUser(userName, token)) - { + + if (sqlInterface->activateUser(userName, token)) { qDebug() << "Accepted activation for user" << QString::fromStdString(cmd.user_name()); if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), clientID, "ACTIVATE_ACCOUNT", "", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + clientID, "ACTIVATE_ACCOUNT", "", true); return Response::RespActivationAccepted; } else { qDebug() << "Failed activation for user" << QString::fromStdString(cmd.user_name()); if (servatrice->getEnableRegistrationAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), clientID, "ACTIVATE_ACCOUNT", "Failed to activate account, incorrect activation token", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + clientID, "ACTIVATE_ACCOUNT", + "Failed to activate account, incorrect activation token", false); return Response::RespActivationFailed; } } -Response::ResponseCode AbstractServerSocketInterface::cmdAccountEdit(const Command_AccountEdit &cmd, ResponseContainer & /* rc */) +Response::ResponseCode AbstractServerSocketInterface::cmdAccountEdit(const Command_AccountEdit &cmd, + ResponseContainer & /* rc */) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -1062,8 +1177,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAccountEdit(const Comma QString userName = QString::fromStdString(userInfo->name()); - - QSqlQuery *query = sqlInterface->prepareQuery("update {prefix}_users set realname=:realName, email=:email, gender=:gender, country=:country where name=:userName"); + QSqlQuery *query = sqlInterface->prepareQuery("update {prefix}_users set realname=:realName, email=:email, " + "gender=:gender, country=:country where name=:userName"); query->bindValue(":realName", realName); query->bindValue(":email", emailAddress); query->bindValue(":gender", sqlInterface->getGenderChar(gender)); @@ -1080,7 +1195,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAccountEdit(const Comma return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer & /* rc */) +Response::ResponseCode AbstractServerSocketInterface::cmdAccountImage(const Command_AccountImage &cmd, + ResponseContainer & /* rc */) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -1098,7 +1214,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAccountImage(const Comm return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer & /* rc */) +Response::ResponseCode AbstractServerSocketInterface::cmdAccountPassword(const Command_AccountPassword &cmd, + ResponseContainer & /* rc */) { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; @@ -1107,31 +1224,36 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAccountPassword(const C QString newPassword = QString::fromStdString(cmd.new_password()); // TODO make this configurable? - if(newPassword.length() < 6) + if (newPassword.length() < 6) return Response::RespPasswordTooShort; QString userName = QString::fromStdString(userInfo->name()); - if(!databaseInterface->changeUserPassword(userName, oldPassword, newPassword, false)) + if (!databaseInterface->changeUserPassword(userName, oldPassword, newPassword, false)) return Response::RespWrongPassword; - + return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordRequest(const Command_ForgotPasswordRequest &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordRequest(const Command_ForgotPasswordRequest &cmd, + ResponseContainer &rc) { qDebug() << "Received forgot password request from user: " << QString::fromStdString(cmd.user_name()); if (!servatrice->getEnableForgotPassword()) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", "Server functionality disabled", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", + "Server functionality disabled", false); return Response::RespFunctionNotAllowed; } if (!sqlInterface->userExists(QString::fromStdString(cmd.user_name()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", "User does not exist", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", + "User does not exist", false); return Response::RespFunctionNotAllowed; } @@ -1139,7 +1261,9 @@ Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordRequest(c if (sqlInterface->doesForgotPasswordExist(QString::fromStdString(cmd.user_name()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", "Request already exists", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", + "Request already exists", true); Response_ForgotPasswordRequest *re = new Response_ForgotPasswordRequest; re->set_challenge_email(false); @@ -1147,28 +1271,36 @@ Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordRequest(c return Response::RespOk; } - QString banReason; int banTimeRemaining; - if (sqlInterface->checkUserIsBanned(this->getAddress(), QString::fromStdString(cmd.user_name()), QString::fromStdString(cmd.clientid()), banReason, banTimeRemaining)) { + QString banReason; + int banTimeRemaining; + if (sqlInterface->checkUserIsBanned(this->getAddress(), QString::fromStdString(cmd.user_name()), + QString::fromStdString(cmd.clientid()), banReason, banTimeRemaining)) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", "User is banned", false); - + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", + "User is banned", false); + return Response::RespFunctionNotAllowed; } if (servatrice->getEnableForgotPasswordChallenge()) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", "Request does not exist, challenge requested", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", + "Request does not exist, challenge requested", true); Response_ForgotPasswordRequest *re = new Response_ForgotPasswordRequest; re->set_challenge_email(true); rc.setResponseExtension(re); return Response::RespOk; - } - else { + } else { if (sqlInterface->addForgotPassword(QString::fromStdString(cmd.user_name()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_REQUEST", "Request does not exist, challenge not requested", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), + "PASSWORD_RESET_REQUEST", + "Request does not exist, challenge not requested", true); Response_ForgotPasswordRequest *re = new Response_ForgotPasswordRequest; re->set_challenge_email(false); @@ -1180,28 +1312,37 @@ Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordRequest(c return Response::RespFunctionNotAllowed; } -Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordReset(const Command_ForgotPasswordReset &cmd, ResponseContainer &rc) +Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordReset(const Command_ForgotPasswordReset &cmd, + ResponseContainer &rc) { Q_UNUSED(rc); qDebug() << "Received forgot password reset from user: " << QString::fromStdString(cmd.user_name()); if (!sqlInterface->doesForgotPasswordExist(QString::fromStdString(cmd.user_name()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET", "Request does not exist for user", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET", + "Request does not exist for user", false); return Response::RespFunctionNotAllowed; } - if (!sqlInterface->validateTableColumnStringData("{prefix}_users", "token", QString::fromStdString(cmd.user_name()), QString::fromStdString(cmd.token()))) { + if (!sqlInterface->validateTableColumnStringData("{prefix}_users", "token", QString::fromStdString(cmd.user_name()), + QString::fromStdString(cmd.token()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET", "Failed token validation", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET", + "Failed token validation", false); return Response::RespFunctionNotAllowed; } - if (sqlInterface->changeUserPassword(QString::fromStdString(cmd.user_name()), "", QString::fromStdString(cmd.new_password()), true)) { + if (sqlInterface->changeUserPassword(QString::fromStdString(cmd.user_name()), "", + QString::fromStdString(cmd.new_password()), true)) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET", "", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET", "", + true); sqlInterface->removeForgotPassword(QString::fromStdString(cmd.user_name())); return Response::RespOk; @@ -1210,50 +1351,63 @@ Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordReset(con return Response::RespFunctionNotAllowed; } -Response::ResponseCode AbstractServerSocketInterface::cmdForgotPasswordChallenge(const Command_ForgotPasswordChallenge &cmd, ResponseContainer &rc) +Response::ResponseCode +AbstractServerSocketInterface::cmdForgotPasswordChallenge(const Command_ForgotPasswordChallenge &cmd, + ResponseContainer &rc) { Q_UNUSED(rc); qDebug() << "Received forgot password challenge from user: " << QString::fromStdString(cmd.user_name()); if (sqlInterface->doesForgotPasswordExist(QString::fromStdString(cmd.user_name()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "Request does not exist for user", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), + "PASSWORD_RESET_CHALLANGE", "Request does not exist for user", false); return Response::RespOk; } - if (sqlInterface->validateTableColumnStringData("{prefix}_users", "email", QString::fromStdString(cmd.user_name()), QString::fromStdString(cmd.email()))) { + if (sqlInterface->validateTableColumnStringData("{prefix}_users", "email", QString::fromStdString(cmd.user_name()), + QString::fromStdString(cmd.email()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "", true); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), + "PASSWORD_RESET_CHALLANGE", "", true); if (sqlInterface->addForgotPassword(QString::fromStdString(cmd.user_name()))) return Response::RespOk; - } - else { + } else { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "Failed to answer email challenge question", false); + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), + QString::fromStdString(cmd.clientid()).simplified(), + "PASSWORD_RESET_CHALLANGE", "Failed to answer email challenge question", + false); } return Response::RespFunctionNotAllowed; } - // ADMIN FUNCTIONS. // Permission is checked by the calling function. -Response::ResponseCode AbstractServerSocketInterface::cmdUpdateServerMessage(const Command_UpdateServerMessage & /*cmd*/, ResponseContainer & /*rc*/) +Response::ResponseCode +AbstractServerSocketInterface::cmdUpdateServerMessage(const Command_UpdateServerMessage & /*cmd*/, + ResponseContainer & /*rc*/) { QMetaObject::invokeMethod(server, "updateLoginMessage"); return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdShutdownServer(const Command_ShutdownServer &cmd, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdShutdownServer(const Command_ShutdownServer &cmd, + ResponseContainer & /*rc*/) { - QMetaObject::invokeMethod(server, "scheduleShutdown", Q_ARG(QString, QString::fromStdString(cmd.reason())), Q_ARG(int, cmd.minutes())); + QMetaObject::invokeMethod(server, "scheduleShutdown", Q_ARG(QString, QString::fromStdString(cmd.reason())), + Q_ARG(int, cmd.minutes())); return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdReloadConfig(const Command_ReloadConfig & /* cmd */, ResponseContainer & /*rc*/) +Response::ResponseCode AbstractServerSocketInterface::cmdReloadConfig(const Command_ReloadConfig & /* cmd */, + ResponseContainer & /*rc*/) { logDebugMessage("Received admin command: reloading configuration"); settingsCache->sync(); @@ -1261,21 +1415,25 @@ Response::ResponseCode AbstractServerSocketInterface::cmdReloadConfig(const Comm return Response::RespOk; } -Response::ResponseCode AbstractServerSocketInterface::cmdAdjustMod(const Command_AdjustMod &cmd, ResponseContainer & /*rc*/) { +Response::ResponseCode AbstractServerSocketInterface::cmdAdjustMod(const Command_AdjustMod &cmd, + ResponseContainer & /*rc*/) +{ QString userName = QString::fromStdString(cmd.user_name()); if (cmd.should_be_mod()) { - QSqlQuery *query = sqlInterface->prepareQuery( - "update {prefix}_users set admin = :adminlevel where name = :username"); + QSqlQuery *query = + sqlInterface->prepareQuery("update {prefix}_users set admin = :adminlevel where name = :username"); query->bindValue(":adminlevel", 2); query->bindValue(":username", userName); - if (!sqlInterface->execSqlQuery(query)){ - logger->logMessage(QString::fromStdString("Failed to promote user %1: %2").arg(userName).arg(query->lastError().text())); + if (!sqlInterface->execSqlQuery(query)) { + logger->logMessage( + QString::fromStdString("Failed to promote user %1: %2").arg(userName).arg(query->lastError().text())); return Response::RespInternalError; } - AbstractServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + AbstractServerSocketInterface *user = + static_cast(server->getUsers().value(userName)); if (user) { Event_NotifyUser event; event.set_type(Event_NotifyUser::PROMOTED); @@ -1284,15 +1442,18 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAdjustMod(const Command delete se; } } else { - QSqlQuery *query = sqlInterface->prepareQuery("update {prefix}_users set admin = :adminlevel where name = :username"); + QSqlQuery *query = + sqlInterface->prepareQuery("update {prefix}_users set admin = :adminlevel where name = :username"); query->bindValue(":adminlevel", 0); query->bindValue(":username", userName); - if (!sqlInterface->execSqlQuery(query)){ - logger->logMessage(QString::fromStdString("Failed to demote user %1: %2").arg(userName).arg(query->lastError().text())); + if (!sqlInterface->execSqlQuery(query)) { + logger->logMessage( + QString::fromStdString("Failed to demote user %1: %2").arg(userName).arg(query->lastError().text())); return Response::RespInternalError; } - AbstractServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + AbstractServerSocketInterface *user = + static_cast(server->getUsers().value(userName)); if (user) { Event_ConnectionClosed event; event.set_reason(Event_ConnectionClosed::DEMOTED); @@ -1310,18 +1471,19 @@ Response::ResponseCode AbstractServerSocketInterface::cmdAdjustMod(const Command return Response::RespOk; } -TcpServerSocketInterface::TcpServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent) - : AbstractServerSocketInterface(_server, _databaseInterface, parent), - messageInProgress(false), +TcpServerSocketInterface::TcpServerSocketInterface(Servatrice *_server, + Servatrice_DatabaseInterface *_databaseInterface, + QObject *parent) + : AbstractServerSocketInterface(_server, _databaseInterface, parent), messageInProgress(false), handshakeStarted(false) { socket = new QTcpSocket(this); socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); connect(socket, SIGNAL(readyRead()), this, SLOT(readClient())); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, + SLOT(catchSocketError(QAbstractSocket::SocketError))); } - TcpServerSocketInterface::~TcpServerSocketInterface() { logger->logMessage("TcpServerSocketInterface destructor", this); @@ -1365,10 +1527,10 @@ void TcpServerSocketInterface::flushOutputQueue() unsigned int size = item.ByteSize(); buf.resize(size + 4); item.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); + 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); // In case socket->write() calls catchSocketError(), the mutex must not be locked during this call. writeToSocket(buf); @@ -1390,10 +1552,10 @@ void TcpServerSocketInterface::readClient() do { if (!messageInProgress) { if (inputBuffer.size() >= 4) { - messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24) - + (((quint32) (unsigned char) inputBuffer[1]) << 16) - + (((quint32) (unsigned char) inputBuffer[2]) << 8) - + ((quint32) (unsigned char) inputBuffer[3]); + messageLength = (((quint32)(unsigned char)inputBuffer[0]) << 24) + + (((quint32)(unsigned char)inputBuffer[1]) << 16) + + (((quint32)(unsigned char)inputBuffer[2]) << 8) + + ((quint32)(unsigned char)inputBuffer[3]); inputBuffer.remove(0, 4); messageInProgress = true; } else @@ -1405,9 +1567,8 @@ void TcpServerSocketInterface::readClient() CommandContainer newCommandContainer; try { newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength); - } - catch(std::exception &e) { - qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ << + } catch (std::exception &e) { + qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ << #ifdef _MSC_VER // Visual Studio __FUNCTION__; #else @@ -1417,8 +1578,7 @@ void TcpServerSocketInterface::readClient() qDebug() << "Message coming from:" << getAddress(); qDebug() << "Message length:" << messageLength; qDebug() << "Message content:" << inputBuffer.toHex(); - } - catch(...) { + } catch (...) { qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ << #ifdef _MSC_VER // Visual Studio __FUNCTION__; @@ -1445,17 +1605,18 @@ void TcpServerSocketInterface::readClient() bool TcpServerSocketInterface::initTcpSession() { - if(!initSession()) + if (!initSession()) return false; - //limit the number of websocket users based on configuration settings + // limit the number of websocket users based on configuration settings bool enforceUserLimit = settingsCache->value("security/enable_max_user_limit", false).toBool(); if (enforceUserLimit) { int userLimit = settingsCache->value("security/max_users_tcp", 500).toInt(); int playerCount = (server->getTCPUserCount() + 1); - if (playerCount > userLimit){ + if (playerCount > userLimit) { std::cerr << "Max Tcp Users Limit Reached, please increase the max_users_tcp setting." << std::endl; - logger->logMessage(QString("Max Tcp Users Limit Reached, please increase the max_users_tcp setting."), this); + logger->logMessage(QString("Max Tcp Users Limit Reached, please increase the max_users_tcp setting."), + this); Event_ConnectionClosed event; event.set_reason(Event_ConnectionClosed::USER_LIMIT_REACHED); SessionEvent *se = prepareSessionEvent(event); @@ -1469,7 +1630,9 @@ bool TcpServerSocketInterface::initTcpSession() } #if QT_VERSION > 0x050300 -WebsocketServerSocketInterface::WebsocketServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent) +WebsocketServerSocketInterface::WebsocketServerSocketInterface(Servatrice *_server, + Servatrice_DatabaseInterface *_databaseInterface, + QObject *parent) : AbstractServerSocketInterface(_server, _databaseInterface, parent) { } @@ -1481,11 +1644,13 @@ WebsocketServerSocketInterface::~WebsocketServerSocketInterface() flushOutputQueue(); } -void WebsocketServerSocketInterface::initConnection(void * _socket) +void WebsocketServerSocketInterface::initConnection(void *_socket) { - socket = (QWebSocket*) _socket; - connect(socket, SIGNAL(binaryMessageReceived(const QByteArray &)), this, SLOT(binaryMessageReceived(const QByteArray &))); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); + socket = (QWebSocket *)_socket; + connect(socket, SIGNAL(binaryMessageReceived(const QByteArray &)), this, + SLOT(binaryMessageReceived(const QByteArray &))); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, + SLOT(catchSocketError(QAbstractSocket::SocketError))); // Add this object to the server's list of connections before it can receive socket events. // Otherwise, in case a of a socket error, it could be removed from the list before it is added. @@ -1493,23 +1658,25 @@ void WebsocketServerSocketInterface::initConnection(void * _socket) logger->logMessage(QString("Incoming websocket connection: %1").arg(socket->peerAddress().toString()), this); - if(!initWebsocketSession()) + if (!initWebsocketSession()) prepareDestroy(); } bool WebsocketServerSocketInterface::initWebsocketSession() { - if(!initSession()) + if (!initSession()) return false; - //limit the number of websocket users based on configuration settings + // limit the number of websocket users based on configuration settings bool enforceUserLimit = settingsCache->value("security/enable_max_user_limit", false).toBool(); if (enforceUserLimit) { int userLimit = settingsCache->value("security/max_users_websocket", 500).toInt(); int playerCount = (server->getWebSocketUserCount() + 1); - if (playerCount > userLimit){ - std::cerr << "Max Websocket Users Limit Reached, please increase the max_users_websocket setting." << std::endl; - logger->logMessage(QString("Max Websocket Users Limit Reached, please increase the max_users_websocket setting."), this); + if (playerCount > userLimit) { + std::cerr << "Max Websocket Users Limit Reached, please increase the max_users_websocket setting." + << std::endl; + logger->logMessage( + QString("Max Websocket Users Limit Reached, please increase the max_users_websocket setting."), this); Event_ConnectionClosed event; event.set_reason(Event_ConnectionClosed::USER_LIMIT_REACHED); SessionEvent *se = prepareSessionEvent(event); @@ -1549,16 +1716,15 @@ void WebsocketServerSocketInterface::flushOutputQueue() flushSocket(); } -void WebsocketServerSocketInterface::binaryMessageReceived(const QByteArray & message) +void WebsocketServerSocketInterface::binaryMessageReceived(const QByteArray &message) { servatrice->incRxBytes(message.size()); CommandContainer newCommandContainer; try { newCommandContainer.ParseFromArray(message.data(), message.size()); - } - catch(std::exception &e) { - qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ << + } catch (std::exception &e) { + qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ << #ifdef _MSC_VER // Visual Studio __FUNCTION__; #else @@ -1568,8 +1734,7 @@ void WebsocketServerSocketInterface::binaryMessageReceived(const QByteArray & me qDebug() << "Message coming from:" << getAddress(); qDebug() << "Message length:" << message.size(); qDebug() << "Message content:" << message.toHex(); - } - catch(...) { + } catch (...) { qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ << #ifdef _MSC_VER // Visual Studio __FUNCTION__; diff --git a/servatrice/src/serversocketinterface.h b/servatrice/src/serversocketinterface.h index 908ea9d3..3123f141 100644 --- a/servatrice/src/serversocketinterface.h +++ b/servatrice/src/serversocketinterface.h @@ -22,11 +22,11 @@ #include #if QT_VERSION > 0x050300 - #include +#include #endif +#include "server_protocolhandler.h" #include #include -#include "server_protocolhandler.h" class Servatrice; class Servatrice_DatabaseInterface; @@ -63,19 +63,21 @@ protected slots: virtual void flushOutputQueue() = 0; signals: void outputQueueChanged(); + protected: void logDebugMessage(const QString &message); bool tooManyRegistrationAttempts(const QString &ipAddress); - virtual void writeToSocket(QByteArray & data) = 0; + virtual void writeToSocket(QByteArray &data) = 0; virtual void flushSocket() = 0; Servatrice *servatrice; QList outputQueue; QMutex outputQueueMutex; + private: Servatrice_DatabaseInterface *sqlInterface; - + Response::ResponseCode cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc); Response::ResponseCode cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc); int getDeckPathId(int basePathId, QStringList path); @@ -104,21 +106,26 @@ private: Response::ResponseCode cmdUpdateServerMessage(const Command_UpdateServerMessage &cmd, ResponseContainer &rc); Response::ResponseCode cmdRegisterAccount(const Command_Register &cmd, ResponseContainer &rc); Response::ResponseCode cmdActivateAccount(const Command_Activate &cmd, ResponseContainer & /* rc */); - Response::ResponseCode cmdReloadConfig(const Command_ReloadConfig &/* cmd */, ResponseContainer & /*rc*/); + Response::ResponseCode cmdReloadConfig(const Command_ReloadConfig & /* cmd */, ResponseContainer & /*rc*/); Response::ResponseCode cmdAdjustMod(const Command_AdjustMod &cmd, ResponseContainer & /*rc*/); Response::ResponseCode cmdForgotPasswordRequest(const Command_ForgotPasswordRequest &cmd, ResponseContainer &rc); Response::ResponseCode cmdForgotPasswordReset(const Command_ForgotPasswordReset &cmd, ResponseContainer &rc); - Response::ResponseCode cmdForgotPasswordChallenge(const Command_ForgotPasswordChallenge &cmd, ResponseContainer &rc); + Response::ResponseCode cmdForgotPasswordChallenge(const Command_ForgotPasswordChallenge &cmd, + ResponseContainer &rc); Response::ResponseCode processExtendedSessionCommand(int cmdType, const SessionCommand &cmd, ResponseContainer &rc); - Response::ResponseCode processExtendedModeratorCommand(int cmdType, const ModeratorCommand &cmd, ResponseContainer &rc); + Response::ResponseCode + processExtendedModeratorCommand(int cmdType, const ModeratorCommand &cmd, ResponseContainer &rc); Response::ResponseCode processExtendedAdminCommand(int cmdType, const AdminCommand &cmd, ResponseContainer &rc); Response::ResponseCode cmdAccountEdit(const Command_AccountEdit &cmd, ResponseContainer &rc); Response::ResponseCode cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer &rc); Response::ResponseCode cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer &rc); + public: - AbstractServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0); - ~AbstractServerSocketInterface() { }; + AbstractServerSocketInterface(Servatrice *_server, + Servatrice_DatabaseInterface *_databaseInterface, + QObject *parent = 0); + ~AbstractServerSocketInterface(){}; bool initSession(); virtual QHostAddress getPeerAddress() const = 0; @@ -131,21 +138,40 @@ class TcpServerSocketInterface : public AbstractServerSocketInterface { Q_OBJECT public: - TcpServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0); + TcpServerSocketInterface(Servatrice *_server, + Servatrice_DatabaseInterface *_databaseInterface, + QObject *parent = 0); ~TcpServerSocketInterface(); - QHostAddress getPeerAddress() const { return socket->peerAddress(); } - QString getAddress() const { return socket->peerAddress().toString(); } - QString getConnectionType() const { return "tcp"; }; + QHostAddress getPeerAddress() const + { + return socket->peerAddress(); + } + QString getAddress() const + { + return socket->peerAddress().toString(); + } + QString getConnectionType() const + { + return "tcp"; + }; + private: QTcpSocket *socket; QByteArray inputBuffer; bool messageInProgress; bool handshakeStarted; int messageLength; + protected: - void writeToSocket(QByteArray & data) { socket->write(data); }; - void flushSocket() { socket->flush(); }; + void writeToSocket(QByteArray &data) + { + socket->write(data); + }; + void flushSocket() + { + socket->flush(); + }; void initSessionDeprecated(); bool initTcpSession(); protected slots: @@ -160,23 +186,42 @@ class WebsocketServerSocketInterface : public AbstractServerSocketInterface { Q_OBJECT public: - WebsocketServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0); + WebsocketServerSocketInterface(Servatrice *_server, + Servatrice_DatabaseInterface *_databaseInterface, + QObject *parent = 0); ~WebsocketServerSocketInterface(); - QHostAddress getPeerAddress() const { return socket->peerAddress(); } - QString getAddress() const { return socket->peerAddress().toString(); } - QString getConnectionType() const { return "websocket"; }; + QHostAddress getPeerAddress() const + { + return socket->peerAddress(); + } + QString getAddress() const + { + return socket->peerAddress().toString(); + } + QString getConnectionType() const + { + return "websocket"; + }; + private: QWebSocket *socket; + protected: - void writeToSocket(QByteArray & data) { socket->sendBinaryMessage(data); }; - void flushSocket() { socket->flush(); }; + void writeToSocket(QByteArray &data) + { + socket->sendBinaryMessage(data); + }; + void flushSocket() + { + socket->flush(); + }; bool initWebsocketSession(); protected slots: - void binaryMessageReceived(const QByteArray & message); + void binaryMessageReceived(const QByteArray &message); void flushOutputQueue(); public slots: - void initConnection(void * _socket); + void initConnection(void *_socket); }; #endif diff --git a/servatrice/src/settingscache.cpp b/servatrice/src/settingscache.cpp index a759b672..f8702074 100644 --- a/servatrice/src/settingscache.cpp +++ b/servatrice/src/settingscache.cpp @@ -1,45 +1,45 @@ #include "settingscache.h" #include +#include #include #include -#include -SettingsCache::SettingsCache(const QString & fileName, QSettings::Format format, QObject * parent) - :QSettings(fileName, format, parent) +SettingsCache::SettingsCache(const QString &fileName, QSettings::Format format, QObject *parent) + : QSettings(fileName, format, parent) { // first, figure out if we are running in portable mode isPortableBuild = QFile::exists(qApp->applicationDirPath() + "/portable.dat"); - QStringList disallowedRegExpStr = value("users/disallowedregexp", "").toString().split(",", QString::SkipEmptyParts); + QStringList disallowedRegExpStr = + value("users/disallowedregexp", "").toString().split(",", QString::SkipEmptyParts); disallowedRegExpStr.removeDuplicates(); for (const QString ®ExpStr : disallowedRegExpStr) { disallowedRegExp.append(QRegExp(regExpStr)); } } -QString SettingsCache::guessConfigurationPath(QString & specificPath) +QString SettingsCache::guessConfigurationPath(QString &specificPath) { - const QString fileName="servatrice.ini"; - if(QFile::exists(qApp->applicationDirPath() + "/portable.dat")) - { + const QString fileName = "servatrice.ini"; + if (QFile::exists(qApp->applicationDirPath() + "/portable.dat")) { qDebug() << "Portable mode enabled"; return fileName; } QString guessFileName; // specific path - if(!specificPath.isEmpty() && QFile::exists(specificPath)) + if (!specificPath.isEmpty() && QFile::exists(specificPath)) return specificPath; // application directory path guessFileName = QCoreApplication::applicationDirPath() + "/" + fileName; - if(QFile::exists(guessFileName)) + if (QFile::exists(guessFileName)) return guessFileName; #ifdef Q_OS_UNIX // /etc guessFileName = "/etc/servatrice/" + fileName; - if(QFile::exists(guessFileName)) + if (QFile::exists(guessFileName)) return guessFileName; #endif diff --git a/servatrice/src/settingscache.h b/servatrice/src/settingscache.h index d952ee06..9ef992d1 100644 --- a/servatrice/src/settingscache.h +++ b/servatrice/src/settingscache.h @@ -1,21 +1,28 @@ #ifndef SERVATRICE_SETTINGSCACHE_H #define SERVATRICE_SETTINGSCACHE_H -#include -#include #include #include +#include +#include -class SettingsCache : public QSettings { +class SettingsCache : public QSettings +{ Q_OBJECT private: QSettings *settings; bool isPortableBuild; + public: - SettingsCache(const QString & fileName="servatrice.ini", QSettings::Format format=QSettings::IniFormat, QObject * parent = 0); - static QString guessConfigurationPath(QString & specificPath); + SettingsCache(const QString &fileName = "servatrice.ini", + QSettings::Format format = QSettings::IniFormat, + QObject *parent = 0); + static QString guessConfigurationPath(QString &specificPath); QList disallowedRegExp; - bool getIsPortableBuild() const { return isPortableBuild; } + bool getIsPortableBuild() const + { + return isPortableBuild; + } }; extern SettingsCache *settingsCache; diff --git a/servatrice/src/signalhandler.cpp b/servatrice/src/signalhandler.cpp index d06fc1db..e4d5d060 100644 --- a/servatrice/src/signalhandler.cpp +++ b/servatrice/src/signalhandler.cpp @@ -1,26 +1,25 @@ #include -#include "signalhandler.h" +#include "main.h" #include "server_logger.h" #include "settingscache.h" -#include "main.h" +#include "signalhandler.h" #ifdef Q_OS_UNIX -#include -#include -#include -#include +#include #include #include -#include +#include +#include +#include +#include #endif #define SIGSEGV_TRACE_LINES 40 int SignalHandler::sigHupFD[2]; -SignalHandler::SignalHandler(QObject *parent) -: QObject(parent) +SignalHandler::SignalHandler(QObject *parent) : QObject(parent) { #ifdef Q_OS_UNIX ::socketpair(AF_UNIX, SOCK_STREAM, 0, sigHupFD); @@ -34,14 +33,14 @@ SignalHandler::SignalHandler(QObject *parent) hup.sa_flags = 0; hup.sa_flags |= SA_RESTART; sigaction(SIGHUP, &hup, 0); - + struct sigaction segv; segv.sa_handler = SignalHandler::sigSegvHandler; segv.sa_flags = SA_RESETHAND; sigemptyset(&segv.sa_mask); sigaction(SIGSEGV, &segv, 0); sigaction(SIGABRT, &segv, 0); - + signal(SIGPIPE, SIG_IGN); #endif } @@ -69,7 +68,7 @@ void SignalHandler::internalSigHupHandler() logger->rotateLogs(); settingsCache->sync(); - + snHup->setEnabled(true); } @@ -90,12 +89,11 @@ void SignalHandler::sigSegvHandler(int sig) logger->logMessage("CRASH: SIGSEGV"); else if (sig == SIGABRT) logger->logMessage("CRASH: SIGABRT"); - + logger->deleteLater(); loggerThread->wait(); delete loggerThread; - + raise(sig); #endif } - diff --git a/servatrice/src/signalhandler.h b/servatrice/src/signalhandler.h index 314afa3b..af9f40cb 100644 --- a/servatrice/src/signalhandler.h +++ b/servatrice/src/signalhandler.h @@ -5,20 +5,20 @@ class QSocketNotifier; -class SignalHandler: public QObject +class SignalHandler : public QObject { - Q_OBJECT + Q_OBJECT public: - SignalHandler(QObject *parent = 0); - ~SignalHandler() { }; - static void sigHupHandler(int /* sig */); - static void sigSegvHandler(int sig); -private: - static int sigHupFD[2]; - QSocketNotifier *snHup; -private slots: - void internalSigHupHandler(); + SignalHandler(QObject *parent = 0); + ~SignalHandler(){}; + static void sigHupHandler(int /* sig */); + static void sigSegvHandler(int sig); +private: + static int sigHupFD[2]; + QSocketNotifier *snHup; +private slots: + void internalSigHupHandler(); }; #endif diff --git a/servatrice/src/smtpclient.cpp b/servatrice/src/smtpclient.cpp index 7e131d3f..6166e041 100644 --- a/servatrice/src/smtpclient.cpp +++ b/servatrice/src/smtpclient.cpp @@ -2,36 +2,37 @@ #include "settingscache.h" #include "smtp/qxtsmtp.h" -#include #include +#include -SmtpClient::SmtpClient(QObject *parent) -: QObject(parent) +SmtpClient::SmtpClient(QObject *parent) : QObject(parent) { smtp = new QxtSmtp(this); connect(smtp, SIGNAL(authenticated()), this, SLOT(authenticated())); - connect(smtp, SIGNAL(authenticationFailed(const QByteArray &)), this, SLOT(authenticationFailed(const QByteArray &))); + connect(smtp, SIGNAL(authenticationFailed(const QByteArray &)), this, + SLOT(authenticationFailed(const QByteArray &))); connect(smtp, SIGNAL(connected()), this, SLOT(connected())); connect(smtp, SIGNAL(connectionFailed(const QByteArray &)), this, SLOT(connectionFailed(const QByteArray &))); connect(smtp, SIGNAL(disconnected()), this, SLOT(disconnected())); connect(smtp, SIGNAL(encrypted()), this, SLOT(encrypted())); connect(smtp, SIGNAL(encryptionFailed(const QByteArray &)), this, SLOT(encryptionFailed(const QByteArray &))); connect(smtp, SIGNAL(finished()), this, SLOT(finished())); - connect(smtp, SIGNAL(mailFailed(int, int, const QByteArray &)), this, SLOT(mailFailed(int, int, const QByteArray &))); + connect(smtp, SIGNAL(mailFailed(int, int, const QByteArray &)), this, + SLOT(mailFailed(int, int, const QByteArray &))); connect(smtp, SIGNAL(mailSent(int)), this, SLOT(mailSent(int))); - connect(smtp, SIGNAL(recipientRejected(int, const QString &, const QByteArray &)), this, SLOT(recipientRejected(int, const QString &, const QByteArray &))); - connect(smtp, SIGNAL(senderRejected(int, const QString &, const QByteArray &)), this, SLOT(senderRejected(int, const QString &, const QByteArray &))); + connect(smtp, SIGNAL(recipientRejected(int, const QString &, const QByteArray &)), this, + SLOT(recipientRejected(int, const QString &, const QByteArray &))); + connect(smtp, SIGNAL(senderRejected(int, const QString &, const QByteArray &)), this, + SLOT(senderRejected(int, const QString &, const QByteArray &))); } SmtpClient::~SmtpClient() { - if(smtp) - { + if (smtp) { delete smtp; smtp = 0; } - } bool SmtpClient::enqueueActivationTokenMail(const QString &nickname, const QString &recipient, const QString &token) @@ -41,32 +42,27 @@ bool SmtpClient::enqueueActivationTokenMail(const QString &nickname, const QStri QString subject = settingsCache->value("smtp/subject", "").toString(); QString body = settingsCache->value("smtp/body", "").toString(); - if(email.isEmpty()) - { + if (email.isEmpty()) { qDebug() << "[MAIL] Missing sender email in configuration"; return false; } - if(subject.isEmpty()) - { + if (subject.isEmpty()) { qDebug() << "[MAIL] Missing subject field in configuration"; return false; } - if(body.isEmpty()) - { + if (body.isEmpty()) { qDebug() << "[MAIL] Missing body field in configuration"; return false; } - if(recipient.isEmpty()) - { + if (recipient.isEmpty()) { qDebug() << "[MAIL] Missing recipient field for user " << nickname; return false; } - if(token.isEmpty()) - { + if (token.isEmpty()) { qDebug() << "[MAIL] Missing token field for user " << nickname; return false; } @@ -89,32 +85,27 @@ bool SmtpClient::enqueueForgotPasswordTokenMail(const QString &nickname, const Q QString subject = settingsCache->value("forgotpassword/subject", "").toString(); QString body = settingsCache->value("forgotpassword/body", "").toString(); - if (email.isEmpty()) - { + if (email.isEmpty()) { qDebug() << "[MAIL] Missing sender email in configuration"; return false; } - if (subject.isEmpty()) - { + if (subject.isEmpty()) { qDebug() << "[MAIL] Missing subject field in configuration"; return false; } - if (body.isEmpty()) - { + if (body.isEmpty()) { qDebug() << "[MAIL] Missing body field in configuration"; return false; } - if (recipient.isEmpty()) - { + if (recipient.isEmpty()) { qDebug() << "[MAIL] Missing recipient field for user " << nickname; return false; } - if (token.isEmpty()) - { + if (token.isEmpty()) { qDebug() << "[MAIL] Missing token field for user " << nickname; return false; } @@ -133,10 +124,10 @@ bool SmtpClient::enqueueForgotPasswordTokenMail(const QString &nickname, const Q void SmtpClient::sendAllEmails() { // still connected from the previous round - if(smtp->socket()->state() == QAbstractSocket::ConnectedState) + if (smtp->socket()->state() == QAbstractSocket::ConnectedState) return; - if(smtp->pendingMessages() == 0) + if (smtp->pendingMessages() == 0) return; QString connectionType = settingsCache->value("smtp/connection", "tcp").toString(); @@ -150,9 +141,8 @@ void SmtpClient::sendAllEmails() smtp->setPassword(password); // Connect - if(connectionType == "ssl") - { - if(acceptAllCerts) + if (connectionType == "ssl") { + if (acceptAllCerts) smtp->sslSocket()->setPeerVerifyMode(QSslSocket::QueryPeer); smtp->connectToSecureHost(host, port); } else { @@ -165,7 +155,7 @@ void SmtpClient::authenticated() qDebug() << "[MAIL] authenticated"; } -void SmtpClient::authenticationFailed(const QByteArray & msg) +void SmtpClient::authenticationFailed(const QByteArray &msg) { qDebug() << "[MAIL] authenticationFailed" << QString(msg); } @@ -175,7 +165,7 @@ void SmtpClient::connected() qDebug() << "[MAIL] connected"; } -void SmtpClient::connectionFailed(const QByteArray & msg) +void SmtpClient::connectionFailed(const QByteArray &msg) { qDebug() << "[MAIL] connectionFailed" << QString(msg); } @@ -190,7 +180,7 @@ void SmtpClient::encrypted() qDebug() << "[MAIL] encrypted"; } -void SmtpClient::encryptionFailed(const QByteArray & msg) +void SmtpClient::encryptionFailed(const QByteArray &msg) { qDebug() << "[MAIL] encryptionFailed" << QString(msg); qDebug() << "[MAIL] Try enabling the \"acceptallcerts\" option in servatrice.ini"; @@ -202,7 +192,7 @@ void SmtpClient::finished() smtp->disconnectFromHost(); } -void SmtpClient::mailFailed(int mailID, int errorCode, const QByteArray & msg) +void SmtpClient::mailFailed(int mailID, int errorCode, const QByteArray &msg) { qDebug() << "[MAIL] mailFailed id=" << mailID << " errorCode=" << errorCode << "msg=" << QString(msg); } @@ -212,12 +202,12 @@ void SmtpClient::mailSent(int mailID) qDebug() << "[MAIL] mailSent" << mailID; } -void SmtpClient::recipientRejected(int mailID, const QString & address, const QByteArray & msg) +void SmtpClient::recipientRejected(int mailID, const QString &address, const QByteArray &msg) { qDebug() << "[MAIL] recipientRejected id=" << mailID << " address=" << address << "msg=" << QString(msg); } -void SmtpClient::senderRejected(int mailID, const QString & address, const QByteArray & msg) +void SmtpClient::senderRejected(int mailID, const QString &address, const QByteArray &msg) { qDebug() << "[MAIL] senderRejected id=" << mailID << " address=" << address << "msg=" << QString(msg); } diff --git a/servatrice/src/smtpclient.h b/servatrice/src/smtpclient.h index 4e07021f..be97ed44 100644 --- a/servatrice/src/smtpclient.h +++ b/servatrice/src/smtpclient.h @@ -6,11 +6,13 @@ class QxtSmtp; class QxtMailMessage; -class SmtpClient : public QObject { +class SmtpClient : public QObject +{ Q_OBJECT public: SmtpClient(QObject *parent = 0); ~SmtpClient(); + protected: QxtSmtp *smtp; public slots: @@ -19,17 +21,17 @@ public slots: void sendAllEmails(); protected slots: void authenticated(); - void authenticationFailed(const QByteArray & msg); + void authenticationFailed(const QByteArray &msg); void connected(); - void connectionFailed(const QByteArray & msg); + void connectionFailed(const QByteArray &msg); void disconnected(); void encrypted(); - void encryptionFailed(const QByteArray & msg); + void encryptionFailed(const QByteArray &msg); void finished(); - void mailFailed(int mailID, int errorCode, const QByteArray & msg); + void mailFailed(int mailID, int errorCode, const QByteArray &msg); void mailSent(int mailID); - void recipientRejected(int mailID, const QString & address, const QByteArray & msg); - void senderRejected(int mailID, const QString & address, const QByteArray & msg); + void recipientRejected(int mailID, const QString &address, const QByteArray &msg); + void senderRejected(int mailID, const QString &address, const QByteArray &msg); }; #endif \ No newline at end of file