Clang-format (#3028)

* 1/3 Add .clang-format file and travis compilation check

* 2/3 Run clang-format

* 3/3 Fix compilation problems due to include reordering

* 3bis/3 AfterControlStatement: false
This commit is contained in:
ctrlaltca 2018-01-27 10:41:32 +01:00 committed by GitHub
parent 8dbdd24c8e
commit b29bd9e070
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
272 changed files with 13378 additions and 9535 deletions

View file

@ -21,7 +21,32 @@ if [[ $BUILDTYPE == "Debug" ]]; then
cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix -DTEST=1 cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix -DTEST=1
make -j2 make -j2
make test 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
fi
if [[ $BUILDTYPE == "Release" ]]; then if [[ $BUILDTYPE == "Release" ]]; then
cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix
make package -j2 make package -j2

View file

@ -3,7 +3,7 @@
if [[ $TRAVIS_OS_NAME == "osx" ]] ; then if [[ $TRAVIS_OS_NAME == "osx" ]] ; then
brew install ccache # enable caching on mac (PATH only set in travis-compile.sh) brew install ccache # enable caching on mac (PATH only set in travis-compile.sh)
brew install --force qt@5.7 brew install --force qt@5.7
brew install protobuf brew install protobuf clang-format
fi fi
if [[ $TRAVIS_OS_NAME == "linux" ]] ; then if [[ $TRAVIS_OS_NAME == "linux" ]] ; then
echo Skipping... packages are installed with the Travis apt addon for sudo disabled container builds echo Skipping... packages are installed with the Travis apt addon for sudo disabled container builds

25
.clang-format Normal file
View file

@ -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

View file

@ -26,8 +26,12 @@ matrix:
#install dependencies for container-based "linux" builds #install dependencies for container-based "linux" builds
addons: addons:
apt: 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: packages:
- bc - bc
- clang-format-5.0
- cmake - cmake
- libprotobuf-dev - libprotobuf-dev
- protobuf-compiler - protobuf-compiler
@ -39,7 +43,6 @@ addons:
- libqt5svg5-dev - libqt5svg5-dev
- libqt5sql5-mysql - libqt5sql5-mysql
before_install: bash ./.ci/travis-dependencies.sh before_install: bash ./.ci/travis-dependencies.sh
script: bash ./.ci/travis-compile.sh script: bash ./.ci/travis-compile.sh

View file

@ -1,15 +1,17 @@
#include "abstractcarddragitem.h" #include "abstractcarddragitem.h"
#include "carddatabase.h" #include "carddatabase.h"
#include <QCursor> #include <QCursor>
#include <QGraphicsSceneMouseEvent>
#include <QDebug> #include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QPainter> #include <QPainter>
static const float CARD_WIDTH_HALF = CARD_WIDTH / 2; static const float CARD_WIDTH_HALF = CARD_WIDTH / 2;
static const float CARD_HEIGHT_HALF = CARD_HEIGHT / 2; static const float CARD_HEIGHT_HALF = CARD_HEIGHT / 2;
const QColor GHOST_MASK = QColor(255, 255, 255, 50); 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) : QGraphicsItem(), item(_item), hotSpot(_hotSpot)
{ {
if (parentDrag) { if (parentDrag) {
@ -27,7 +29,10 @@ AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, const QPoint
setZValue(2000000007); setZValue(2000000007);
} }
if (item->getTapped()) 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); setCacheMode(DeviceCoordinateCache);
} }

View file

@ -7,24 +7,42 @@ class QGraphicsScene;
class CardZone; class CardZone;
class CardInfo; class CardInfo;
class AbstractCardDragItem : public QObject, public QGraphicsItem { class AbstractCardDragItem : public QObject, public QGraphicsItem
{
Q_OBJECT Q_OBJECT
Q_INTERFACES(QGraphicsItem) Q_INTERFACES(QGraphicsItem)
protected: protected:
AbstractCardItem *item; AbstractCardItem *item;
QPointF hotSpot; QPointF hotSpot;
QList<AbstractCardDragItem *> childDrags; QList<AbstractCardDragItem *> childDrags;
public: public:
enum { Type = typeCardDrag }; enum
int type() const { return Type; } {
Type = typeCardDrag
};
int type() const
{
return Type;
}
AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
~AbstractCardDragItem(); ~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); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
AbstractCardItem *getItem() const { return item; } AbstractCardItem *getItem() const
QPointF getHotSpot() const { return hotSpot; } {
return item;
}
QPointF getHotSpot() const
{
return hotSpot;
}
void addChildDrag(AbstractCardDragItem *child); void addChildDrag(AbstractCardDragItem *child);
virtual void updatePosition(const QPointF &cursorScenePos) = 0; virtual void updatePosition(const QPointF &cursorScenePos) = 0;
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
}; };

View file

@ -1,21 +1,22 @@
#include <QPainter>
#include <QGraphicsScene>
#include <QCursor> #include <QCursor>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneMouseEvent>
#include <cmath> #include <QPainter>
#include <algorithm> #include <algorithm>
#include <cmath>
#ifdef _WIN32 #ifdef _WIN32
#include "round.h" #include "round.h"
#endif /* _WIN32 */ #endif /* _WIN32 */
#include "carddatabase.h"
#include "abstractcarditem.h" #include "abstractcarditem.h"
#include "carddatabase.h"
#include "gamescene.h"
#include "main.h"
#include "pictureloader.h" #include "pictureloader.h"
#include "settingscache.h" #include "settingscache.h"
#include "main.h"
#include "gamescene.h"
AbstractCardItem::AbstractCardItem(const QString &_name, Player *_owner, int _id, QGraphicsItem *parent) 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); setCursor(Qt::OpenHandCursor);
setFlag(ItemIsSelectable); setFlag(ItemIsSelectable);
@ -59,10 +60,8 @@ void AbstractCardItem::setRealZValue(qreal _zValue)
QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const
{ {
return QSizeF( return QSizeF(painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(),
painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(), painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length());
painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length()
);
} }
void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle) void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle)
@ -92,14 +91,12 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS
QPixmap translatedPixmap; QPixmap translatedPixmap;
bool paintImage = true; bool paintImage = true;
if(facedown || name.isEmpty()) if (facedown || name.isEmpty()) {
{
// never reveal card color, always paint the card back // never reveal card color, always paint the card back
PictureLoader::getCardBackPixmap(translatedPixmap, translatedSize.toSize()); PictureLoader::getCardBackPixmap(translatedPixmap, translatedSize.toSize());
} else { } else {
// don't even spend time trying to load the picture if our size is too small // 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()); PictureLoader::getPixmap(translatedPixmap, info, translatedSize.toSize());
if (translatedPixmap.isNull()) if (translatedPixmap.isNull())
paintImage = false; paintImage = false;
@ -141,7 +138,9 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS
nameStr = "# " + QString::number(id); nameStr = "# " + QString::number(id);
else else
nameStr = name; 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();
} }
@ -213,16 +212,14 @@ void AbstractCardItem::setColor(const QString &_color)
void AbstractCardItem::cacheBgColor() void AbstractCardItem::cacheBgColor()
{ {
QChar colorChar; QChar colorChar;
if (color.isEmpty()) if (color.isEmpty()) {
{
if (info) if (info)
colorChar = info->getColorChar(); colorChar = info->getColorChar();
} else { } else {
colorChar = color.at(0); colorChar = color.at(0);
} }
switch(colorChar.toLower().toLatin1()) switch (colorChar.toLower().toLatin1()) {
{
case 'b': case 'b':
bgColor = QColor(0, 0, 0); bgColor = QColor(0, 0, 0);
break; break;
@ -257,7 +254,10 @@ void AbstractCardItem::setTapped(bool _tapped, bool canAnimate)
static_cast<GameScene *>(scene())->registerAnimationItem(this); static_cast<GameScene *>(scene())->registerAnimationItem(this);
else { else {
tapAngle = tapped ? 90 : 0; 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(); update();
} }
} }
@ -273,8 +273,7 @@ void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
if ((event->modifiers() & Qt::ControlModifier)) { if ((event->modifiers() & Qt::ControlModifier)) {
setSelected(!isSelected()); setSelected(!isSelected());
} } else if (!isSelected()) {
else if (!isSelected()) {
scene()->clearSelection(); scene()->clearSelection();
setSelected(true); setSelected(true);
} }
@ -307,4 +306,3 @@ QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change,
} else } else
return QGraphicsItem::itemChange(change, value); return QGraphicsItem::itemChange(change, value);
} }

View file

@ -9,7 +9,8 @@ class Player;
const int CARD_WIDTH = 72; const int CARD_WIDTH = 72;
const int CARD_HEIGHT = 102; const int CARD_HEIGHT = 102;
class AbstractCardItem : public ArrowTarget { class AbstractCardItem : public ArrowTarget
{
Q_OBJECT Q_OBJECT
protected: protected:
CardInfo *info; CardInfo *info;
@ -20,44 +21,83 @@ protected:
int tapAngle; int tapAngle;
QString color; QString color;
QColor bgColor; QColor bgColor;
private: private:
bool isHovered; bool isHovered;
qreal realZValue; qreal realZValue;
private slots: private slots:
void pixmapUpdated(); void pixmapUpdated();
void cardInfoUpdated(); void cardInfoUpdated();
void callUpdate() { update(); } void callUpdate()
{
update();
}
signals: signals:
void hovered(AbstractCardItem *card); void hovered(AbstractCardItem *card);
void showCardInfoPopup(QPoint pos, QString cardName); void showCardInfoPopup(QPoint pos, QString cardName);
void deleteCardInfoPopup(QString cardName); void deleteCardInfoPopup(QString cardName);
void updateCardMenu(AbstractCardItem *card); void updateCardMenu(AbstractCardItem *card);
void sigPixmapUpdated(); void sigPixmapUpdated();
public: public:
enum { Type = typeCard }; enum
int type() const { return Type; } {
Type = typeCard
};
int type() const
{
return Type;
}
AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0); AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0);
~AbstractCardItem(); ~AbstractCardItem();
QRectF boundingRect() const; QRectF boundingRect() const;
QSizeF getTranslatedSize(QPainter *painter) const; QSizeF getTranslatedSize(QPainter *painter) const;
void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle); void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
CardInfo *getInfo() const { return info; } CardInfo *getInfo() const
int getId() const { return id; } {
void setId(int _id) { id = _id; } return info;
QString getName() const { return name; } }
int getId() const
{
return id;
}
void setId(int _id)
{
id = _id;
}
QString getName() const
{
return name;
}
void setName(const QString &_name = QString()); void setName(const QString &_name = QString());
qreal getRealZValue() const { return realZValue; } qreal getRealZValue() const
{
return realZValue;
}
void setRealZValue(qreal _zValue); void setRealZValue(qreal _zValue);
void setHovered(bool _hovered); void setHovered(bool _hovered);
QString getColor() const { return color; } QString getColor() const
{
return color;
}
void setColor(const QString &_color); void setColor(const QString &_color);
bool getTapped() const { return tapped; } bool getTapped() const
{
return tapped;
}
void setTapped(bool _tapped, bool canAnimate = false); void setTapped(bool _tapped, bool canAnimate = false);
bool getFaceDown() const { return facedown; } bool getFaceDown() const
{
return facedown;
}
void setFaceDown(bool _facedown); void setFaceDown(bool _facedown);
void processHoverEvent(); void processHoverEvent();
void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); } void deleteCardInfoPopup()
{
emit deleteCardInfoPopup(name);
}
protected: protected:
void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle); void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle);
void mousePressEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event);

View file

@ -1,28 +1,27 @@
#include "abstractclient.h" #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/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_identification.pb.h"
#include "pb/event_server_message.pb.h" #include "pb/event_server_message.pb.h"
#include "pb/event_server_shutdown.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_joined.pb.h"
#include "pb/event_user_left.pb.h" #include "pb/event_user_left.pb.h"
#include "pb/event_game_joined.pb.h" #include "pb/event_user_message.pb.h"
#include "pb/event_replay_added.pb.h" #include "pb/server_message.pb.h"
#include "get_pb_extension.h" #include "pending_command.h"
#include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.h>
#include "client_metatypes.h"
#include "featureset.h"
AbstractClient::AbstractClient(QObject *parent) AbstractClient::AbstractClient(QObject *parent) : QObject(parent), nextCmdId(0), status(StatusDisconnected)
: QObject(parent), nextCmdId(0), status(StatusDisconnected)
{ {
qRegisterMetaType<QVariant>("QVariant"); qRegisterMetaType<QVariant>("QVariant");
qRegisterMetaType<CommandContainer>("CommandContainer"); qRegisterMetaType<CommandContainer>("CommandContainer");
@ -77,20 +76,47 @@ void AbstractClient::processProtocolItem(const ServerMessage &item)
case ServerMessage::SESSION_EVENT: { case ServerMessage::SESSION_EVENT: {
const SessionEvent &event = item.session_event(); const SessionEvent &event = item.session_event();
switch ((SessionEvent::SessionEventType)getPbExtension(event)) { switch ((SessionEvent::SessionEventType)getPbExtension(event)) {
case SessionEvent::SERVER_IDENTIFICATION: emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext)); break; case SessionEvent::SERVER_IDENTIFICATION:
case SessionEvent::SERVER_MESSAGE: emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext)); break; emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext));
case SessionEvent::SERVER_SHUTDOWN: emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext)); break; break;
case SessionEvent::CONNECTION_CLOSED: emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext)); break; case SessionEvent::SERVER_MESSAGE:
case SessionEvent::USER_MESSAGE: emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext)); break; emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext));
case SessionEvent::NOTIFY_USER: emit notifyUserEventReceived(event.GetExtension(Event_NotifyUser::ext)); break; break;
case SessionEvent::LIST_ROOMS: emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext)); break; case SessionEvent::SERVER_SHUTDOWN:
case SessionEvent::ADD_TO_LIST: emit addToListEventReceived(event.GetExtension(Event_AddToList::ext)); break; emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext));
case SessionEvent::REMOVE_FROM_LIST: emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext)); break; break;
case SessionEvent::USER_JOINED: emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext)); break; case SessionEvent::CONNECTION_CLOSED:
case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break; emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext));
case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break; break;
case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break; case SessionEvent::USER_MESSAGE:
default: break; 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; break;
} }

View file

@ -1,11 +1,11 @@
#ifndef ABSTRACTCLIENT_H #ifndef ABSTRACTCLIENT_H
#define ABSTRACTCLIENT_H #define ABSTRACTCLIENT_H
#include <QObject>
#include <QVariant>
#include <QMutex>
#include "pb/response.pb.h" #include "pb/response.pb.h"
#include "pb/serverinfo_user.pb.h" #include "pb/serverinfo_user.pb.h"
#include <QMutex>
#include <QObject>
#include <QVariant>
class PendingCommand; class PendingCommand;
class CommandContainer; class CommandContainer;
@ -27,7 +27,8 @@ class Event_ServerShutdown;
class Event_ReplayAdded; class Event_ReplayAdded;
class FeatureSet; class FeatureSet;
enum ClientStatus { enum ClientStatus
{
StatusDisconnected, StatusDisconnected,
StatusDisconnecting, StatusDisconnecting,
StatusConnecting, StatusConnecting,
@ -40,7 +41,8 @@ enum ClientStatus {
StatusSubmitForgotPasswordChallenge, StatusSubmitForgotPasswordChallenge,
}; };
class AbstractClient : public QObject { class AbstractClient : public QObject
{
Q_OBJECT Q_OBJECT
signals: signals:
void statusChanged(ClientStatus _status); void statusChanged(ClientStatus _status);
@ -71,6 +73,7 @@ signals:
void activateAccepted(); void activateAccepted();
void sigQueuePendingCommand(PendingCommand *pend); void sigQueuePendingCommand(PendingCommand *pend);
private: private:
int nextCmdId; int nextCmdId;
mutable QMutex clientMutex; mutable QMutex clientMutex;
@ -79,22 +82,34 @@ private slots:
void queuePendingCommand(PendingCommand *pend); void queuePendingCommand(PendingCommand *pend);
protected slots: protected slots:
void processProtocolItem(const ServerMessage &item); void processProtocolItem(const ServerMessage &item);
protected: protected:
QMap<int, PendingCommand *> pendingCommands; QMap<int, PendingCommand *> pendingCommands;
QString userName, password, email, country, realName, token; QString userName, password, email, country, realName, token;
int gender; int gender;
void setStatus(ClientStatus _status); void setStatus(ClientStatus _status);
int getNewCmdId() { return nextCmdId++; } int getNewCmdId()
{
return nextCmdId++;
}
virtual void sendCommandContainer(const CommandContainer &cont) = 0; virtual void sendCommandContainer(const CommandContainer &cont) = 0;
public: public:
AbstractClient(QObject *parent = 0); AbstractClient(QObject *parent = 0);
~AbstractClient(); ~AbstractClient();
ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; } ClientStatus getStatus() const
{
QMutexLocker locker(&clientMutex);
return status;
}
void sendCommand(const CommandContainer &cont); void sendCommand(const CommandContainer &cont);
void sendCommand(PendingCommand *pend); void sendCommand(PendingCommand *pend);
const QString getUserName() {return userName;} const QString getUserName()
{
return userName;
}
static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd); static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd);
static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId); static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId);

View file

@ -1,16 +1,24 @@
#include "abstractcounter.h" #include "abstractcounter.h"
#include "player.h"
#include "settingscache.h"
#include <QPainter>
#include <QMenu>
#include <QAction>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneHoverEvent>
#include "pb/command_inc_counter.pb.h" #include "pb/command_inc_counter.pb.h"
#include "pb/command_set_counter.pb.h" #include "pb/command_set_counter.pb.h"
#include "player.h"
#include "settingscache.h"
#include <QAction>
#include <QGraphicsSceneHoverEvent>
#include <QGraphicsSceneMouseEvent>
#include <QMenu>
#include <QPainter>
AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, bool _useNameForShortcut, QGraphicsItem *parent) AbstractCounter::AbstractCounter(Player *_player,
: QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), useNameForShortcut(_useNameForShortcut), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) 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); setAcceptHoverEvents(true);
@ -152,8 +160,8 @@ void AbstractCounter::setCounter()
{ {
bool ok; bool ok;
dialogSemaphore = true; dialogSemaphore = true;
int newValue = int newValue = QInputDialog::getInt(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value,
QInputDialog::getInt(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok); -2000000000, 2000000000, 1, &ok);
if (deleteAfterDialog) { if (deleteAfterDialog) {
deleteLater(); deleteLater();
return; return;

View file

@ -7,7 +7,8 @@ class Player;
class QMenu; class QMenu;
class QAction; class QAction;
class AbstractCounter : public QObject, public QGraphicsItem { class AbstractCounter : public QObject, public QGraphicsItem
{
Q_OBJECT Q_OBJECT
Q_INTERFACES(QGraphicsItem) Q_INTERFACES(QGraphicsItem)
protected: protected:
@ -20,6 +21,7 @@ protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
private: private:
QAction *aSet, *aDec, *aInc; QAction *aSet, *aDec, *aInc;
QMenu *menu; QMenu *menu;
@ -29,17 +31,39 @@ private slots:
void refreshShortcuts(); void refreshShortcuts();
void incrementCounter(); void incrementCounter();
void setCounter(); void setCounter();
public: 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(); ~AbstractCounter();
QMenu *getMenu() const { return menu; } QMenu *getMenu() const
{
return menu;
}
void retranslateUi(); void retranslateUi();
int getId() const { return id; } int getId() const
QString getName() const { return name; } {
bool getShownInCounterArea() const { return shownInCounterArea; } return id;
int getValue() const { return value; } }
QString getName() const
{
return name;
}
bool getShownInCounterArea() const
{
return shownInCounterArea;
}
int getValue() const
{
return value;
}
void setValue(int _value); void setValue(int _value);
void delCounter(); void delCounter();

View file

@ -1,7 +1,12 @@
#include "abstractgraphicsitem.h" #include "abstractgraphicsitem.h"
#include <QPainter> #include <QPainter>
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(); painter->save();
@ -27,9 +32,13 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QC
qreal yOffset = 20; qreal yOffset = 20;
qreal spacing = 2; qreal spacing = 2;
if (position < 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 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->drawEllipse(textRect);

View file

@ -3,7 +3,8 @@
#include <QGraphicsItem> #include <QGraphicsItem>
enum GraphicsItemType { enum GraphicsItemType
{
typeCard = QGraphicsItem::UserType + 1, typeCard = QGraphicsItem::UserType + 1,
typeCardDrag = QGraphicsItem::UserType + 2, typeCardDrag = QGraphicsItem::UserType + 2,
typeZone = QGraphicsItem::UserType + 3, typeZone = QGraphicsItem::UserType + 3,
@ -12,13 +13,17 @@ enum GraphicsItemType {
typeOther = QGraphicsItem::UserType + 6 typeOther = QGraphicsItem::UserType + 6
}; };
class AbstractGraphicsItem : public QObject, public QGraphicsItem { class AbstractGraphicsItem : public QObject, public QGraphicsItem
{
Q_OBJECT Q_OBJECT
Q_INTERFACES(QGraphicsItem) Q_INTERFACES(QGraphicsItem)
protected: protected:
void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter); void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter);
public: public:
AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { } AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent)
{
}
}; };
#endif #endif

View file

@ -2,16 +2,16 @@
#include <cmath> #include <cmath>
#include "arrowitem.h" #include "arrowitem.h"
#include "playertarget.h"
#include "carditem.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "carditem.h"
#include "cardzone.h" #include "cardzone.h"
#include "player.h" #include "player.h"
#include "playertarget.h"
#include "settingscache.h" #include "settingscache.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsScene>
#include <QDebug> #include <QDebug>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include "color.h" #include "color.h"
#include "pb/command_attach_card.pb.h" #include "pb/command_attach_card.pb.h"
@ -19,7 +19,8 @@
#include "pb/command_delete_arrow.pb.h" #include "pb/command_delete_arrow.pb.h"
ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &_color) 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<QGraphicsItem *>(startItem); qDebug() << "ArrowItem constructor: startItem=" << static_cast<QGraphicsItem *>(startItem);
setZValue(2000000005); setZValue(2000000005);
@ -60,7 +61,8 @@ void ArrowItem::updatePath()
if (!targetItem) if (!targetItem)
return; 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); updatePath(endPoint);
} }
@ -68,13 +70,15 @@ void ArrowItem::updatePath(const QPointF &endPoint)
{ {
const double arrowWidth = 15.0; const double arrowWidth = 15.0;
const double headWidth = 40.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; const double phi = 15;
if (!startItem) if (!startItem)
return; 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); QLineF line(startPoint, endPoint);
qreal lineLength = line.length(); qreal lineLength = line.length();
@ -92,10 +96,14 @@ void ArrowItem::updatePath(const QPointF &endPoint)
QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage); QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage);
QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001)); QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001));
qreal alpha = testLine.angle() - 90; qreal alpha = testLine.angle() - 90;
QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); QPointF endPoint1 =
QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); 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 endPoint2 =
QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); 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 = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
path.quadTo(c, endPoint1); path.quadTo(c, endPoint1);

View file

@ -9,12 +9,14 @@ class QMenu;
class Player; class Player;
class ArrowTarget; class ArrowTarget;
class ArrowItem : public QObject, public QGraphicsItem { class ArrowItem : public QObject, public QGraphicsItem
{
Q_OBJECT Q_OBJECT
Q_INTERFACES(QGraphicsItem) Q_INTERFACES(QGraphicsItem)
private: private:
QPainterPath path; QPainterPath path;
QMenu *menu; QMenu *menu;
protected: protected:
Player *player; Player *player;
int id; int id;
@ -22,40 +24,70 @@ protected:
QColor color; QColor color;
bool fullColor; bool fullColor;
void mousePressEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event);
public: public:
ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color); ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color);
~ArrowItem(); ~ArrowItem();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QRectF boundingRect() const { return path.boundingRect(); } QRectF boundingRect() const
QPainterPath shape() const { return path; } {
return path.boundingRect();
}
QPainterPath shape() const
{
return path;
}
void updatePath(); void updatePath();
void updatePath(const QPointF &endPoint); void updatePath(const QPointF &endPoint);
int getId() const { return id; } int getId() const
Player *getPlayer() const { return player; } {
void setStartItem(ArrowTarget *_item) { startItem = _item; } return id;
void setTargetItem(ArrowTarget *_item) { targetItem = _item; } }
ArrowTarget *getStartItem() const { return startItem; } Player *getPlayer() const
ArrowTarget *getTargetItem() const { return targetItem; } {
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(); void delArrow();
}; };
class ArrowDragItem : public ArrowItem { class ArrowDragItem : public ArrowItem
{
Q_OBJECT Q_OBJECT
private: private:
QList<ArrowDragItem *> childArrows; QList<ArrowDragItem *> childArrows;
public: public:
ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color); ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color);
void addChildArrow(ArrowDragItem *childArrow); void addChildArrow(ArrowDragItem *childArrow);
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
}; };
class ArrowAttachItem : public ArrowItem { class ArrowAttachItem : public ArrowItem
{
Q_OBJECT Q_OBJECT
public: public:
ArrowAttachItem(ArrowTarget *_startItem); ArrowAttachItem(ArrowTarget *_startItem);
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

View file

@ -7,29 +7,56 @@
class Player; class Player;
class ArrowItem; class ArrowItem;
class ArrowTarget : public AbstractGraphicsItem { class ArrowTarget : public AbstractGraphicsItem
{
Q_OBJECT Q_OBJECT
protected: protected:
Player *owner; Player *owner;
private: private:
bool beingPointedAt; bool beingPointedAt;
QList<ArrowItem *> arrowsFrom, arrowsTo; QList<ArrowItem *> arrowsFrom, arrowsTo;
public: public:
ArrowTarget(Player *_owner, QGraphicsItem *parent = 0); ArrowTarget(Player *_owner, QGraphicsItem *parent = 0);
~ArrowTarget(); ~ArrowTarget();
Player *getOwner() const { return owner; } Player *getOwner() const
{
return owner;
}
void setBeingPointedAt(bool _beingPointedAt); void setBeingPointedAt(bool _beingPointedAt);
bool getBeingPointedAt() const { return beingPointedAt; } bool getBeingPointedAt() const
{
return beingPointedAt;
}
const QList<ArrowItem *> &getArrowsFrom() const { return arrowsFrom; } const QList<ArrowItem *> &getArrowsFrom() const
void addArrowFrom(ArrowItem *arrow) { arrowsFrom.append(arrow); } {
void removeArrowFrom(ArrowItem *arrow) { arrowsFrom.removeAt(arrowsFrom.indexOf(arrow)); } return arrowsFrom;
}
void addArrowFrom(ArrowItem *arrow)
{
arrowsFrom.append(arrow);
}
void removeArrowFrom(ArrowItem *arrow)
{
arrowsFrom.removeAt(arrowsFrom.indexOf(arrow));
}
const QList<ArrowItem *> &getArrowsTo() const { return arrowsTo; } const QList<ArrowItem *> &getArrowsTo() const
void addArrowTo(ArrowItem *arrow) { arrowsTo.append(arrow); } {
void removeArrowTo(ArrowItem *arrow) { arrowsTo.removeAt(arrowsTo.indexOf(arrow)); } return arrowsTo;
}
void addArrowTo(ArrowItem *arrow)
{
arrowsTo.append(arrow);
}
void removeArrowTo(ArrowItem *arrow)
{
arrowsTo.removeAt(arrowsTo.indexOf(arrow));
}
}; };
#endif #endif

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,14 @@
#ifndef CARDDATABASE_H #ifndef CARDDATABASE_H
#define CARDDATABASE_H #define CARDDATABASE_H
#include <QHash>
#include <QPixmap>
#include <QMap>
#include <QDate>
#include <QDataStream>
#include <QList>
#include <QXmlStreamReader>
#include <QBasicMutex> #include <QBasicMutex>
#include <QDataStream>
#include <QDate>
#include <QHash>
#include <QList>
#include <QMap>
#include <QPixmap>
#include <QXmlStreamReader>
class CardDatabase; class CardDatabase;
class CardInfo; class CardInfo;
@ -29,26 +29,62 @@ class CardSet : public QList<CardInfo *>
bool enabled, isknown; bool enabled, isknown;
public: public:
explicit CardSet(const QString &_shortName = QString(), const QString &_longName = QString(), const QString &_setType = QString(), const QDate &_releaseDate = QDate()); explicit CardSet(const QString &_shortName = QString(),
const QString &_longName = QString(),
const QString &_setType = QString(),
const QDate &_releaseDate = QDate());
QString getCorrectedShortName() const; QString getCorrectedShortName() const;
QString getShortName() const { return shortName; } QString getShortName() const
QString getLongName() const { return longName; } {
QString getSetType() const { return setType; } return shortName;
QDate getReleaseDate() const { return releaseDate; } }
void setLongName(QString & _longName) { longName = _longName; } QString getLongName() const
void setSetType(QString & _setType) { setType = _setType; } {
void setReleaseDate(QDate & _releaseDate) { releaseDate = _releaseDate; } 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(); void loadSetOptions();
int getSortKey() const { return sortKey; } int getSortKey() const
{
return sortKey;
}
void setSortKey(unsigned int _sortKey); void setSortKey(unsigned int _sortKey);
bool getEnabled() const { return enabled; } bool getEnabled() const
{
return enabled;
}
void setEnabled(bool _enabled); void setEnabled(bool _enabled);
bool getIsKnown() const { return isknown; } bool getIsKnown() const
{
return isknown;
}
void setIsKnown(bool _isknown); void setIsKnown(bool _isknown);
// Determine incomplete sets. // Determine incomplete sets.
bool getIsKnownIgnored() const { return longName.length() + setType.length() + releaseDate.toString().length() == 0 ; } bool getIsKnownIgnored() const
{
return longName.length() + setType.length() + releaseDate.toString().length() == 0;
}
}; };
class SetList : public QList<CardSet *> class SetList : public QList<CardSet *>
@ -128,53 +164,159 @@ class CardInfo : public QObject
const QStringMap &_customPicURLs = QStringMap(), const QStringMap &_customPicURLs = QStringMap(),
MuidMap muids = MuidMap(), MuidMap muids = MuidMap(),
QStringMap _collectorNumbers = QStringMap(), QStringMap _collectorNumbers = QStringMap(),
QStringMap _rarities = QStringMap() QStringMap _rarities = QStringMap());
);
~CardInfo() override; ~CardInfo() override;
inline const QString &getName() const { return name; } inline const QString &getName() const
inline const QString &getSetsNames() const { return setsNames; } {
const QString &getSimpleName() const { return simpleName; } return name;
bool getIsToken() const { return isToken; } }
const SetList &getSets() const { return sets; } inline const QString &getSetsNames() const
inline const QString &getManaCost() const { return manacost; } {
inline const QString &getCmc() const { return cmc; } return setsNames;
inline const QString &getCardType() const { return cardtype; } }
inline const QString &getPowTough() const { return powtough; } const QString &getSimpleName() const
const QString &getText() const { return text; } {
const QString &getPixmapCacheKey() const { return pixmapCacheKey; } return simpleName;
const int &getLoyalty() const { return loyalty; } }
bool getCipt() const { return cipt; } 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 setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); }
// void setCmc(const QString &_cmc) { cmc = _cmc; emit cardInfoChanged(this); } // void setCmc(const QString &_cmc) { cmc = _cmc; emit cardInfoChanged(this); }
void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); } void setCardType(const QString &_cardType)
void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); } {
void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); } cardtype = _cardType;
void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); } 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 QChar getColorChar() const;
const QStringList &getColors() const { return colors; } const QStringList &getColors() const
const QList<CardRelation *> &getRelatedCards() const { return relatedCards; } {
const QList<CardRelation *> &getReverseRelatedCards() const { return reverseRelatedCards; } return colors;
const QList<CardRelation *> &getReverseRelatedCards2Me() const { return reverseRelatedCardsToMe; } }
const QList<CardRelation *> &getRelatedCards() const
{
return relatedCards;
}
const QList<CardRelation *> &getReverseRelatedCards() const
{
return reverseRelatedCards;
}
const QList<CardRelation *> &getReverseRelatedCards2Me() const
{
return reverseRelatedCardsToMe;
}
void resetReverseRelatedCards2Me(); void resetReverseRelatedCards2Me();
void addReverseRelatedCards2Me(CardRelation * cardRelation) { reverseRelatedCardsToMe.append(cardRelation); } void addReverseRelatedCards2Me(CardRelation *cardRelation)
bool getUpsideDownArt() const { return upsideDownArt; } {
QString getCustomPicURL(const QString &set) const { return customPicURLs.value(set); } reverseRelatedCardsToMe.append(cardRelation);
int getMuId(const QString &set) const { return muIds.value(set); } }
QString getCollectorNumber(const QString &set) const { return collectorNumbers.value(set); } bool getUpsideDownArt() const
QString getRarity(const QString &set) const { return rarities.value(set); } {
QStringMap getRarities() const { return rarities; } 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 getMainCardType() const;
QString getCorrectedName() const; QString getCorrectedName() const;
int getTableRow() const { return tableRow; } int getTableRow() const
void setTableRow(int _tableRow) { tableRow = _tableRow; } {
return tableRow;
}
void setTableRow(int _tableRow)
{
tableRow = _tableRow;
}
// void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); } // void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); }
//void setCustomPicURL(const QString &_set, const QString &_customPicURL) { customPicURLs.insert(_set, _customPicURL); } // void setCustomPicURL(const QString &_set, const QString &_customPicURL) { customPicURLs.insert(_set,
void setMuId(const QString &_set, const int &_muId) { muIds.insert(_set, _muId); } // _customPicURL); }
void setSetNumber(const QString &_set, const QString &_setNumber) { collectorNumbers.insert(_set, _setNumber); } void setMuId(const QString &_set, const int &_muId)
void setRarity(const QString &_set, const QString &_setNumber) { rarities.insert(_set, _setNumber); } {
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 addToSet(CardSet *set);
void emitPixmapUpdated() { emit pixmapUpdated(); } void emitPixmapUpdated()
{
emit pixmapUpdated();
}
void refreshCachedSetNames(); void refreshCachedSetNames();
/** /**
@ -188,7 +330,15 @@ class CardInfo : public QObject
void cardInfoChanged(CardInfo *card); void cardInfoChanged(CardInfo *card);
}; };
enum LoadStatus { Ok, VersionTooOld, Invalid, NotLoaded, FileError, NoCards }; enum LoadStatus
{
Ok,
VersionTooOld,
Invalid,
NotLoaded,
FileError,
NoCards
};
typedef QHash<QString, CardInfo *> CardNameMap; typedef QHash<QString, CardInfo *> CardNameMap;
typedef QHash<QString, CardSet *> SetNameMap; typedef QHash<QString, CardSet *> SetNameMap;
@ -213,6 +363,7 @@ class CardDatabase : public QObject
SetNameMap sets; SetNameMap sets;
LoadStatus loadStatus; LoadStatus loadStatus;
private: private:
static const int versionNeeded; static const int versionNeeded;
void loadCardsFromXml(QXmlStreamReader &xml); void loadCardsFromXml(QXmlStreamReader &xml);
@ -222,10 +373,8 @@ class CardDatabase : public QObject
void checkUnknownSets(); void checkUnknownSets();
void refreshCachedReverseRelatedCards(); void refreshCachedReverseRelatedCards();
QBasicMutex *reloadDatabaseMutex = new QBasicMutex(), QBasicMutex *reloadDatabaseMutex = new QBasicMutex(), *clearDatabaseMutex = new QBasicMutex(),
*clearDatabaseMutex = new QBasicMutex(), *loadFromFileMutex = new QBasicMutex(), *addCardMutex = new QBasicMutex(),
*loadFromFileMutex = new QBasicMutex(),
*addCardMutex = new QBasicMutex(),
*removeCardMutex = new QBasicMutex(); *removeCardMutex = new QBasicMutex();
public: public:
@ -246,14 +395,20 @@ class CardDatabase : public QObject
CardInfo *getCardBySimpleName(const QString &cardName) const; CardInfo *getCardBySimpleName(const QString &cardName) const;
CardSet *getSet(const QString &setName); CardSet *getSet(const QString &setName);
QList<CardInfo *> getCardList() const { return cards.values(); } QList<CardInfo *> getCardList() const
{
return cards.values();
}
SetList getSetList() const; SetList getSetList() const;
LoadStatus loadFromFile(const QString &fileName); LoadStatus loadFromFile(const QString &fileName);
bool saveToFile(const QString &fileName, bool tokens = false); bool saveToFile(const QString &fileName, bool tokens = false);
bool saveCustomTokensToFile(); bool saveCustomTokensToFile();
QStringList getAllColors() const; QStringList getAllColors() const;
QStringList getAllMainCardTypes() const; QStringList getAllMainCardTypes() const;
LoadStatus getLoadStatus() const { return loadStatus; } LoadStatus getLoadStatus() const
{
return loadStatus;
}
void enableAllUnknownSets(); void enableAllUnknownSets();
void markAllSetsAsKnown(); void markAllSetsAsKnown();
void notifyEnabledSetsChanged(); void notifyEnabledSetsChanged();
@ -280,19 +435,37 @@ class CardRelation : public QObject
bool isCreateAllExclusion; bool isCreateAllExclusion;
bool isVariableCount; bool isVariableCount;
int defaultCount; int defaultCount;
public: public:
explicit CardRelation(const QString &_name = QString(), explicit CardRelation(const QString &_name = QString(),
bool _doesAttach = false, bool _doesAttach = false,
bool _isCreateAllExclusion = false, bool _isCreateAllExclusion = false,
bool _isVariableCount = false, bool _isVariableCount = false,
int _defaultCount = 1 int _defaultCount = 1);
);
inline const QString &getName() const { return name; } inline const QString &getName() const
bool getDoesAttach() const { return doesAttach; } {
bool getCanCreateAnother() const { return !doesAttach; } return name;
bool getIsCreateAllExclusion() const { return isCreateAllExclusion; } }
bool getIsVariable() const { return isVariableCount; } bool getDoesAttach() const
int getDefaultCount() const { return defaultCount; } {
return doesAttach;
}
bool getCanCreateAnother() const
{
return !doesAttach;
}
bool getIsCreateAllExclusion() const
{
return isCreateAllExclusion;
}
bool getIsVariable() const
{
return isVariableCount;
}
int getDefaultCount() const
{
return defaultCount;
}
}; };
#endif #endif

View file

@ -29,23 +29,27 @@ int CardDatabaseModel::columnCount(const QModelIndex &/*parent*/) const
QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid() || if (!index.isValid() || index.row() >= cardList.size() || index.column() >= CARDDBMODEL_COLUMNS ||
index.row() >= cardList.size() ||
index.column() >= CARDDBMODEL_COLUMNS ||
(role != Qt::DisplayRole && role != SortRole)) (role != Qt::DisplayRole && role != SortRole))
return QVariant(); return QVariant();
CardInfo *card = cardList.at(index.row()); CardInfo *card = cardList.at(index.row());
switch (index.column()) { switch (index.column()) {
case NameColumn: return card->getName(); case NameColumn:
case SetListColumn: return card->getSetsNames(); return card->getName();
case ManaCostColumn: return role == SortRole ? case SetListColumn:
QString("%1%2").arg(card->getCmc(), 4, QChar('0')).arg(card->getManaCost()) : return card->getSetsNames();
card->getManaCost(); case ManaCostColumn:
case CardTypeColumn: return card->getCardType(); return role == SortRole ? QString("%1%2").arg(card->getCmc(), 4, QChar('0')).arg(card->getManaCost())
case PTColumn: return card->getPowTough(); : card->getManaCost();
case ColorColumn: return card->getColors().join(""); case CardTypeColumn:
default: return QVariant(); 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) if (orientation != Qt::Horizontal)
return QVariant(); return QVariant();
switch (section) { switch (section) {
case NameColumn: return QString(tr("Name")); case NameColumn:
case SetListColumn: return QString(tr("Sets")); return QString(tr("Name"));
case ManaCostColumn: return QString(tr("Mana cost")); case SetListColumn:
case CardTypeColumn: return QString(tr("Card type")); return QString(tr("Sets"));
case PTColumn: return QString(tr("P/T")); case ManaCostColumn:
case ColorColumn: return QString(tr("Color(s)")); return QString(tr("Mana cost"));
default: return QVariant(); case CardTypeColumn:
return QString(tr("Card type"));
case PTColumn:
return QString(tr("P/T"));
case ColorColumn:
return QString(tr("Color(s)"));
default:
return QVariant();
} }
} }
@ -80,8 +91,7 @@ bool CardDatabaseModel::checkCardHasAtLeastOneEnabledSet(CardInfo *card)
if (!showOnlyCardsFromEnabledSets) if (!showOnlyCardsFromEnabledSets)
return true; return true;
foreach(CardSet * set, card->getSets()) foreach (CardSet *set, card->getSets()) {
{
if (set->getEnabled()) if (set->getEnabled())
return true; return true;
} }
@ -92,15 +102,13 @@ bool CardDatabaseModel::checkCardHasAtLeastOneEnabledSet(CardInfo *card)
void CardDatabaseModel::cardDatabaseEnabledSetsChanged() void CardDatabaseModel::cardDatabaseEnabledSetsChanged()
{ {
// remove all the cards no more present in at least one enabled set // remove all the cards no more present in at least one enabled set
foreach(CardInfo * card, cardList) foreach (CardInfo *card, cardList) {
{
if (!checkCardHasAtLeastOneEnabledSet(card)) if (!checkCardHasAtLeastOneEnabledSet(card))
cardRemoved(card); cardRemoved(card);
} }
// re-check all the card currently not shown, maybe their part of a newly-enabled set // re-check all the card currently not shown, maybe their part of a newly-enabled set
foreach(CardInfo * card, db->getCardList()) foreach (CardInfo *card, db->getCardList()) {
{
if (!cardList.contains(card)) if (!cardList.contains(card))
cardAdded(card); cardAdded(card);
} }
@ -108,8 +116,7 @@ void CardDatabaseModel::cardDatabaseEnabledSetsChanged()
void CardDatabaseModel::cardAdded(CardInfo *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 // add the card if it's present in at least one enabled set
beginInsertRows(QModelIndex(), cardList.size(), cardList.size()); beginInsertRows(QModelIndex(), cardList.size(), cardList.size());
cardList.append(card); cardList.append(card);
@ -130,9 +137,7 @@ void CardDatabaseModel::cardRemoved(CardInfo *card)
endRemoveRows(); endRemoveRows();
} }
CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) : QSortFilterProxyModel(parent), isToken(ShowAll)
: QSortFilterProxyModel(parent),
isToken(ShowAll)
{ {
filterTree = NULL; filterTree = NULL;
setFilterCaseSensitivity(Qt::CaseInsensitive); setFilterCaseSensitivity(Qt::CaseInsensitive);
@ -162,13 +167,13 @@ int CardDatabaseDisplayModel::rowCount(const QModelIndex &parent) const
return qMin(QSortFilterProxyModel::rowCount(parent), loadedRowCount); 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 leftString = sourceModel()->data(left, CardDatabaseModel::SortRole).toString();
QString rightString = sourceModel()->data(right, 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 isLeftType = leftString.startsWith(cardName, Qt::CaseInsensitive);
bool isRightType = rightString.startsWith(cardName, Qt::CaseInsensitive); bool isRightType = rightString.startsWith(cardName, Qt::CaseInsensitive);
@ -180,8 +185,7 @@ bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelInd
// same checks for the right string // same checks for the right string
if (isRightType && (!isLeftType || rightString.size() == cardName.size())) if (isRightType && (!isLeftType || rightString.size() == cardName.size()))
return false; 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 leftList = leftString.split("/");
QStringList rightList = rightString.split("/"); QStringList rightList = rightString.split("/");
@ -191,8 +195,7 @@ bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelInd
int lessThanNum = lessThanNumerically(leftList.at(0), rightList.at(0)); int lessThanNum = lessThanNumerically(leftList.at(0), rightList.at(0));
if (lessThanNum != 0) { if (lessThanNum != 0) {
return lessThanNum < 0; return lessThanNum < 0;
} } else {
else {
// power equal, check toughness // power equal, check toughness
return lessThanNumerically(leftList.at(1), rightList.at(1)) < 0; 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; 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) { if (left == right) {
return 0; return 0;
} }
@ -213,11 +217,9 @@ int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QSt
if (okLeft && okRight) { if (okLeft && okRight) {
if (leftNum < rightNum) { if (leftNum < rightNum) {
return -1; return -1;
} } else if (leftNum > rightNum) {
else if(leftNum > rightNum){
return 1; return 1;
} } else {
else {
return 0; return 0;
} }
} }
@ -254,21 +256,17 @@ int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QSt
// both parsed as numbers, but different number // both parsed as numbers, but different number
if (leftNum < rightNum) { if (leftNum < rightNum) {
return -1; return -1;
} } else {
else {
return 1; return 1;
} }
} } else {
else {
// both parsed, same number, but at least one has something else // both parsed, same number, but at least one has something else
// so compare the part after the number - prefer nothing // so compare the part after the number - prefer nothing
return QString::localeAwareCompare(leftAfterNum, rightAfterNum); return QString::localeAwareCompare(leftAfterNum, rightAfterNum);
} }
} } else if (okLeft) {
else if (okLeft) {
return -1; return -1;
} } else if (okRight) {
else if (okRight) {
return 1; return 1;
} }
// couldn't parse it, just return String comparison // couldn't parse it, just return String comparison
@ -284,7 +282,8 @@ bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex
return rowMatchesCardName(info); 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)) if (!cardName.isEmpty() && !info->getName().contains(cardName, Qt::CaseInsensitive))
return false; return false;
@ -323,10 +322,8 @@ void CardDatabaseDisplayModel::filterTreeChanged()
invalidate(); invalidate();
} }
TokenDisplayModel::TokenDisplayModel(QObject *parent) TokenDisplayModel::TokenDisplayModel(QObject *parent) : CardDatabaseDisplayModel(parent)
: CardDatabaseDisplayModel(parent)
{ {
} }
bool TokenDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const bool TokenDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const

View file

@ -1,27 +1,46 @@
#ifndef CARDDATABASEMODEL_H #ifndef CARDDATABASEMODEL_H
#define CARDDATABASEMODEL_H #define CARDDATABASEMODEL_H
#include "carddatabase.h"
#include <QAbstractListModel> #include <QAbstractListModel>
#include <QSortFilterProxyModel>
#include <QList> #include <QList>
#include <QSet> #include <QSet>
#include "carddatabase.h" #include <QSortFilterProxyModel>
class FilterTree; class FilterTree;
class CardDatabaseModel : public QAbstractListModel { class CardDatabaseModel : public QAbstractListModel
{
Q_OBJECT Q_OBJECT
public: public:
enum Columns { NameColumn, SetListColumn, ManaCostColumn, PTColumn, CardTypeColumn, ColorColumn }; enum Columns
enum Role { SortRole=Qt::UserRole }; {
NameColumn,
SetListColumn,
ManaCostColumn,
PTColumn,
CardTypeColumn,
ColorColumn
};
enum Role
{
SortRole = Qt::UserRole
};
CardDatabaseModel(CardDatabase *_db, bool _showOnlyCardsFromEnabledSets, QObject *parent = 0); CardDatabaseModel(CardDatabase *_db, bool _showOnlyCardsFromEnabledSets, QObject *parent = 0);
~CardDatabaseModel(); ~CardDatabaseModel();
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
CardDatabase *getDatabase() const { return db; } CardDatabase *getDatabase() const
CardInfo *getCard(int index) const { return cardList[index]; } {
return db;
}
CardInfo *getCard(int index) const
{
return cardList[index];
}
private: private:
QList<CardInfo *> cardList; QList<CardInfo *> cardList;
CardDatabase *db; CardDatabase *db;
@ -35,10 +54,17 @@ private slots:
void cardDatabaseEnabledSetsChanged(); void cardDatabaseEnabledSetsChanged();
}; };
class CardDatabaseDisplayModel : public QSortFilterProxyModel { class CardDatabaseDisplayModel : public QSortFilterProxyModel
{
Q_OBJECT Q_OBJECT
public: public:
enum FilterBool { ShowTrue, ShowFalse, ShowAll }; enum FilterBool
{
ShowTrue,
ShowFalse,
ShowAll
};
private: private:
FilterBool isToken; FilterBool isToken;
QString cardNameBeginning, cardName, cardText; QString cardNameBeginning, cardName, cardText;
@ -46,19 +72,52 @@ private:
QSet<QString> cardNameSet, cardTypes, cardColors; QSet<QString> cardNameSet, cardTypes, cardColors;
FilterTree *filterTree; FilterTree *filterTree;
int loadedRowCount; int loadedRowCount;
public: public:
CardDatabaseDisplayModel(QObject *parent = 0); CardDatabaseDisplayModel(QObject *parent = 0);
void setFilterTree(FilterTree *filterTree); void setFilterTree(FilterTree *filterTree);
void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } void setIsToken(FilterBool _isToken)
void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } {
void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } isToken = _isToken;
void setCardNameSet(const QSet<QString> &_cardNameSet) { cardNameSet = _cardNameSet; invalidate(); } invalidate();
void setSearchTerm(const QString &_searchTerm) { searchTerm = _searchTerm; } }
void setCardText(const QString &_cardText) { cardText = _cardText; invalidate(); } void setCardNameBeginning(const QString &_beginning)
void setCardTypes(const QSet<QString> &_cardTypes) { cardTypes = _cardTypes; invalidate(); } {
void setCardColors(const QSet<QString> &_cardColors) { cardColors = _cardColors; invalidate(); } cardNameBeginning = _beginning;
invalidate();
}
void setCardName(const QString &_cardName)
{
cardName = _cardName;
invalidate();
}
void setCardNameSet(const QSet<QString> &_cardNameSet)
{
cardNameSet = _cardNameSet;
invalidate();
}
void setSearchTerm(const QString &_searchTerm)
{
searchTerm = _searchTerm;
}
void setCardText(const QString &_cardText)
{
cardText = _cardText;
invalidate();
}
void setCardTypes(const QSet<QString> &_cardTypes)
{
cardTypes = _cardTypes;
invalidate();
}
void setCardColors(const QSet<QString> &_cardColors)
{
cardColors = _cardColors;
invalidate();
}
void clearFilterAll(); void clearFilterAll();
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
protected: protected:
bool lessThan(const QModelIndex &left, const QModelIndex &right) const; 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);
@ -70,11 +129,13 @@ private slots:
void filterTreeChanged(); void filterTreeChanged();
}; };
class TokenDisplayModel : public CardDatabaseDisplayModel { class TokenDisplayModel : public CardDatabaseDisplayModel
{
Q_OBJECT Q_OBJECT
public: public:
TokenDisplayModel(QObject *parent = 0); TokenDisplayModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
protected: protected:
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
}; };

View file

@ -1,14 +1,18 @@
#include "carddragitem.h" #include "carddragitem.h"
#include "carditem.h" #include "carditem.h"
#include "cardzone.h" #include "cardzone.h"
#include "gamescene.h"
#include "tablezone.h" #include "tablezone.h"
#include "zoneviewzone.h" #include "zoneviewzone.h"
#include "gamescene.h"
#include <QGraphicsSceneMouseEvent>
#include <QCursor> #include <QCursor>
#include <QGraphicsSceneMouseEvent>
#include <QPainter> #include <QPainter>
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) : AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0)
{ {
} }
@ -23,7 +27,9 @@ void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
void CardDragItem::updatePosition(const QPointF &cursorScenePos) void CardDragItem::updatePosition(const QPointF &cursorScenePos)
{ {
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, static_cast<GameScene *>(scene())->getViewTransform()); QList<QGraphicsItem *> colliding =
scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder,
static_cast<GameScene *>(scene())->getViewTransform());
CardZone *cardZone = 0; CardZone *cardZone = 0;
ZoneViewZone *zoneViewZone = 0; ZoneViewZone *zoneViewZone = 0;

View file

@ -5,19 +5,32 @@
class CardItem; class CardItem;
class CardDragItem : public AbstractCardDragItem { class CardDragItem : public AbstractCardDragItem
{
Q_OBJECT Q_OBJECT
private: private:
int id; int id;
bool faceDown; bool faceDown;
bool occupied; bool occupied;
CardZone *currentZone; CardZone *currentZone;
public: public:
CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0); CardDragItem(CardItem *_item,
int getId() const { return id; } int _id,
bool getFaceDown() const { return faceDown; } 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 paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void updatePosition(const QPointF &cursorScenePos); void updatePosition(const QPointF &cursorScenePos);
protected: protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
}; };

View file

@ -3,9 +3,11 @@
#include <QString> #include <QString>
class CardFilter { class CardFilter
{
public: public:
enum Type { enum Type
{
TypeAnd = 0, TypeAnd = 0,
TypeOr, TypeOr,
TypeAndNot, TypeAndNot,
@ -15,7 +17,8 @@ public:
/* if you add an atribute here you also need to /* if you add an atribute here you also need to
* add its string representation in attrName */ * add its string representation in attrName */
enum Attr { enum Attr
{
AttrCmc = 0, AttrCmc = 0,
AttrColor, AttrColor,
AttrManaCost, AttrManaCost,
@ -37,9 +40,18 @@ private:
public: 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; } Type type() const
const QString &term() const { return trm; } {
Attr attr() const { return a; } return t;
}
const QString &term() const
{
return trm;
}
Attr attr() const
{
return a;
}
static const char *typeName(Type t); static const char *typeName(Type t);
static const char *attrName(Attr a); static const char *attrName(Attr a);

View file

@ -1,10 +1,10 @@
#include "cardframe.h" #include "cardframe.h"
#include "carditem.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "main.h"
#include "cardinfopicture.h" #include "cardinfopicture.h"
#include "cardinfotext.h" #include "cardinfotext.h"
#include "carditem.h"
#include "main.h"
#include "settingscache.h" #include "settingscache.h"
#include <QSplitter> #include <QSplitter>
@ -71,8 +71,7 @@ void CardFrame::setViewMode(int mode)
if (currentIndex() != mode) if (currentIndex() != mode)
setCurrentIndex(mode); setCurrentIndex(mode);
switch (mode) switch (mode) {
{
case ImageOnlyView: case ImageOnlyView:
case TextOnlyView: case TextOnlyView:
tab1Layout->addWidget(pic); tab1Layout->addWidget(pic);
@ -91,15 +90,13 @@ void CardFrame::setViewMode(int mode)
void CardFrame::setCard(CardInfo *card) void CardFrame::setCard(CardInfo *card)
{ {
if (info) if (info) {
{
disconnect(info, nullptr, this, nullptr); disconnect(info, nullptr, this, nullptr);
} }
info = card; info = card;
if (info) if (info) {
{
connect(info, SIGNAL(destroyed()), this, SLOT(clear())); connect(info, SIGNAL(destroyed()), this, SLOT(clear()));
} }
@ -114,8 +111,7 @@ void CardFrame::setCard(const QString &cardName)
void CardFrame::setCard(AbstractCardItem *card) void CardFrame::setCard(AbstractCardItem *card)
{ {
if (card) if (card) {
{
setCard(card->getInfo()); setCard(card->getInfo());
} }
} }

View file

@ -23,7 +23,12 @@ class CardFrame : public QTabWidget
QSplitter *splitter; QSplitter *splitter;
public: public:
enum ViewMode { ImageOnlyView, TextOnlyView, ImageAndTextView }; enum ViewMode
{
ImageOnlyView,
TextOnlyView,
ImageAndTextView
};
explicit CardFrame(const QString &cardName = QString(), QWidget *parent = nullptr); explicit CardFrame(const QString &cardName = QString(), QWidget *parent = nullptr);
void retranslateUi(); void retranslateUi();

View file

@ -1,33 +1,28 @@
#include "cardinfopicture.h" #include "cardinfopicture.h"
#include <QWidget>
#include <QPainter> #include <QPainter>
#include <QStyle> #include <QStyle>
#include <QWidget>
#include "carditem.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "pictureloader.h" #include "carditem.h"
#include "main.h" #include "main.h"
#include "pictureloader.h"
CardInfoPicture::CardInfoPicture(QWidget *parent) CardInfoPicture::CardInfoPicture(QWidget *parent) : QWidget(parent), info(nullptr), pixmapDirty(true)
: QWidget(parent),
info(nullptr),
pixmapDirty(true)
{ {
setMinimumHeight(100); setMinimumHeight(100);
} }
void CardInfoPicture::setCard(CardInfo *card) void CardInfoPicture::setCard(CardInfo *card)
{ {
if (info) if (info) {
{
disconnect(info, nullptr, this, nullptr); disconnect(info, nullptr, this, nullptr);
} }
info = card; info = card;
if (info) if (info) {
{
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap()));
} }

View file

@ -6,7 +6,8 @@
class AbstractCardItem; class AbstractCardItem;
class CardInfo; class CardInfo;
class CardInfoPicture : public QWidget { class CardInfoPicture : public QWidget
{
Q_OBJECT Q_OBJECT
private: private:
@ -16,6 +17,7 @@ private:
public: public:
CardInfoPicture(QWidget *parent = 0); CardInfoPicture(QWidget *parent = 0);
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
void paintEvent(QPaintEvent *); void paintEvent(QPaintEvent *);

View file

@ -1,14 +1,13 @@
#include "cardinfotext.h" #include "cardinfotext.h"
#include "carddatabase.h"
#include "carditem.h"
#include "main.h"
#include <QGridLayout>
#include <QLabel> #include <QLabel>
#include <QTextEdit> #include <QTextEdit>
#include <QGridLayout>
#include "carditem.h"
#include "carddatabase.h"
#include "main.h"
CardInfoText::CardInfoText(QWidget *parent) CardInfoText::CardInfoText(QWidget *parent) : QFrame(parent), info(nullptr)
: QFrame(parent), info(nullptr)
{ {
nameLabel1 = new QLabel; nameLabel1 = new QLabel;
nameLabel2 = new QLabel; nameLabel2 = new QLabel;
@ -59,8 +58,7 @@ CardInfoText::CardInfoText(QWidget *parent)
void CardInfoText::setCard(CardInfo *card) void CardInfoText::setCard(CardInfo *card)
{ {
if (card) if (card) {
{
nameLabel2->setText(card->getName()); nameLabel2->setText(card->getName());
manacostLabel2->setText(card->getManaCost()); manacostLabel2->setText(card->getManaCost());
colorLabel2->setText(card->getColors().join("")); colorLabel2->setText(card->getColors().join(""));
@ -68,9 +66,7 @@ void CardInfoText::setCard(CardInfo *card)
powtoughLabel2->setText(card->getPowTough()); powtoughLabel2->setText(card->getPowTough());
loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString());
textLabel->setText(card->getText()); textLabel->setText(card->getText());
} } else {
else
{
nameLabel2->setText(""); nameLabel2->setText("");
manacostLabel2->setText(""); manacostLabel2->setText("");
colorLabel2->setText(""); colorLabel2->setText("");

View file

@ -7,7 +7,8 @@ class QLabel;
class QTextEdit; class QTextEdit;
class CardInfo; class CardInfo;
class CardInfoText : public QFrame { class CardInfoText : public QFrame
{
Q_OBJECT Q_OBJECT
private: private:

View file

@ -1,16 +1,14 @@
#include <QVBoxLayout>
#include <QDesktopWidget>
#include "cardinfowidget.h" #include "cardinfowidget.h"
#include "carditem.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "cardinfopicture.h" #include "cardinfopicture.h"
#include "cardinfotext.h" #include "cardinfotext.h"
#include "carditem.h"
#include "main.h" #include "main.h"
#include <QDesktopWidget>
#include <QVBoxLayout>
CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::WindowFlags flags) CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::WindowFlags flags)
: QFrame(parent, flags) : QFrame(parent, flags), aspectRatio((qreal)CARD_HEIGHT / (qreal)CARD_WIDTH), info(nullptr)
, aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH)
, info(nullptr)
{ {
setContentsMargins(3, 3, 3, 3); setContentsMargins(3, 3, 3, 3);
pic = new CardInfoPicture(); pic = new CardInfoPicture();

View file

@ -1,16 +1,17 @@
#ifndef CARDINFOWIDGET_H #ifndef CARDINFOWIDGET_H
#define CARDINFOWIDGET_H #define CARDINFOWIDGET_H
#include <QComboBox>
#include <QFrame> #include <QFrame>
#include <QStringList> #include <QStringList>
#include <QComboBox>
class CardInfo; class CardInfo;
class CardInfoPicture; class CardInfoPicture;
class CardInfoText; class CardInfoText;
class AbstractCardItem; class AbstractCardItem;
class CardInfoWidget : public QFrame { class CardInfoWidget : public QFrame
{
Q_OBJECT Q_OBJECT
private: private:
@ -18,6 +19,7 @@ private:
CardInfo *info; CardInfo *info;
CardInfoPicture *pic; CardInfoPicture *pic;
CardInfoText *text; CardInfoText *text;
public: public:
CardInfoWidget(const QString &cardName, QWidget *parent = 0, Qt::WindowFlags f = 0); CardInfoWidget(const QString &cardName, QWidget *parent = 0, Qt::WindowFlags f = 0);

View file

@ -1,24 +1,24 @@
#include <QApplication>
#include <QPainter>
#include <QMenu>
#include <QGraphicsSceneMouseEvent>
#include "gamescene.h"
#include "carditem.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 "arrowitem.h"
#include "carddatabase.h"
#include "carddragitem.h"
#include "cardzone.h"
#include "gamescene.h"
#include "main.h" #include "main.h"
#include "pb/serverinfo_card.pb.h"
#include "player.h"
#include "settingscache.h" #include "settingscache.h"
#include "tab_game.h" #include "tab_game.h"
#include "pb/serverinfo_card.pb.h" #include "tablezone.h"
#include "zoneviewzone.h"
#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QMenu>
#include <QPainter>
CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _revealedCard, QGraphicsItem *parent) CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _revealedCard, QGraphicsItem *parent)
: AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0) : AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false),
destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0)
{ {
owner->addCard(this); owner->addCard(this);
@ -90,8 +90,7 @@ void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
int i = 0; int i = 0;
QMapIterator<int, int> counterIterator(counters); QMapIterator<int, int> counterIterator(counters);
while (counterIterator.hasNext()) while (counterIterator.hasNext()) {
{
counterIterator.next(); counterIterator.next();
QColor color; QColor color;
color.setHsv(counterIterator.key() * 60, 150, 255); color.setHsv(counterIterator.key() * 60, 150, 255);
@ -103,13 +102,11 @@ void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QSizeF translatedSize = getTranslatedSize(painter); QSizeF translatedSize = getTranslatedSize(painter);
qreal scaleFactor = translatedSize.width() / boundingRect().width(); qreal scaleFactor = translatedSize.width() / boundingRect().width();
if (!pt.isEmpty()) if (!pt.isEmpty()) {
{
painter->save(); painter->save();
transformPainter(painter, translatedSize, tapAngle); transformPainter(painter, translatedSize, tapAngle);
if(info) if (info) {
{
QStringList ptSplit = pt.split("/"); QStringList ptSplit = pt.split("/");
QStringList ptDbSplit = info->getPowTough().split("/"); QStringList ptDbSplit = info->getPowTough().split("/");
@ -117,20 +114,19 @@ void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
painter->setPen(QColor(255, 150, 0)); painter->setPen(QColor(255, 150, 0));
else else
painter->setPen(Qt::white); painter->setPen(Qt::white);
} } else {
else
{
painter->setPen(Qt::white); painter->setPen(Qt::white);
} }
painter->setBackground(Qt::black); painter->setBackground(Qt::black);
painter->setBackgroundMode(Qt::OpaqueMode); 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(); painter->restore();
} }
if (!annotation.isEmpty()) if (!annotation.isEmpty()) {
{
painter->save(); painter->save();
transformPainter(painter, translatedSize, tapAngle); transformPainter(painter, translatedSize, tapAngle);
@ -138,18 +134,18 @@ void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
painter->setBackgroundMode(Qt::OpaqueMode); painter->setBackgroundMode(Qt::OpaqueMode);
painter->setPen(Qt::white); painter->setPen(Qt::white);
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation); painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor,
translatedSize.height() - 8 * scaleFactor),
Qt::AlignCenter | Qt::TextWrapAnywhere, annotation);
painter->restore(); painter->restore();
} }
if (getBeingPointedAt()) if (getBeingPointedAt()) {
{
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
painter->restore(); painter->restore();
} }
if (doesntUntap) if (doesntUntap) {
{
painter->save(); painter->save();
painter->setRenderHint(QPainter::Antialiasing, false); painter->setRenderHint(QPainter::Antialiasing, false);
@ -303,7 +299,8 @@ void CardItem::drawArrow(const QColor &arrowColor)
void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->buttons().testFlag(Qt::RightButton)) { if (event->buttons().testFlag(Qt::RightButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() <
2 * QApplication::startDragDistance())
return; return;
QColor arrowColor = Qt::red; QColor arrowColor = Qt::red;
@ -316,7 +313,8 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
drawArrow(arrowColor); drawArrow(arrowColor);
} else if (event->buttons().testFlag(Qt::LeftButton)) { } else if (event->buttons().testFlag(Qt::LeftButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
2 * QApplication::startDragDistance())
return; return;
if (zone->getIsView()) { if (zone->getIsView()) {
const ZoneViewZone *const view = static_cast<const ZoneViewZone *const>(zone); const ZoneViewZone *const view = static_cast<const ZoneViewZone *const>(zone);
@ -399,7 +397,6 @@ void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
event->accept(); event->accept();
} }
bool CardItem::animationEvent() bool CardItem::animationEvent()
{ {
int rotation = ROTATION_DEGREES_PER_FRAME; int rotation = ROTATION_DEGREES_PER_FRAME;
@ -408,7 +405,10 @@ bool CardItem::animationEvent()
tapAngle += rotation; 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); setHovered(false);
update(); update();

View file

@ -16,7 +16,8 @@ const float CARD_WIDTH_HALF = CARD_WIDTH / 2;
const float CARD_HEIGHT_HALF = CARD_HEIGHT / 2; const float CARD_HEIGHT_HALF = CARD_HEIGHT / 2;
const int ROTATION_DEGREES_PER_FRAME = 10; const int ROTATION_DEGREES_PER_FRAME = 10;
class CardItem : public AbstractCardItem { class CardItem : public AbstractCardItem
{
Q_OBJECT Q_OBJECT
private: private:
CardZone *zone; CardZone *zone;
@ -37,50 +38,125 @@ private:
void prepareDelete(); void prepareDelete();
public slots: public slots:
void deleteLater(); void deleteLater();
public: public:
enum { Type = typeCard }; enum
int type() const { return Type; } {
CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0); Type = typeCard
};
int type() const
{
return Type;
}
CardItem(Player *_owner,
const QString &_name = QString(),
int _cardid = -1,
bool revealedCard = false,
QGraphicsItem *parent = 0);
~CardItem(); ~CardItem();
void retranslateUi(); void retranslateUi();
CardZone *getZone() const { return zone; } CardZone *getZone() const
{
return zone;
}
void setZone(CardZone *_zone); void setZone(CardZone *_zone);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QPoint getGridPoint() const { return gridPoint; } QPoint getGridPoint() const
void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; } {
QPoint getGridPos() const { return gridPoint; } return gridPoint;
Player *getOwner() const { return owner; } }
void setOwner(Player *_owner) { owner = _owner; } void setGridPoint(const QPoint &_gridPoint)
bool getRevealedCard() const { return revealedCard; } {
bool getAttacking() const { return attacking; } 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); void setAttacking(bool _attacking);
const QMap<int, int> &getCounters() const { return counters; } const QMap<int, int> &getCounters() const
{
return counters;
}
void setCounter(int _id, int _value); void setCounter(int _id, int _value);
QString getAnnotation() const { return annotation; } QString getAnnotation() const
{
return annotation;
}
void setAnnotation(const QString &_annotation); void setAnnotation(const QString &_annotation);
bool getDoesntUntap() const { return doesntUntap; } bool getDoesntUntap() const
{
return doesntUntap;
}
void setDoesntUntap(bool _doesntUntap); void setDoesntUntap(bool _doesntUntap);
QString getPT() const { return pt; } QString getPT() const
{
return pt;
}
void setPT(const QString &_pt); void setPT(const QString &_pt);
bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } bool getDestroyOnZoneChange() const
void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } {
CardItem *getAttachedTo() const { return attachedTo; } return destroyOnZoneChange;
}
void setDestroyOnZoneChange(bool _destroy)
{
destroyOnZoneChange = _destroy;
}
CardItem *getAttachedTo() const
{
return attachedTo;
}
void setAttachedTo(CardItem *_attachedTo); void setAttachedTo(CardItem *_attachedTo);
void addAttachedCard(CardItem *card) { attachedCards.append(card); } void addAttachedCard(CardItem *card)
void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } {
const QList<CardItem *> &getAttachedCards() const { return attachedCards; } attachedCards.append(card);
}
void removeAttachedCard(CardItem *card)
{
attachedCards.removeAt(attachedCards.indexOf(card));
}
const QList<CardItem *> &getAttachedCards() const
{
return attachedCards;
}
void resetState(); void resetState();
void processCardInfo(const ServerInfo_Card &info); void processCardInfo(const ServerInfo_Card &info);
QMenu *getCardMenu() const { return cardMenu; } QMenu *getCardMenu() const
QMenu *getPTMenu() const { return ptMenu; } {
QMenu *getMoveMenu() const { return moveMenu; } return cardMenu;
}
QMenu *getPTMenu() const
{
return ptMenu;
}
QMenu *getMoveMenu() const
{
return moveMenu;
}
bool animationEvent(); bool animationEvent();
CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown); CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown);
void deleteDragItem(); void deleteDragItem();
void drawArrow(const QColor &arrowColor); void drawArrow(const QColor &arrowColor);
void playCard(bool faceDown); void playCard(bool faceDown);
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

View file

@ -1,9 +1,8 @@
#include "cardlist.h" #include "cardlist.h"
#include "carditem.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "carditem.h"
CardList::CardList(bool _contentsKnown) CardList::CardList(bool _contentsKnown) : QList<CardItem *>(), contentsKnown(_contentsKnown)
: QList<CardItem *>(), contentsKnown(_contentsKnown)
{ {
} }
@ -32,9 +31,11 @@ CardItem *CardList::findCard(const int id, const bool remove, int *position)
return 0; return 0;
} }
class CardList::compareFunctor { class CardList::compareFunctor
{
private: private:
int flags; int flags;
public: public:
compareFunctor(int _flags) : flags(_flags) compareFunctor(int _flags) : flags(_flags)
{ {

View file

@ -5,16 +5,26 @@
class CardItem; class CardItem;
class CardList : public QList<CardItem *> { class CardList : public QList<CardItem *>
{
private: private:
class compareFunctor; class compareFunctor;
protected: protected:
bool contentsKnown; bool contentsKnown;
public: public:
enum SortFlags { SortByName = 1, SortByType = 2 }; enum SortFlags
{
SortByName = 1,
SortByType = 2
};
CardList(bool _contentsKnown); CardList(bool _contentsKnown);
CardItem *findCard(const int id, const bool remove, int *position = NULL); CardItem *findCard(const int id, const bool remove, int *position = NULL);
bool getContentsKnown() const { return contentsKnown; } bool getContentsKnown() const
{
return contentsKnown;
}
void sort(int flags = SortByName); void sort(int flags = SortByName);
}; };

View file

@ -1,16 +1,23 @@
#include <QMenu>
#include <QAction>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include "cardzone.h" #include "cardzone.h"
#include "carditem.h" #include "carditem.h"
#include "player.h"
#include "zoneviewzone.h"
#include "pb/command_move_card.pb.h" #include "pb/command_move_card.pb.h"
#include "pb/serverinfo_user.pb.h" #include "pb/serverinfo_user.pb.h"
#include "player.h"
#include "zoneviewzone.h"
#include <QAction>
#include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QMenu>
CardZone::CardZone(Player *_p, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool _isView) CardZone::CardZone(Player *_p,
: AbstractGraphicsItem(parent), player(_p), name(_name), cards(_contentsKnown), view(NULL), menu(NULL), doubleClickAction(0), hasCardAttr(_hasCardAttr), isShufflable(_isShufflable), isView(_isView) 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) if (!isView)
player->addZone(this); player->addZone(this);
@ -31,10 +38,9 @@ void CardZone::retranslateUi()
void CardZone::clearContents() void CardZone::clearContents()
{ {
for (int i = 0; i < cards.size(); i++) 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
// If an incorrectly implemented server doesn't return attached cards to whom they belong before dropping a player, // player, we have to return them to avoid a crash.
// we have to return them to avoid a crash.
const QList<CardItem *> &attachedCards = cards[i]->getAttachedCards(); const QList<CardItem *> &attachedCards = cards[i]->getAttachedCards();
for (auto attachedCard : attachedCards) for (auto attachedCard : attachedCards)
attachedCard->setParentItem(attachedCard->getZone()); attachedCard->setParentItem(attachedCard->getZone());
@ -49,61 +55,37 @@ QString CardZone::getTranslatedName(bool theirOwn, GrammaticalCase gc) const
{ {
QString ownerName = player->getName(); QString ownerName = player->getName();
if (name == "hand") if (name == "hand")
return (theirOwn return (theirOwn ? tr("their hand", "nominative") : tr("%1's hand", "nominative").arg(ownerName));
? tr("their hand", "nominative")
: tr("%1's hand", "nominative").arg(ownerName)
);
else if (name == "deck") else if (name == "deck")
switch (gc) { switch (gc) {
case CaseLookAtZone: case CaseLookAtZone:
return (theirOwn return (theirOwn ? tr("their library", "look at zone")
? tr("their library", "look at zone") : tr("%1's library", "look at zone").arg(ownerName));
: tr("%1's library", "look at zone").arg(ownerName)
);
case CaseTopCardsOfZone: case CaseTopCardsOfZone:
return (theirOwn return (theirOwn ? tr("of their library", "top cards of zone,")
? tr("of their library", "top cards of zone,") : tr("of %1's library", "top cards of zone").arg(ownerName));
: tr("of %1's library", "top cards of zone").arg(ownerName)
);
case CaseRevealZone: case CaseRevealZone:
return (theirOwn return (theirOwn ? tr("their library", "reveal zone")
? tr("their library", "reveal zone") : tr("%1's library", "reveal zone").arg(ownerName));
: tr("%1's library", "reveal zone").arg(ownerName)
);
case CaseShuffleZone: case CaseShuffleZone:
return (theirOwn return (theirOwn ? tr("their library", "shuffle") : tr("%1's library", "shuffle").arg(ownerName));
? tr("their library", "shuffle")
: tr("%1's library", "shuffle").arg(ownerName)
);
default: default:
return (theirOwn return (theirOwn ? tr("their library", "nominative") : tr("%1's library", "nominative").arg(ownerName));
? tr("their library", "nominative")
: tr("%1's library", "nominative").arg(ownerName)
);
} }
else if (name == "grave") else if (name == "grave")
return (theirOwn return (theirOwn ? tr("their graveyard", "nominative") : tr("%1's graveyard", "nominative").arg(ownerName));
? tr("their graveyard", "nominative")
: tr("%1's graveyard", "nominative").arg(ownerName)
);
else if (name == "rfg") else if (name == "rfg")
return (theirOwn return (theirOwn ? tr("their exile", "nominative") : tr("%1's exile", "nominative").arg(ownerName));
? tr("their exile", "nominative")
: tr("%1's exile", "nominative").arg(ownerName)
);
else if (name == "sb") else if (name == "sb")
switch (gc) { switch (gc) {
case CaseLookAtZone: case CaseLookAtZone:
return (theirOwn return (theirOwn ? tr("their sideboard", "look at zone")
? tr("their sideboard", "look at zone") : tr("%1's sideboard", "look at zone").arg(ownerName));
: tr("%1's sideboard", "look at zone").arg(ownerName)
);
case CaseNominative: case CaseNominative:
return (theirOwn return (theirOwn ? tr("their sideboard", "nominative")
? tr("their sideboard", "nominative") : tr("%1's sideboard", "nominative").arg(ownerName));
: tr("%1's sideboard", "nominative").arg(ownerName) default:
); break;
default: break;
} }
return QString(); return QString();
} }

View file

@ -1,10 +1,10 @@
#ifndef CARDZONE_H #ifndef CARDZONE_H
#define CARDZONE_H #define CARDZONE_H
#include <QString>
#include "cardlist.h"
#include "abstractgraphicsitem.h" #include "abstractgraphicsitem.h"
#include "cardlist.h"
#include "translation.h" #include "translation.h"
#include <QString>
class Player; class Player;
class ZoneViewZone; class ZoneViewZone;
@ -13,7 +13,8 @@ class QAction;
class QPainter; class QPainter;
class CardDragItem; class CardDragItem;
class CardZone : public AbstractGraphicsItem { class CardZone : public AbstractGraphicsItem
{
Q_OBJECT Q_OBJECT
protected: protected:
Player *player; Player *player;
@ -34,36 +35,90 @@ signals:
public slots: public slots:
void moveAllToZone(); void moveAllToZone();
bool showContextMenu(const QPoint &screenPos); bool showContextMenu(const QPoint &screenPos);
public: public:
enum { Type = typeZone }; enum
int type() const { return Type; } {
virtual void handleDropEvent(const QList<CardDragItem *> &dragItem, CardZone *startZone, const QPoint &dropPoint) = 0; Type = typeZone
CardZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool _isView = false); };
int type() const
{
return Type;
}
virtual void
handleDropEvent(const QList<CardDragItem *> &dragItem, CardZone *startZone, const QPoint &dropPoint) = 0;
CardZone(Player *_player,
const QString &_name,
bool _hasCardAttr,
bool _isShufflable,
bool _contentsKnown,
QGraphicsItem *parent = 0,
bool _isView = false);
~CardZone(); ~CardZone();
void retranslateUi(); void retranslateUi();
void clearContents(); void clearContents();
bool getHasCardAttr() const { return hasCardAttr; } bool getHasCardAttr() const
bool getIsShufflable() const { return isShufflable; } {
QMenu *getMenu() const { return menu; } return hasCardAttr;
void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; } }
QString getName() const { return name; } 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; QString getTranslatedName(bool theirOwn, GrammaticalCase gc) const;
Player *getPlayer() const { return player; } Player *getPlayer() const
bool contentsKnown() const { return cards.getContentsKnown(); } {
const CardList &getCards() const { return cards; } 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); void addCard(CardItem *card, bool reorganize, int x, int y = -1);
// getCard() finds a card by id. // getCard() finds a card by id.
CardItem *getCard(int cardId, const QString &cardName); CardItem *getCard(int cardId, const QString &cardName);
// takeCard() finds a card by position and removes it from the zone and from all of its views. // takeCard() finds a card by position and removes it from the zone and from all of its views.
virtual CardItem *takeCard(int position, int cardId, bool canResize = true); virtual CardItem *takeCard(int position, int cardId, bool canResize = true);
void removeCard(CardItem *card); void removeCard(CardItem *card);
ZoneViewZone *getView() const { return view; } ZoneViewZone *getView() const
void setView(ZoneViewZone *_view) { view = _view; } {
return view;
}
void setView(ZoneViewZone *_view)
{
view = _view;
}
virtual void reorganizeCards() = 0; virtual void reorganizeCards() = 0;
virtual QPointF closestGridPoint(const QPointF &point); virtual QPointF closestGridPoint(const QPointF &point);
bool getIsView() const { return isView; } bool getIsView() const
bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } {
void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } return isView;
}
bool getAlwaysRevealTopCard() const
{
return alwaysRevealTopCard;
}
void setAlwaysRevealTopCard(bool _alwaysRevealTopCard)
{
alwaysRevealTopCard = _alwaysRevealTopCard;
}
}; };
#endif #endif

View file

@ -1,6 +1,7 @@
#ifndef COCKATRICE_USERLISTPROXY_H #ifndef COCKATRICE_USERLISTPROXY_H
#define COCKATRICE_USERLISTPROXY_H #define COCKATRICE_USERLISTPROXY_H
class QString;
class ServerInfo_User; class ServerInfo_User;
/** /**

View file

@ -2,7 +2,14 @@
#include "pixmapgenerator.h" #include "pixmapgenerator.h"
#include <QPainter> #include <QPainter>
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) : AbstractCounter(_player, _id, _name, true, _value, useNameForShortcut, parent), color(_color), radius(_radius)
{ {
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);

View file

@ -3,13 +3,22 @@
#include "abstractcounter.h" #include "abstractcounter.h"
class GeneralCounter : public AbstractCounter { class GeneralCounter : public AbstractCounter
{
Q_OBJECT Q_OBJECT
private: private:
QColor color; QColor color;
int radius; int radius;
public: public:
GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, 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; QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
}; };

View file

@ -1,53 +1,50 @@
#include <QStringList>
#include <QFile>
#include <QDebug>
#include "deck_loader.h" #include "deck_loader.h"
#include "decklist.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "decklist.h"
#include "main.h" #include "main.h"
#include <QDebug>
#include <QFile>
#include <QStringList>
const QStringList DeckLoader::fileNameFilters = QStringList() const QStringList DeckLoader::fileNameFilters =
<< QObject::tr("Common deck formats (*.cod *.dec *.txt *.mwDeck)") QStringList() << QObject::tr("Common deck formats (*.cod *.dec *.txt *.mwDeck)") << QObject::tr("All files (*.*)");
<< QObject::tr("All files (*.*)");
DeckLoader::DeckLoader() : DeckList(), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1) 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) bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
{ {
QFile file(fileName); QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
{
return false; return false;
} }
bool result = false; bool result = false;
switch (fmt) switch (fmt) {
{ case PlainTextFormat:
case PlainTextFormat: result = loadFromFile_Plain(&file); break; result = loadFromFile_Plain(&file);
case CockatriceFormat: break;
{ case CockatriceFormat: {
result = loadFromFile_Native(&file); result = loadFromFile_Native(&file);
qDebug() << "Loaded from" << fileName << "-" << result; qDebug() << "Loaded from" << fileName << "-" << result;
if (!result) if (!result) {
{
qDebug() << "Retying as plain format"; qDebug() << "Retying as plain format";
file.seek(0); file.seek(0);
result = loadFromFile_Plain(&file); result = loadFromFile_Plain(&file);
@ -60,8 +57,7 @@ bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
break; break;
} }
if (result) if (result) {
{
lastFileName = fileName; lastFileName = fileName;
lastFileFormat = fmt; lastFileFormat = fmt;
@ -75,8 +71,7 @@ bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
{ {
bool result = loadFromString_Native(nativeString); bool result = loadFromString_Native(nativeString);
if (result) if (result) {
{
lastFileName = QString(); lastFileName = QString();
lastFileFormat = CockatriceFormat; lastFileFormat = CockatriceFormat;
lastRemoteDeckId = remoteDeckId; lastRemoteDeckId = remoteDeckId;
@ -89,20 +84,21 @@ bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt)
{ {
QFile file(fileName); QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
{
return false; return false;
} }
bool result = false; bool result = false;
switch (fmt) switch (fmt) {
{ case PlainTextFormat:
case PlainTextFormat: result = saveToFile_Plain(&file); break; result = saveToFile_Plain(&file);
case CockatriceFormat: result = saveToFile_Native(&file); break; break;
case CockatriceFormat:
result = saveToFile_Native(&file);
break;
} }
if (result) if (result) {
{
lastFileName = fileName; lastFileName = fileName;
lastFileFormat = fmt; lastFileFormat = fmt;
} }
@ -118,21 +114,20 @@ struct FormatDeckListForExport
QString &mainBoardCards; QString &mainBoardCards;
QString &sideBoardCards; QString &sideBoardCards;
// create main operator for struct, allowing the foreachcard to work. // create main operator for struct, allowing the foreachcard to work.
FormatDeckListForExport(QString &_mainBoardCards, QString &_sideBoardCards) : mainBoardCards(_mainBoardCards), sideBoardCards(_sideBoardCards){}; FormatDeckListForExport(QString &_mainBoardCards, QString &_sideBoardCards)
: mainBoardCards(_mainBoardCards), sideBoardCards(_sideBoardCards){};
void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const
{ {
// Get the card name // Get the card name
CardInfo *dbCard = db->getCard(card->getName()); CardInfo *dbCard = db->getCard(card->getName());
if (!dbCard || dbCard->getIsToken()) if (!dbCard || dbCard->getIsToken()) {
{
// If it's a token, we don't care about the card. // If it's a token, we don't care about the card.
return; return;
} }
// Check if it's a sideboard card. // Check if it's a sideboard card.
if (node->getName() == DECK_ZONE_SIDE) if (node->getName() == DECK_ZONE_SIDE) {
{
// Get the number of cards and add the card name // Get the number of cards and add the card name
sideBoardCards += QString::number(card->getNumber()); sideBoardCards += QString::number(card->getNumber());
// Add a space between card num and name // Add a space between card num and name
@ -141,8 +136,7 @@ struct FormatDeckListForExport
sideBoardCards += card->getName(); sideBoardCards += card->getName();
// Add a return at the end of the card // Add a return at the end of the card
sideBoardCards += "%0A"; sideBoardCards += "%0A";
} } else // If it's a mainboard card, do the same thing, but for the mainboard card string
else //If it's a mainboard card, do the same thing, but for the mainboard card string
{ {
mainBoardCards += QString::number(card->getNumber()); mainBoardCards += QString::number(card->getNumber());
mainBoardCards += "%20"; mainBoardCards += "%20";
@ -179,8 +173,7 @@ QString DeckLoader::exportDeckToDecklist()
DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName)
{ {
if (fileName.endsWith(".cod", Qt::CaseInsensitive)) if (fileName.endsWith(".cod", Qt::CaseInsensitive)) {
{
return CockatriceFormat; return CockatriceFormat;
} }
return PlainTextFormat; return PlainTextFormat;
@ -188,14 +181,12 @@ DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName)
bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments) bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments)
{ {
if (addComments) if (addComments) {
{
saveToStream_DeckHeader(out); saveToStream_DeckHeader(out);
} }
// loop zones // loop zones
for (int i = 0; i < getRoot()->size(); i++) for (int i = 0; i < getRoot()->size(); i++) {
{
const auto *zoneNode = dynamic_cast<InnerDecklistNode *>(getRoot()->at(i)); const auto *zoneNode = dynamic_cast<InnerDecklistNode *>(getRoot()->at(i));
saveToStream_DeckZone(out, zoneNode, addComments); saveToStream_DeckZone(out, zoneNode, addComments);
@ -209,16 +200,13 @@ bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments)
void DeckLoader::saveToStream_DeckHeader(QTextStream &out) void DeckLoader::saveToStream_DeckHeader(QTextStream &out)
{ {
if (!getName().isEmpty()) if (!getName().isEmpty()) {
{
out << "// " << getName() << "\n\n"; out << "// " << getName() << "\n\n";
} }
if (!getComments().isEmpty()) if (!getComments().isEmpty()) {
{
QStringList commentRows = getComments().split(QRegExp("\n|\r\n|\r")); QStringList commentRows = getComments().split(QRegExp("\n|\r\n|\r"));
foreach(QString row, commentRows) foreach (QString row, commentRows) {
{
out << "// " << row << "\n"; out << "// " << row << "\n";
} }
out << "\n"; out << "\n";
@ -232,8 +220,7 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode
QMap<QString, int> cardTotalByType; QMap<QString, int> cardTotalByType;
int cardTotal = 0; int cardTotal = 0;
for (int j = 0; j < zoneNode->size(); j++) for (int j = 0; j < zoneNode->size(); j++) {
{
auto *card = dynamic_cast<DecklistCardNode *>(zoneNode->at(j)); auto *card = dynamic_cast<DecklistCardNode *>(zoneNode->at(j));
CardInfo *info = db->getCard(card->getName()); CardInfo *info = db->getCard(card->getName());
@ -241,28 +228,22 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode
cardsByType.insert(cardType, card); cardsByType.insert(cardType, card);
if (cardTotalByType.contains(cardType)) if (cardTotalByType.contains(cardType)) {
{
cardTotalByType[cardType] += card->getNumber(); cardTotalByType[cardType] += card->getNumber();
} } else {
else
{
cardTotalByType[cardType] = card->getNumber(); cardTotalByType[cardType] = card->getNumber();
} }
cardTotal += card->getNumber(); cardTotal += card->getNumber();
} }
if (addComments) if (addComments) {
{
out << "// " << cardTotal << " " << zoneNode->getVisibleName() << "\n"; out << "// " << cardTotal << " " << zoneNode->getVisibleName() << "\n";
} }
// print cards to stream // print cards to stream
foreach(QString cardType, cardsByType.uniqueKeys()) foreach (QString cardType, cardsByType.uniqueKeys()) {
{ if (addComments) {
if (addComments)
{
out << "// " << cardTotalByType[cardType] << " " << cardType << "\n"; out << "// " << cardTotalByType[cardType] << " " << cardType << "\n";
} }
@ -270,22 +251,22 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode
saveToStream_DeckZoneCards(out, zoneNode, cards, addComments); saveToStream_DeckZoneCards(out, zoneNode, cards, addComments);
if (addComments) if (addComments) {
{
out << "\n"; out << "\n";
} }
} }
} }
void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out, const InnerDecklistNode *zoneNode, QList <DecklistCardNode*> cards, bool addComments) void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out,
const InnerDecklistNode *zoneNode,
QList<DecklistCardNode *> cards,
bool addComments)
{ {
// QMultiMap sorts values in reverse order // QMultiMap sorts values in reverse order
for (int i = cards.size() - 1; i >= 0; --i) for (int i = cards.size() - 1; i >= 0; --i) {
{
DecklistCardNode *card = cards[i]; DecklistCardNode *card = cards[i];
if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) {
{
out << "SB: "; out << "SB: ";
} }
@ -297,8 +278,7 @@ QString DeckLoader::getCardZoneFromName(QString cardName, QString currentZoneNam
{ {
CardInfo *card = db->getCard(cardName); CardInfo *card = db->getCard(cardName);
if (card && card->getIsToken()) if (card && card->getIsToken()) {
{
return DECK_ZONE_TOKENS; return DECK_ZONE_TOKENS;
} }
@ -307,11 +287,9 @@ QString DeckLoader::getCardZoneFromName(QString cardName, QString currentZoneNam
QString DeckLoader::getCompleteCardName(const QString cardName) const QString DeckLoader::getCompleteCardName(const QString cardName) const
{ {
if (db) if (db) {
{
CardInfo *temp = db->getCardBySimpleName(cardName); CardInfo *temp = db->getCardBySimpleName(cardName);
if (temp) if (temp) {
{
return temp->getName(); return temp->getName();
} }
} }

View file

@ -10,7 +10,11 @@ class DeckLoader : public DeckList
void deckLoaded(); void deckLoaded();
public: public:
enum FileFormat { PlainTextFormat, CockatriceFormat }; enum FileFormat
{
PlainTextFormat,
CockatriceFormat
};
static const QStringList fileNameFilters; static const QStringList fileNameFilters;
private: private:
@ -23,9 +27,18 @@ class DeckLoader : public DeckList
DeckLoader(const QString &nativeString); DeckLoader(const QString &nativeString);
DeckLoader(const DeckList &other); DeckLoader(const DeckList &other);
DeckLoader(const DeckLoader &other); DeckLoader(const DeckLoader &other);
const QString &getLastFileName() const { return lastFileName; } const QString &getLastFileName() const
FileFormat getLastFileFormat() const { return lastFileFormat; } {
int getLastRemoteDeckId() const { return lastRemoteDeckId; } return lastFileName;
}
FileFormat getLastFileFormat() const
{
return lastFileFormat;
}
int getLastRemoteDeckId() const
{
return lastRemoteDeckId;
}
static FileFormat getFormatFromName(const QString &fileName); static FileFormat getFormatFromName(const QString &fileName);
@ -40,7 +53,10 @@ class DeckLoader : public DeckList
protected: protected:
void saveToStream_DeckHeader(QTextStream &out); void saveToStream_DeckHeader(QTextStream &out);
void saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments = true); void saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments = true);
void saveToStream_DeckZoneCards(QTextStream &out, const InnerDecklistNode *zoneNode, QList <DecklistCardNode*> cards, bool addComments = true); void saveToStream_DeckZoneCards(QTextStream &out,
const InnerDecklistNode *zoneNode,
QList<DecklistCardNode *> cards,
bool addComments = true);
virtual QString getCardZoneFromName(QString cardName, QString currentZoneName); virtual QString getCardZoneFromName(QString cardName, QString currentZoneName);
virtual QString getCompleteCardName(const QString cardName) const; virtual QString getCompleteCardName(const QString cardName) const;
}; };

View file

@ -1,17 +1,17 @@
#include <QFile>
#include <QTextStream>
#include <QFont>
#include <QBrush>
#include <QTextCursor>
#include <QTextDocument>
#include <QPrinter>
#include <QTextTable>
#include <QProgressDialog>
#include "main.h"
#include "decklistmodel.h" #include "decklistmodel.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "settingscache.h"
#include "deck_loader.h" #include "deck_loader.h"
#include "main.h"
#include "settingscache.h"
#include <QBrush>
#include <QFile>
#include <QFont>
#include <QPrinter>
#include <QProgressDialog>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextStream>
#include <QTextTable>
DeckListModel::DeckListModel(QObject *parent) DeckListModel::DeckListModel(QObject *parent)
: QAbstractItemModel(parent), lastKnownColumn(1), lastKnownOrder(Qt::AscendingOrder) : QAbstractItemModel(parent), lastKnownColumn(1), lastKnownOrder(Qt::AscendingOrder)
@ -35,18 +35,15 @@ void DeckListModel::rebuildTree()
InnerDecklistNode *listRoot = deckList->getRoot(); InnerDecklistNode *listRoot = deckList->getRoot();
for (int i = 0; i < listRoot->size(); i++) for (int i = 0; i < listRoot->size(); i++) {
{
auto *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i)); auto *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
auto *node = new InnerDecklistNode(currentZone->getName(), root); 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<DecklistCardNode *>(currentZone->at(j)); auto *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
// TODO: better sanity checking // TODO: better sanity checking
if (currentCard == nullptr) if (currentCard == nullptr) {
{
continue; continue;
} }
@ -55,8 +52,7 @@ void DeckListModel::rebuildTree()
auto *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType)); auto *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType));
if (!cardTypeNode) if (!cardTypeNode) {
{
cardTypeNode = new InnerDecklistNode(cardType, node); cardTypeNode = new InnerDecklistNode(cardType, node);
} }
@ -71,12 +67,9 @@ int DeckListModel::rowCount(const QModelIndex &parent) const
{ {
// debugIndexInfo("rowCount", parent); // debugIndexInfo("rowCount", parent);
auto *node = getNode<InnerDecklistNode *>(parent); auto *node = getNode<InnerDecklistNode *>(parent);
if (node) if (node) {
{
return node->size(); return node->size();
} } else {
else
{
return 0; return 0;
} }
} }
@ -89,34 +82,27 @@ int DeckListModel::columnCount(const QModelIndex &/*parent*/) const
QVariant DeckListModel::data(const QModelIndex &index, int role) const QVariant DeckListModel::data(const QModelIndex &index, int role) const
{ {
// debugIndexInfo("data", index); // debugIndexInfo("data", index);
if (!index.isValid()) if (!index.isValid()) {
{
return QVariant(); return QVariant();
} }
if (index.column() >= columnCount()) if (index.column() >= columnCount()) {
{
return QVariant(); return QVariant();
} }
auto *temp = static_cast<AbstractDecklistNode *>(index.internalPointer()); auto *temp = static_cast<AbstractDecklistNode *>(index.internalPointer());
auto *card = dynamic_cast<DecklistModelCardNode *>(temp); auto *card = dynamic_cast<DecklistModelCardNode *>(temp);
if (card == nullptr) if (card == nullptr) {
{
auto *node = dynamic_cast<InnerDecklistNode *>(temp); auto *node = dynamic_cast<InnerDecklistNode *>(temp);
switch (role) switch (role) {
{ case Qt::FontRole: {
case Qt::FontRole:
{
QFont f; QFont f;
f.setBold(true); f.setBold(true);
return f; return f;
} }
case Qt::DisplayRole: case Qt::DisplayRole:
case Qt::EditRole: case Qt::EditRole: {
{ switch (index.column()) {
switch (index.column())
{
case 0: case 0:
return node->recursiveCount(true); return node->recursiveCount(true);
case 1: case 1:
@ -125,39 +111,34 @@ QVariant DeckListModel::data(const QModelIndex &index, int role) const
return QVariant(); return QVariant();
} }
} }
case Qt::BackgroundRole: case Qt::BackgroundRole: {
{
int color = 90 + 60 * node->depth(); int color = 90 + 60 * node->depth();
return QBrush(QColor(color, 255, color)); return QBrush(QColor(color, 255, color));
} }
case Qt::ForegroundRole: case Qt::ForegroundRole: {
{
return QBrush(QColor(0, 0, 0)); return QBrush(QColor(0, 0, 0));
} }
default: return QVariant(); default:
return QVariant();
} }
} } else {
else switch (role) {
{
switch (role)
{
case Qt::DisplayRole: case Qt::DisplayRole:
case Qt::EditRole: case Qt::EditRole: {
{ switch (index.column()) {
switch (index.column()) case 0:
{ return card->getNumber();
case 0: return card->getNumber(); case 1:
case 1: return card->getName(); return card->getName();
default: return QVariant(); default:
return QVariant();
} }
} }
case Qt::BackgroundRole: case Qt::BackgroundRole: {
{
int color = 255 - (index.row() % 2) * 30; int color = 255 - (index.row() % 2) * 30;
return QBrush(QColor(color, color, color)); return QBrush(QColor(color, color, color));
} }
case Qt::ForegroundRole: case Qt::ForegroundRole: {
{
return QBrush(QColor(0, 0, 0)); return QBrush(QColor(0, 0, 0));
} }
default: default:
@ -168,41 +149,38 @@ QVariant DeckListModel::data(const QModelIndex &index, int role) const
QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) {
{
return QVariant(); return QVariant();
} }
if (section >= columnCount()) if (section >= columnCount()) {
{
return QVariant(); return QVariant();
} }
switch (section) switch (section) {
{ case 0:
case 0: return tr("Number"); return tr("Number");
case 1: return tr("Card"); case 1:
default: return QVariant(); return tr("Card");
default:
return QVariant();
} }
} }
QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const
{ {
// debugIndexInfo("index", parent); // debugIndexInfo("index", parent);
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent)) {
{
return {}; return {};
} }
auto *parentNode = getNode<InnerDecklistNode *>(parent); auto *parentNode = getNode<InnerDecklistNode *>(parent);
return row >= parentNode->size() ? QModelIndex() : createIndex(row, column, parentNode->at(row)); return row >= parentNode->size() ? QModelIndex() : createIndex(row, column, parentNode->at(row));
} }
QModelIndex DeckListModel::parent(const QModelIndex &ind) const QModelIndex DeckListModel::parent(const QModelIndex &ind) const
{ {
if (!ind.isValid()) if (!ind.isValid()) {
{
return {}; return {};
} }
@ -211,8 +189,7 @@ QModelIndex DeckListModel::parent(const QModelIndex &ind) const
Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid()) {
{
return nullptr; return nullptr;
} }
@ -224,8 +201,7 @@ Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const
void DeckListModel::emitRecursiveUpdates(const QModelIndex &index) void DeckListModel::emitRecursiveUpdates(const QModelIndex &index)
{ {
if (!index.isValid()) if (!index.isValid()) {
{
return; return;
} }
@ -236,16 +212,19 @@ void DeckListModel::emitRecursiveUpdates(const QModelIndex &index)
bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role) bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{ {
auto *node = getNode<DecklistModelCardNode *>(index); auto *node = getNode<DecklistModelCardNode *>(index);
if (!node || (role != Qt::EditRole)) if (!node || (role != Qt::EditRole)) {
{
return false; return false;
} }
switch (index.column()) switch (index.column()) {
{ case 0:
case 0: node->setNumber(value.toInt()); break; node->setNumber(value.toInt());
case 1: node->setName(value.toString()); break; break;
default: return false; case 1:
node->setName(value.toString());
break;
default:
return false;
} }
emitRecursiveUpdates(index); 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) bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent)
{ {
auto *node = getNode<InnerDecklistNode *>(parent); auto *node = getNode<InnerDecklistNode *>(parent);
if (!node) if (!node) {
{
return false; return false;
} }
if (row + count > node->size()) if (row + count > node->size()) {
{
return false; return false;
} }
beginRemoveRows(parent, row, row + count - 1); beginRemoveRows(parent, row, row + count - 1);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++) {
{
AbstractDecklistNode *toDelete = node->takeAt(row); AbstractDecklistNode *toDelete = node->takeAt(row);
if (auto *temp = dynamic_cast<DecklistModelCardNode *>(toDelete)) if (auto *temp = dynamic_cast<DecklistModelCardNode *>(toDelete)) {
{
deckList->deleteNode(temp->getDataNode()); deckList->deleteNode(temp->getDataNode());
} }
delete toDelete; delete toDelete;
} }
endRemoveRows(); endRemoveRows();
if (node->empty() && (node != root)) if (node->empty() && (node != root)) {
{
removeRows(parent.row(), 1, parent.parent()); removeRows(parent.row(), 1, parent.parent());
} } else {
else
{
emitRecursiveUpdates(parent); emitRecursiveUpdates(parent);
} }
@ -293,8 +265,7 @@ bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent)
InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent) InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent)
{ {
auto *newNode = dynamic_cast<InnerDecklistNode *>(parent->findChild(name)); auto *newNode = dynamic_cast<InnerDecklistNode *>(parent->findChild(name));
if (!newNode) if (!newNode) {
{
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
newNode = new InnerDecklistNode(name, parent); newNode = new InnerDecklistNode(name, parent);
endInsertRows(); endInsertRows();
@ -309,21 +280,18 @@ DecklistModelCardNode *DeckListModel::findCardNode(const QString &cardName, cons
QString cardType; QString cardType;
zoneNode = dynamic_cast<InnerDecklistNode *>(root->findChild(zoneName)); zoneNode = dynamic_cast<InnerDecklistNode *>(root->findChild(zoneName));
if (!zoneNode) if (!zoneNode) {
{
return nullptr; return nullptr;
} }
info = db->getCard(cardName); info = db->getCard(cardName);
if (!info) if (!info) {
{
return nullptr; return nullptr;
} }
cardType = info->getMainCardType(); cardType = info->getMainCardType();
typeNode = dynamic_cast<InnerDecklistNode *>(zoneNode->findChild(cardType)); typeNode = dynamic_cast<InnerDecklistNode *>(zoneNode->findChild(cardType));
if (!typeNode) if (!typeNode) {
{
return nullptr; return nullptr;
} }
@ -335,8 +303,7 @@ QModelIndex DeckListModel::findCard(const QString &cardName, const QString &zone
DecklistModelCardNode *cardNode; DecklistModelCardNode *cardNode;
cardNode = findCardNode(cardName, zoneName); cardNode = findCardNode(cardName, zoneName);
if (!cardNode) if (!cardNode) {
{
return {}; 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) QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway)
{ {
CardInfo *info = db->getCard(cardName); CardInfo *info = db->getCard(cardName);
if (info == nullptr) if (info == nullptr) {
{ if (abAddAnyway) {
if (abAddAnyway)
{
// We need to keep this card added no matter what // We need to keep this card added no matter what
// This is usually called from tab_deck_editor // This is usually called from tab_deck_editor
// So we'll create a new CardInfo with the name // So we'll create a new CardInfo with the name
// and default values for all fields // and default values for all fields
info = new CardInfo( info = new CardInfo(cardName, false, nullptr, nullptr, "unknown", nullptr, nullptr, QStringList(),
cardName, QList<CardRelation *>(), QList<CardRelation *>(), false, 0, false, 0, SetList(),
false, QStringMap(), MuidMap(), QStringMap(), QStringMap());
nullptr, } else {
nullptr,
"unknown",
nullptr,
nullptr,
QStringList(),
QList<CardRelation *>(),
QList<CardRelation *>(),
false,
0,
false,
0,
SetList(),
QStringMap(),
MuidMap(),
QStringMap(),
QStringMap()
);
}
else
{
return {}; return {};
} }
} }
@ -389,15 +334,12 @@ QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneN
QModelIndex parentIndex = nodeToIndex(cardTypeNode); QModelIndex parentIndex = nodeToIndex(cardTypeNode);
auto *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName)); auto *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName));
if (!cardNode) if (!cardNode) {
{
DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName);
beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size());
cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode);
endInsertRows(); endInsertRows();
} } else {
else
{
cardNode->setNumber(cardNode->getNumber() + 1); cardNode->setNumber(cardNode->getNumber() + 1);
deckList->updateDeckHash(); deckList->updateDeckHash();
} }
@ -408,8 +350,7 @@ QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneN
QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const
{ {
if (node == nullptr || node == root) if (node == nullptr || node == root) {
{
return {}; return {};
} }
@ -424,13 +365,11 @@ void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order)
QModelIndexList from, to; QModelIndexList from, to;
int columns = columnCount(); 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 fromRow = sortResult[i].first;
const int toRow = sortResult[i].second; const int toRow = sortResult[i].second;
AbstractDecklistNode *temp = node->at(toRow); AbstractDecklistNode *temp = node->at(toRow);
for (int j = 0; j < columns; ++j) for (int j = 0; j < columns; ++j) {
{
from << createIndex(fromRow, j, temp); from << createIndex(fromRow, j, temp);
to << createIndex(toRow, j, temp); to << createIndex(toRow, j, temp);
} }
@ -438,11 +377,9 @@ void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order)
changePersistentIndexList(from, to); changePersistentIndexList(from, to);
// Recursion // Recursion
for (int i = node->size() - 1; i >= 0; --i) for (int i = node->size() - 1; i >= 0; --i) {
{
auto *subNode = dynamic_cast<InnerDecklistNode *>(node->at(i)); auto *subNode = dynamic_cast<InnerDecklistNode *>(node->at(i));
if (subNode) if (subNode) {
{
sortHelper(subNode, order); sortHelper(subNode, order);
} }
} }
@ -455,8 +392,7 @@ void DeckListModel::sort(int column, Qt::SortOrder order)
emit layoutAboutToBeChanged(); emit layoutAboutToBeChanged();
DeckSortMethod sortMethod; DeckSortMethod sortMethod;
switch(column) switch (column) {
{
case 0: case 0:
sortMethod = ByNumber; sortMethod = ByNumber;
break; break;
@ -490,8 +426,7 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no
{ {
const int totalColumns = 2; const int totalColumns = 2;
if (node->height() == 1) if (node->height() == 1) {
{
QTextBlockFormat blockFormat; QTextBlockFormat blockFormat;
QTextCharFormat charFormat; QTextCharFormat charFormat;
charFormat.setFontPointSize(11); charFormat.setFontPointSize(11);
@ -503,8 +438,7 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no
tableFormat.setCellSpacing(0); tableFormat.setCellSpacing(0);
tableFormat.setBorder(0); tableFormat.setBorder(0);
QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat);
for (int i = 0; i < node->size(); i++) for (int i = 0; i < node->size(); i++) {
{
auto *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i)); auto *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i));
QTextCharFormat cellCharFormat; QTextCharFormat cellCharFormat;
@ -519,11 +453,8 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no
cell.setFormat(cellCharFormat); cell.setFormat(cellCharFormat);
cellCursor = cell.firstCursorPosition(); cellCursor = cell.firstCursorPosition();
cellCursor.insertText(card->getName()); cellCursor.insertText(card->getName());
} }
} } else if (node->height() == 2) {
else if (node->height() == 2)
{
QTextBlockFormat blockFormat; QTextBlockFormat blockFormat;
QTextCharFormat charFormat; QTextCharFormat charFormat;
charFormat.setFontPointSize(14); charFormat.setFontPointSize(14);
@ -536,15 +467,13 @@ void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *no
tableFormat.setCellSpacing(0); tableFormat.setCellSpacing(0);
tableFormat.setBorder(0); tableFormat.setBorder(0);
QVector<QTextLength> constraints; QVector<QTextLength> constraints;
for (int i = 0; i < totalColumns; i++) for (int i = 0; i < totalColumns; i++) {
{
constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns);
} }
tableFormat.setColumnWidthConstraints(constraints); tableFormat.setColumnWidthConstraints(constraints);
QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat);
for (int i = 0; i < node->size(); i++) for (int i = 0; i < node->size(); i++) {
{
QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition();
printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i))); printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i)));
} }
@ -576,8 +505,7 @@ void DeckListModel::printDeckList(QPrinter *printer)
cursor.insertText(deckList->getComments()); cursor.insertText(deckList->getComments());
cursor.insertBlock(headerBlockFormat, headerCharFormat); cursor.insertBlock(headerBlockFormat, headerCharFormat);
for (int i = 0; i < root->size(); i++) for (int i = 0; i < root->size(); i++) {
{
cursor.insertHtml("<br><img src=theme:hr.jpg>"); cursor.insertHtml("<br><img src=theme:hr.jpg>");
// cursor.insertHtml("<hr>"); // cursor.insertHtml("<hr>");
cursor.insertBlock(headerBlockFormat, headerCharFormat); cursor.insertBlock(headerBlockFormat, headerCharFormat);

View file

@ -1,9 +1,9 @@
#ifndef DECKLISTMODEL_H #ifndef DECKLISTMODEL_H
#define DECKLISTMODEL_H #define DECKLISTMODEL_H
#include "decklist.h"
#include <QAbstractItemModel> #include <QAbstractItemModel>
#include <QList> #include <QList>
#include "decklist.h"
class DeckLoader; class DeckLoader;
class CardDatabase; class CardDatabase;
@ -11,19 +11,40 @@ class QProgressDialog;
class QPrinter; class QPrinter;
class QTextCursor; class QTextCursor;
class DecklistModelCardNode : public AbstractDecklistCardNode { class DecklistModelCardNode : public AbstractDecklistCardNode
{
private: private:
DecklistCardNode *dataNode; DecklistCardNode *dataNode;
public: public:
DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent)
int getNumber() const { return dataNode->getNumber(); } : AbstractDecklistCardNode(_parent), dataNode(_dataNode)
void setNumber(int _number) { dataNode->setNumber(_number); } {
QString getName() const { return dataNode->getName(); } }
void setName(const QString &_name) { dataNode->setName(_name); } int getNumber() const
DecklistCardNode *getDataNode() const { return dataNode; } {
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 Q_OBJECT
private slots: private slots:
void rebuildTree(); void rebuildTree();
@ -31,6 +52,7 @@ public slots:
void printDeckList(QPrinter *printer); void printDeckList(QPrinter *printer);
signals: signals:
void deckHashChanged(); void deckHashChanged();
public: public:
DeckListModel(QObject *parent = 0); DeckListModel(QObject *parent = 0);
~DeckListModel(); ~DeckListModel();
@ -47,8 +69,12 @@ public:
QModelIndex addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway = false); QModelIndex addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway = false);
void sort(int column, Qt::SortOrder order); void sort(int column, Qt::SortOrder order);
void cleanList(); void cleanList();
DeckLoader *getDeckList() const { return deckList; } DeckLoader *getDeckList() const
{
return deckList;
}
void setDeckList(DeckLoader *_deck); void setDeckList(DeckLoader *_deck);
private: private:
DeckLoader *deckList; DeckLoader *deckList;
InnerDecklistNode *root; InnerDecklistNode *root;

View file

@ -1,17 +1,15 @@
#include "deckstats_interface.h" #include "deckstats_interface.h"
#include "decklist.h" #include "decklist.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QRegExp>
#include <QMessageBox>
#include <QDesktopServices> #include <QDesktopServices>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegExp>
#include <QUrlQuery> #include <QUrlQuery>
DeckStatsInterface::DeckStatsInterface( DeckStatsInterface::DeckStatsInterface(CardDatabase &_cardDatabase, QObject *parent)
CardDatabase &_cardDatabase, : QObject(parent), cardDatabase(_cardDatabase)
QObject *parent
) : QObject(parent), cardDatabase(_cardDatabase)
{ {
manager = new QNetworkAccessManager(this); manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *)));
@ -66,34 +64,26 @@ void DeckStatsInterface::analyzeDeck(DeckList *deck)
manager->post(request, data); manager->post(request, data);
} }
struct CopyIfNotAToken { struct CopyIfNotAToken
{
CardDatabase &cardDatabase; CardDatabase &cardDatabase;
DeckList &destination; DeckList &destination;
CopyIfNotAToken( CopyIfNotAToken(CardDatabase &_cardDatabase, DeckList &_destination)
CardDatabase &_cardDatabase, : cardDatabase(_cardDatabase), destination(_destination){};
DeckList &_destination
) : cardDatabase(_cardDatabase), destination(_destination) {};
void operator()( void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const
const InnerDecklistNode *node, {
const DecklistCardNode *card
) const {
CardInfo *dbCard = cardDatabase.getCard(card->getName()); CardInfo *dbCard = cardDatabase.getCard(card->getName());
if (dbCard && !dbCard->getIsToken()) { if (dbCard && !dbCard->getIsToken()) {
DecklistCardNode *addedCard = destination.addCard( DecklistCardNode *addedCard = destination.addCard(card->getName(), node->getName());
card->getName(),
node->getName()
);
addedCard->setNumber(card->getNumber()); addedCard->setNumber(card->getNumber());
} }
} }
}; };
void DeckStatsInterface::copyDeckWithoutTokens( void DeckStatsInterface::copyDeckWithoutTokens(const DeckList &source, DeckList &destination)
const DeckList &source, {
DeckList &destination
) {
CopyIfNotAToken copyIfNotAToken(cardDatabase, destination); CopyIfNotAToken copyIfNotAToken(cardDatabase, destination);
source.forEachCard(copyIfNotAToken); source.forEachCard(copyIfNotAToken);
} }

View file

@ -10,7 +10,8 @@ class QNetworkAccessManager;
class QNetworkReply; class QNetworkReply;
class DeckList; class DeckList;
class DeckStatsInterface : public QObject { class DeckStatsInterface : public QObject
{
Q_OBJECT Q_OBJECT
private: private:
QNetworkAccessManager *manager; QNetworkAccessManager *manager;
@ -27,6 +28,7 @@ private:
private slots: private slots:
void queryFinished(QNetworkReply *reply); void queryFinished(QNetworkReply *reply);
void getAnalyzeRequestData(DeckList *deck, QByteArray *data); void getAnalyzeRequestData(DeckList *deck, QByteArray *data);
public: public:
DeckStatsInterface(CardDatabase &_cardDatabase, QObject *parent = 0); DeckStatsInterface(CardDatabase &_cardDatabase, QObject *parent = 0);
void analyzeDeck(DeckList *deck); void analyzeDeck(DeckList *deck);

View file

@ -1,15 +1,17 @@
#include "deckview.h"
#include "carddatabase.h"
#include "decklist.h"
#include "main.h"
#include "settingscache.h"
#include "thememanager.h"
#include <QApplication> #include <QApplication>
#include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneMouseEvent>
#include <QMouseEvent> #include <QMouseEvent>
#include <math.h> #include <math.h>
#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) : AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0)
{ {
} }
@ -90,7 +92,8 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
2 * QApplication::startDragDistance())
return; return;
if (static_cast<DeckViewScene *>(scene())->getLocked()) if (static_cast<DeckViewScene *>(scene())->getLocked())
@ -122,8 +125,7 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
if (static_cast<DeckViewScene *>(scene())->getLocked()) if (static_cast<DeckViewScene *>(scene())->getLocked())
return; return;
if (event->button() == Qt::LeftButton) if (event->button() == Qt::LeftButton) {
{
QList<MoveCard_ToZone> result; QList<MoveCard_ToZone> result;
QList<QGraphicsItem *> sel = scene()->selectedItems(); QList<QGraphicsItem *> sel = scene()->selectedItems();
@ -156,8 +158,7 @@ void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
processHoverEvent(); processHoverEvent();
} }
DeckViewCardContainer::DeckViewCardContainer(const QString &_name) DeckViewCardContainer::DeckViewCardContainer(const QString &_name) : QGraphicsItem(), name(_name), width(0), height(0)
: QGraphicsItem(), name(_name), width(0), height(0)
{ {
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);
} }
@ -181,7 +182,8 @@ void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsI
f.setPixelSize(24); f.setPixelSize(24);
f.setWeight(QFont::Bold); f.setWeight(QFont::Bold);
painter->setFont(f); painter->setFont(f);
painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size())); painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine,
InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size()));
f.setPixelSize(16); f.setPixelSize(16);
painter->setFont(f); painter->setFont(f);
@ -302,8 +304,7 @@ void DeckViewCardContainer::setWidth(qreal _width)
update(); update();
} }
DeckViewScene::DeckViewScene(QObject *parent) DeckViewScene::DeckViewScene(QObject *parent) : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
: QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
{ {
} }
@ -435,7 +436,8 @@ void DeckViewScene::rearrangeItems()
// Add row to category // Add row to category
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
const int maxCardCount = cardCountList[maxIndex1][maxIndex2]; const int maxCardCount = cardCountList[maxIndex1][maxIndex2];
rowsAndColsList[maxIndex1][maxIndex2] = QPair<int, int>(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1))); rowsAndColsList[maxIndex1][maxIndex2] =
QPair<int, int>(maxRows + 1, (int)ceil((qreal)maxCardCount / (qreal)(maxRows + 1)));
} }
totalHeight = -spacing; totalHeight = -spacing;
@ -484,8 +486,7 @@ void DeckViewScene::resetSideboardPlan()
rearrangeItems(); rearrangeItems();
} }
DeckView::DeckView(QWidget *parent) DeckView::DeckView(QWidget *parent) : QGraphicsView(parent)
: QGraphicsView(parent)
{ {
deckViewScene = new DeckViewScene(this); deckViewScene = new DeckViewScene(this);

View file

@ -1,12 +1,12 @@
#ifndef DECKVIEW_H #ifndef DECKVIEW_H
#define DECKVIEW_H #define DECKVIEW_H
#include "abstractcarddragitem.h"
#include <QGraphicsScene> #include <QGraphicsScene>
#include <QGraphicsView> #include <QGraphicsView>
#include <QMap> #include <QMap>
#include <QMultiMap> #include <QMultiMap>
#include <QPixmap> #include <QPixmap>
#include "abstractcarddragitem.h"
#include "pb/move_card_to_zone.pb.h" #include "pb/move_card_to_zone.pb.h"
@ -17,32 +17,42 @@ class DeckViewCardContainer;
class DeckViewCardDragItem; class DeckViewCardDragItem;
class MoveCardToZone; class MoveCardToZone;
class DeckViewCard : public AbstractCardItem { class DeckViewCard : public AbstractCardItem
{
private: private:
QString originZone; QString originZone;
DeckViewCardDragItem *dragItem; DeckViewCardDragItem *dragItem;
public: public:
DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0); DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0);
~DeckViewCard(); ~DeckViewCard();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
const QString &getOriginZone() const { return originZone; } const QString &getOriginZone() const
{
return originZone;
}
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
}; };
class DeckViewCardDragItem : public AbstractCardDragItem { class DeckViewCardDragItem : public AbstractCardDragItem
{
private: private:
DeckViewCardContainer *currentZone; DeckViewCardContainer *currentZone;
void handleDrop(DeckViewCardContainer *target); void handleDrop(DeckViewCardContainer *target);
public: public:
DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
void updatePosition(const QPointF &cursorScenePos); void updatePosition(const QPointF &cursorScenePos);
protected: protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
}; };
class DeckViewCardContainer : public QGraphicsItem { class DeckViewCardContainer : public QGraphicsItem
{
private: private:
static const int separatorY = 20; static const int separatorY = 20;
static const int paddingY = 10; static const int paddingY = 10;
@ -54,16 +64,29 @@ private:
QList<QPair<int, int>> currentRowsAndCols; QList<QPair<int, int>> currentRowsAndCols;
qreal width, height; qreal width, height;
int getCardTypeTextWidth() const; int getCardTypeTextWidth() const;
public: public:
enum { Type = typeDeckViewCardContainer }; enum
int type() const { return Type; } {
Type = typeDeckViewCardContainer
};
int type() const
{
return Type;
}
DeckViewCardContainer(const QString &_name); DeckViewCardContainer(const QString &_name);
QRectF boundingRect() const; QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void addCard(DeckViewCard *card); void addCard(DeckViewCard *card);
void removeCard(DeckViewCard *card); void removeCard(DeckViewCard *card);
const QList<DeckViewCard *> &getCards() const { return cards; } const QList<DeckViewCard *> &getCards() const
const QString &getName() const { return name; } {
return cards;
}
const QString &getName() const
{
return name;
}
void setWidth(qreal _width); void setWidth(qreal _width);
QList<QPair<int, int>> getRowsAndCols() const; QList<QPair<int, int>> getRowsAndCols() const;
@ -71,11 +94,13 @@ public:
void rearrangeItems(const QList<QPair<int, int>> &rowsAndCols); void rearrangeItems(const QList<QPair<int, int>> &rowsAndCols);
}; };
class DeckViewScene : public QGraphicsScene { class DeckViewScene : public QGraphicsScene
{
Q_OBJECT Q_OBJECT
signals: signals:
void newCardAdded(AbstractCardItem *card); void newCardAdded(AbstractCardItem *card);
void sideboardPlanChanged(); void sideboardPlanChanged();
private: private:
bool locked; bool locked;
DeckList *deck; DeckList *deck;
@ -83,13 +108,23 @@ private:
qreal optimalAspectRatio; qreal optimalAspectRatio;
void clearContents(); void clearContents();
void rebuildTree(); void rebuildTree();
public: public:
DeckViewScene(QObject *parent = 0); DeckViewScene(QObject *parent = 0);
~DeckViewScene(); ~DeckViewScene();
void setLocked(bool _locked) { locked = _locked; } void setLocked(bool _locked)
bool getLocked() const { return locked; } {
locked = _locked;
}
bool getLocked() const
{
return locked;
}
void setDeck(const DeckList &_deck); void setDeck(const DeckList &_deck);
void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } void setOptimalAspectRatio(qreal _optimalAspectRatio)
{
optimalAspectRatio = _optimalAspectRatio;
}
void rearrangeItems(); void rearrangeItems();
void updateContents(); void updateContents();
QList<MoveCard_ToZone> getSideboardPlan() const; QList<MoveCard_ToZone> getSideboardPlan() const;
@ -97,10 +132,12 @@ public:
void applySideboardPlan(const QList<MoveCard_ToZone> &plan); void applySideboardPlan(const QList<MoveCard_ToZone> &plan);
}; };
class DeckView : public QGraphicsView { class DeckView : public QGraphicsView
{
Q_OBJECT Q_OBJECT
private: private:
DeckViewScene *deckViewScene; DeckViewScene *deckViewScene;
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
public slots: public slots:
@ -108,11 +145,18 @@ public slots:
signals: signals:
void newCardAdded(AbstractCardItem *card); void newCardAdded(AbstractCardItem *card);
void sideboardPlanChanged(); void sideboardPlanChanged();
public: public:
DeckView(QWidget *parent = 0); DeckView(QWidget *parent = 0);
void setDeck(const DeckList &_deck); void setDeck(const DeckList &_deck);
void setLocked(bool _locked) { deckViewScene->setLocked(_locked); } void setLocked(bool _locked)
QList<MoveCard_ToZone> getSideboardPlan() const { return deckViewScene->getSideboardPlan(); } {
deckViewScene->setLocked(_locked);
}
QList<MoveCard_ToZone> getSideboardPlan() const
{
return deckViewScene->getSideboardPlan();
}
void mouseDoubleClickEvent(QMouseEvent *event); void mouseDoubleClickEvent(QMouseEvent *event);
void resetSideboardPlan(); void resetSideboardPlan();
}; };

View file

@ -1,17 +1,17 @@
#include <QLabel>
#include <QCheckBox>
#include <QComboBox>
#include <QRadioButton>
#include <QGridLayout>
#include <QDialogButtonBox>
#include <QEvent>
#include <QKeyEvent>
#include <QMessageBox>
#include <QGroupBox>
#include <QPushButton>
#include "dlg_connect.h" #include "dlg_connect.h"
#include "settingscache.h" #include "settingscache.h"
#include "userconnection_information.h" #include "userconnection_information.h"
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QEvent>
#include <QGridLayout>
#include <QGroupBox>
#include <QKeyEvent>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
#include <QRadioButton>
#define PUBLIC_SERVERS_URL "https://github.com/Cockatrice/Cockatrice/wiki/Public-Servers" #define PUBLIC_SERVERS_URL "https://github.com/Cockatrice/Cockatrice/wiki/Public-Servers"
@ -52,7 +52,8 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
autoConnectCheckBox = new QCheckBox(tr("A&uto connect")); autoConnectCheckBox = new QCheckBox(tr("A&uto connect"));
autoConnectCheckBox->setToolTip(tr("Automatically connect to the most recent login when Cockatrice opens")); autoConnectCheckBox->setToolTip(tr("Automatically connect to the most recent login when Cockatrice opens"));
publicServersLabel = new QLabel(QString("(<a href=\"%1\">%2</a>)").arg(PUBLIC_SERVERS_URL).arg(tr("Public Servers"))); publicServersLabel =
new QLabel(QString("(<a href=\"%1\">%2</a>)").arg(PUBLIC_SERVERS_URL).arg(tr("Public Servers")));
publicServersLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); publicServersLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
publicServersLabel->setWordWrap(true); publicServersLabel->setWordWrap(true);
publicServersLabel->setTextFormat(Qt::RichText); publicServersLabel->setTextFormat(Qt::RichText);
@ -60,13 +61,10 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
publicServersLabel->setOpenExternalLinks(true); publicServersLabel->setOpenExternalLinks(true);
publicServersLabel->setAlignment(Qt::AlignCenter); publicServersLabel->setAlignment(Qt::AlignCenter);
if (savePasswordCheckBox->isChecked()) if (savePasswordCheckBox->isChecked()) {
{
autoConnectCheckBox->setChecked(static_cast<bool>(settingsCache->servers().getAutoConnect())); autoConnectCheckBox->setChecked(static_cast<bool>(settingsCache->servers().getAutoConnect()));
autoConnectCheckBox->setEnabled(true); autoConnectCheckBox->setEnabled(true);
} } else {
else
{
settingsCache->servers().setAutoConnect(0); settingsCache->servers().setAutoConnect(0);
autoConnectCheckBox->setChecked(false); autoConnectCheckBox->setChecked(false);
autoConnectCheckBox->setEnabled(false); autoConnectCheckBox->setEnabled(false);
@ -140,7 +138,8 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
previousHostButton->setChecked(true); 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(); playernameEdit->setFocus();
} }
@ -148,24 +147,13 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
void DlgConnect::actSaveConfig() void DlgConnect::actSaveConfig()
{ {
bool updateSuccess = settingsCache->servers().updateExistingServer( bool updateSuccess = settingsCache->servers().updateExistingServer(
saveEdit->text().trimmed(), saveEdit->text().trimmed(), hostEdit->text().trimmed(), portEdit->text().trimmed(),
hostEdit->text().trimmed(), playernameEdit->text().trimmed(), passwordEdit->text(), savePasswordCheckBox->isChecked());
portEdit->text().trimmed(),
playernameEdit->text().trimmed(),
passwordEdit->text(),
savePasswordCheckBox->isChecked()
);
if (! updateSuccess) if (!updateSuccess) {
{ settingsCache->servers().addNewServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(),
settingsCache->servers().addNewServer( portEdit->text().trimmed(), playernameEdit->text().trimmed(),
saveEdit->text().trimmed(), passwordEdit->text(), savePasswordCheckBox->isChecked());
hostEdit->text().trimmed(),
portEdit->text().trimmed(),
playernameEdit->text().trimmed(),
passwordEdit->text(),
savePasswordCheckBox->isChecked()
);
} }
rebuildComboBoxList(); rebuildComboBoxList();
@ -178,8 +166,7 @@ void DlgConnect::rebuildComboBoxList()
UserConnection_Information uci; UserConnection_Information uci;
savedHostList = uci.getServerInfo(); savedHostList = uci.getServerInfo();
if (savedHostList.size() == 1) if (savedHostList.size() == 1) {
{
settingsCache->servers().addNewServer("Woogerworks", "cockatrice.woogerworks.com", "4747", "", "", false); settingsCache->servers().addNewServer("Woogerworks", "cockatrice.woogerworks.com", "4747", "", "", false);
settingsCache->servers().addNewServer("Chickatrice", "chickatrice.net", "4747", "", "", false); settingsCache->servers().addNewServer("Chickatrice", "chickatrice.net", "4747", "", "", false);
settingsCache->servers().addNewServer("cockatric.es", "cockatric.es", "4747", "", "", false); settingsCache->servers().addNewServer("cockatric.es", "cockatric.es", "4747", "", "", false);
@ -188,15 +175,12 @@ void DlgConnect::rebuildComboBoxList()
savedHostList = uci.getServerInfo(); savedHostList = uci.getServerInfo();
int i = 0; int i = 0;
for (UserConnection_Information tmp : savedHostList) for (UserConnection_Information tmp : savedHostList) {
{
QString saveName = tmp.getSaveName(); QString saveName = tmp.getSaveName();
if (saveName.size()) if (saveName.size()) {
{
previousHosts->addItem(saveName); previousHosts->addItem(saveName);
if (settingsCache->servers().getPrevioushostName() == saveName) if (settingsCache->servers().getPrevioushostName() == saveName) {
{
previousHosts->setCurrentIndex(i); previousHosts->setCurrentIndex(i);
} }
@ -205,11 +189,9 @@ void DlgConnect::rebuildComboBoxList()
} }
} }
void DlgConnect::previousHostSelected(bool state) void DlgConnect::previousHostSelected(bool state)
{ {
if (state) if (state) {
{
saveEdit->setDisabled(true); saveEdit->setDisabled(true);
previousHosts->setDisabled(false); previousHosts->setDisabled(false);
} }
@ -217,8 +199,7 @@ void DlgConnect::previousHostSelected(bool state)
void DlgConnect::updateDisplayInfo(const QString &saveName) void DlgConnect::updateDisplayInfo(const QString &saveName)
{ {
if (saveEdit == nullptr) if (saveEdit == nullptr) {
{
return; return;
} }
@ -233,16 +214,14 @@ void DlgConnect::updateDisplayInfo(const QString &saveName)
playernameEdit->setText(data.at(3)); playernameEdit->setText(data.at(3));
savePasswordCheckBox->setChecked(savePasswordStatus); savePasswordCheckBox->setChecked(savePasswordStatus);
if (savePasswordStatus) if (savePasswordStatus) {
{
passwordEdit->setText(data.at(4)); passwordEdit->setText(data.at(4));
} }
} }
void DlgConnect::newHostSelected(bool state) void DlgConnect::newHostSelected(bool state)
{ {
if (state) if (state) {
{
previousHosts->setDisabled(true); previousHosts->setDisabled(true);
hostEdit->clear(); hostEdit->clear();
portEdit->clear(); portEdit->clear();
@ -252,23 +231,17 @@ void DlgConnect::newHostSelected(bool state)
saveEdit->clear(); saveEdit->clear();
saveEdit->setPlaceholderText("New Menu Name"); saveEdit->setPlaceholderText("New Menu Name");
saveEdit->setDisabled(false); saveEdit->setDisabled(false);
} } else {
else
{
rebuildComboBoxList(); rebuildComboBoxList();
} }
} }
void DlgConnect::passwordSaved(int state) void DlgConnect::passwordSaved(int state)
{ {
Q_UNUSED(state); Q_UNUSED(state);
if (savePasswordCheckBox->isChecked()) if (savePasswordCheckBox->isChecked()) {
{
autoConnectCheckBox->setEnabled(true); autoConnectCheckBox->setEnabled(true);
} } else {
else
{
autoConnectCheckBox->setChecked(false); autoConnectCheckBox->setChecked(false);
autoConnectCheckBox->setEnabled(false); autoConnectCheckBox->setEnabled(false);
} }
@ -276,40 +249,25 @@ void DlgConnect::passwordSaved(int state)
void DlgConnect::actOk() void DlgConnect::actOk()
{ {
if (newHostButton->isChecked()) if (newHostButton->isChecked()) {
{ if (saveEdit->text().isEmpty()) {
if (saveEdit->text().isEmpty())
{
QMessageBox::critical(this, tr("Connection Warning"), tr("You need to name your new connection profile.")); QMessageBox::critical(this, tr("Connection Warning"), tr("You need to name your new connection profile."));
return; return;
} }
settingsCache->servers().addNewServer( settingsCache->servers().addNewServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(),
saveEdit->text().trimmed(), portEdit->text().trimmed(), playernameEdit->text().trimmed(),
hostEdit->text().trimmed(), passwordEdit->text(), savePasswordCheckBox->isChecked());
portEdit->text().trimmed(), } else {
playernameEdit->text().trimmed(), settingsCache->servers().updateExistingServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(),
passwordEdit->text(), portEdit->text().trimmed(), playernameEdit->text().trimmed(),
savePasswordCheckBox->isChecked() 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().setPrevioushostName(saveEdit->text());
settingsCache->servers().setAutoConnect(autoConnectCheckBox->isChecked()); 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.")); QMessageBox::critical(this, tr("Connect Warning"), tr("The player name can't be empty."));
return; return;
} }
@ -317,7 +275,6 @@ void DlgConnect::actOk()
accept(); accept();
} }
QString DlgConnect::getHost() const QString DlgConnect::getHost() const
{ {
return hostEdit->text().trimmed(); return hostEdit->text().trimmed();
@ -332,12 +289,10 @@ void DlgConnect::actCancel()
bool DeleteHighlightedItemWhenShiftDelPressedEventFilter::eventFilter(QObject *obj, QEvent *event) bool DeleteHighlightedItemWhenShiftDelPressedEventFilter::eventFilter(QObject *obj, QEvent *event)
{ {
if (event->type() == QEvent::KeyPress) if (event->type() == QEvent::KeyPress) {
{
auto *keyEvent = dynamic_cast<QKeyEvent *>(event); auto *keyEvent = dynamic_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Delete) if (keyEvent->key() == Qt::Key_Delete) {
{
auto *combobox = reinterpret_cast<QComboBox *>(obj); auto *combobox = reinterpret_cast<QComboBox *>(obj);
combobox->removeItem(combobox->currentIndex()); combobox->removeItem(combobox->currentIndex());
return true; return true;

View file

@ -18,17 +18,27 @@ protected:
bool eventFilter(QObject *obj, QEvent *event); bool eventFilter(QObject *obj, QEvent *event);
}; };
class DlgConnect : public QDialog
class DlgConnect : public QDialog { {
Q_OBJECT Q_OBJECT
signals: signals:
void sigStartForgotPasswordRequest(); void sigStartForgotPasswordRequest();
public: public:
DlgConnect(QWidget *parent = 0); DlgConnect(QWidget *parent = 0);
QString getHost() const; QString getHost() const;
int getPort() const { return portEdit->text().toInt(); } int getPort() const
QString getPlayerName() const { return playernameEdit->text(); } {
QString getPassword() const { return passwordEdit->text(); } return portEdit->text().toInt();
}
QString getPlayerName() const
{
return playernameEdit->text();
}
QString getPassword() const
{
return passwordEdit->text();
}
private slots: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
@ -39,6 +49,7 @@ private slots:
void actForgotPassword(); void actForgotPassword();
void updateDisplayInfo(const QString &saveName); void updateDisplayInfo(const QString &saveName);
void rebuildComboBoxList(); void rebuildComboBoxList();
private: private:
QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *saveLabel, *publicServersLabel; QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *saveLabel, *publicServersLabel;
QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *saveEdit; QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *saveEdit;

View file

@ -1,23 +1,23 @@
#include <QCheckBox>
#include <QCloseEvent>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel> #include <QLabel>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
#include <QCheckBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDialogButtonBox>
#include <QGroupBox>
#include <QTreeView>
#include <QRadioButton> #include <QRadioButton>
#include <QHeaderView> #include <QTreeView>
#include <QCloseEvent> #include <QVBoxLayout>
#include "carddatabasemodel.h"
#include "cardinfopicture.h"
#include "decklist.h" #include "decklist.h"
#include "dlg_create_token.h" #include "dlg_create_token.h"
#include "carddatabasemodel.h"
#include "main.h" #include "main.h"
#include "settingscache.h" #include "settingscache.h"
#include "cardinfopicture.h"
DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent) DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent)
: QDialog(parent), predefinedTokens(_predefinedTokens) : QDialog(parent), predefinedTokens(_predefinedTokens)
@ -94,16 +94,14 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa
chooseTokenView->header()->hideSection(1); // Sets chooseTokenView->header()->hideSection(1); // Sets
chooseTokenView->header()->hideSection(2); // Mana Cost chooseTokenView->header()->hideSection(2); // Mana Cost
chooseTokenView->header()->setSectionResizeMode(5, QHeaderView::ResizeToContents); // Color(s) 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())); connect(chooseTokenView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(actOk()));
if (predefinedTokens.isEmpty()) if (predefinedTokens.isEmpty()) {
{
chooseTokenFromAllRadioButton->setChecked(true); chooseTokenFromAllRadioButton->setChecked(true);
chooseTokenFromDeckRadioButton->setDisabled(true); // No tokens in deck = no need for option chooseTokenFromDeckRadioButton->setDisabled(true); // No tokens in deck = no need for option
} } else {
else
{
chooseTokenFromDeckRadioButton->setChecked(true); chooseTokenFromDeckRadioButton->setChecked(true);
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens)); cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens));
} }
@ -148,8 +146,7 @@ void DlgCreateToken::tokenSelectionChanged(const QModelIndex &current, const QMo
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : 0; CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : 0;
if(cardInfo) if (cardInfo) {
{
updateSearchFieldWithoutUpdatingFilter(cardInfo->getName()); updateSearchFieldWithoutUpdatingFilter(cardInfo->getName());
const QChar cardColor = cardInfo->getColorChar(); const QChar cardColor = cardInfo->getColorChar();
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
@ -166,7 +163,8 @@ void DlgCreateToken::tokenSelectionChanged(const QModelIndex &current, const QMo
pic->setCard(cardInfo); pic->setCard(cardInfo);
} }
void DlgCreateToken::updateSearchFieldWithoutUpdatingFilter(const QString &newValue) const { void DlgCreateToken::updateSearchFieldWithoutUpdatingFilter(const QString &newValue) const
{
nameEdit->blockSignals(true); nameEdit->blockSignals(true);
nameEdit->setText(newValue); nameEdit->setText(newValue);
nameEdit->blockSignals(false); nameEdit->blockSignals(false);

View file

@ -17,7 +17,8 @@ class CardDatabaseModel;
class TokenDisplayModel; class TokenDisplayModel;
class CardInfoPicture; class CardInfoPicture;
class DlgCreateToken : public QDialog { class DlgCreateToken : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0); DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0);
@ -26,6 +27,7 @@ public:
QString getPT() const; QString getPT() const;
QString getAnnotation() const; QString getAnnotation() const;
bool getDestroy() const; bool getDestroy() const;
protected: protected:
void closeEvent(QCloseEvent *event); void closeEvent(QCloseEvent *event);
private slots: private slots:
@ -35,6 +37,7 @@ private slots:
void actChooseTokenFromDeck(bool checked); void actChooseTokenFromDeck(bool checked);
void actOk(); void actOk();
void actReject(); void actReject();
private: private:
CardDatabaseModel *cardDatabaseModel; CardDatabaseModel *cardDatabaseModel;
TokenDisplayModel *cardDatabaseDisplayModel; TokenDisplayModel *cardDatabaseDisplayModel;

View file

@ -1,23 +1,24 @@
#include "dlg_creategame.h"
#include "settingscache.h"
#include "tab_room.h"
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel> #include <QLabel>
#include <QLineEdit> #include <QLineEdit>
#include <QCheckBox>
#include <QPushButton>
#include <QGridLayout>
#include <QRadioButton>
#include <QSpinBox>
#include <QGroupBox>
#include <QDialogButtonBox>
#include <QMessageBox> #include <QMessageBox>
#include <QPushButton>
#include <QRadioButton>
#include <QSet> #include <QSet>
#include <QSpinBox>
#include <QWizard> #include <QWizard>
#include "dlg_creategame.h"
#include "tab_room.h"
#include "settingscache.h"
#include "pending_command.h"
#include "pb/serverinfo_game.pb.h" #include "pb/serverinfo_game.pb.h"
#include "pending_command.h"
void DlgCreateGame::sharedCtor() { void DlgCreateGame::sharedCtor()
{
rememberGameSettings = new QCheckBox(tr("Re&member settings")); rememberGameSettings = new QCheckBox(tr("Re&member settings"));
descriptionLabel = new QLabel(tr("&Description:")); descriptionLabel = new QLabel(tr("&Description:"));
descriptionEdit = new QLineEdit; descriptionEdit = new QLineEdit;
@ -106,7 +107,8 @@ void DlgCreateGame::sharedCtor() {
} }
DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent) DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent)
: QDialog(parent), room(_room), gameTypes(_gameTypes) { : QDialog(parent), room(_room), gameTypes(_gameTypes)
{
sharedCtor(); sharedCtor();
rememberGameSettings->setChecked(settingsCache->getRememberGameSettings()); rememberGameSettings->setChecked(settingsCache->getRememberGameSettings());
@ -139,7 +141,8 @@ DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameType
} }
DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QString> &_gameTypes, QWidget *parent) DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QString> &_gameTypes, QWidget *parent)
: QDialog(parent), room(0), gameTypes(_gameTypes) { : QDialog(parent), room(0), gameTypes(_gameTypes)
{
sharedCtor(); sharedCtor();
rememberGameSettings->setEnabled(false); rememberGameSettings->setEnabled(false);
@ -180,7 +183,8 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QS
setWindowTitle(tr("Game information")); setWindowTitle(tr("Game information"));
} }
void DlgCreateGame::actReset() { void DlgCreateGame::actReset()
{
descriptionEdit->setText(""); descriptionEdit->setText("");
maxPlayersEdit->setValue(2); maxPlayersEdit->setValue(2);
@ -205,8 +209,8 @@ void DlgCreateGame::actReset() {
descriptionEdit->setFocus(); descriptionEdit->setFocus();
} }
void DlgCreateGame::actOK()
void DlgCreateGame::actOK() { {
Command_CreateGame cmd; Command_CreateGame cmd;
cmd.set_description(descriptionEdit->text().simplified().toStdString()); cmd.set_description(descriptionEdit->text().simplified().toStdString());
cmd.set_password(passwordEdit->text().toStdString()); cmd.set_password(passwordEdit->text().toStdString());
@ -247,7 +251,8 @@ void DlgCreateGame::actOK() {
buttonBox->setEnabled(false); buttonBox->setEnabled(false);
} }
void DlgCreateGame::checkResponse(const Response &response) { void DlgCreateGame::checkResponse(const Response &response)
{
buttonBox->setEnabled(true); buttonBox->setEnabled(true);
if (response.response_code() == Response::RespOk) 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); spectatorsNeedPasswordCheckBox->setEnabled(state);
spectatorsCanTalkCheckBox->setEnabled(state); spectatorsCanTalkCheckBox->setEnabled(state);
spectatorsSeeEverythingCheckBox->setEnabled(state); spectatorsSeeEverythingCheckBox->setEnabled(state);
} }

View file

@ -17,7 +17,8 @@ class TabRoom;
class Response; class Response;
class ServerInfo_Game; class ServerInfo_Game;
class DlgCreateGame : public QDialog { class DlgCreateGame : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent = 0); DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent = 0);
@ -27,6 +28,7 @@ private slots:
void actReset(); void actReset();
void checkResponse(const Response &response); void checkResponse(const Response &response);
void spectatorsAllowedChanged(int state); void spectatorsAllowedChanged(int state);
private: private:
TabRoom *room; TabRoom *room;
QMap<int, QString> gameTypes; QMap<int, QString> gameTypes;
@ -37,7 +39,8 @@ private:
QLineEdit *descriptionEdit, *passwordEdit; QLineEdit *descriptionEdit, *passwordEdit;
QSpinBox *maxPlayersEdit; QSpinBox *maxPlayersEdit;
QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox; QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox;
QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox; QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox,
*spectatorsSeeEverythingCheckBox;
QDialogButtonBox *buttonBox; QDialogButtonBox *buttonBox;
QPushButton *clearButton; QPushButton *clearButton;
QCheckBox *rememberGameSettings; QCheckBox *rememberGameSettings;

View file

@ -10,15 +10,15 @@
#include "dlg_edit_avatar.h" #include "dlg_edit_avatar.h"
DlgEditAvatar::DlgEditAvatar(QWidget *parent) DlgEditAvatar::DlgEditAvatar(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
imageLabel = new QLabel(tr("No image chosen.")); imageLabel = new QLabel(tr("No image chosen."));
imageLabel->setFixedSize(400, 200); imageLabel->setFixedSize(400, 200);
imageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); imageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
imageLabel->setStyleSheet("border: 1px solid #000"); 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...")); browseButton = new QPushButton(tr("Browse..."));
connect(browseButton, SIGNAL(clicked()), this, SLOT(actBrowse())); connect(browseButton, SIGNAL(clicked()), this, SLOT(actBrowse()));
@ -53,9 +53,9 @@ void DlgEditAvatar::actCancel()
void DlgEditAvatar::actBrowse() void DlgEditAvatar::actBrowse()
{ {
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)")); QString fileName =
if(fileName.isEmpty()) QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)"));
{ if (fileName.isEmpty()) {
imageLabel->setText(tr("No image chosen.")); imageLabel->setText(tr("No image chosen."));
return; return;
} }
@ -64,8 +64,7 @@ void DlgEditAvatar::actBrowse()
QImageReader imgReader; QImageReader imgReader;
imgReader.setDecideFormatFromContent(true); imgReader.setDecideFormatFromContent(true);
imgReader.setFileName(fileName); imgReader.setFileName(fileName);
if(!imgReader.read(&image)) if (!imgReader.read(&image)) {
{
qDebug() << "Avatar image loading failed for file:" << fileName; qDebug() << "Avatar image loading failed for file:" << fileName;
imageLabel->setText(tr("Invalid image chosen.")); imageLabel->setText(tr("Invalid image chosen."));
return; return;

View file

@ -1,15 +1,16 @@
#ifndef DLG_EDITAVATAR_H #ifndef DLG_EDITAVATAR_H
#define DLG_EDITAVATAR_H #define DLG_EDITAVATAR_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgEditAvatar : public QDialog { class DlgEditAvatar : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgEditAvatar(QWidget *parent = 0); DlgEditAvatar(QWidget *parent = 0);
@ -18,6 +19,7 @@ private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
void actBrowse(); void actBrowse();
private: private:
QLabel *textLabel, *imageLabel; QLabel *textLabel, *imageLabel;
QPushButton *browseButton; QPushButton *browseButton;

View file

@ -4,11 +4,10 @@
#include <QLabel> #include <QLabel>
#include <QMessageBox> #include <QMessageBox>
#include "settingscache.h"
#include "dlg_edit_password.h" #include "dlg_edit_password.h"
#include "settingscache.h"
DlgEditPassword::DlgEditPassword(QWidget *parent) DlgEditPassword::DlgEditPassword(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
oldPasswordLabel = new QLabel(tr("Old password:")); oldPasswordLabel = new QLabel(tr("Old password:"));
@ -54,8 +53,7 @@ DlgEditPassword::DlgEditPassword(QWidget *parent)
void DlgEditPassword::actOk() 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.")); QMessageBox::warning(this, tr("Error"), tr("The new passwords don't match."));
return; return;
} }

View file

@ -1,23 +1,31 @@
#ifndef DLG_EDITPASSWORD_H #ifndef DLG_EDITPASSWORD_H
#define DLG_EDITPASSWORD_H #define DLG_EDITPASSWORD_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgEditPassword : public QDialog { class DlgEditPassword : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgEditPassword(QWidget *parent = 0); DlgEditPassword(QWidget *parent = 0);
QString getOldPassword() const { return oldPasswordEdit->text(); } QString getOldPassword() const
QString getNewPassword() const { return newPasswordEdit->text(); } {
return oldPasswordEdit->text();
}
QString getNewPassword() const
{
return newPasswordEdit->text();
}
private slots: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
private: private:
QLabel *oldPasswordLabel, *newPasswordLabel, *newPasswordLabel2; QLabel *oldPasswordLabel, *newPasswordLabel, *newPasswordLabel2;
QLineEdit *oldPasswordEdit, *newPasswordEdit, *newPasswordEdit2; QLineEdit *oldPasswordEdit, *newPasswordEdit, *newPasswordEdit2;

View file

@ -2,23 +2,22 @@
#include "carddatabase.h" #include "carddatabase.h"
#include "carddatabasemodel.h" #include "carddatabasemodel.h"
#include "main.h" #include "main.h"
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QComboBox>
#include <QLineEdit>
#include <QGroupBox>
#include <QTreeView>
#include <QHeaderView>
#include <QToolBar>
#include <QAction> #include <QAction>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QInputDialog> #include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox> #include <QMessageBox>
#include <QToolBar>
#include <QTreeView>
#include <QVBoxLayout>
DlgEditTokens::DlgEditTokens(QWidget *parent) DlgEditTokens::DlgEditTokens(QWidget *parent) : QDialog(parent), currentCard(0)
: QDialog(parent), currentCard(0)
{ {
nameLabel = new QLabel(tr("&Name:")); nameLabel = new QLabel(tr("&Name:"));
nameEdit = new QLineEdit; nameEdit = new QLineEdit;
@ -80,7 +79,8 @@ DlgEditTokens::DlgEditTokens(QWidget *parent)
chooseTokenView->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents); chooseTokenView->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
chooseTokenView->header()->setSectionResizeMode(4, 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); QAction *aAddToken = new QAction(tr("Add token"), this);
aAddToken->setIcon(QPixmap("theme:icons/increment")); aAddToken->setIcon(QPixmap("theme:icons/increment"));
@ -118,8 +118,7 @@ void DlgEditTokens::tokenSelectionChanged(const QModelIndex &current, const QMod
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
currentCard = current.row() >= 0 ? databaseModel->getCard(realIndex.row()) : 0; currentCard = current.row() >= 0 ? databaseModel->getCard(realIndex.row()) : 0;
if(currentCard) if (currentCard) {
{
nameEdit->setText(currentCard->getName()); nameEdit->setText(currentCard->getName());
const QChar cardColor = currentCard->getColorChar(); const QChar cardColor = currentCard->getColorChar();
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
@ -142,13 +141,14 @@ void DlgEditTokens::actAddToken()
if (name.isEmpty()) if (name.isEmpty())
return; return;
if (databaseModel->getDatabase()->getCard(name)) { 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 { } else {
askAgain = false; askAgain = false;
} }
} while (askAgain); } while (askAgain);
CardInfo *card = new CardInfo(name, true); CardInfo *card = new CardInfo(name, true);
card->addToSet(databaseModel->getDatabase()->getSet(CardDatabase::TOKENS_SETNAME)); card->addToSet(databaseModel->getDatabase()->getSet(CardDatabase::TOKENS_SETNAME));
card->setCardType("Token"); card->setCardType("Token");

View file

@ -12,7 +12,8 @@ class QLineEdit;
class QTreeView; class QTreeView;
class CardInfo; class CardInfo;
class DlgEditTokens : public QDialog { class DlgEditTokens : public QDialog
{
Q_OBJECT Q_OBJECT
private slots: private slots:
void tokenSelectionChanged(const QModelIndex &current, const QModelIndex &previous); void tokenSelectionChanged(const QModelIndex &current, const QModelIndex &previous);
@ -22,6 +23,7 @@ private slots:
void actAddToken(); void actAddToken();
void actRemoveToken(); void actRemoveToken();
private: private:
CardInfo *currentCard; CardInfo *currentCard;
CardDatabaseModel *databaseModel; CardDatabaseModel *databaseModel;
@ -31,6 +33,7 @@ private:
QComboBox *colorEdit; QComboBox *colorEdit;
QLineEdit *nameEdit, *ptEdit, *annotationEdit; QLineEdit *nameEdit, *ptEdit, *annotationEdit;
QTreeView *chooseTokenView; QTreeView *chooseTokenView;
public: public:
DlgEditTokens(QWidget *parent = 0); DlgEditTokens(QWidget *parent = 0);
}; };

View file

@ -1,14 +1,13 @@
#include <QLabel> #include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout> #include <QGridLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QDialogButtonBox> #include <QLabel>
#include <QDebug>
#include "dlg_edit_user.h" #include "dlg_edit_user.h"
#include "settingscache.h" #include "settingscache.h"
DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QString realName) DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QString realName) : QDialog(parent)
: QDialog(parent)
{ {
emailLabel = new QLabel(tr("Email:")); emailLabel = new QLabel(tr("Email:"));
emailEdit = new QLineEdit(); emailEdit = new QLineEdit();
@ -23,8 +22,7 @@ DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QStrin
QStringList countries = settingsCache->getCountries(); QStringList countries = settingsCache->getCountries();
int i = 1; int i = 1;
foreach(QString c, countries) foreach (QString c, countries) {
{
countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c); countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c);
if (c == country) if (c == country)
countryEdit->setCurrentIndex(i); countryEdit->setCurrentIndex(i);

View file

@ -1,25 +1,42 @@
#ifndef DLG_EDITUSER_H #ifndef DLG_EDITUSER_H
#define DLG_EDITUSER_H #define DLG_EDITUSER_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgEditUser : public QDialog { class DlgEditUser : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgEditUser(QWidget *parent = 0, QString email = QString(), QString country = QString(), QString realName = QString()); DlgEditUser(QWidget *parent = 0,
QString getEmail() const { return emailEdit->text(); } QString email = QString(),
int getGender() const { return -1; } //This will return GenderUnknown for protocol purposes. QString country = QString(),
QString getCountry() const { return countryEdit->currentIndex() == 0 ? "" : countryEdit->currentText(); } QString realName = QString());
QString getRealName() const { return realnameEdit->text(); } 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: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
private: private:
QLabel *emailLabel, *countryLabel, *realnameLabel; QLabel *emailLabel, *countryLabel, *realnameLabel;
QLineEdit *emailEdit, *realnameEdit; QLineEdit *emailEdit, *realnameEdit;

View file

@ -1,20 +1,20 @@
#include "dlg_filter_games.h" #include "dlg_filter_games.h"
#include <QCheckBox> #include <QCheckBox>
#include <QPushButton> #include <QCryptographicHash>
#include <QLabel> #include <QDialogButtonBox>
#include <QSpinBox> #include <QGridLayout>
#include <QLineEdit>
#include <QGroupBox> #include <QGroupBox>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QGridLayout>
#include <QDialogButtonBox>
#include <QCryptographicHash>
DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_allGameTypes, const GamesProxyModel *_gamesProxyModel, QWidget *parent) DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_allGameTypes,
: QDialog(parent), const GamesProxyModel *_gamesProxyModel,
allGameTypes(_allGameTypes), QWidget *parent)
gamesProxyModel(_gamesProxyModel) : QDialog(parent), allGameTypes(_allGameTypes), gamesProxyModel(_gamesProxyModel)
{ {
showBuddiesOnlyGames = new QCheckBox(tr("Show '&buddies only' games")); showBuddiesOnlyGames = new QCheckBox(tr("Show '&buddies only' games"));
showBuddiesOnlyGames->setChecked(gamesProxyModel->getShowBuddiesOnlyGames()); showBuddiesOnlyGames->setChecked(gamesProxyModel->getShowBuddiesOnlyGames());
@ -84,7 +84,6 @@ DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_allGameTypes, const Ga
QGroupBox *restrictionsGroupBox = new QGroupBox(tr("Restrictions")); QGroupBox *restrictionsGroupBox = new QGroupBox(tr("Restrictions"));
restrictionsGroupBox->setLayout(restrictionsLayout); restrictionsGroupBox->setLayout(restrictionsLayout);
QGridLayout *leftGrid = new QGridLayout; QGridLayout *leftGrid = new QGridLayout;
leftGrid->addWidget(gameNameFilterLabel, 0, 0); leftGrid->addWidget(gameNameFilterLabel, 0, 0);
leftGrid->addWidget(gameNameFilterEdit, 0, 1); leftGrid->addWidget(gameNameFilterEdit, 0, 1);
@ -93,7 +92,6 @@ DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_allGameTypes, const Ga
leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2); leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2);
leftGrid->addWidget(restrictionsGroupBox, 3, 0, 1, 2); leftGrid->addWidget(restrictionsGroupBox, 3, 0, 1, 2);
QVBoxLayout *leftColumn = new QVBoxLayout; QVBoxLayout *leftColumn = new QVBoxLayout;
leftColumn->addLayout(leftGrid); leftColumn->addLayout(leftGrid);
leftColumn->addStretch(); leftColumn->addStretch();
@ -117,7 +115,8 @@ DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_allGameTypes, const Ga
setWindowTitle(tr("Filter games")); setWindowTitle(tr("Filter games"));
} }
void DlgFilterGames::actOk() { void DlgFilterGames::actOk()
{
accept(); accept();
} }
@ -205,5 +204,6 @@ int DlgFilterGames::getMaxPlayersFilterMax() const
void DlgFilterGames::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax) void DlgFilterGames::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax)
{ {
maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin); maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin);
maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax); maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum()
: _maxPlayersFilterMax);
} }

View file

@ -1,17 +1,18 @@
#ifndef DLG_FILTER_GAMES_H #ifndef DLG_FILTER_GAMES_H
#define DLG_FILTER_GAMES_H #define DLG_FILTER_GAMES_H
#include <QDialog>
#include <QSet>
#include <QMap>
#include <QCheckBox>
#include "gamesmodel.h" #include "gamesmodel.h"
#include <QCheckBox>
#include <QDialog>
#include <QMap>
#include <QSet>
class QCheckBox; class QCheckBox;
class QLineEdit; class QLineEdit;
class QSpinBox; class QSpinBox;
class DlgFilterGames : public QDialog { class DlgFilterGames : public QDialog
{
Q_OBJECT Q_OBJECT
private: private:
QCheckBox *showBuddiesOnlyGames; QCheckBox *showBuddiesOnlyGames;
@ -28,8 +29,11 @@ private:
private slots: private slots:
void actOk(); void actOk();
public: public:
DlgFilterGames(const QMap<int, QString> &_allGameTypes, const GamesProxyModel *_gamesProxyModel, QWidget *parent = 0); DlgFilterGames(const QMap<int, QString> &_allGameTypes,
const GamesProxyModel *_gamesProxyModel,
QWidget *parent = 0);
bool getUnavailableGamesVisible() const; bool getUnavailableGamesVisible() const;
void setUnavailableGamesVisible(bool _unavailableGamesVisible); void setUnavailableGamesVisible(bool _unavailableGamesVisible);

View file

@ -1,32 +1,36 @@
#include <QLabel>
#include <QCheckBox> #include <QCheckBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout> #include <QGridLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QDialogButtonBox> #include <QLabel>
#include <QMessageBox> #include <QMessageBox>
#include <QDebug>
#include "dlg_forgotpasswordchallenge.h" #include "dlg_forgotpasswordchallenge.h"
#include "settingscache.h" #include "settingscache.h"
DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
QString lastfphost; QString lastfpport; QString lastfpplayername; QString lastfphost;
QString lastfpport;
QString lastfpplayername;
lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com"); lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com");
lastfpport = settingsCache->servers().getPort("4747"); lastfpport = settingsCache->servers().getPort("4747");
lastfpplayername = settingsCache->servers().getPlayerName("Player"); 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(); lastfphost = settingsCache->servers().getFPHostname();
lastfpport = settingsCache->servers().getFPPort(); lastfpport = settingsCache->servers().getFPPort();
lastfpplayername = settingsCache->servers().getFPPlayerName(); lastfpplayername = settingsCache->servers().getFPPlayerName();
} }
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()) {
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.")); 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(); actCancel();
} }
@ -46,7 +50,8 @@ DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent)
emailEdit = new QLineEdit(); emailEdit = new QLineEdit();
emailLabel->setBuddy(emailLabel); 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(); hostLabel->hide();
hostEdit->hide(); hostEdit->hide();
portLabel->hide(); portLabel->hide();
@ -81,8 +86,7 @@ DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent)
void DlgForgotPasswordChallenge::actOk() 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.")); QMessageBox::critical(this, tr("Forgot Password Challenge Warning"), tr("The email address can't be empty."));
return; return;
} }

View file

@ -1,25 +1,39 @@
#ifndef DLG_FORGOTPASSWORDCHALLENGE_H #ifndef DLG_FORGOTPASSWORDCHALLENGE_H
#define DLG_FORGOTPASSWORDCHALLENGE_H #define DLG_FORGOTPASSWORDCHALLENGE_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgForgotPasswordChallenge : public QDialog { class DlgForgotPasswordChallenge : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgForgotPasswordChallenge(QWidget *parent = 0); DlgForgotPasswordChallenge(QWidget *parent = 0);
QString getHost() const { return hostEdit->text(); } QString getHost() const
int getPort() const { return portEdit->text().toInt(); } {
QString getPlayerName() const { return playernameEdit->text(); } return hostEdit->text();
QString getEmail() const { return emailEdit->text(); } }
int getPort() const
{
return portEdit->text().toInt();
}
QString getPlayerName() const
{
return playernameEdit->text();
}
QString getEmail() const
{
return emailEdit->text();
}
private slots: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
private: private:
QLabel *hostLabel, *portLabel, *playernameLabel, *emailLabel; QLabel *hostLabel, *portLabel, *playernameLabel, *emailLabel;
QLineEdit *hostEdit, *portEdit, *playernameEdit, *emailEdit; QLineEdit *hostEdit, *portEdit, *playernameEdit, *emailEdit;

View file

@ -1,24 +1,26 @@
#include <QLabel>
#include <QCheckBox> #include <QCheckBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout> #include <QGridLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QDialogButtonBox> #include <QLabel>
#include <QMessageBox> #include <QMessageBox>
#include <QDebug>
#include "dlg_forgotpasswordrequest.h" #include "dlg_forgotpasswordrequest.h"
#include "settingscache.h" #include "settingscache.h"
DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent) DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
QString lastfphost; QString lastfpport; QString lastfpplayername; QString lastfphost;
QString lastfpport;
QString lastfpplayername;
lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com"); lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com");
lastfpport = settingsCache->servers().getPort("4747"); lastfpport = settingsCache->servers().getPort("4747");
lastfpplayername = settingsCache->servers().getPlayerName("Player"); 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(); lastfphost = settingsCache->servers().getFPHostname();
lastfpport = settingsCache->servers().getFPPort(); lastfpport = settingsCache->servers().getFPPort();
lastfpplayername = settingsCache->servers().getFPPlayerName(); lastfpplayername = settingsCache->servers().getFPPlayerName();
@ -60,8 +62,7 @@ DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent)
void DlgForgotPasswordRequest::actOk() 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.")); QMessageBox::critical(this, tr("Forgot Password Request Warning"), tr("The player name can't be empty."));
return; return;
} }

View file

@ -1,24 +1,35 @@
#ifndef DLG_FORGOTPASSWORDREQUEST_H #ifndef DLG_FORGOTPASSWORDREQUEST_H
#define DLG_FORGOTPASSWORDREQUEST_H #define DLG_FORGOTPASSWORDREQUEST_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgForgotPasswordRequest : public QDialog { class DlgForgotPasswordRequest : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgForgotPasswordRequest(QWidget *parent = 0); DlgForgotPasswordRequest(QWidget *parent = 0);
QString getHost() const { return hostEdit->text(); } QString getHost() const
int getPort() const { return portEdit->text().toInt(); } {
QString getPlayerName() const { return playernameEdit->text(); } return hostEdit->text();
}
int getPort() const
{
return portEdit->text().toInt();
}
QString getPlayerName() const
{
return playernameEdit->text();
}
private slots: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
private: private:
QLabel *hostLabel, *portLabel, *playernameLabel; QLabel *hostLabel, *portLabel, *playernameLabel;
QLineEdit *hostEdit, *portEdit, *playernameEdit; QLineEdit *hostEdit, *portEdit, *playernameEdit;

View file

@ -1,32 +1,36 @@
#include <QLabel>
#include <QCheckBox> #include <QCheckBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout> #include <QGridLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QDialogButtonBox> #include <QLabel>
#include <QMessageBox> #include <QMessageBox>
#include <QDebug>
#include "dlg_forgotpasswordreset.h" #include "dlg_forgotpasswordreset.h"
#include "settingscache.h" #include "settingscache.h"
DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
QString lastfphost; QString lastfpport; QString lastfpplayername; QString lastfphost;
QString lastfpport;
QString lastfpplayername;
lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com"); lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com");
lastfpport = settingsCache->servers().getPort("4747"); lastfpport = settingsCache->servers().getPort("4747");
lastfpplayername = settingsCache->servers().getPlayerName("Player"); 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(); lastfphost = settingsCache->servers().getFPHostname();
lastfpport = settingsCache->servers().getFPPort(); lastfpport = settingsCache->servers().getFPPort();
lastfpplayername = settingsCache->servers().getFPPlayerName(); lastfpplayername = settingsCache->servers().getFPPlayerName();
} }
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()) {
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.")); 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(); actCancel();
} }
@ -56,7 +60,8 @@ DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent)
newpasswordverifyLabel->setBuddy(newpasswordEdit); newpasswordverifyLabel->setBuddy(newpasswordEdit);
newpasswordverifyEdit->setEchoMode(QLineEdit::Password); 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(); hostLabel->hide();
hostEdit->hide(); hostEdit->hide();
portLabel->hide(); portLabel->hide();
@ -95,26 +100,22 @@ DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent)
void DlgForgotPasswordReset::actOk() 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.")); QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The player name can't be empty."));
return; return;
} }
if (tokenEdit->text().isEmpty()) if (tokenEdit->text().isEmpty()) {
{
QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The token can't be empty.")); QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The token can't be empty."));
return; 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.")); QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The new password can't be empty."));
return; 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.")); QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The passwords do not match."));
return; return;
} }

View file

@ -1,26 +1,43 @@
#ifndef DLG_FORGOTPASSWORDRESET_H #ifndef DLG_FORGOTPASSWORDRESET_H
#define DLG_FORGOTPASSWORDRESET_H #define DLG_FORGOTPASSWORDRESET_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgForgotPasswordReset : public QDialog { class DlgForgotPasswordReset : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgForgotPasswordReset(QWidget *parent = 0); DlgForgotPasswordReset(QWidget *parent = 0);
QString getHost() const { return hostEdit->text(); } QString getHost() const
int getPort() const { return portEdit->text().toInt(); } {
QString getPlayerName() const { return playernameEdit->text(); } return hostEdit->text();
QString getToken() const { return tokenEdit->text(); } }
QString getPassword() const { return newpasswordEdit->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: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
private: private:
QLabel *hostLabel, *portLabel, *playernameLabel, *tokenLabel, *newpasswordLabel, *newpasswordverifyLabel; QLabel *hostLabel, *portLabel, *playernameLabel, *tokenLabel, *newpasswordLabel, *newpasswordverifyLabel;
QLineEdit *hostEdit, *portEdit, *playernameEdit, *tokenEdit, *newpasswordEdit, *newpasswordverifyEdit; QLineEdit *hostEdit, *portEdit, *playernameEdit, *tokenEdit, *newpasswordEdit, *newpasswordverifyEdit;

View file

@ -1,14 +1,14 @@
#include <QClipboard>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QApplication>
#include <QTextStream>
#include <QDialogButtonBox>
#include <QMessageBox>
#include "dlg_load_deck_from_clipboard.h" #include "dlg_load_deck_from_clipboard.h"
#include "deck_loader.h" #include "deck_loader.h"
#include "settingscache.h" #include "settingscache.h"
#include <QApplication>
#include <QClipboard>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QTextStream>
#include <QVBoxLayout>
DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) : QDialog(parent), deckList(nullptr) DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) : QDialog(parent), deckList(nullptr)
{ {
@ -52,26 +52,18 @@ void DlgLoadDeckFromClipboard::actOK()
QTextStream stream(&buffer); QTextStream stream(&buffer);
auto *deckLoader = new DeckLoader; auto *deckLoader = new DeckLoader;
if (buffer.contains("<cockatrice_deck version=\"1\">")) if (buffer.contains("<cockatrice_deck version=\"1\">")) {
{ if (deckLoader->loadFromString_Native(buffer)) {
if (deckLoader->loadFromString_Native(buffer))
{
deckList = deckLoader; deckList = deckLoader;
accept(); accept();
} else {
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list."));
delete deckLoader;
} }
else } else if (deckLoader->loadFromStream_Plain(stream)) {
{ deckList = deckLoader;
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); accept();
delete deckLoader; } else {
}
}
else if (deckLoader->loadFromStream_Plain(stream))
{
deckList = deckLoader;
accept();
}
else
{
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); QMessageBox::critical(this, tr("Error"), tr("Invalid deck list."));
delete deckLoader; delete deckLoader;
} }

View file

@ -22,7 +22,10 @@ class DlgLoadDeckFromClipboard : public QDialog
public: public:
explicit DlgLoadDeckFromClipboard(QWidget *parent = nullptr); explicit DlgLoadDeckFromClipboard(QWidget *parent = nullptr);
DeckLoader *getDeckList() const { return deckList; } DeckLoader *getDeckList() const
{
return deckList;
}
}; };
#endif #endif

View file

@ -1,13 +1,12 @@
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDialogButtonBox>
#include "remotedecklist_treewidget.h"
#include "dlg_load_remote_deck.h" #include "dlg_load_remote_deck.h"
#include "main.h" #include "main.h"
#include "remotedecklist_treewidget.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QPushButton>
#include <QVBoxLayout>
DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) : QDialog(parent), client(_client)
: QDialog(parent), client(_client)
{ {
dirView = new RemoteDeckList_TreeWidget(client); dirView = new RemoteDeckList_TreeWidget(client);
@ -26,15 +25,19 @@ DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent)
setMinimumWidth(sizeHint().width()); setMinimumWidth(sizeHint().width());
resize(400, 600); 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 &current, const QModelIndex & /*previous*/) void DlgLoadRemoteDeck::currentItemChanged(const QModelIndex &current, const QModelIndex & /*previous*/)
{ {
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(dynamic_cast<RemoteDeckList_TreeModel::FileNode *>(dirView->getNode(current))); buttonBox->button(QDialogButtonBox::Ok)
->setEnabled(dynamic_cast<RemoteDeckList_TreeModel::FileNode *>(dirView->getNode(current)));
} }
int DlgLoadRemoteDeck::getDeckId() const int DlgLoadRemoteDeck::getDeckId() const
{ {
return dynamic_cast<RemoteDeckList_TreeModel::FileNode *>(dirView->getNode(dirView->selectionModel()->currentIndex()))->getId(); return dynamic_cast<RemoteDeckList_TreeModel::FileNode *>(
dirView->getNode(dirView->selectionModel()->currentIndex()))
->getId();
} }

View file

@ -9,7 +9,8 @@ class AbstractClient;
class QPushButton; class QPushButton;
class QDialogButtonBox; class QDialogButtonBox;
class DlgLoadRemoteDeck: public QDialog { class DlgLoadRemoteDeck : public QDialog
{
Q_OBJECT Q_OBJECT
private: private:
AbstractClient *client; AbstractClient *client;
@ -17,6 +18,7 @@ private:
QDialogButtonBox *buttonBox; QDialogButtonBox *buttonBox;
private slots: private slots:
void currentItemChanged(const QModelIndex &current, const QModelIndex &previous); void currentItemChanged(const QModelIndex &current, const QModelIndex &previous);
public: public:
DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0); DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0);
int getDeckId() const; int getDeckId() const;

View file

@ -1,17 +1,16 @@
#include <QLabel>
#include <QCheckBox> #include <QCheckBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout> #include <QGridLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QDialogButtonBox> #include <QLabel>
#include <QMessageBox> #include <QMessageBox>
#include <QDebug>
#include "dlg_register.h" #include "dlg_register.h"
#include "settingscache.h"
#include "pb/serverinfo_user.pb.h" #include "pb/serverinfo_user.pb.h"
#include "settingscache.h"
DlgRegister::DlgRegister(QWidget *parent) DlgRegister::DlgRegister(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
hostLabel = new QLabel(tr("&Host:")); hostLabel = new QLabel(tr("&Host:"));
hostEdit = new QLineEdit(settingsCache->servers().getHostname("cockatrice.woogerworks.com")); hostEdit = new QLineEdit(settingsCache->servers().getHostname("cockatrice.woogerworks.com"));
@ -341,18 +340,15 @@ DlgRegister::DlgRegister(QWidget *parent)
void DlgRegister::actOk() void DlgRegister::actOk()
{ {
if (passwordEdit->text() != passwordConfirmationEdit->text()) if (passwordEdit->text() != passwordConfirmationEdit->text()) {
{
QMessageBox::critical(this, tr("Registration Warning"), tr("Your passwords do not match, please try again.")); QMessageBox::critical(this, tr("Registration Warning"), tr("Your passwords do not match, please try again."));
return; return;
} } else if (emailConfirmationEdit->text() != emailEdit->text()) {
else if (emailConfirmationEdit->text() != emailEdit->text()) QMessageBox::critical(this, tr("Registration Warning"),
{ tr("Your email addresses do not match, please try again."));
QMessageBox::critical(this, tr("Registration Warning"), tr("Your email addresses do not match, please try again."));
return; return;
} }
if(playernameEdit->text().isEmpty()) if (playernameEdit->text().isEmpty()) {
{
QMessageBox::critical(this, tr("Registration Warning"), tr("The player name can't be empty.")); QMessageBox::critical(this, tr("Registration Warning"), tr("The player name can't be empty."));
return; return;
} }

View file

@ -1,32 +1,60 @@
#ifndef DLG_REGISTER_H #ifndef DLG_REGISTER_H
#define DLG_REGISTER_H #define DLG_REGISTER_H
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QLineEdit> #include <QLineEdit>
#include <QComboBox>
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class QCheckBox; class QCheckBox;
class DlgRegister : public QDialog { class DlgRegister : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgRegister(QWidget *parent = 0); DlgRegister(QWidget *parent = 0);
QString getHost() const { return hostEdit->text(); } QString getHost() const
int getPort() const { return portEdit->text().toInt(); } {
QString getPlayerName() const { return playernameEdit->text(); } return hostEdit->text();
QString getPassword() const { return passwordEdit->text(); } }
QString getEmail() const { return emailEdit->text(); } int getPort() const
int getGender() const { return -1; } //This will return GenderUnknown for the protocol. {
QString getCountry() const { return countryEdit->currentIndex() == 0 ? "" : countryEdit->currentText(); } return portEdit->text().toInt();
QString getRealName() const { return realnameEdit->text(); } }
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: private slots:
void actOk(); void actOk();
void actCancel(); void actCancel();
private: private:
QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *passwordConfirmationLabel, *emailLabel, *emailConfirmationLabel, *countryLabel, *realnameLabel; QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *passwordConfirmationLabel, *emailLabel,
QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *passwordConfirmationEdit, *emailEdit, *emailConfirmationEdit, *realnameEdit; *emailConfirmationLabel, *countryLabel, *realnameLabel;
QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *passwordConfirmationEdit, *emailEdit,
*emailConfirmationEdit, *realnameEdit;
QComboBox *countryEdit; QComboBox *countryEdit;
}; };

View file

@ -1,36 +1,35 @@
#include <QLabel> #include "dlg_settings.h"
#include <QLineEdit> #include "carddatabase.h"
#include <QComboBox> #include "main.h"
#include <QCheckBox> #include "releasechannel.h"
#include <QGroupBox> #include "sequenceEdit/shortcutstab.h"
#include <QPushButton> #include "settingscache.h"
#include <QGridLayout> #include "soundengine.h"
#include <QListWidget> #include "spoilerbackgroundupdater.h"
#include <QStackedWidget> #include "thememanager.h"
#include <QCloseEvent>
#include <QMessageBox>
#include <QFileDialog>
#include <QToolBar>
#include <QTranslator>
#include <QAction> #include <QAction>
#include <QApplication> #include <QApplication>
#include <QInputDialog> #include <QCheckBox>
#include <QSpinBox> #include <QCloseEvent>
#include <QDialogButtonBox> #include <QComboBox>
#include <QRadioButton>
#include <QDebug> #include <QDebug>
#include <QDesktopWidget>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QGridLayout>
#include <QGroupBox>
#include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QMessageBox>
#include <QPushButton>
#include <QRadioButton>
#include <QSlider> #include <QSlider>
#include <QSpinBox> #include <QSpinBox>
#include <QDesktopWidget> #include <QStackedWidget>
#include "carddatabase.h" #include <QToolBar>
#include "dlg_settings.h" #include <QTranslator>
#include "main.h"
#include "settingscache.h"
#include "thememanager.h"
#include "releasechannel.h"
#include "soundengine.h"
#include "sequenceEdit/shortcutstab.h"
#include "spoilerbackgroundupdater.h"
#define WIKI_CUSTOM_PIC_URL "https://github.com/Cockatrice/Cockatrice/wiki/Custom-Picture-Download-URLs" #define WIKI_CUSTOM_PIC_URL "https://github.com/Cockatrice/Cockatrice/wiki/Custom-Picture-Download-URLs"
@ -41,7 +40,8 @@ GeneralSettingsPage::GeneralSettingsPage()
for (int i = 0; i < qmFiles.size(); i++) { for (int i = 0; i < qmFiles.size(); i++) {
QString langName = languageName(qmFiles[i]); QString langName = languageName(qmFiles[i]);
languageBox.addItem(langName, 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); languageBox.setCurrentIndex(i);
} }
@ -49,8 +49,7 @@ GeneralSettingsPage::GeneralSettingsPage()
// updates // updates
QList<ReleaseChannel *> channels = settingsCache->getUpdateReleaseChannels(); QList<ReleaseChannel *> channels = settingsCache->getUpdateReleaseChannels();
foreach(ReleaseChannel* chan, channels) foreach (ReleaseChannel *chan, channels) {
{
updateReleaseChannelBox.insertItem(chan->getIndex(), tr(chan->getName().toUtf8())); updateReleaseChannelBox.insertItem(chan->getIndex(), tr(chan->getName().toUtf8()));
} }
updateReleaseChannelBox.setCurrentIndex(settingsCache->getUpdateReleaseChannel()->getIndex()); updateReleaseChannelBox.setCurrentIndex(settingsCache->getUpdateReleaseChannel()->getIndex());
@ -72,7 +71,8 @@ GeneralSettingsPage::GeneralSettingsPage()
connect(&languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int))); connect(&languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int)));
connect(&picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int))); connect(&picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int)));
connect(&pixmapCacheEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setPixmapCacheSize(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(&updateNotificationCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotifyAboutUpdate(int)));
connect(&picDownloadCheckBox, SIGNAL(clicked(bool)), this, SLOT(setEnabledStatus(bool))); connect(&picDownloadCheckBox, SIGNAL(clicked(bool)), this, SLOT(setEnabledStatus(bool)));
connect(defaultUrlEdit, SIGNAL(textChanged(QString)), settingsCache, SLOT(setPicUrl(QString))); connect(defaultUrlEdit, SIGNAL(textChanged(QString)), settingsCache, SLOT(setPicUrl(QString)));
@ -131,8 +131,7 @@ GeneralSettingsPage::GeneralSettingsPage()
QPushButton *tokenDatabasePathButton = new QPushButton("..."); QPushButton *tokenDatabasePathButton = new QPushButton("...");
connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked())); connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked()));
if (settingsCache->getIsPortableBuild()) if (settingsCache->getIsPortableBuild()) {
{
deckPathEdit->setEnabled(false); deckPathEdit->setEnabled(false);
replaysPathEdit->setEnabled(false); replaysPathEdit->setEnabled(false);
picsPathEdit->setEnabled(false); picsPathEdit->setEnabled(false);
@ -290,8 +289,7 @@ void GeneralSettingsPage::retranslateUi()
languageLabel.setText(tr("Language:")); languageLabel.setText(tr("Language:"));
picDownloadCheckBox.setText(tr("Download card pictures on the fly")); picDownloadCheckBox.setText(tr("Download card pictures on the fly"));
if(settingsCache->getIsPortableBuild()) if (settingsCache->getIsPortableBuild()) {
{
pathsGroupBox->setTitle(tr("Paths (editing disabled in portable mode)")); pathsGroupBox->setTitle(tr("Paths (editing disabled in portable mode)"));
} else { } else {
pathsGroupBox->setTitle(tr("Paths")); pathsGroupBox->setTitle(tr("Paths"));
@ -305,7 +303,8 @@ void GeneralSettingsPage::retranslateUi()
pixmapCacheLabel.setText(tr("Picture cache size:")); pixmapCacheLabel.setText(tr("Picture cache size:"));
defaultUrlLabel.setText(tr("Primary download URL:")); defaultUrlLabel.setText(tr("Primary download URL:"));
fallbackUrlLabel.setText(tr("Fallback download URL:")); fallbackUrlLabel.setText(tr("Fallback download URL:"));
urlLinkLabel.setText(QString("<a href='%1'>%2</a>").arg(WIKI_CUSTOM_PIC_URL).arg(tr("How to set a custom picture url"))); urlLinkLabel.setText(
QString("<a href='%1'>%2</a>").arg(WIKI_CUSTOM_PIC_URL).arg(tr("How to set a custom picture url")));
clearDownloadedPicsButton.setText(tr("Reset/clear downloaded pictures")); clearDownloadedPicsButton.setText(tr("Reset/clear downloaded pictures"));
updateReleaseChannelLabel.setText(tr("Update channel")); updateReleaseChannelLabel.setText(tr("Update channel"));
updateNotificationCheckBox.setText(tr("Notify if a feature supported by the server is missing in my client")); 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); handGroupBox->setLayout(handGrid);
invertVerticalCoordinateCheckBox.setChecked(settingsCache->getInvertVerticalCoordinate()); 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.setMinimum(2);
minPlayersForMultiColumnLayoutEdit.setValue(settingsCache->getMinPlayersForMultiColumnLayout()); 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); minPlayersForMultiColumnLayoutLabel.setBuddy(&minPlayersForMultiColumnLayoutEdit);
connect(&maxFontSizeForCardsEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMaxFontSize(int))); connect(&maxFontSizeForCardsEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMaxFontSize(int)));
@ -429,12 +430,14 @@ void AppearanceSettingsPage::retranslateUi()
UserInterfaceSettingsPage::UserInterfaceSettingsPage() UserInterfaceSettingsPage::UserInterfaceSettingsPage()
{ {
notificationsEnabledCheckBox.setChecked(settingsCache->getNotificationsEnabled()); notificationsEnabledCheckBox.setChecked(settingsCache->getNotificationsEnabled());
connect(&notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotificationsEnabled(int))); connect(&notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache,
SLOT(setNotificationsEnabled(int)));
connect(&notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setSpecNotificationEnabled(int))); connect(&notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setSpecNotificationEnabled(int)));
specNotificationsEnabledCheckBox.setChecked(settingsCache->getSpectatorNotificationsEnabled()); specNotificationsEnabledCheckBox.setChecked(settingsCache->getSpectatorNotificationsEnabled());
specNotificationsEnabledCheckBox.setEnabled(settingsCache->getNotificationsEnabled()); 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()); doubleClickToPlayCheckBox.setChecked(settingsCache->getDoubleClickToPlay());
connect(&doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int))); connect(&doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int)));
@ -471,7 +474,8 @@ UserInterfaceSettingsPage::UserInterfaceSettingsPage()
setLayout(mainLayout); setLayout(mainLayout);
} }
void UserInterfaceSettingsPage::setSpecNotificationEnabled(int i) { void UserInterfaceSettingsPage::setSpecNotificationEnabled(int i)
{
specNotificationsEnabledCheckBox.setEnabled(i != 0); specNotificationsEnabledCheckBox.setEnabled(i != 0);
} }
@ -557,8 +561,7 @@ QString DeckEditorSettingsPage::getLastUpdateTime()
QDir fileDir(fi.path()); QDir fileDir(fi.path());
QFile file(fileName); QFile file(fileName);
if (file.exists()) if (file.exists()) {
{
return fi.lastModified().toString("MMM d, hh:mm"); return fi.lastModified().toString("MMM d, hh:mm");
} }
@ -568,8 +571,7 @@ QString DeckEditorSettingsPage::getLastUpdateTime()
void DeckEditorSettingsPage::spoilerPathButtonClicked() void DeckEditorSettingsPage::spoilerPathButtonClicked()
{ {
QString lsPath = QFileDialog::getExistingDirectory(this, tr("Choose path")); QString lsPath = QFileDialog::getExistingDirectory(this, tr("Choose path"));
if (lsPath.isEmpty()) if (lsPath.isEmpty()) {
{
return; return;
} }
@ -586,8 +588,7 @@ void DeckEditorSettingsPage::setSpoilersEnabled(bool anInput)
updateNowButton->setEnabled(anInput); updateNowButton->setEnabled(anInput);
infoOnSpoilersLabel.setEnabled(anInput); infoOnSpoilersLabel.setEnabled(anInput);
if (! anInput) if (!anInput) {
{
SpoilerBackgroundUpdater::deleteSpoilerFile(); SpoilerBackgroundUpdater::deleteSpoilerFile();
} }
} }
@ -598,12 +599,10 @@ void DeckEditorSettingsPage::retranslateUi()
mcDownloadSpoilersCheckBox.setText(tr("Download Spoilers Automatically")); mcDownloadSpoilersCheckBox.setText(tr("Download Spoilers Automatically"));
mcSpoilerSaveLabel.setText(tr("Spoiler Location:")); mcSpoilerSaveLabel.setText(tr("Spoiler Location:"));
mcGeneralMessageLabel.setText(tr("Hey, something's here finally!")); mcGeneralMessageLabel.setText(tr("Hey, something's here finally!"));
infoOnSpoilersLabel.setText( infoOnSpoilersLabel.setText(tr("Last Updated") + ": " + getLastUpdateTime() + "\n\n" +
tr("Last Updated") + ": " + getLastUpdateTime() + "\n\n" +
tr("Spoilers download automatically on launch") + "\n" + tr("Spoilers download automatically on launch") + "\n" +
tr("Press the button to manually update without relaunching") + "\n\n" + tr("Press the button to manually update without relaunching") + "\n\n" +
tr("Do not close settings until manual update complete") tr("Do not close settings until manual update complete"));
);
} }
MessagesSettingsPage::MessagesSettingsPage() MessagesSettingsPage::MessagesSettingsPage()
@ -612,12 +611,14 @@ MessagesSettingsPage::MessagesSettingsPage()
connect(&chatMentionCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setChatMention(int))); connect(&chatMentionCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setChatMention(int)));
chatMentionCompleterCheckbox.setChecked(settingsCache->getChatMentionCompleter()); 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()); ignoreUnregUsersMainChat.setChecked(settingsCache->getIgnoreUnregisteredUsers());
ignoreUnregUserMessages.setChecked(settingsCache->getIgnoreUnregisteredUserMessages()); ignoreUnregUserMessages.setChecked(settingsCache->getIgnoreUnregisteredUserMessages());
connect(&ignoreUnregUsersMainChat, SIGNAL(stateChanged(int)), settingsCache, SLOT(setIgnoreUnregisteredUsers(int))); 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()); invertMentionForeground.setChecked(settingsCache->getChatMentionForeground());
connect(&invertMentionForeground, SIGNAL(stateChanged(int)), this, SLOT(updateTextColor(int))); connect(&invertMentionForeground, SIGNAL(stateChanged(int)), this, SLOT(updateTextColor(int)));
@ -748,8 +749,8 @@ void MessagesSettingsPage::updateMentionPreview()
void MessagesSettingsPage::updateHighlightPreview() void MessagesSettingsPage::updateHighlightPreview()
{ {
highlightColor->setStyleSheet("QLineEdit{background:#" + settingsCache->getChatHighlightColor() + highlightColor->setStyleSheet("QLineEdit{background:#" + settingsCache->getChatHighlightColor() + ";color: " +
";color: " + (settingsCache->getChatHighlightForeground() ? "white" : "black") + ";}"); (settingsCache->getChatHighlightForeground() ? "white" : "black") + ";}");
} }
void MessagesSettingsPage::storeSettings() void MessagesSettingsPage::storeSettings()
@ -796,7 +797,6 @@ void MessagesSettingsPage::retranslateUi()
customAlertStringLabel.setText(tr("Separate words with a space, alphanumeric characters only")); customAlertStringLabel.setText(tr("Separate words with a space, alphanumeric characters only"));
} }
SoundSettingsPage::SoundSettingsPage() SoundSettingsPage::SoundSettingsPage()
{ {
soundEnabledCheckBox.setChecked(settingsCache->getSoundEnabled()); soundEnabledCheckBox.setChecked(settingsCache->getSoundEnabled());
@ -952,7 +952,8 @@ void DlgSettings::createIcons()
shortcutsButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); shortcutsButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
shortcutsButton->setIcon(QPixmap("theme:config/shorcuts")); 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) void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous)
@ -990,75 +991,69 @@ void DlgSettings::closeEvent(QCloseEvent *event)
QString loadErrorMessage = tr("Unknown Error loading card database"); QString loadErrorMessage = tr("Unknown Error loading card database");
LoadStatus loadStatus = db->getLoadStatus(); LoadStatus loadStatus = db->getLoadStatus();
qDebug() << "Card Database load status: " << loadStatus; qDebug() << "Card Database load status: " << loadStatus;
switch(loadStatus) switch (loadStatus) {
{
case Ok: case Ok:
showLoadError = false; showLoadError = false;
break; break;
case Invalid: case Invalid:
loadErrorMessage = loadErrorMessage = tr("Your card database is invalid.\n\n"
tr("Your card database is invalid.\n\n"
"Cockatrice may not function correctly with an invalid database\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" "You may need to rerun oracle to update your card database.\n\n"
"Would you like to change your database location setting?"); "Would you like to change your database location setting?");
break; break;
case VersionTooOld: case VersionTooOld:
loadErrorMessage = loadErrorMessage = tr("Your card database version is too old.\n\n"
tr("Your card database version is too old.\n\n"
"This can cause problems loading card information or images\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" "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?"); "Would you like to change your database location setting?");
break; break;
case NotLoaded: case NotLoaded:
loadErrorMessage = loadErrorMessage = tr("Your card database did not finish loading\n\n"
tr("Your card database did not finish loading\n\n" "Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues with your "
"Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues with your cards.xml attached\n\n" "cards.xml attached\n\n"
"Would you like to change your database location setting?"); "Would you like to change your database location setting?");
break; break;
case FileError: case FileError:
loadErrorMessage = loadErrorMessage = tr("File Error loading your card database.\n\n"
tr("File Error loading your card database.\n\n"
"Would you like to change your database location setting?"); "Would you like to change your database location setting?");
break; break;
case NoCards: case NoCards:
loadErrorMessage = loadErrorMessage = tr("Your card database was loaded but contains no cards.\n\n"
tr("Your card database was loaded but contains no cards.\n\n"
"Would you like to change your database location setting?"); "Would you like to change your database location setting?");
break; break;
default: default:
loadErrorMessage = loadErrorMessage = tr("Unknown card database load status\n\n"
tr("Unknown card database load status\n\n"
"Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues\n\n" "Please file a ticket at http://github.com/Cockatrice/Cockatrice/issues\n\n"
"Would you like to change your database location setting?"); "Would you like to change your database location setting?");
break; break;
} }
if (showLoadError) if (showLoadError) {
{
if (QMessageBox::critical(this, tr("Error"), loadErrorMessage, QMessageBox::Yes | QMessageBox::No) == if (QMessageBox::critical(this, tr("Error"), loadErrorMessage, QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::Yes) QMessageBox::Yes) {
{
event->ignore(); event->ignore();
return; return;
} }
} }
if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) {
{
// TODO: Prompt to create it // 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(); event->ignore();
return; return;
} }
} }
if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) {
{
// TODO: Prompt to create it // 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(); event->ignore();
return; return;
} }

View file

@ -1,8 +1,8 @@
#ifndef DLG_SETTINGS_H #ifndef DLG_SETTINGS_H
#define DLG_SETTINGS_H #define DLG_SETTINGS_H
#include <QComboBox>
#include <QCheckBox> #include <QCheckBox>
#include <QComboBox>
#include <QDialog> #include <QDialog>
#include <QGroupBox> #include <QGroupBox>
#include <QLabel> #include <QLabel>
@ -239,7 +239,8 @@ class DlgSettings : public QDialog
private: private:
QListWidget *contentsWidget; QListWidget *contentsWidget;
QStackedWidget *pagesWidget; QStackedWidget *pagesWidget;
QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton, *soundButton; QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton,
*soundButton;
QListWidgetItem *shortcutsButton; QListWidgetItem *shortcutsButton;
void createIcons(); void createIcons();
void retranslateUi(); void retranslateUi();

View file

@ -1,13 +1,13 @@
#include <QtNetwork>
#include <QProgressDialog>
#include <QDesktopServices> #include <QDesktopServices>
#include <QMessageBox> #include <QMessageBox>
#include <QProgressDialog>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QtNetwork>
#include <QPushButton> #include <QApplication>
#include <QLabel> #include <QLabel>
#include <QProgressBar> #include <QProgressBar>
#include <QApplication> #include <QPushButton>
#include <version_string.h> #include <version_string.h>
#include "dlg_update.h" #include "dlg_update.h"
@ -15,13 +15,17 @@
#include "settingscache.h" #include "settingscache.h"
#include "window_main.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 = new QLabel(this);
statusLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); statusLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
statusLabel->setWordWrap(true); 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); progress = new QProgressBar(this);
buttonBox = new QDialogButtonBox(this); buttonBox = new QDialogButtonBox(this);
@ -53,7 +57,8 @@ DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) {
if (!QSslSocket::supportsSsl()) { if (!QSslSocket::supportsSsl()) {
enableUpdateButton(false); enableUpdateButton(false);
QMessageBox::critical(this, tr("Error"), 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
@ -63,43 +68,49 @@ DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) {
connect(uDownloader, SIGNAL(error(QString)), this, SLOT(downloadError(QString))); connect(uDownloader, SIGNAL(error(QString)), this, SLOT(downloadError(QString)));
ReleaseChannel *channel = settingsCache->getUpdateReleaseChannel(); ReleaseChannel *channel = settingsCache->getUpdateReleaseChannel();
connect(channel, SIGNAL(finishedCheck(bool, bool, Release *)), this, SLOT(finishedUpdateCheck(bool, bool, Release *))); connect(channel, SIGNAL(finishedCheck(bool, bool, Release *)), this,
SLOT(finishedUpdateCheck(bool, bool, Release *)));
connect(channel, SIGNAL(error(QString)), this, SLOT(updateCheckError(QString))); connect(channel, SIGNAL(error(QString)), this, SLOT(updateCheckError(QString)));
// Check for updates // Check for updates
beginUpdateCheck(); beginUpdateCheck();
} }
void DlgUpdate::closeDialog() { void DlgUpdate::closeDialog()
{
accept(); accept();
} }
void DlgUpdate::gotoDownloadPage()
void DlgUpdate::gotoDownloadPage() { {
QDesktopServices::openUrl(settingsCache->getUpdateReleaseChannel()->getManualDownloadUrl()); QDesktopServices::openUrl(settingsCache->getUpdateReleaseChannel()->getManualDownloadUrl());
} }
void DlgUpdate::downloadUpdate() { void DlgUpdate::downloadUpdate()
{
setLabel(tr("Downloading update...")); setLabel(tr("Downloading update..."));
addStopDownloadAndRemoveOthers(true); // Will remove all other buttons addStopDownloadAndRemoveOthers(true); // Will remove all other buttons
uDownloader->beginDownload(updateUrl); uDownloader->beginDownload(updateUrl);
} }
void DlgUpdate::cancelDownload() { void DlgUpdate::cancelDownload()
{
emit uDownloader->stopDownload(); emit uDownloader->stopDownload();
setLabel("Download canceled"); setLabel("Download canceled");
addStopDownloadAndRemoveOthers(false); addStopDownloadAndRemoveOthers(false);
downloadProgressMade(0, 1); downloadProgressMade(0, 1);
} }
void DlgUpdate::beginUpdateCheck() { void DlgUpdate::beginUpdateCheck()
{
progress->setMinimum(0); progress->setMinimum(0);
progress->setMaximum(0); progress->setMaximum(0);
setLabel(tr("Checking for updates...")); setLabel(tr("Checking for updates..."));
settingsCache->getUpdateReleaseChannel()->checkForUpdates(); settingsCache->getUpdateReleaseChannel()->checkForUpdates();
} }
void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Release *release) { void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Release *release)
{
QString publishDate, versionName; QString publishDate, versionName;
@ -114,11 +125,13 @@ void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Releas
if (!needToUpdate) { if (!needToUpdate) {
// If there's no need to update, tell them that. However we still allow them to run the // 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 // downloader themselves if there's a compatible build
QMessageBox::information(this, tr("No Update Available"), QMessageBox::information(
tr("Cockatrice is up to date!") + "<br><br>" this, tr("No Update Available"),
+ tr("You are already running the latest version available in the chosen release channel.") + "<br>" tr("Cockatrice is up to date!") + "<br><br>" +
+ "<b>" + tr("Current version") + QString(":</b> %1<br>").arg(VERSION_STRING) tr("You are already running the latest version available in the chosen release channel.") + "<br>" +
+ "<b>" + tr("Selected release channel") + QString(":</b> %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8()))); "<b>" + tr("Current version") + QString(":</b> %1<br>").arg(VERSION_STRING) + "<b>" +
tr("Selected release channel") +
QString(":</b> %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8())));
return; return;
} }
@ -128,81 +141,92 @@ void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Releas
updateUrl = release->getDownloadUrl(); updateUrl = release->getDownloadUrl();
int reply; int reply;
reply = QMessageBox::question(this, tr("Update Available"), reply = QMessageBox::question(
tr("A new version of Cockatrice is available!") + "<br><br>" this, tr("Update Available"),
+ "<b>" + tr("New version") + QString(":</b> %1<br>").arg(release->getName()) tr("A new version of Cockatrice is available!") + "<br><br>" + "<b>" + tr("New version") +
+ "<b>" + tr("Released") + QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + ")</a><br><br>" QString(":</b> %1<br>").arg(release->getName()) + "<b>" + tr("Released") +
+ tr("Do you want to update now?"), QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") +
")</a><br><br>" + tr("Do you want to update now?"),
QMessageBox::Yes | QMessageBox::No); QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) if (reply == QMessageBox::Yes)
downloadUpdate(); downloadUpdate();
} else { } else {
QMessageBox::information(this, tr("Update Available"), QMessageBox::information(
tr("A new version of Cockatrice is available!") + "<br><br>" this, tr("Update Available"),
+ "<b>" + tr("New version") + QString(":</b> %1<br>").arg(release->getName()) tr("A new version of Cockatrice is available!") + "<br><br>" + "<b>" + tr("New version") +
+ "<b>" + tr("Released") + QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + ")</a><br><br>" QString(":</b> %1<br>").arg(release->getName()) + "<b>" + tr("Released") +
+ tr("Unfortunately there are no download packages available for your operating system. \nYou may have to build from source yourself.") + "<br><br>" QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") +
+ tr("Please check the download page manually and visit the wiki for instructions on compiling.")); ")</a><br><br>" +
tr("Unfortunately there are no download packages available for your operating system. \nYou may have "
"to build from source yourself.") +
"<br><br>" +
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); manualDownload->setEnabled(enable);
} }
void DlgUpdate::addStopDownloadAndRemoveOthers(bool enable) { void DlgUpdate::addStopDownloadAndRemoveOthers(bool enable)
{
if (enable) { if (enable) {
buttonBox->addButton(stopDownload, QDialogButtonBox::ActionRole); buttonBox->addButton(stopDownload, QDialogButtonBox::ActionRole);
buttonBox->removeButton(manualDownload); buttonBox->removeButton(manualDownload);
buttonBox->removeButton(gotoDownload); buttonBox->removeButton(gotoDownload);
} } else {
else {
buttonBox->removeButton(stopDownload); buttonBox->removeButton(stopDownload);
buttonBox->addButton(manualDownload, QDialogButtonBox::ActionRole); buttonBox->addButton(manualDownload, QDialogButtonBox::ActionRole);
buttonBox->addButton(gotoDownload, QDialogButtonBox::ActionRole); buttonBox->addButton(gotoDownload, QDialogButtonBox::ActionRole);
} }
} }
void DlgUpdate::enableOkButton(bool enable) { void DlgUpdate::enableOkButton(bool enable)
{
ok->setEnabled(enable); ok->setEnabled(enable);
} }
void DlgUpdate::setLabel(QString newText) { void DlgUpdate::setLabel(QString newText)
{
statusLabel->setText(newText); statusLabel->setText(newText);
} }
void DlgUpdate::updateCheckError(QString errorString) { void DlgUpdate::updateCheckError(QString errorString)
{
setLabel(tr("Error")); setLabel(tr("Error"));
QMessageBox::critical(this, tr("Update 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")); setLabel(tr("Error"));
enableUpdateButton(true); enableUpdateButton(true);
QMessageBox::critical(this, tr("Update Error"), 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...")); setLabel(tr("Installing..."));
// Try to open the installer. If it opens, quit Cockatrice // Try to open the installer. If it opens, quit Cockatrice
if (QDesktopServices::openUrl(filepath)) if (QDesktopServices::openUrl(filepath)) {
{
QMetaObject::invokeMethod(static_cast<MainWindow *>(parent()), "close", Qt::QueuedConnection); QMetaObject::invokeMethod(static_cast<MainWindow *>(parent()), "close", Qt::QueuedConnection);
qDebug() << "Opened downloaded update file successfully - closing Cockatrice"; qDebug() << "Opened downloaded update file successfully - closing Cockatrice";
close(); close();
} else { } else {
setLabel(tr("Error")); setLabel(tr("Error"));
QMessageBox::critical(this, tr("Update Error"), QMessageBox::critical(this, tr("Update Error"),
tr("Cockatrice is unable to open the installer.") + "<br><br>" tr("Cockatrice is unable to open the installer.") + "<br><br>" +
+ tr("Try to update manually by closing Cockatrice and running the installer.") + "<br>" tr("Try to update manually by closing Cockatrice and running the installer.") +
+ tr("Download location") + QString(": %1").arg(filepath.toLocalFile())); "<br>" + 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->setMaximum(totalBytes);
progress->setValue(bytesRead); progress->setValue(bytesRead);
} }

View file

@ -1,14 +1,15 @@
#ifndef DLG_UPDATE_H #ifndef DLG_UPDATE_H
#define DLG_UPDATE_H #define DLG_UPDATE_H
#include <QtNetwork>
#include <QProgressDialog>
#include <QDialogButtonBox> #include <QDialogButtonBox>
#include <QProgressDialog>
#include <QtNetwork>
#include "update_downloader.h" #include "update_downloader.h"
class Release; class Release;
class DlgUpdate : public QDialog { class DlgUpdate : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
DlgUpdate(QWidget *parent); DlgUpdate(QWidget *parent);
@ -23,6 +24,7 @@ private slots:
void downloadProgressMade(qint64 bytesRead, qint64 totalBytes); void downloadProgressMade(qint64 bytesRead, qint64 totalBytes);
void downloadError(QString errorString); void downloadError(QString errorString);
void closeDialog(); void closeDialog();
private: private:
QUrl updateUrl; QUrl updateUrl;
void enableUpdateButton(bool enable); void enableUpdateButton(bool enable);

View file

@ -2,13 +2,12 @@
#include "logger.h" #include "logger.h"
#include "settingscache.h" #include "settingscache.h"
#include <QVBoxLayout>
#include <QPlainTextEdit> #include <QPlainTextEdit>
#include <QVBoxLayout>
DlgViewLog::DlgViewLog(QWidget *parent) : QDialog(parent) DlgViewLog::DlgViewLog(QWidget *parent) : QDialog(parent)
{ {
logArea = new QPlainTextEdit; logArea = new QPlainTextEdit;
logArea->setReadOnly(true); logArea->setReadOnly(true);
@ -49,8 +48,7 @@ void DlgViewLog::logEntryAdded(QString message)
void DlgViewLog::closeEvent(QCloseEvent * /* event */) void DlgViewLog::closeEvent(QCloseEvent * /* event */)
{ {
if (coClearLog->isChecked()) if (coClearLog->isChecked()) {
{
logArea->clear(); logArea->clear();
} }

View file

@ -1,18 +1,21 @@
#ifndef DLG_VIEWLOG_H #ifndef DLG_VIEWLOG_H
#define DLG_VIEWLOG_H #define DLG_VIEWLOG_H
#include <QDialog>
#include <QCheckBox> #include <QCheckBox>
#include <QDialog>
class QPlainTextEdit; class QPlainTextEdit;
class QCloseEvent; class QCloseEvent;
class DlgViewLog : public QDialog { class DlgViewLog : public QDialog
{
Q_OBJECT Q_OBJECT
public: public:
explicit DlgViewLog(QWidget *parent); explicit DlgViewLog(QWidget *parent);
protected: protected:
void closeEvent(QCloseEvent *event) override; void closeEvent(QCloseEvent *event) override;
private: private:
QPlainTextEdit *logArea; QPlainTextEdit *logArea;
QCheckBox *coClearLog; QCheckBox *coClearLog;

View file

@ -1,30 +1,23 @@
#include "filterbuilder.h" #include "filterbuilder.h"
#include <QGridLayout>
#include <QComboBox> #include <QComboBox>
#include <QPushButton> #include <QGridLayout>
#include <QLineEdit> #include <QLineEdit>
#include <QPushButton>
#include "cardfilter.h" #include "cardfilter.h"
FilterBuilder::FilterBuilder(QWidget *parent) FilterBuilder::FilterBuilder(QWidget *parent) : QWidget(parent)
: QWidget(parent)
{ {
filterCombo = new QComboBox; filterCombo = new QComboBox;
filterCombo->setObjectName("filterCombo"); filterCombo->setObjectName("filterCombo");
for (int i = 0; i < CardFilter::AttrEnd; i++) for (int i = 0; i < CardFilter::AttrEnd; i++)
filterCombo->addItem( filterCombo->addItem(tr(CardFilter::attrName(static_cast<CardFilter::Attr>(i))), QVariant(i));
tr(CardFilter::attrName(static_cast<CardFilter::Attr>(i))),
QVariant(i)
);
typeCombo = new QComboBox; typeCombo = new QComboBox;
typeCombo->setObjectName("typeCombo"); typeCombo->setObjectName("typeCombo");
for (int i = 0; i < CardFilter::TypeEnd; i++) for (int i = 0; i < CardFilter::TypeEnd; i++)
typeCombo->addItem( typeCombo->addItem(tr(CardFilter::typeName(static_cast<CardFilter::Type>(i))), QVariant(i));
tr(CardFilter::typeName(static_cast<CardFilter::Type>(i))),
QVariant(i)
);
QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString()); QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString());
ok->setObjectName("ok"); ok->setObjectName("ok");
@ -79,8 +72,7 @@ void FilterBuilder::emit_add()
return; return;
destroyFilter(); destroyFilter();
fltr = new CardFilter(txt, fltr = new CardFilter(txt, static_cast<CardFilter::Type>(comboCurrentIntData(typeCombo)),
static_cast<CardFilter::Type>(comboCurrentIntData(typeCombo)),
static_cast<CardFilter::Attr>(comboCurrentIntData(filterCombo))); static_cast<CardFilter::Attr>(comboCurrentIntData(filterCombo)));
emit add(fltr); emit add(fltr);
edit->clear(); edit->clear();

View file

@ -8,7 +8,8 @@ class QComboBox;
class QLineEdit; class QLineEdit;
class CardFilter; class CardFilter;
class FilterBuilder : public QWidget { class FilterBuilder : public QWidget
{
Q_OBJECT Q_OBJECT
private: private:
@ -29,6 +30,7 @@ signals:
public slots: public slots:
private slots: private slots:
void emit_add(); void emit_add();
protected: protected:
}; };

View file

@ -1,17 +1,15 @@
#include "filtertree.h" #include "filtertree.h"
#include "cardfilter.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "cardfilter.h"
#include <QList> #include <QList>
template <class T> template <class T> FilterTreeNode *FilterTreeBranch<T>::nodeAt(int i) const
FilterTreeNode *FilterTreeBranch<T>::nodeAt(int i) const
{ {
return (childNodes.size() > i) ? childNodes.at(i) : nullptr; return (childNodes.size() > i) ? childNodes.at(i) : nullptr;
} }
template <class T> template <class T> void FilterTreeBranch<T>::deleteAt(int i)
void FilterTreeBranch<T>::deleteAt(int i)
{ {
preRemoveChild(this, i); preRemoveChild(this, i);
delete childNodes.takeAt(i); delete childNodes.takeAt(i);
@ -19,19 +17,16 @@ void FilterTreeBranch<T>::deleteAt(int i)
nodeChanged(); nodeChanged();
} }
template <class T> template <class T> int FilterTreeBranch<T>::childIndex(const FilterTreeNode *node) const
int FilterTreeBranch<T>::childIndex(const FilterTreeNode *node) const
{ {
auto *unconst = const_cast<FilterTreeNode *>(node); auto *unconst = const_cast<FilterTreeNode *>(node);
auto downcasted = dynamic_cast<T>(unconst); auto downcasted = dynamic_cast<T>(unconst);
return (downcasted) ? childNodes.indexOf(downcasted) : -1; return (downcasted) ? childNodes.indexOf(downcasted) : -1;
} }
template <class T> template <class T> FilterTreeBranch<T>::~FilterTreeBranch()
FilterTreeBranch<T>::~FilterTreeBranch()
{
while (!childNodes.isEmpty())
{ {
while (!childNodes.isEmpty()) {
delete childNodes.takeFirst(); delete childNodes.takeFirst();
} }
} }
@ -40,10 +35,8 @@ const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const
{ {
QList<FilterItemList *>::const_iterator i; QList<FilterItemList *>::const_iterator i;
for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) {
{ if ((*i)->type == type) {
if ((*i)->type == type)
{
return *i; return *i;
} }
} }
@ -56,17 +49,14 @@ FilterItemList *LogicMap::typeList(CardFilter::Type type)
QList<FilterItemList *>::iterator i; QList<FilterItemList *>::iterator i;
int count = 0; int count = 0;
for (i = childNodes.begin(); i != childNodes.end(); i++) for (i = childNodes.begin(); i != childNodes.end(); i++) {
{ if ((*i)->type == type) {
if ((*i)->type == type)
{
break; break;
} }
count++; count++;
} }
if (i == childNodes.end()) if (i == childNodes.end()) {
{
preInsertChild(this, count); preInsertChild(this, count);
i = childNodes.insert(i, new FilterItemList(type, this)); i = childNodes.insert(i, new FilterItemList(type, this));
postInsertChild(this, count); postInsertChild(this, count);
@ -83,10 +73,8 @@ FilterTreeNode *LogicMap::parent() const
int FilterItemList::termIndex(const QString &term) const int FilterItemList::termIndex(const QString &term) const
{ {
for (int i = 0; i < childNodes.count(); i++) for (int i = 0; i < childNodes.count(); i++) {
{ if ((childNodes.at(i))->term == term) {
if ((childNodes.at(i))->term == term)
{
return i; return i;
} }
} }
@ -97,8 +85,7 @@ int FilterItemList::termIndex(const QString &term) const
FilterTreeNode *FilterItemList::termNode(const QString &term) FilterTreeNode *FilterItemList::termNode(const QString &term)
{ {
int i = termIndex(term); int i = termIndex(term);
if (i < 0) if (i < 0) {
{
FilterItem *fi = new FilterItem(term, this); FilterItem *fi = new FilterItem(term, this);
int count = childNodes.count(); int count = childNodes.count();
@ -115,15 +102,12 @@ FilterTreeNode *FilterItemList::termNode(const QString &term)
bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const
{ {
for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) {
{ if (!(*i)->isEnabled()) {
if (! (*i)->isEnabled())
{
continue; continue;
} }
if (! (*i)->acceptCardAttr(info, attr)) if (!(*i)->acceptCardAttr(info, attr)) {
{
return false; return false;
} }
} }
@ -141,20 +125,16 @@ bool FilterItemList::testTypeOr(const CardInfo *info, CardFilter::Attr attr) con
{ {
bool noChildEnabledChild = true; bool noChildEnabledChild = true;
for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) {
{ if (!(*i)->isEnabled()) {
if (! (*i)->isEnabled())
{
continue; continue;
} }
if (noChildEnabledChild) if (noChildEnabledChild) {
{
noChildEnabledChild = false; noChildEnabledChild = false;
} }
if ((*i)->acceptCardAttr(info, attr)) if ((*i)->acceptCardAttr(info, attr)) {
{
return true; return true;
} }
} }
@ -198,8 +178,7 @@ bool FilterItem::acceptColor(const CardInfo *info) const
converted_term.replace(QString(" "), QString(""), Qt::CaseInsensitive); converted_term.replace(QString(" "), QString(""), Qt::CaseInsensitive);
// Colorless card filter // Colorless card filter
if (converted_term.toLower() == "c" && info->getColors().length() < 1) if (converted_term.toLower() == "c" && info->getColors().length() < 1) {
{
return true; 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 * then we should match all of them to the card's colors
*/ */
int match_count = 0; int match_count = 0;
for (auto &it : converted_term) for (auto &it : converted_term) {
{ for (auto i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) {
for (auto i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) if ((*i).contains(it, Qt::CaseInsensitive)) {
{
if ((*i).contains(it, Qt::CaseInsensitive))
{
match_count++; match_count++;
} }
} }
@ -230,11 +206,9 @@ bool FilterItem::acceptText(const CardInfo *info) const
bool FilterItem::acceptSet(const CardInfo *info) const bool FilterItem::acceptSet(const CardInfo *info) const
{ {
bool status = false; bool status = false;
for (auto i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) for (auto i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) {
{ if ((*i)->getShortName().compare(term, Qt::CaseInsensitive) == 0 ||
if ((*i)->getShortName().compare(term, Qt::CaseInsensitive) == 0 (*i)->getLongName().compare(term, Qt::CaseInsensitive) == 0) {
|| (*i)->getLongName().compare(term, Qt::CaseInsensitive) == 0)
{
status = true; status = true;
break; break;
} }
@ -286,25 +260,36 @@ bool FilterItem::acceptRarity(const CardInfo *info) const
* Will also need to replace just "mythic" * Will also need to replace just "mythic"
*/ */
converted_term.replace("mythic", "mythic rare", Qt::CaseInsensitive); converted_term.replace("mythic", "mythic rare", Qt::CaseInsensitive);
for (int i = 0; converted_term.length() <= 3 && i <= 6; i++) for (int i = 0; converted_term.length() <= 3 && i <= 6; i++) {
{ switch (i) {
switch (i) case 0:
{ converted_term.replace("mr", "mythic rare", Qt::CaseInsensitive);
case 0: converted_term.replace("mr", "mythic rare", Qt::CaseInsensitive); break; break;
case 1: converted_term.replace("m r", "mythic rare", Qt::CaseInsensitive); break; case 1:
case 2: converted_term.replace("m", "mythic rare", Qt::CaseInsensitive); break; converted_term.replace("m r", "mythic rare", Qt::CaseInsensitive);
case 3: converted_term.replace("c", "common", Qt::CaseInsensitive); break; break;
case 4: converted_term.replace("u", "uncommon", Qt::CaseInsensitive); break; case 2:
case 5: converted_term.replace("r", "rare", Qt::CaseInsensitive); break; converted_term.replace("m", "mythic rare", Qt::CaseInsensitive);
case 6: converted_term.replace("s", "special", Qt::CaseInsensitive); break; break;
default: 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()) foreach (QString rareLevel, info->getRarities()) {
{ if (rareLevel.compare(converted_term, Qt::CaseInsensitive) == 0) {
if (rareLevel.compare(converted_term, Qt::CaseInsensitive) == 0)
{
return true; return true;
} }
} }
@ -313,19 +298,29 @@ bool FilterItem::acceptRarity(const CardInfo *info) const
bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const
{ {
switch (attr) switch (attr) {
{ case CardFilter::AttrName:
case CardFilter::AttrName: return acceptName(info); return acceptName(info);
case CardFilter::AttrType: return acceptType(info); case CardFilter::AttrType:
case CardFilter::AttrColor: return acceptColor(info); return acceptType(info);
case CardFilter::AttrText: return acceptText(info); case CardFilter::AttrColor:
case CardFilter::AttrSet: return acceptSet(info); return acceptColor(info);
case CardFilter::AttrManaCost: return acceptManaCost(info); case CardFilter::AttrText:
case CardFilter::AttrCmc: return acceptCmc(info); return acceptText(info);
case CardFilter::AttrRarity: return acceptRarity(info); case CardFilter::AttrSet:
case CardFilter::AttrPow: return acceptPower(info); return acceptSet(info);
case CardFilter::AttrTough: return acceptToughness(info); case CardFilter::AttrManaCost:
default: return true; /* ignore this attribute */ 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<LogicMap *>::iterator i; QList<LogicMap *>::iterator i;
int count = 0; int count = 0;
for (i = childNodes.begin(); i != childNodes.end(); i++) for (i = childNodes.begin(); i != childNodes.end(); i++) {
{ if ((*i)->attr == attr) {
if ((*i)->attr == attr)
{
break; break;
} }
count++; count++;
} }
if (i == childNodes.end()) if (i == childNodes.end()) {
{
preInsertChild(this, count); preInsertChild(this, count);
i = childNodes.insert(i, new LogicMap(attr, this)); i = childNodes.insert(i, new LogicMap(attr, this));
postInsertChild(this, count); postInsertChild(this, count);
@ -397,32 +389,27 @@ bool FilterTree::testAttr(const CardInfo *info, const LogicMap *lm) const
bool status = true; bool status = true;
fil = lm->findTypeList(CardFilter::TypeAnd); 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; return false;
} }
fil = lm->findTypeList(CardFilter::TypeAndNot); 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; return false;
} }
fil = lm->findTypeList(CardFilter::TypeOr); fil = lm->findTypeList(CardFilter::TypeOr);
if (fil && fil->isEnabled()) if (fil && fil->isEnabled()) {
{
status = false; status = false;
// if this is true we can return because it is OR'd with the OrNot list // 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; return true;
} }
} }
fil = lm->findTypeList(CardFilter::TypeOrNot); 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; return true;
} }
@ -431,10 +418,8 @@ bool FilterTree::testAttr(const CardInfo *info, const LogicMap *lm) const
bool FilterTree::acceptsCard(const CardInfo *info) const bool FilterTree::acceptsCard(const CardInfo *info) const
{ {
for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) for (auto i = childNodes.constBegin(); i != childNodes.constEnd(); i++) {
{ if ((*i)->isEnabled() && !testAttr(info, *i)) {
if ((*i)->isEnabled() && !testAttr(info, *i))
{
return false; return false;
} }
} }
@ -444,8 +429,7 @@ bool FilterTree::acceptsCard(const CardInfo *info) const
void FilterTree::clear() void FilterTree::clear()
{ {
while (childCount() > 0) while (childCount() > 0) {
{
deleteAt(0); deleteAt(0);
} }
} }

View file

@ -9,55 +9,111 @@
class CardInfo; class CardInfo;
class FilterTreeNode { class FilterTreeNode
{
private: private:
bool enabled; bool enabled;
public: public:
FilterTreeNode() : enabled(true) {} FilterTreeNode() : enabled(true)
virtual bool isEnabled() const { return enabled; } {
virtual void enable() { enabled = true; nodeChanged(); }
virtual void disable() { enabled = false; nodeChanged(); }
virtual FilterTreeNode *parent() const { return NULL; }
virtual FilterTreeNode *nodeAt(int /* i */) const { return NULL; }
virtual void deleteAt(int /* i */) {}
virtual int childCount() const { return 0; }
virtual int childIndex(const FilterTreeNode * /* node */) const { return -1; }
virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; }
virtual QString text() const { return QString(textCStr()); }
virtual bool isLeaf() const { return false; }
virtual const char *textCStr() const { return ""; }
virtual void nodeChanged() const {
if (parent() != NULL) parent()->nodeChanged();
} }
virtual void preInsertChild(const FilterTreeNode *p, int i) const { virtual bool isEnabled() const
if (parent() != NULL) parent()->preInsertChild(p, i); {
return enabled;
} }
virtual void postInsertChild(const FilterTreeNode *p, int i) const { virtual void enable()
if (parent() != NULL) parent()->postInsertChild(p, i); {
enabled = true;
nodeChanged();
} }
virtual void preRemoveChild(const FilterTreeNode *p, int i) const { virtual void disable()
if (parent() != NULL) parent()->preRemoveChild(p, i); {
enabled = false;
nodeChanged();
} }
virtual void postRemoveChild(const FilterTreeNode *p, int i) const { virtual FilterTreeNode *parent() const
if (parent() != NULL) parent()->postRemoveChild(p, i); {
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 T> template <class T> class FilterTreeBranch : public FilterTreeNode
class FilterTreeBranch : public FilterTreeNode { {
protected: protected:
QList<T> childNodes; QList<T> childNodes;
public: public:
virtual ~FilterTreeBranch(); virtual ~FilterTreeBranch();
FilterTreeNode *nodeAt(int i) const; FilterTreeNode *nodeAt(int i) const;
void deleteAt(int i); void deleteAt(int i);
int childCount() const { return childNodes.size(); } int childCount() const
{
return childNodes.size();
}
int childIndex(const FilterTreeNode *node) const; int childIndex(const FilterTreeNode *node) const;
}; };
class FilterItemList; class FilterItemList;
class FilterTree; class FilterTree;
class LogicMap : public FilterTreeBranch<FilterItemList *> { class LogicMap : public FilterTreeBranch<FilterItemList *>
{
private: private:
FilterTree *const p; FilterTree *const p;
@ -65,28 +121,44 @@ private:
public: public:
const CardFilter::Attr attr; const CardFilter::Attr attr;
LogicMap(CardFilter::Attr a, FilterTree *parent) LogicMap(CardFilter::Attr a, FilterTree *parent) : p(parent), attr(a)
: p(parent), attr(a) {} {
}
const FilterItemList *findTypeList(CardFilter::Type type) const; const FilterItemList *findTypeList(CardFilter::Type type) const;
FilterItemList *typeList(CardFilter::Type type); FilterItemList *typeList(CardFilter::Type type);
FilterTreeNode *parent() const; FilterTreeNode *parent() const;
const char* textCStr() const { return CardFilter::attrName(attr); } const char *textCStr() const
{
return CardFilter::attrName(attr);
}
}; };
class FilterItem; class FilterItem;
class FilterItemList : public FilterTreeBranch<FilterItem *> { class FilterItemList : public FilterTreeBranch<FilterItem *>
{
private: private:
LogicMap *const p; LogicMap *const p;
public: public:
const CardFilter::Type type; const CardFilter::Type type;
FilterItemList(CardFilter::Type t, LogicMap *parent) FilterItemList(CardFilter::Type t, LogicMap *parent) : p(parent), type(t)
: p(parent), type(t) {} {
CardFilter::Attr attr() const { return p->attr; } }
FilterTreeNode *parent() const { return p; } CardFilter::Attr attr() const
{
return p->attr;
}
FilterTreeNode *parent() const
{
return p;
}
int termIndex(const QString &term) const; int termIndex(const QString &term) const;
FilterTreeNode *termNode(const QString &term); 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 testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const;
bool testTypeAndNot(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; bool testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const;
}; };
class FilterItem : public FilterTreeNode { class FilterItem : public FilterTreeNode
{
private: private:
FilterItemList *const p; FilterItemList *const p;
public: public:
const QString term; const QString term;
FilterItem(QString trm, FilterItemList *parent) FilterItem(QString trm, FilterItemList *parent) : p(parent), term(trm)
: p(parent), term(trm) {} {
}
virtual ~FilterItem(){}; virtual ~FilterItem(){};
CardFilter::Attr attr() const { return p->attr(); } CardFilter::Attr attr() const
CardFilter::Type type() const { return p->type; } {
FilterTreeNode *parent() const { return p; } return p->attr();
QString text() const { return term; } }
const char *textCStr() const { return term.toStdString().c_str(); } CardFilter::Type type() const
bool isLeaf() const { return true; } {
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 acceptName(const CardInfo *info) const;
bool acceptType(const CardInfo *info) const; bool acceptType(const CardInfo *info) const;
@ -124,7 +217,8 @@ public:
bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const; bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const;
}; };
class FilterTree : public QObject, public FilterTreeBranch<LogicMap *> { class FilterTree : public QObject, public FilterTreeBranch<LogicMap *>
{
Q_OBJECT Q_OBJECT
signals: signals:
@ -136,30 +230,47 @@ signals:
private: private:
LogicMap *attrLogicMap(CardFilter::Attr attr); LogicMap *attrLogicMap(CardFilter::Attr attr);
FilterItemList *attrTypeList(CardFilter::Attr attr, FilterItemList *attrTypeList(CardFilter::Attr attr, CardFilter::Type type);
CardFilter::Type type);
bool testAttr(const CardInfo *info, const LogicMap *lm) const; bool testAttr(const CardInfo *info, const LogicMap *lm) const;
void nodeChanged() const { emit changed(); } void nodeChanged() const
void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } {
void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } emit changed();
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 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: public:
FilterTree(); FilterTree();
~FilterTree(); ~FilterTree();
int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, const QString &term);
const QString &term);
int findTermIndex(const CardFilter *f); int findTermIndex(const CardFilter *f);
FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, const QString &term);
const QString &term);
FilterTreeNode *termNode(const CardFilter *f); FilterTreeNode *termNode(const CardFilter *f);
FilterTreeNode *attrTypeNode(CardFilter::Attr attr, FilterTreeNode *attrTypeNode(CardFilter::Attr attr, CardFilter::Type type);
CardFilter::Type type); const char *textCStr() const
const char *textCStr() const { return "root"; } {
int index() const { return 0; } return "root";
}
int index() const
{
return 0;
}
bool acceptsCard(const CardInfo *info) const; bool acceptsCard(const CardInfo *info) const;
void clear(); void clear();

View file

@ -1,24 +1,19 @@
#include <QFont>
#include "filtertreemodel.h" #include "filtertreemodel.h"
#include "filtertree.h"
#include "cardfilter.h" #include "cardfilter.h"
#include "filtertree.h"
#include <QFont>
FilterTreeModel::FilterTreeModel(QObject *parent) FilterTreeModel::FilterTreeModel(QObject *parent) : QAbstractItemModel(parent)
: QAbstractItemModel(parent)
{ {
fTree = new FilterTree; fTree = new FilterTree;
connect(fTree, connect(fTree, SIGNAL(preInsertRow(const FilterTreeNode *, int)), this,
SIGNAL(preInsertRow(const FilterTreeNode *, int)), SLOT(proxyBeginInsertRow(const FilterTreeNode *, int)));
this, SLOT(proxyBeginInsertRow(const FilterTreeNode *, int))); connect(fTree, SIGNAL(postInsertRow(const FilterTreeNode *, int)), this,
connect(fTree, SLOT(proxyEndInsertRow(const FilterTreeNode *, int)));
SIGNAL(postInsertRow(const FilterTreeNode *, int)), connect(fTree, SIGNAL(preRemoveRow(const FilterTreeNode *, int)), this,
this, SLOT(proxyEndInsertRow(const FilterTreeNode *, int))); SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int)));
connect(fTree, connect(fTree, SIGNAL(postRemoveRow(const FilterTreeNode *, int)), this,
SIGNAL(preRemoveRow(const FilterTreeNode *, int)), SLOT(proxyEndRemoveRow(const FilterTreeNode *, int)));
this, SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int)));
connect(fTree,
SIGNAL(postRemoveRow(const FilterTreeNode *, int)),
this, SLOT(proxyEndRemoveRow(const FilterTreeNode *, int)));
} }
FilterTreeModel::~FilterTreeModel() FilterTreeModel::~FilterTreeModel()
@ -149,8 +144,7 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
return QVariant(); return QVariant();
} }
bool FilterTreeModel::setData(const QModelIndex &index, bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
const QVariant &value, int role)
{ {
FilterTreeNode *node; FilterTreeNode *node;
@ -208,8 +202,7 @@ QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int
return createIndex(row, column, child); return createIndex(row, column, child);
} }
QModelIndex FilterTreeModel::index(int row, int column, QModelIndex FilterTreeModel::index(int row, int column, const QModelIndex &parent) const
const QModelIndex &parent) const
{ {
const FilterTreeNode *node; const FilterTreeNode *node;

View file

@ -7,7 +7,8 @@ class FilterTree;
class CardFilter; class CardFilter;
class FilterTreeNode; class FilterTreeNode;
class FilterTreeModel : public QAbstractItemModel { class FilterTreeModel : public QAbstractItemModel
{
Q_OBJECT Q_OBJECT
private: private:
FilterTree *fTree; FilterTree *fTree;
@ -28,16 +29,17 @@ private:
public: public:
FilterTreeModel(QObject *parent = 0); FilterTreeModel(QObject *parent = 0);
~FilterTreeModel(); ~FilterTreeModel();
FilterTree *filterTree() const { return fTree; } FilterTree *filterTree() const
{
return fTree;
}
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const; int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
int role = Qt::EditRole);
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex &index) const;
QModelIndex parent(const QModelIndex &ind) const; QModelIndex parent(const QModelIndex &ind) const;
QModelIndex index(int row, int column, QModelIndex index(int row, int column, const QModelIndex &parent) const;
const QModelIndex &parent) const;
bool removeRows(int row, int count, const QModelIndex &parent); bool removeRows(int row, int count, const QModelIndex &parent);
}; };

View file

@ -1,23 +1,20 @@
#include "gamescene.h" #include "gamescene.h"
#include "carditem.h"
#include "phasestoolbar.h"
#include "player.h" #include "player.h"
#include "settingscache.h"
#include "zoneviewwidget.h" #include "zoneviewwidget.h"
#include "zoneviewzone.h" #include "zoneviewzone.h"
#include "phasestoolbar.h"
#include "settingscache.h"
#include "carditem.h"
#include <math.h>
#include <QAction> #include <QAction>
#include <QGraphicsSceneMouseEvent>
#include <QSet>
#include <QBasicTimer> #include <QBasicTimer>
#include <QGraphicsView>
#include <QDebug> #include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <QSet>
#include <math.h>
GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent) GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent)
: QGraphicsScene(parent), : QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()), playerRotation(0)
phasesToolbar(_phasesToolbar),
viewSize(QSize()),
playerRotation(0)
{ {
animationTimer = new QBasicTimer; animationTimer = new QBasicTimer;
addItem(phasesToolbar); addItem(phasesToolbar);
@ -161,7 +158,10 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb
item->setPos(340, 80); item->setPos(340, 80);
} }
void GameScene::addRevealedZoneView(Player *player, CardZone *zone, const QList<const ServerInfo_Card *> &cardList, bool withWritePermission) void GameScene::addRevealedZoneView(Player *player,
CardZone *zone,
const QList<const ServerInfo_Card *> &cardList,
bool withWritePermission)
{ {
ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList); ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList);
zoneViews.append(item); zoneViews.append(item);
@ -240,7 +240,8 @@ void GameScene::processViewSizeChange(const QSize &newSize)
void GameScene::updateHover(const QPointF &scenePos) void GameScene::updateHover(const QPointF &scenePos)
{ {
QList<QGraphicsItem *> itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); QList<QGraphicsItem *> itemList =
items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform());
// Search for the topmost zone and ignore all cards not belonging to that zone. // Search for the topmost zone and ignore all cards not belonging to that zone.
CardZone *zone = 0; CardZone *zone = 0;

View file

@ -15,7 +15,8 @@ class ServerInfo_Card;
class PhasesToolbar; class PhasesToolbar;
class QBasicTimer; class QBasicTimer;
class GameScene : public QGraphicsScene { class GameScene : public QGraphicsScene
{
Q_OBJECT Q_OBJECT
private: private:
static const int playerAreaSpacing = 5; static const int playerAreaSpacing = 5;
@ -30,6 +31,7 @@ private:
QSet<CardItem *> cardsToAnimate; QSet<CardItem *> cardsToAnimate;
int playerRotation; int playerRotation;
void updateHover(const QPointF &scenePos); void updateHover(const QPointF &scenePos);
public: public:
GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0); GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0);
~GameScene(); ~GameScene();
@ -46,7 +48,10 @@ public:
void unregisterAnimationItem(AbstractCardItem *card); void unregisterAnimationItem(AbstractCardItem *card);
public slots: public slots:
void toggleZoneView(Player *player, const QString &zoneName, int numberCards); void toggleZoneView(Player *player, const QString &zoneName, int numberCards);
void addRevealedZoneView(Player *player, CardZone *zone, const QList<const ServerInfo_Card *> &cardList, bool withWritePermission); void addRevealedZoneView(Player *player,
CardZone *zone,
const QList<const ServerInfo_Card *> &cardList,
bool withWritePermission);
void removeZoneView(ZoneViewWidget *item); void removeZoneView(ZoneViewWidget *item);
void addPlayer(Player *player); void addPlayer(Player *player);
void removePlayer(Player *player); void removePlayer(Player *player);
@ -54,6 +59,7 @@ public slots:
void closeMostRecentZoneView(); void closeMostRecentZoneView();
void adjustPlayerRotation(int rotationAdjustment); void adjustPlayerRotation(int rotationAdjustment);
void rearrange(); void rearrange();
protected: protected:
bool event(QEvent *event); bool event(QEvent *event);
void timerEvent(QTimerEvent *event); void timerEvent(QTimerEvent *event);

View file

@ -1,30 +1,36 @@
#include <QTreeView> #include "gameselector.h"
#include <QCheckBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QHeaderView>
#include <QInputDialog>
#include <QDebug>
#include "tab_supervisor.h"
#include "dlg_creategame.h" #include "dlg_creategame.h"
#include "dlg_filter_games.h" #include "dlg_filter_games.h"
#include "gameselector.h"
#include "gamesmodel.h" #include "gamesmodel.h"
#include "tab_room.h" #include "pb/response.pb.h"
#include "pending_command.h"
#include "pb/room_commands.pb.h" #include "pb/room_commands.pb.h"
#include "pb/serverinfo_game.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 <QCheckBox>
#include <QDebug>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QInputDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QTreeView>
#include <QVBoxLayout>
GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, const bool restoresettings, const bool showfilters, QWidget *parent) GameSelector::GameSelector(AbstractClient *_client,
const TabSupervisor *_tabSupervisor,
TabRoom *_room,
const QMap<int, QString> &_rooms,
const QMap<int, GameTypeMap> &_gameTypes,
const bool restoresettings,
const bool showfilters,
QWidget *parent)
: QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room) : QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room)
{ {
gameListView = new QTreeView; gameListView = new QTreeView;
gameListModel = new GamesModel(_rooms, _gameTypes, this); gameListModel = new GamesModel(_rooms, _gameTypes, this);
if(showfilters) if (showfilters) {
{
gameListProxyModel = new GamesProxyModel(this, tabSupervisor->isOwnUserRegistered()); gameListProxyModel = new GamesProxyModel(this, tabSupervisor->isOwnUserRegistered());
gameListProxyModel->setSourceModel(gameListModel); gameListProxyModel->setSourceModel(gameListModel);
gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
@ -74,8 +80,7 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup
spectateButton = new QPushButton; spectateButton = new QPushButton;
QHBoxLayout *buttonLayout = new QHBoxLayout; QHBoxLayout *buttonLayout = new QHBoxLayout;
if(showfilters) if (showfilters) {
{
buttonLayout->addWidget(filterButton); buttonLayout->addWidget(filterButton);
buttonLayout->addWidget(clearFilterButton); buttonLayout->addWidget(clearFilterButton);
} }
@ -98,7 +103,8 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup
connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin())); connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin()));
connect(spectateButton, 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())); connect(gameListView, SIGNAL(activated(const QModelIndex &)), this, SLOT(actJoin()));
} }
@ -147,14 +153,30 @@ void GameSelector::checkResponse(const Response &response)
joinButton->setEnabled(true); joinButton->setEnabled(true);
switch (response.response_code()) { switch (response.response_code()) {
case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break; case Response::RespNotInRoom:
case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break; QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first."));
case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break; break;
case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break; case Response::RespWrongPassword:
case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break; QMessageBox::critical(this, tr("Error"), tr("Wrong password."));
case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break; break;
case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break; case Response::RespSpectatorsNotAllowed:
case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break; 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:; default:;
} }

View file

@ -1,8 +1,8 @@
#ifndef GAMESELECTOR_H #ifndef GAMESELECTOR_H
#define GAMESELECTOR_H #define GAMESELECTOR_H
#include <QGroupBox>
#include "gametypemap.h" #include "gametypemap.h"
#include <QGroupBox>
class QTreeView; class QTreeView;
class GamesModel; class GamesModel;
@ -15,7 +15,8 @@ class TabRoom;
class ServerInfo_Game; class ServerInfo_Game;
class Response; class Response;
class GameSelector : public QGroupBox { class GameSelector : public QGroupBox
{
Q_OBJECT Q_OBJECT
private slots: private slots:
void actSetFilter(); void actSetFilter();
@ -26,6 +27,7 @@ private slots:
void checkResponse(const Response &response); void checkResponse(const Response &response);
signals: signals:
void gameJoined(int gameId); void gameJoined(int gameId);
private: private:
AbstractClient *client; AbstractClient *client;
const TabSupervisor *tabSupervisor; const TabSupervisor *tabSupervisor;
@ -36,8 +38,16 @@ private:
GamesProxyModel *gameListProxyModel; GamesProxyModel *gameListProxyModel;
QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton; QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton;
GameTypeMap gameTypeMap; GameTypeMap gameTypeMap;
public: public:
GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, const bool restoresettings, const bool showfilters, QWidget *parent = 0); GameSelector(AbstractClient *_client,
const TabSupervisor *_tabSupervisor,
TabRoom *_room,
const QMap<int, QString> &_rooms,
const QMap<int, GameTypeMap> &_gameTypes,
const bool restoresettings,
const bool showfilters,
QWidget *parent = 0);
void retranslateUi(); void retranslateUi();
void processGameInfo(const ServerInfo_Game &info); void processGameInfo(const ServerInfo_Game &info);
}; };

View file

@ -3,14 +3,25 @@
#include "pixmapgenerator.h" #include "pixmapgenerator.h"
#include "settingscache.h" #include "settingscache.h"
#include <QDateTime>
#include <QDebug> #include <QDebug>
#include <QIcon> #include <QIcon>
#include <QStringList> #include <QStringList>
#include <QDateTime>
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; QString ret;
if (secs < SECS_PER_MIN * 2) // for first min we display "New" if (secs < SECS_PER_MIN * 2) // for first min we display "New"
@ -56,10 +67,14 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
int secs = then.secsTo(QDateTime::currentDateTime()); int secs = then.secsTo(QDateTime::currentDateTime());
switch (role) { switch (role) {
case Qt::DisplayRole: return getGameCreatedString(secs); case Qt::DisplayRole:
case SORT_ROLE: return QVariant(secs); return getGameCreatedString(secs);
case Qt::TextAlignmentRole: return Qt::AlignCenter; case SORT_ROLE:
default: return QVariant(); return QVariant(secs);
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
default:
return QVariant();
} }
} }
case DESCRIPTION: case DESCRIPTION:
@ -78,7 +93,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case Qt::DisplayRole: case Qt::DisplayRole:
return QString::fromStdString(g.creator_info().name()); return QString::fromStdString(g.creator_info().name());
case Qt::DecorationRole: { case Qt::DecorationRole: {
QPixmap avatarPixmap = UserLevelPixmapGenerator::generatePixmap(13, (UserLevelFlags)g.creator_info().user_level(), false, QString::fromStdString(g.creator_info().privlevel())); QPixmap avatarPixmap = UserLevelPixmapGenerator::generatePixmap(
13, (UserLevelFlags)g.creator_info().user_level(), false,
QString::fromStdString(g.creator_info().privlevel()));
return QIcon(avatarPixmap); return QIcon(avatarPixmap);
} }
default: default:
@ -140,16 +157,15 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
QString result; QString result;
result.append(QString::number(g.spectators_count())); result.append(QString::number(g.spectators_count()));
if (g.spectators_can_chat() && g.spectators_omniscient()) if (g.spectators_can_chat() && g.spectators_omniscient()) {
{ result.append(" (")
result.append(" (").append(tr("can chat")).append(" & ").append(tr("see hands")).append(")"); .append(tr("can chat"))
} .append(" & ")
else if (g.spectators_can_chat()) .append(tr("see hands"))
{ .append(")");
} else if (g.spectators_can_chat()) {
result.append(" (").append(tr("can chat")).append(")"); result.append(" (").append(tr("can chat")).append(")");
} } else if (g.spectators_omniscient()) {
else if (g.spectators_omniscient())
{
result.append(" (").append(tr("can see hands")).append(")"); result.append(" (").append(tr("can see hands")).append(")");
} }
@ -162,7 +178,8 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
default: default:
return QVariant(); return QVariant();
} }
default: return QVariant(); default:
return QVariant();
} }
} }
@ -171,7 +188,8 @@ QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, in
if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole)) if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole))
return QVariant(); return QVariant();
switch (section) { switch (section) {
case ROOM: return tr("Room"); case ROOM:
return tr("Room");
case CREATED: { case CREATED: {
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
@ -180,10 +198,14 @@ QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, in
return Qt::AlignCenter; return Qt::AlignCenter;
} }
} }
case DESCRIPTION: return tr("Description"); case DESCRIPTION:
case CREATOR: return tr("Creator"); return tr("Description");
case GAME_TYPE: return tr("Type"); case CREATOR:
case RESTRICTIONS: return tr("Restrictions"); return tr("Creator");
case GAME_TYPE:
return tr("Type");
case RESTRICTIONS:
return tr("Restrictions");
case PLAYERS: { case PLAYERS: {
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
@ -192,8 +214,10 @@ QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, in
return Qt::AlignCenter; return Qt::AlignCenter;
} }
} }
case SPECTATORS: return tr("Spectators"); case SPECTATORS:
default: return QVariant(); return tr("Spectators");
default:
return QVariant();
} }
} }
@ -226,19 +250,15 @@ void GamesModel::updateGameList(const ServerInfo_Game &game)
} }
GamesProxyModel::GamesProxyModel(QObject *parent, bool _ownUserIsRegistered) GamesProxyModel::GamesProxyModel(QObject *parent, bool _ownUserIsRegistered)
: QSortFilterProxyModel(parent), : QSortFilterProxyModel(parent), ownUserIsRegistered(_ownUserIsRegistered), showBuddiesOnlyGames(false),
ownUserIsRegistered(_ownUserIsRegistered), unavailableGamesVisible(false), showPasswordProtectedGames(true), maxPlayersFilterMin(-1), maxPlayersFilterMax(-1)
showBuddiesOnlyGames(false),
unavailableGamesVisible(false),
showPasswordProtectedGames(true),
maxPlayersFilterMin(-1),
maxPlayersFilterMax(-1)
{ {
setSortRole(GamesModel::SORT_ROLE); setSortRole(GamesModel::SORT_ROLE);
setDynamicSortFilter(true); setDynamicSortFilter(true);
} }
void GamesProxyModel::setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames) { void GamesProxyModel::setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames)
{
showBuddiesOnlyGames = _showBuddiesOnlyGames; showBuddiesOnlyGames = _showBuddiesOnlyGames;
invalidateFilter(); invalidateFilter();
} }

View file

@ -1,14 +1,15 @@
#ifndef GAMESMODEL_H #ifndef GAMESMODEL_H
#define GAMESMODEL_H #define GAMESMODEL_H
#include <QAbstractTableModel>
#include <QSortFilterProxyModel>
#include <QList>
#include <QSet>
#include "gametypemap.h" #include "gametypemap.h"
#include "pb/serverinfo_game.pb.h" #include "pb/serverinfo_game.pb.h"
#include <QAbstractTableModel>
#include <QList>
#include <QSet>
#include <QSortFilterProxyModel>
class GamesModel : public QAbstractTableModel { class GamesModel : public QAbstractTableModel
{
Q_OBJECT Q_OBJECT
private: private:
QList<ServerInfo_Game> gameList; QList<ServerInfo_Game> gameList;
@ -19,12 +20,19 @@ private:
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_TEN_MIN = 600;
static const int SECS_PER_HOUR = 3600; static const int SECS_PER_HOUR = 3600;
public: public:
static const int SORT_ROLE = Qt::UserRole + 1; static const int SORT_ROLE = Qt::UserRole + 1;
GamesModel(const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, QObject *parent = 0); GamesModel(const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : gameList.size(); } int rowCount(const QModelIndex &parent = QModelIndex()) const
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return NUM_COLS; } {
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 data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
const QString getGameCreatedString(const int secs) const; const QString getGameCreatedString(const int secs) const;
@ -35,15 +43,25 @@ public:
*/ */
void updateGameList(const ServerInfo_Game &game); void updateGameList(const ServerInfo_Game &game);
int roomColIndex() { return 0; } int roomColIndex()
int startTimeColIndex() { return 1; } {
return 0;
}
int startTimeColIndex()
{
return 1;
}
const QMap<int, GameTypeMap> &getGameTypes() { return gameTypes; } const QMap<int, GameTypeMap> &getGameTypes()
{
return gameTypes;
}
}; };
class ServerInfo_User; class ServerInfo_User;
class GamesProxyModel : public QSortFilterProxyModel { class GamesProxyModel : public QSortFilterProxyModel
{
Q_OBJECT Q_OBJECT
private: private:
bool ownUserIsRegistered; bool ownUserIsRegistered;
@ -55,27 +73,53 @@ private:
int maxPlayersFilterMin, maxPlayersFilterMax; int maxPlayersFilterMin, maxPlayersFilterMax;
static const int DEFAULT_MAX_PLAYERS_MAX = 99; static const int DEFAULT_MAX_PLAYERS_MAX = 99;
public: public:
GamesProxyModel(QObject *parent = 0, bool _ownUserIsRegistered = false); GamesProxyModel(QObject *parent = 0, bool _ownUserIsRegistered = false);
bool getShowBuddiesOnlyGames() const {return showBuddiesOnlyGames; } bool getShowBuddiesOnlyGames() const
{
return showBuddiesOnlyGames;
}
void setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames); void setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames);
bool getUnavailableGamesVisible() const { return unavailableGamesVisible; } bool getUnavailableGamesVisible() const
{
return unavailableGamesVisible;
}
void setUnavailableGamesVisible(bool _unavailableGamesVisible); void setUnavailableGamesVisible(bool _unavailableGamesVisible);
bool getShowPasswordProtectedGames() const { return showPasswordProtectedGames; } bool getShowPasswordProtectedGames() const
{
return showPasswordProtectedGames;
}
void setShowPasswordProtectedGames(bool _showPasswordProtectedGames); void setShowPasswordProtectedGames(bool _showPasswordProtectedGames);
QString getGameNameFilter() const { return gameNameFilter; } QString getGameNameFilter() const
{
return gameNameFilter;
}
void setGameNameFilter(const QString &_gameNameFilter); void setGameNameFilter(const QString &_gameNameFilter);
QString getCreatorNameFilter() const { return creatorNameFilter; } QString getCreatorNameFilter() const
{
return creatorNameFilter;
}
void setCreatorNameFilter(const QString &_creatorNameFilter); void setCreatorNameFilter(const QString &_creatorNameFilter);
QSet<int> getGameTypeFilter() const { return gameTypeFilter; } QSet<int> getGameTypeFilter() const
{
return gameTypeFilter;
}
void setGameTypeFilter(const QSet<int> &_gameTypeFilter); void setGameTypeFilter(const QSet<int> &_gameTypeFilter);
int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; } int getMaxPlayersFilterMin() const
int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; } {
return maxPlayersFilterMin;
}
int getMaxPlayersFilterMax() const
{
return maxPlayersFilterMax;
}
void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax);
void resetFilterParameters(); void resetFilterParameters();
void loadFilterParameters(const QMap<int, QString> &allGameTypes); void loadFilterParameters(const QMap<int, QString> &allGameTypes);
void saveFilterParameters(const QMap<int, QString> &allGameTypes); void saveFilterParameters(const QMap<int, QString> &allGameTypes);
protected: protected:
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
}; };

View file

@ -1,12 +1,11 @@
#include "gameview.h" #include "gameview.h"
#include "gamescene.h" #include "gamescene.h"
#include "settingscache.h" #include "settingscache.h"
#include <QResizeEvent>
#include <QAction> #include <QAction>
#include <QResizeEvent>
#include <QRubberBand> #include <QRubberBand>
GameView::GameView(QGraphicsScene *scene, QWidget *parent) GameView::GameView(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent), rubberBand(0)
: QGraphicsView(scene, parent), rubberBand(0)
{ {
setBackgroundBrush(QBrush(QColor(0, 0, 0))); setBackgroundBrush(QBrush(QColor(0, 0, 0)));
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing); setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing);

View file

@ -5,12 +5,14 @@
class QRubberBand; class QRubberBand;
class GameView : public QGraphicsView { class GameView : public QGraphicsView
{
Q_OBJECT Q_OBJECT
private: private:
QAction *aCloseMostRecentZoneView; QAction *aCloseMostRecentZoneView;
QRubberBand *rubberBand; QRubberBand *rubberBand;
QPointF selectionOrigin; QPointF selectionOrigin;
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
private slots: private slots:
@ -20,6 +22,7 @@ private slots:
void refreshShortcuts(); void refreshShortcuts();
public slots: public slots:
void updateSceneRect(const QRectF &rect); void updateSceneRect(const QRectF &rect);
public: public:
GameView(QGraphicsScene *scene, QWidget *parent = 0); GameView(QGraphicsScene *scene, QWidget *parent = 0);
}; };

View file

@ -1,11 +1,10 @@
#include <QPainter>
#include <QPixmapCache>
#include <QGraphicsSceneMouseEvent>
#include "handcounter.h" #include "handcounter.h"
#include "cardzone.h" #include "cardzone.h"
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QPixmapCache>
HandCounter::HandCounter(QGraphicsItem *parent) HandCounter::HandCounter(QGraphicsItem *parent) : AbstractGraphicsItem(parent), number(0)
: AbstractGraphicsItem(parent), number(0)
{ {
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);
} }

View file

@ -1,25 +1,34 @@
#ifndef HANDCOUNTER_H #ifndef HANDCOUNTER_H
#define HANDCOUNTER_H #define HANDCOUNTER_H
#include <QString>
#include "abstractgraphicsitem.h" #include "abstractgraphicsitem.h"
#include <QString>
class QPainter; class QPainter;
class QPixmap; class QPixmap;
class HandCounter : public AbstractGraphicsItem { class HandCounter : public AbstractGraphicsItem
{
Q_OBJECT Q_OBJECT
private: private:
int number; int number;
protected: protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event);
public slots: public slots:
void updateNumber(); void updateNumber();
signals: signals:
void showContextMenu(const QPoint &screenPos); void showContextMenu(const QPoint &screenPos);
public: public:
enum { Type = typeOther }; enum
int type() const { return Type; } {
Type = typeOther
};
int type() const
{
return Type;
}
HandCounter(QGraphicsItem *parent = 0); HandCounter(QGraphicsItem *parent = 0);
~HandCounter(); ~HandCounter();
QRectF boundingRect() const; QRectF boundingRect() const;

View file

@ -1,10 +1,10 @@
#include <QPainter>
#include "handzone.h" #include "handzone.h"
#include "settingscache.h"
#include "thememanager.h"
#include "player.h"
#include "carddragitem.h" #include "carddragitem.h"
#include "carditem.h" #include "carditem.h"
#include "player.h"
#include "settingscache.h"
#include "thememanager.h"
#include <QPainter>
#include "pb/command_move_card.pb.h" #include "pb/command_move_card.pb.h"
@ -86,7 +86,8 @@ void HandZone::reorganizeCards()
bool leftJustified = settingsCache->getLeftJustified(); bool leftJustified = settingsCache->getLeftJustified();
qreal cardWidth = cards.at(0)->boundingRect().width(); qreal cardWidth = cards.at(0)->boundingRect().width();
const int xPadding = leftJustified ? cardWidth * 1.4 : 5; 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++) { for (int i = 0; i < cardCount; i++) {
CardItem *c = cards.at(i); CardItem *c = cards.at(i);
@ -95,8 +96,9 @@ void HandZone::reorganizeCards()
if (cardWidth * cardCount > totalWidth) 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 { else {
qreal xPosition = leftJustified ? xPadding + ((qreal) i) * cardWidth : qreal xPosition =
xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2; leftJustified ? xPadding + ((qreal)i) * cardWidth
: xPadding + ((qreal)i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2;
c->setPos(xPosition, 5); c->setPos(xPosition, 5);
} }
c->setRealZValue(i); c->setRealZValue(i);

Some files were not shown because too many files have changed in this diff Show more