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
make -j2
make test
if [[ $TRAVIS_OS_NAME == "linux" ]]; then
cd ..
clang-format -i \
common/*.h \
common/*.cpp \
cockatrice/src/*.h \
cockatrice/src/*.cpp \
oracle/src/*.h \
oracle/src/*.cpp \
servatrice/src/*.h \
servatrice/src/*.cpp
git clean -f
git diff --quiet || (
echo "*****************************************************";
echo "*** This PR is not clean against our code style ***";
echo "*** Run clang-format and fix up any differences ***";
echo "*** Check our CONTRIBUTING.md file for details! ***";
echo "*** Thank you ♥ ***";
echo "*****************************************************";
)
git diff --exit-code
fi
fi
if [[ $BUILDTYPE == "Release" ]]; then
cmake .. -DWITH_SERVER=1 -DCMAKE_BUILD_TYPE=$BUILDTYPE $prefix
make package -j2

View file

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

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
addons:
apt:
sources:
- sourceline: 'deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-5.0 main'
key_url: 'http://llvm.org/apt/llvm-snapshot.gpg.key'
packages:
- bc
- clang-format-5.0
- cmake
- libprotobuf-dev
- protobuf-compiler
@ -39,7 +43,6 @@ addons:
- libqt5svg5-dev
- libqt5sql5-mysql
before_install: bash ./.ci/travis-dependencies.sh
script: bash ./.ci/travis-compile.sh

View file

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

View file

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

View file

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

View file

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

View file

@ -1,28 +1,27 @@
#include "abstractclient.h"
#include "pending_command.h"
#include "client_metatypes.h"
#include "featureset.h"
#include "get_pb_extension.h"
#include "pb/commands.pb.h"
#include "pb/server_message.pb.h"
#include "pb/event_add_to_list.pb.h"
#include "pb/event_connection_closed.pb.h"
#include "pb/event_game_joined.pb.h"
#include "pb/event_list_rooms.pb.h"
#include "pb/event_notify_user.pb.h"
#include "pb/event_remove_from_list.pb.h"
#include "pb/event_replay_added.pb.h"
#include "pb/event_server_identification.pb.h"
#include "pb/event_server_message.pb.h"
#include "pb/event_server_shutdown.pb.h"
#include "pb/event_connection_closed.pb.h"
#include "pb/event_user_message.pb.h"
#include "pb/event_notify_user.pb.h"
#include "pb/event_list_rooms.pb.h"
#include "pb/event_add_to_list.pb.h"
#include "pb/event_remove_from_list.pb.h"
#include "pb/event_user_joined.pb.h"
#include "pb/event_user_left.pb.h"
#include "pb/event_game_joined.pb.h"
#include "pb/event_replay_added.pb.h"
#include "get_pb_extension.h"
#include "pb/event_user_message.pb.h"
#include "pb/server_message.pb.h"
#include "pending_command.h"
#include <google/protobuf/descriptor.h>
#include "client_metatypes.h"
#include "featureset.h"
AbstractClient::AbstractClient(QObject *parent)
: QObject(parent), nextCmdId(0), status(StatusDisconnected)
AbstractClient::AbstractClient(QObject *parent) : QObject(parent), nextCmdId(0), status(StatusDisconnected)
{
qRegisterMetaType<QVariant>("QVariant");
qRegisterMetaType<CommandContainer>("CommandContainer");
@ -44,9 +43,9 @@ AbstractClient::AbstractClient(QObject *parent)
qRegisterMetaType<Event_UserMessage>("Event_UserMessage");
qRegisterMetaType<Event_NotifyUser>("Event_NotifyUser");
qRegisterMetaType<ServerInfo_User>("ServerInfo_User");
qRegisterMetaType<QList<ServerInfo_User> >("QList<ServerInfo_User>");
qRegisterMetaType<QList<ServerInfo_User>>("QList<ServerInfo_User>");
qRegisterMetaType<Event_ReplayAdded>("Event_ReplayAdded");
qRegisterMetaType<QList<QString> >("missingFeatures");
qRegisterMetaType<QList<QString>>("missingFeatures");
FeatureSet features;
features.initalizeFeatureList(clientFeatures);
@ -76,21 +75,48 @@ void AbstractClient::processProtocolItem(const ServerMessage &item)
}
case ServerMessage::SESSION_EVENT: {
const SessionEvent &event = item.session_event();
switch ((SessionEvent::SessionEventType) getPbExtension(event)) {
case SessionEvent::SERVER_IDENTIFICATION: emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext)); break;
case SessionEvent::SERVER_MESSAGE: emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext)); break;
case SessionEvent::SERVER_SHUTDOWN: emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext)); break;
case SessionEvent::CONNECTION_CLOSED: emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext)); break;
case SessionEvent::USER_MESSAGE: emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext)); break;
case SessionEvent::NOTIFY_USER: emit notifyUserEventReceived(event.GetExtension(Event_NotifyUser::ext)); break;
case SessionEvent::LIST_ROOMS: emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext)); break;
case SessionEvent::ADD_TO_LIST: emit addToListEventReceived(event.GetExtension(Event_AddToList::ext)); break;
case SessionEvent::REMOVE_FROM_LIST: emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext)); break;
case SessionEvent::USER_JOINED: emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext)); break;
case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break;
case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break;
case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break;
default: break;
switch ((SessionEvent::SessionEventType)getPbExtension(event)) {
case SessionEvent::SERVER_IDENTIFICATION:
emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext));
break;
case SessionEvent::SERVER_MESSAGE:
emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext));
break;
case SessionEvent::SERVER_SHUTDOWN:
emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext));
break;
case SessionEvent::CONNECTION_CLOSED:
emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext));
break;
case SessionEvent::USER_MESSAGE:
emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext));
break;
case SessionEvent::NOTIFY_USER:
emit notifyUserEventReceived(event.GetExtension(Event_NotifyUser::ext));
break;
case SessionEvent::LIST_ROOMS:
emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext));
break;
case SessionEvent::ADD_TO_LIST:
emit addToListEventReceived(event.GetExtension(Event_AddToList::ext));
break;
case SessionEvent::REMOVE_FROM_LIST:
emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext));
break;
case SessionEvent::USER_JOINED:
emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext));
break;
case SessionEvent::USER_LEFT:
emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext));
break;
case SessionEvent::GAME_JOINED:
emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext));
break;
case SessionEvent::REPLAY_ADDED:
emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext));
break;
default:
break;
}
break;
}

View file

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

View file

@ -1,16 +1,24 @@
#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_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)
: QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), useNameForShortcut(_useNameForShortcut), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea)
AbstractCounter::AbstractCounter(Player *_player,
int _id,
const QString &_name,
bool _shownInCounterArea,
int _value,
bool _useNameForShortcut,
QGraphicsItem *parent)
: QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value),
useNameForShortcut(_useNameForShortcut), hovered(false), aDec(0), aInc(0), dialogSemaphore(false),
deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea)
{
setAcceptHoverEvents(true);
@ -38,7 +46,7 @@ AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name,
} else
menu = nullptr;
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts()));
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts()));
refreshShortcuts();
retranslateUi();
}
@ -93,7 +101,7 @@ void AbstractCounter::setShortcutsInactive()
void AbstractCounter::refreshShortcuts()
{
if(shortcutActive)
if (shortcutActive)
setShortcutsActive();
}
@ -123,7 +131,7 @@ void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
menu->exec(event->screenPos());
event->accept();
}
}else
} else
event->ignore();
}
@ -152,8 +160,8 @@ void AbstractCounter::setCounter()
{
bool ok;
dialogSemaphore = true;
int newValue =
QInputDialog::getInt(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok);
int newValue = QInputDialog::getInt(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value,
-2000000000, 2000000000, 1, &ok);
if (deleteAfterDialog) {
deleteLater();
return;

View file

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

View file

@ -1,7 +1,12 @@
#include "abstractgraphicsitem.h"
#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();
@ -27,9 +32,13 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QC
qreal yOffset = 20;
qreal spacing = 2;
if (position < 2)
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h);
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
yOffset, w, h);
else
textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h);
textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
yOffset + (spacing + h) * (position / 2), w, h);
}
painter->drawEllipse(textRect);

View file

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

View file

@ -2,16 +2,16 @@
#include <cmath>
#include "arrowitem.h"
#include "playertarget.h"
#include "carditem.h"
#include "carddatabase.h"
#include "carditem.h"
#include "cardzone.h"
#include "player.h"
#include "playertarget.h"
#include "settingscache.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsScene>
#include <QDebug>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include "color.h"
#include "pb/command_attach_card.pb.h"
@ -19,7 +19,8 @@
#include "pb/command_delete_arrow.pb.h"
ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &_color)
: QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color), fullColor(true)
: QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color),
fullColor(true)
{
qDebug() << "ArrowItem constructor: startItem=" << static_cast<QGraphicsItem *>(startItem);
setZValue(2000000005);
@ -60,7 +61,8 @@ void ArrowItem::updatePath()
if (!targetItem)
return;
QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2));
QPointF endPoint = targetItem->mapToScene(
QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2));
updatePath(endPoint);
}
@ -68,13 +70,15 @@ void ArrowItem::updatePath(const QPointF &endPoint)
{
const double arrowWidth = 15.0;
const double headWidth = 40.0;
const double headLength = headWidth / pow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++
const double headLength =
headWidth / pow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++
const double phi = 15;
if (!startItem)
return;
QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2));
QPointF startPoint =
startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2));
QLineF line(startPoint, endPoint);
qreal lineLength = line.length();
@ -92,10 +96,14 @@ void ArrowItem::updatePath(const QPointF &endPoint)
QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage);
QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001));
qreal alpha = testLine.angle() - 90;
QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
QPointF endPoint1 =
arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
QPointF endPoint2 =
arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
QPointF point1 =
endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
QPointF point2 =
endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
path.quadTo(c, endPoint1);
@ -229,15 +237,15 @@ void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
PlayerTarget *targetPlayer = qgraphicsitem_cast<PlayerTarget *>(targetItem);
cmd.set_target_player_id(targetPlayer->getOwner()->getId());
}
if (startZone->getName().compare("hand") == 0) {
if (startZone->getName().compare("hand") == 0) {
startCard->playCard(false);
CardInfo *ci = startCard->getInfo();
if (ci && (((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) ||
((settingsCache->getPlayToStack() && ci->getTableRow() != 0) &&
startCard->getZone()->getName().toStdString() != "stack"))))
((settingsCache->getPlayToStack() && ci->getTableRow() != 0) &&
startCard->getZone()->getName().toStdString() != "stack"))))
cmd.set_start_zone("stack");
else
cmd.set_start_zone(settingsCache->getPlayToStack() ? "stack" :"table");
cmd.set_start_zone(settingsCache->getPlayToStack() ? "stack" : "table");
}
player->sendGameCommand(cmd);
}

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,14 @@
#ifndef CARDDATABASE_H
#define CARDDATABASE_H
#include <QHash>
#include <QPixmap>
#include <QMap>
#include <QDate>
#include <QDataStream>
#include <QList>
#include <QXmlStreamReader>
#include <QBasicMutex>
#include <QDataStream>
#include <QDate>
#include <QHash>
#include <QList>
#include <QMap>
#include <QPixmap>
#include <QXmlStreamReader>
class CardDatabase;
class CardInfo;
@ -21,174 +21,324 @@ typedef QMap<QString, int> MuidMap;
class CardSet : public QList<CardInfo *>
{
private:
QString shortName, longName;
unsigned int sortKey;
QDate releaseDate;
QString setType;
bool enabled, isknown;
private:
QString shortName, longName;
unsigned int sortKey;
QDate releaseDate;
QString setType;
bool enabled, isknown;
public:
explicit CardSet(const QString &_shortName = QString(), const QString &_longName = QString(), const QString &_setType = QString(), const QDate &_releaseDate = QDate());
QString getCorrectedShortName() const;
QString getShortName() const { return shortName; }
QString getLongName() const { return longName; }
QString getSetType() const { return setType; }
QDate getReleaseDate() const { return releaseDate; }
void setLongName(QString & _longName) { longName = _longName; }
void setSetType(QString & _setType) { setType = _setType; }
void setReleaseDate(QDate & _releaseDate) { releaseDate = _releaseDate; }
public:
explicit CardSet(const QString &_shortName = QString(),
const QString &_longName = QString(),
const QString &_setType = QString(),
const QDate &_releaseDate = QDate());
QString getCorrectedShortName() const;
QString getShortName() const
{
return shortName;
}
QString getLongName() const
{
return longName;
}
QString getSetType() const
{
return setType;
}
QDate getReleaseDate() const
{
return releaseDate;
}
void setLongName(QString &_longName)
{
longName = _longName;
}
void setSetType(QString &_setType)
{
setType = _setType;
}
void setReleaseDate(QDate &_releaseDate)
{
releaseDate = _releaseDate;
}
void loadSetOptions();
int getSortKey() const { return sortKey; }
void setSortKey(unsigned int _sortKey);
bool getEnabled() const { return enabled; }
void setEnabled(bool _enabled);
bool getIsKnown() const { return isknown; }
void setIsKnown(bool _isknown);
void loadSetOptions();
int getSortKey() const
{
return sortKey;
}
void setSortKey(unsigned int _sortKey);
bool getEnabled() const
{
return enabled;
}
void setEnabled(bool _enabled);
bool getIsKnown() const
{
return isknown;
}
void setIsKnown(bool _isknown);
//Determine incomplete sets.
bool getIsKnownIgnored() const { return longName.length() + setType.length() + releaseDate.toString().length() == 0 ; }
// Determine incomplete sets.
bool getIsKnownIgnored() const
{
return longName.length() + setType.length() + releaseDate.toString().length() == 0;
}
};
class SetList : public QList<CardSet *>
{
private:
class KeyCompareFunctor;
private:
class KeyCompareFunctor;
public:
void sortByKey();
void guessSortKeys();
void enableAllUnknown();
void enableAll();
void markAllAsKnown();
int getEnabledSetsNum();
int getUnknownSetsNum();
QStringList getUnknownSetsNames();
public:
void sortByKey();
void guessSortKeys();
void enableAllUnknown();
void enableAll();
void markAllAsKnown();
int getEnabledSetsNum();
int getUnknownSetsNum();
QStringList getUnknownSetsNames();
};
class CardInfo : public QObject
{
Q_OBJECT
private:
QString name;
private:
QString name;
/*
* The name without punctuation or capitalization, for better card tag name
* recognition.
*/
QString simpleName;
/*
* The name without punctuation or capitalization, for better card tag name
* recognition.
*/
QString simpleName;
bool isToken;
SetList sets;
QString manacost;
QString cmc;
QString cardtype;
QString powtough;
QString text;
QStringList colors;
bool isToken;
SetList sets;
QString manacost;
QString cmc;
QString cardtype;
QString powtough;
QString text;
QStringList colors;
// the cards i'm related to
QList<CardRelation *> relatedCards;
// the cards i'm related to
QList<CardRelation *> relatedCards;
// the card i'm reverse-related to
QList<CardRelation *> reverseRelatedCards;
// the card i'm reverse-related to
QList<CardRelation *> reverseRelatedCards;
// the cards thare are reverse-related to me
QList<CardRelation *> reverseRelatedCardsToMe;
// the cards thare are reverse-related to me
QList<CardRelation *> reverseRelatedCardsToMe;
QString setsNames;
QString setsNames;
bool upsideDownArt;
int loyalty;
QStringMap customPicURLs;
MuidMap muIds;
QStringMap collectorNumbers;
QStringMap rarities;
bool cipt;
int tableRow;
QString pixmapCacheKey;
bool upsideDownArt;
int loyalty;
QStringMap customPicURLs;
MuidMap muIds;
QStringMap collectorNumbers;
QStringMap rarities;
bool cipt;
int tableRow;
QString pixmapCacheKey;
public:
explicit CardInfo(const QString &_name = QString(),
bool _isToken = false,
const QString &_manacost = QString(),
const QString &_cmc = QString(),
const QString &_cardtype = QString(),
const QString &_powtough = QString(),
const QString &_text = QString(),
const QStringList &_colors = QStringList(),
const QList<CardRelation *> &_relatedCards = QList<CardRelation *>(),
const QList<CardRelation *> &_reverseRelatedCards = QList<CardRelation *>(),
bool _upsideDownArt = false,
int _loyalty = 0,
bool _cipt = false,
int _tableRow = 0,
const SetList &_sets = SetList(),
const QStringMap &_customPicURLs = QStringMap(),
MuidMap muids = MuidMap(),
QStringMap _collectorNumbers = QStringMap(),
QStringMap _rarities = QStringMap()
);
~CardInfo() override;
public:
explicit CardInfo(const QString &_name = QString(),
bool _isToken = false,
const QString &_manacost = QString(),
const QString &_cmc = QString(),
const QString &_cardtype = QString(),
const QString &_powtough = QString(),
const QString &_text = QString(),
const QStringList &_colors = QStringList(),
const QList<CardRelation *> &_relatedCards = QList<CardRelation *>(),
const QList<CardRelation *> &_reverseRelatedCards = QList<CardRelation *>(),
bool _upsideDownArt = false,
int _loyalty = 0,
bool _cipt = false,
int _tableRow = 0,
const SetList &_sets = SetList(),
const QStringMap &_customPicURLs = QStringMap(),
MuidMap muids = MuidMap(),
QStringMap _collectorNumbers = QStringMap(),
QStringMap _rarities = QStringMap());
~CardInfo() override;
inline const QString &getName() const { return name; }
inline const QString &getSetsNames() const { return setsNames; }
const QString &getSimpleName() const { return simpleName; }
bool getIsToken() const { return isToken; }
const SetList &getSets() const { return sets; }
inline const QString &getManaCost() const { return manacost; }
inline const QString &getCmc() const { return cmc; }
inline const QString &getCardType() const { return cardtype; }
inline const QString &getPowTough() const { return powtough; }
const QString &getText() const { return text; }
const QString &getPixmapCacheKey() const { return pixmapCacheKey; }
const int &getLoyalty() const { return loyalty; }
bool getCipt() const { return cipt; }
//void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); }
//void setCmc(const QString &_cmc) { cmc = _cmc; emit cardInfoChanged(this); }
void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); }
void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); }
void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); }
void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); }
const QChar getColorChar() const;
const QStringList &getColors() const { return colors; }
const QList<CardRelation *> &getRelatedCards() const { return relatedCards; }
const QList<CardRelation *> &getReverseRelatedCards() const { return reverseRelatedCards; }
const QList<CardRelation *> &getReverseRelatedCards2Me() const { return reverseRelatedCardsToMe; }
void resetReverseRelatedCards2Me();
void addReverseRelatedCards2Me(CardRelation * cardRelation) { reverseRelatedCardsToMe.append(cardRelation); }
bool getUpsideDownArt() const { return upsideDownArt; }
QString getCustomPicURL(const QString &set) const { return customPicURLs.value(set); }
int getMuId(const QString &set) const { return muIds.value(set); }
QString getCollectorNumber(const QString &set) const { return collectorNumbers.value(set); }
QString getRarity(const QString &set) const { return rarities.value(set); }
QStringMap getRarities() const { return rarities; }
QString getMainCardType() const;
QString getCorrectedName() const;
int getTableRow() const { return tableRow; }
void setTableRow(int _tableRow) { tableRow = _tableRow; }
//void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); }
//void setCustomPicURL(const QString &_set, const QString &_customPicURL) { customPicURLs.insert(_set, _customPicURL); }
void setMuId(const QString &_set, const int &_muId) { muIds.insert(_set, _muId); }
void setSetNumber(const QString &_set, const QString &_setNumber) { collectorNumbers.insert(_set, _setNumber); }
void setRarity(const QString &_set, const QString &_setNumber) { rarities.insert(_set, _setNumber); }
void addToSet(CardSet *set);
void emitPixmapUpdated() { emit pixmapUpdated(); }
void refreshCachedSetNames();
inline const QString &getName() const
{
return name;
}
inline const QString &getSetsNames() const
{
return setsNames;
}
const QString &getSimpleName() const
{
return simpleName;
}
bool getIsToken() const
{
return isToken;
}
const SetList &getSets() const
{
return sets;
}
inline const QString &getManaCost() const
{
return manacost;
}
inline const QString &getCmc() const
{
return cmc;
}
inline const QString &getCardType() const
{
return cardtype;
}
inline const QString &getPowTough() const
{
return powtough;
}
const QString &getText() const
{
return text;
}
const QString &getPixmapCacheKey() const
{
return pixmapCacheKey;
}
const int &getLoyalty() const
{
return loyalty;
}
bool getCipt() const
{
return cipt;
}
// void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); }
// void setCmc(const QString &_cmc) { cmc = _cmc; emit cardInfoChanged(this); }
void setCardType(const QString &_cardType)
{
cardtype = _cardType;
emit cardInfoChanged(this);
}
void setPowTough(const QString &_powTough)
{
powtough = _powTough;
emit cardInfoChanged(this);
}
void setText(const QString &_text)
{
text = _text;
emit cardInfoChanged(this);
}
void setColors(const QStringList &_colors)
{
colors = _colors;
emit cardInfoChanged(this);
}
const QChar getColorChar() const;
const QStringList &getColors() const
{
return colors;
}
const QList<CardRelation *> &getRelatedCards() const
{
return relatedCards;
}
const QList<CardRelation *> &getReverseRelatedCards() const
{
return reverseRelatedCards;
}
const QList<CardRelation *> &getReverseRelatedCards2Me() const
{
return reverseRelatedCardsToMe;
}
void resetReverseRelatedCards2Me();
void addReverseRelatedCards2Me(CardRelation *cardRelation)
{
reverseRelatedCardsToMe.append(cardRelation);
}
bool getUpsideDownArt() const
{
return upsideDownArt;
}
QString getCustomPicURL(const QString &set) const
{
return customPicURLs.value(set);
}
int getMuId(const QString &set) const
{
return muIds.value(set);
}
QString getCollectorNumber(const QString &set) const
{
return collectorNumbers.value(set);
}
QString getRarity(const QString &set) const
{
return rarities.value(set);
}
QStringMap getRarities() const
{
return rarities;
}
QString getMainCardType() const;
QString getCorrectedName() const;
int getTableRow() const
{
return tableRow;
}
void setTableRow(int _tableRow)
{
tableRow = _tableRow;
}
// void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); }
// void setCustomPicURL(const QString &_set, const QString &_customPicURL) { customPicURLs.insert(_set,
// _customPicURL); }
void setMuId(const QString &_set, const int &_muId)
{
muIds.insert(_set, _muId);
}
void setSetNumber(const QString &_set, const QString &_setNumber)
{
collectorNumbers.insert(_set, _setNumber);
}
void setRarity(const QString &_set, const QString &_setNumber)
{
rarities.insert(_set, _setNumber);
}
void addToSet(CardSet *set);
void emitPixmapUpdated()
{
emit pixmapUpdated();
}
void refreshCachedSetNames();
/**
* Simplify a name to have no punctuation and lowercase all letters, for
* less strict name-matching.
*/
static QString simplifyName(const QString &name);
/**
* Simplify a name to have no punctuation and lowercase all letters, for
* less strict name-matching.
*/
static QString simplifyName(const QString &name);
signals:
void pixmapUpdated();
void cardInfoChanged(CardInfo *card);
signals:
void pixmapUpdated();
void cardInfoChanged(CardInfo *card);
};
enum LoadStatus { Ok, VersionTooOld, Invalid, NotLoaded, FileError, NoCards };
enum LoadStatus
{
Ok,
VersionTooOld,
Invalid,
NotLoaded,
FileError,
NoCards
};
typedef QHash<QString, CardInfo *> CardNameMap;
typedef QHash<QString, CardSet *> SetNameMap;
@ -196,103 +346,126 @@ typedef QHash<QString, CardSet *> SetNameMap;
class CardDatabase : public QObject
{
Q_OBJECT
protected:
/*
* The cards, indexed by name.
*/
CardNameMap cards;
protected:
/*
* The cards, indexed by name.
*/
CardNameMap cards;
/**
* The cards, indexed by their simple name.
*/
CardNameMap simpleNameCards;
/**
* The cards, indexed by their simple name.
*/
CardNameMap simpleNameCards;
/*
* The sets, indexed by short name.
*/
SetNameMap sets;
/*
* The sets, indexed by short name.
*/
SetNameMap sets;
LoadStatus loadStatus;
private:
static const int versionNeeded;
void loadCardsFromXml(QXmlStreamReader &xml);
void loadSetsFromXml(QXmlStreamReader &xml);
LoadStatus loadStatus;
CardInfo *getCardFromMap(const CardNameMap &cardMap, const QString &cardName) const;
void checkUnknownSets();
void refreshCachedReverseRelatedCards();
private:
static const int versionNeeded;
void loadCardsFromXml(QXmlStreamReader &xml);
void loadSetsFromXml(QXmlStreamReader &xml);
QBasicMutex *reloadDatabaseMutex = new QBasicMutex(),
*clearDatabaseMutex = new QBasicMutex(),
*loadFromFileMutex = new QBasicMutex(),
*addCardMutex = new QBasicMutex(),
CardInfo *getCardFromMap(const CardNameMap &cardMap, const QString &cardName) const;
void checkUnknownSets();
void refreshCachedReverseRelatedCards();
QBasicMutex *reloadDatabaseMutex = new QBasicMutex(), *clearDatabaseMutex = new QBasicMutex(),
*loadFromFileMutex = new QBasicMutex(), *addCardMutex = new QBasicMutex(),
*removeCardMutex = new QBasicMutex();
public:
static const char* TOKENS_SETNAME;
public:
static const char *TOKENS_SETNAME;
explicit CardDatabase(QObject *parent = nullptr);
~CardDatabase() override;
void clear();
void addCard(CardInfo *card);
void removeCard(CardInfo *card);
CardInfo *getCard(const QString &cardName) const;
QList <CardInfo *> getCards(const QStringList &cardNames) const;
explicit CardDatabase(QObject *parent = nullptr);
~CardDatabase() override;
void clear();
void addCard(CardInfo *card);
void removeCard(CardInfo *card);
CardInfo *getCard(const QString &cardName) const;
QList<CardInfo *> getCards(const QStringList &cardNames) const;
/*
* Get a card by its simple name. The name will be simplified in this
* function, so you don't need to simplify it beforehand.
*/
CardInfo *getCardBySimpleName(const QString &cardName) const;
/*
* Get a card by its simple name. The name will be simplified in this
* function, so you don't need to simplify it beforehand.
*/
CardInfo *getCardBySimpleName(const QString &cardName) const;
CardSet *getSet(const QString &setName);
QList<CardInfo *> getCardList() const { return cards.values(); }
SetList getSetList() const;
LoadStatus loadFromFile(const QString &fileName);
bool saveToFile(const QString &fileName, bool tokens = false);
bool saveCustomTokensToFile();
QStringList getAllColors() const;
QStringList getAllMainCardTypes() const;
LoadStatus getLoadStatus() const { return loadStatus; }
void enableAllUnknownSets();
void markAllSetsAsKnown();
void notifyEnabledSetsChanged();
CardSet *getSet(const QString &setName);
QList<CardInfo *> getCardList() const
{
return cards.values();
}
SetList getSetList() const;
LoadStatus loadFromFile(const QString &fileName);
bool saveToFile(const QString &fileName, bool tokens = false);
bool saveCustomTokensToFile();
QStringList getAllColors() const;
QStringList getAllMainCardTypes() const;
LoadStatus getLoadStatus() const
{
return loadStatus;
}
void enableAllUnknownSets();
void markAllSetsAsKnown();
void notifyEnabledSetsChanged();
public slots:
LoadStatus loadCardDatabases();
private slots:
LoadStatus loadCardDatabase(const QString &path);
signals:
void cardDatabaseLoadingFailed();
void cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknownSetsNames);
void cardDatabaseAllNewSetsEnabled();
void cardDatabaseEnabledSetsChanged();
void cardAdded(CardInfo *card);
void cardRemoved(CardInfo *card);
public slots:
LoadStatus loadCardDatabases();
private slots:
LoadStatus loadCardDatabase(const QString &path);
signals:
void cardDatabaseLoadingFailed();
void cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknownSetsNames);
void cardDatabaseAllNewSetsEnabled();
void cardDatabaseEnabledSetsChanged();
void cardAdded(CardInfo *card);
void cardRemoved(CardInfo *card);
};
class CardRelation : public QObject
{
Q_OBJECT
private:
QString name;
bool doesAttach;
bool isCreateAllExclusion;
bool isVariableCount;
int defaultCount;
public:
explicit CardRelation(const QString &_name = QString(),
bool _doesAttach = false,
bool _isCreateAllExclusion = false,
bool _isVariableCount = false,
int _defaultCount = 1
);
private:
QString name;
bool doesAttach;
bool isCreateAllExclusion;
bool isVariableCount;
int defaultCount;
inline const QString &getName() const { return name; }
bool getDoesAttach() const { return doesAttach; }
bool getCanCreateAnother() const { return !doesAttach; }
bool getIsCreateAllExclusion() const { return isCreateAllExclusion; }
bool getIsVariable() const { return isVariableCount; }
int getDefaultCount() const { return defaultCount; }
public:
explicit CardRelation(const QString &_name = QString(),
bool _doesAttach = false,
bool _isCreateAllExclusion = false,
bool _isVariableCount = false,
int _defaultCount = 1);
inline const QString &getName() const
{
return name;
}
bool getDoesAttach() const
{
return doesAttach;
}
bool getCanCreateAnother() const
{
return !doesAttach;
}
bool getIsCreateAllExclusion() const
{
return isCreateAllExclusion;
}
bool getIsVariable() const
{
return isVariableCount;
}
int getDefaultCount() const
{
return defaultCount;
}
};
#endif

View file

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

View file

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

View file

@ -1,14 +1,18 @@
#include "carddragitem.h"
#include "carditem.h"
#include "cardzone.h"
#include "gamescene.h"
#include "tablezone.h"
#include "zoneviewzone.h"
#include "gamescene.h"
#include <QGraphicsSceneMouseEvent>
#include <QCursor>
#include <QGraphicsSceneMouseEvent>
#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)
{
}
@ -23,7 +27,9 @@ void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
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;
ZoneViewZone *zoneViewZone = 0;
@ -85,7 +91,7 @@ void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
}
}
if(currentZone)
if (currentZone)
currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint());
event->accept();

View file

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

View file

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

View file

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

View file

@ -13,26 +13,31 @@ class QSplitter;
class CardFrame : public QTabWidget
{
Q_OBJECT
private:
CardInfo *info;
CardInfoPicture *pic;
CardInfoText *text;
bool cardTextOnly;
QWidget *tab1, *tab2, *tab3;
QVBoxLayout *tab1Layout, *tab2Layout, *tab3Layout;
QSplitter *splitter;
private:
CardInfo *info;
CardInfoPicture *pic;
CardInfoText *text;
bool cardTextOnly;
QWidget *tab1, *tab2, *tab3;
QVBoxLayout *tab1Layout, *tab2Layout, *tab3Layout;
QSplitter *splitter;
public:
enum ViewMode { ImageOnlyView, TextOnlyView, ImageAndTextView };
explicit CardFrame(const QString &cardName = QString(), QWidget *parent = nullptr);
void retranslateUi();
public:
enum ViewMode
{
ImageOnlyView,
TextOnlyView,
ImageAndTextView
};
explicit CardFrame(const QString &cardName = QString(), QWidget *parent = nullptr);
void retranslateUi();
public slots:
void setCard(CardInfo *card);
void setCard(const QString &cardName);
void setCard(AbstractCardItem *card);
void clear();
void setViewMode(int mode);
public slots:
void setCard(CardInfo *card);
void setCard(const QString &cardName);
void setCard(AbstractCardItem *card);
void clear();
void setViewMode(int mode);
};
#endif

View file

@ -1,33 +1,28 @@
#include "cardinfopicture.h"
#include <QWidget>
#include <QPainter>
#include <QStyle>
#include <QWidget>
#include "carditem.h"
#include "carddatabase.h"
#include "pictureloader.h"
#include "carditem.h"
#include "main.h"
#include "pictureloader.h"
CardInfoPicture::CardInfoPicture(QWidget *parent)
: QWidget(parent),
info(nullptr),
pixmapDirty(true)
CardInfoPicture::CardInfoPicture(QWidget *parent) : QWidget(parent), info(nullptr), pixmapDirty(true)
{
setMinimumHeight(100);
}
void CardInfoPicture::setCard(CardInfo *card)
{
if (info)
{
if (info) {
disconnect(info, nullptr, this, nullptr);
}
info = card;
if (info)
{
if (info) {
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap()));
}
@ -47,7 +42,7 @@ void CardInfoPicture::updatePixmap()
void CardInfoPicture::loadPixmap()
{
if(info)
if (info)
PictureLoader::getPixmap(resizedPixmap, info, size());
else
PictureLoader::getCardBackPixmap(resizedPixmap, size());
@ -58,7 +53,7 @@ void CardInfoPicture::paintEvent(QPaintEvent *)
if (width() == 0 || height() == 0)
return;
if(pixmapDirty)
if (pixmapDirty)
loadPixmap();
QPainter painter(this);

View file

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

View file

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

View file

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

View file

@ -1,16 +1,14 @@
#include <QVBoxLayout>
#include <QDesktopWidget>
#include "cardinfowidget.h"
#include "carditem.h"
#include "carddatabase.h"
#include "cardinfopicture.h"
#include "cardinfotext.h"
#include "carditem.h"
#include "main.h"
#include <QDesktopWidget>
#include <QVBoxLayout>
CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::WindowFlags flags)
: QFrame(parent, flags)
, aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH)
, info(nullptr)
: QFrame(parent, flags), aspectRatio((qreal)CARD_HEIGHT / (qreal)CARD_WIDTH), info(nullptr)
{
setContentsMargins(3, 3, 3, 3);
pic = new CardInfoPicture();
@ -18,7 +16,7 @@ CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::Win
text = new CardInfoText();
text->setObjectName("text");
QVBoxLayout * layout = new QVBoxLayout();
QVBoxLayout *layout = new QVBoxLayout();
layout->setObjectName("layout");
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
@ -45,7 +43,7 @@ void CardInfoWidget::setCard(CardInfo *card)
if (info)
disconnect(info, nullptr, this, nullptr);
info = card;
if(info)
if (info)
connect(info, SIGNAL(destroyed()), this, SLOT(clear()));
text->setCard(info);
@ -64,5 +62,5 @@ void CardInfoWidget::setCard(AbstractCardItem *card)
void CardInfoWidget::clear()
{
setCard((CardInfo *) nullptr);
setCard((CardInfo *)nullptr);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,7 +2,14 @@
#include "pixmapgenerator.h"
#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)
{
setCacheMode(DeviceCoordinateCache);
@ -26,7 +33,7 @@ void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /
if (value) {
QFont f("Serif");
f.setPixelSize(qMax((int) (radius * scaleFactor), 10));
f.setPixelSize(qMax((int)(radius * scaleFactor), 10));
f.setWeight(QFont::Bold);
painter->setPen(Qt::black);
painter->setFont(f);

View file

@ -3,13 +3,22 @@
#include "abstractcounter.h"
class GeneralCounter : public AbstractCounter {
class GeneralCounter : public AbstractCounter
{
Q_OBJECT
private:
QColor color;
int radius;
public:
GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, bool useNameForShortcut = false, QGraphicsItem *parent = 0);
GeneralCounter(Player *_player,
int _id,
const QString &_name,
const QColor &_color,
int _radius,
int _value,
bool useNameForShortcut = false,
QGraphicsItem *parent = 0);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
};

View file

@ -1,53 +1,50 @@
#include <QStringList>
#include <QFile>
#include <QDebug>
#include "deck_loader.h"
#include "decklist.h"
#include "carddatabase.h"
#include "decklist.h"
#include "main.h"
#include <QDebug>
#include <QFile>
#include <QStringList>
const QStringList DeckLoader::fileNameFilters = QStringList()
<< QObject::tr("Common deck formats (*.cod *.dec *.txt *.mwDeck)")
<< QObject::tr("All files (*.*)");
const QStringList DeckLoader::fileNameFilters =
QStringList() << QObject::tr("Common deck formats (*.cod *.dec *.txt *.mwDeck)") << QObject::tr("All files (*.*)");
DeckLoader::DeckLoader() : DeckList(), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1)
{
}
DeckLoader::DeckLoader(const QString &nativeString) : DeckList(nativeString), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1)
DeckLoader::DeckLoader(const QString &nativeString)
: DeckList(nativeString), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1)
{
}
DeckLoader::DeckLoader(const DeckList &other) : DeckList(other), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1)
DeckLoader::DeckLoader(const DeckList &other)
: DeckList(other), lastFileName(QString()), lastFileFormat(CockatriceFormat), lastRemoteDeckId(-1)
{
}
DeckLoader::DeckLoader(const DeckLoader &other) : DeckList(other), lastFileName(other.lastFileName), lastFileFormat(other.lastFileFormat), lastRemoteDeckId(other.lastRemoteDeckId)
DeckLoader::DeckLoader(const DeckLoader &other)
: DeckList(other), lastFileName(other.lastFileName), lastFileFormat(other.lastFileFormat),
lastRemoteDeckId(other.lastRemoteDeckId)
{
}
bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return false;
}
bool result = false;
switch (fmt)
{
case PlainTextFormat: result = loadFromFile_Plain(&file); break;
case CockatriceFormat:
{
switch (fmt) {
case PlainTextFormat:
result = loadFromFile_Plain(&file);
break;
case CockatriceFormat: {
result = loadFromFile_Native(&file);
qDebug() << "Loaded from" << fileName << "-" << result;
if (!result)
{
if (!result) {
qDebug() << "Retying as plain format";
file.seek(0);
result = loadFromFile_Plain(&file);
@ -60,8 +57,7 @@ bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
break;
}
if (result)
{
if (result) {
lastFileName = fileName;
lastFileFormat = fmt;
@ -75,8 +71,7 @@ bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
{
bool result = loadFromString_Native(nativeString);
if (result)
{
if (result) {
lastFileName = QString();
lastFileFormat = CockatriceFormat;
lastRemoteDeckId = remoteDeckId;
@ -89,98 +84,96 @@ bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt)
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
bool result = false;
switch (fmt)
{
case PlainTextFormat: result = saveToFile_Plain(&file); break;
case CockatriceFormat: result = saveToFile_Native(&file); break;
switch (fmt) {
case PlainTextFormat:
result = saveToFile_Plain(&file);
break;
case CockatriceFormat:
result = saveToFile_Native(&file);
break;
}
if (result)
{
if (result) {
lastFileName = fileName;
lastFileFormat = fmt;
}
return result;
}
//This struct is here to support the forEachCard function call, defined in decklist. It
//requires a function to be called for each card, and passes an inner node and a card for
//each card in the decklist.
// This struct is here to support the forEachCard function call, defined in decklist. It
// requires a function to be called for each card, and passes an inner node and a card for
// each card in the decklist.
struct FormatDeckListForExport
{
//Create refrences for the strings that will be passed in.
// Create refrences for the strings that will be passed in.
QString &mainBoardCards;
QString &sideBoardCards;
//create main operator for struct, allowing the foreachcard to work.
FormatDeckListForExport(QString &_mainBoardCards, QString &_sideBoardCards) : mainBoardCards(_mainBoardCards), sideBoardCards(_sideBoardCards){};
// create main operator for struct, allowing the foreachcard to work.
FormatDeckListForExport(QString &_mainBoardCards, QString &_sideBoardCards)
: mainBoardCards(_mainBoardCards), sideBoardCards(_sideBoardCards){};
void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const
{
//Get the card name
CardInfo * dbCard = db->getCard(card->getName());
if (!dbCard || dbCard->getIsToken())
{
//If it's a token, we don't care about the card.
// Get the card name
CardInfo *dbCard = db->getCard(card->getName());
if (!dbCard || dbCard->getIsToken()) {
// If it's a token, we don't care about the card.
return;
}
//Check if it's a sideboard card.
if (node->getName() == DECK_ZONE_SIDE)
// Check if it's a sideboard card.
if (node->getName() == DECK_ZONE_SIDE) {
// Get the number of cards and add the card name
sideBoardCards += QString::number(card->getNumber());
// Add a space between card num and name
sideBoardCards += "%20";
// Add card name
sideBoardCards += card->getName();
// Add a return at the end of the card
sideBoardCards += "%0A";
} else // If it's a mainboard card, do the same thing, but for the mainboard card string
{
//Get the number of cards and add the card name
sideBoardCards+=QString::number(card->getNumber());
//Add a space between card num and name
sideBoardCards+="%20";
//Add card name
sideBoardCards+=card->getName();
//Add a return at the end of the card
sideBoardCards+="%0A";
}
else //If it's a mainboard card, do the same thing, but for the mainboard card string
{
mainBoardCards+=QString::number(card->getNumber());
mainBoardCards+="%20";
mainBoardCards+=card->getName();
mainBoardCards+="%0A";
mainBoardCards += QString::number(card->getNumber());
mainBoardCards += "%20";
mainBoardCards += card->getName();
mainBoardCards += "%0A";
}
}
};
//Export deck to decklist function, called to format the deck in a way to be sent to a server
// Export deck to decklist function, called to format the deck in a way to be sent to a server
QString DeckLoader::exportDeckToDecklist()
{
//Add the base url
// Add the base url
QString deckString = "https://www.decklist.org/?";
//Create two strings to pass to function
// Create two strings to pass to function
QString mainBoardCards, sideBoardCards;
//Set up the struct to call.
// Set up the struct to call.
FormatDeckListForExport formatDeckListForExport(mainBoardCards, sideBoardCards);
//call our struct function for each card in the deck
// call our struct function for each card in the deck
forEachCard(formatDeckListForExport);
//Remove the extra return at the end of the last cards
// Remove the extra return at the end of the last cards
mainBoardCards.chop(3);
sideBoardCards.chop(3);
//if after we've called it for each card, and the strings are empty, we know that
//there were no non-token cards in the deck, so show an error message.
if((QString::compare(mainBoardCards, "", Qt::CaseInsensitive) == 0) &&
(QString::compare(sideBoardCards, "", Qt::CaseInsensitive) == 0)) {
// if after we've called it for each card, and the strings are empty, we know that
// there were no non-token cards in the deck, so show an error message.
if ((QString::compare(mainBoardCards, "", Qt::CaseInsensitive) == 0) &&
(QString::compare(sideBoardCards, "", Qt::CaseInsensitive) == 0)) {
return "";
}
//return a string with the url for decklist export
deckString+="deckmain="+mainBoardCards+"&deckside="+sideBoardCards;
// return a string with the url for decklist export
deckString += "deckmain=" + mainBoardCards + "&deckside=" + sideBoardCards;
return deckString;
}
DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName)
{
if (fileName.endsWith(".cod", Qt::CaseInsensitive))
{
if (fileName.endsWith(".cod", Qt::CaseInsensitive)) {
return CockatriceFormat;
}
return PlainTextFormat;
@ -188,14 +181,12 @@ DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName)
bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments)
{
if (addComments)
{
if (addComments) {
saveToStream_DeckHeader(out);
}
// loop zones
for (int i = 0; i < getRoot()->size(); i++)
{
for (int i = 0; i < getRoot()->size(); i++) {
const auto *zoneNode = dynamic_cast<InnerDecklistNode *>(getRoot()->at(i));
saveToStream_DeckZone(out, zoneNode, addComments);
@ -209,16 +200,13 @@ bool DeckLoader::saveToStream_Plain(QTextStream &out, bool addComments)
void DeckLoader::saveToStream_DeckHeader(QTextStream &out)
{
if (!getName().isEmpty())
{
if (!getName().isEmpty()) {
out << "// " << getName() << "\n\n";
}
if (!getComments().isEmpty())
{
if (!getComments().isEmpty()) {
QStringList commentRows = getComments().split(QRegExp("\n|\r\n|\r"));
foreach(QString row, commentRows)
{
foreach (QString row, commentRows) {
out << "// " << row << "\n";
}
out << "\n";
@ -227,13 +215,12 @@ void DeckLoader::saveToStream_DeckHeader(QTextStream &out)
void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments)
{
// group cards by card type and count the subtotals
QMultiMap<QString, DecklistCardNode*> cardsByType;
// group cards by card type and count the subtotals
QMultiMap<QString, DecklistCardNode *> cardsByType;
QMap<QString, int> cardTotalByType;
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));
CardInfo *info = db->getCard(card->getName());
@ -241,51 +228,45 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode
cardsByType.insert(cardType, card);
if (cardTotalByType.contains(cardType))
{
if (cardTotalByType.contains(cardType)) {
cardTotalByType[cardType] += card->getNumber();
}
else
{
} else {
cardTotalByType[cardType] = card->getNumber();
}
cardTotal += card->getNumber();
}
if (addComments)
{
if (addComments) {
out << "// " << cardTotal << " " << zoneNode->getVisibleName() << "\n";
}
// print cards to stream
foreach(QString cardType, cardsByType.uniqueKeys())
{
if (addComments)
{
foreach (QString cardType, cardsByType.uniqueKeys()) {
if (addComments) {
out << "// " << cardTotalByType[cardType] << " " << cardType << "\n";
}
QList <DecklistCardNode*> cards = cardsByType.values(cardType);
QList<DecklistCardNode *> cards = cardsByType.values(cardType);
saveToStream_DeckZoneCards(out, zoneNode, cards, addComments);
if (addComments)
{
if (addComments) {
out << "\n";
}
}
}
void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out, const InnerDecklistNode *zoneNode, QList <DecklistCardNode*> cards, bool addComments)
void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out,
const InnerDecklistNode *zoneNode,
QList<DecklistCardNode *> cards,
bool addComments)
{
// QMultiMap sorts values in reverse order
for (int i = cards.size() - 1; i >= 0; --i)
{
DecklistCardNode* card = cards[i];
for (int i = cards.size() - 1; i >= 0; --i) {
DecklistCardNode *card = cards[i];
if (zoneNode->getName() == DECK_ZONE_SIDE && addComments)
{
if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) {
out << "SB: ";
}
@ -297,8 +278,7 @@ QString DeckLoader::getCardZoneFromName(QString cardName, QString currentZoneNam
{
CardInfo *card = db->getCard(cardName);
if (card && card->getIsToken())
{
if (card && card->getIsToken()) {
return DECK_ZONE_TOKENS;
}
@ -307,11 +287,9 @@ QString DeckLoader::getCardZoneFromName(QString cardName, QString currentZoneNam
QString DeckLoader::getCompleteCardName(const QString cardName) const
{
if (db)
{
if (db) {
CardInfo *temp = db->getCardBySimpleName(cardName);
if (temp)
{
if (temp) {
return temp->getName();
}
}

View file

@ -6,43 +6,59 @@
class DeckLoader : public DeckList
{
Q_OBJECT
signals:
void deckLoaded();
signals:
void deckLoaded();
public:
enum FileFormat { PlainTextFormat, CockatriceFormat };
static const QStringList fileNameFilters;
public:
enum FileFormat
{
PlainTextFormat,
CockatriceFormat
};
static const QStringList fileNameFilters;
private:
QString lastFileName;
FileFormat lastFileFormat;
int lastRemoteDeckId;
private:
QString lastFileName;
FileFormat lastFileFormat;
int lastRemoteDeckId;
public:
DeckLoader();
DeckLoader(const QString &nativeString);
DeckLoader(const DeckList &other);
DeckLoader(const DeckLoader &other);
const QString &getLastFileName() const { return lastFileName; }
FileFormat getLastFileFormat() const { return lastFileFormat; }
int getLastRemoteDeckId() const { return lastRemoteDeckId; }
public:
DeckLoader();
DeckLoader(const QString &nativeString);
DeckLoader(const DeckList &other);
DeckLoader(const DeckLoader &other);
const QString &getLastFileName() const
{
return lastFileName;
}
FileFormat getLastFileFormat() const
{
return lastFileFormat;
}
int getLastRemoteDeckId() const
{
return lastRemoteDeckId;
}
static FileFormat getFormatFromName(const QString &fileName);
static FileFormat getFormatFromName(const QString &fileName);
bool loadFromFile(const QString &fileName, FileFormat fmt);
bool loadFromRemote(const QString &nativeString, int remoteDeckId);
bool saveToFile(const QString &fileName, FileFormat fmt);
QString exportDeckToDecklist();
bool loadFromFile(const QString &fileName, FileFormat fmt);
bool loadFromRemote(const QString &nativeString, int remoteDeckId);
bool saveToFile(const QString &fileName, FileFormat fmt);
QString exportDeckToDecklist();
// overload
bool saveToStream_Plain(QTextStream &out, bool addComments = true);
// overload
bool saveToStream_Plain(QTextStream &out, bool addComments = true);
protected:
void saveToStream_DeckHeader(QTextStream &out);
void saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments = true);
void saveToStream_DeckZoneCards(QTextStream &out, const InnerDecklistNode *zoneNode, QList <DecklistCardNode*> cards, bool addComments = true);
virtual QString getCardZoneFromName(QString cardName, QString currentZoneName);
virtual QString getCompleteCardName(const QString cardName) const;
protected:
void saveToStream_DeckHeader(QTextStream &out);
void saveToStream_DeckZone(QTextStream &out, const InnerDecklistNode *zoneNode, bool addComments = true);
void saveToStream_DeckZoneCards(QTextStream &out,
const InnerDecklistNode *zoneNode,
QList<DecklistCardNode *> cards,
bool addComments = true);
virtual QString getCardZoneFromName(QString cardName, QString currentZoneName);
virtual QString getCompleteCardName(const QString cardName) const;
};
#endif

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

View file

@ -1,9 +1,9 @@
#ifndef DECKLISTMODEL_H
#define DECKLISTMODEL_H
#include "decklist.h"
#include <QAbstractItemModel>
#include <QList>
#include "decklist.h"
class DeckLoader;
class CardDatabase;
@ -11,19 +11,40 @@ class QProgressDialog;
class QPrinter;
class QTextCursor;
class DecklistModelCardNode : public AbstractDecklistCardNode {
class DecklistModelCardNode : public AbstractDecklistCardNode
{
private:
DecklistCardNode *dataNode;
public:
DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { }
int getNumber() const { return dataNode->getNumber(); }
void setNumber(int _number) { dataNode->setNumber(_number); }
QString getName() const { return dataNode->getName(); }
void setName(const QString &_name) { dataNode->setName(_name); }
DecklistCardNode *getDataNode() const { return dataNode; }
DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent)
: AbstractDecklistCardNode(_parent), dataNode(_dataNode)
{
}
int getNumber() const
{
return dataNode->getNumber();
}
void setNumber(int _number)
{
dataNode->setNumber(_number);
}
QString getName() const
{
return dataNode->getName();
}
void setName(const QString &_name)
{
dataNode->setName(_name);
}
DecklistCardNode *getDataNode() const
{
return dataNode;
}
};
class DeckListModel : public QAbstractItemModel {
class DeckListModel : public QAbstractItemModel
{
Q_OBJECT
private slots:
void rebuildTree();
@ -31,11 +52,12 @@ public slots:
void printDeckList(QPrinter *printer);
signals:
void deckHashChanged();
public:
DeckListModel(QObject *parent = 0);
~DeckListModel();
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const;
int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex &parent) const;
@ -47,8 +69,12 @@ public:
QModelIndex addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway = false);
void sort(int column, Qt::SortOrder order);
void cleanList();
DeckLoader *getDeckList() const { return deckList; }
DeckLoader *getDeckList() const
{
return deckList;
}
void setDeckList(DeckLoader *_deck);
private:
DeckLoader *deckList;
InnerDecklistNode *root;
@ -62,7 +88,7 @@ private:
void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node);
template<typename T> T getNode(const QModelIndex &index) const
template <typename T> T getNode(const QModelIndex &index) const
{
if (!index.isValid())
return dynamic_cast<T>(root);

View file

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

View file

@ -10,7 +10,8 @@ class QNetworkAccessManager;
class QNetworkReply;
class DeckList;
class DeckStatsInterface : public QObject {
class DeckStatsInterface : public QObject
{
Q_OBJECT
private:
QNetworkAccessManager *manager;
@ -22,11 +23,12 @@ private:
* closest non-token card instead. So we construct a new deck which has no
* tokens.
*/
void copyDeckWithoutTokens(const DeckList &source, DeckList& destination);
void copyDeckWithoutTokens(const DeckList &source, DeckList &destination);
private slots:
void queryFinished(QNetworkReply *reply);
void getAnalyzeRequestData(DeckList *deck, QByteArray *data);
public:
DeckStatsInterface(CardDatabase &_cardDatabase, QObject *parent = 0);
void analyzeDeck(DeckList *deck);

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 <QGraphicsSceneMouseEvent>
#include <QMouseEvent>
#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)
{
}
@ -90,7 +92,8 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
2 * QApplication::startDragDistance())
return;
if (static_cast<DeckViewScene *>(scene())->getLocked())
@ -122,8 +125,7 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
if (static_cast<DeckViewScene *>(scene())->getLocked())
return;
if (event->button() == Qt::LeftButton)
{
if (event->button() == Qt::LeftButton) {
QList<MoveCard_ToZone> result;
QList<QGraphicsItem *> sel = scene()->selectedItems();
@ -156,8 +158,7 @@ void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
processHoverEvent();
}
DeckViewCardContainer::DeckViewCardContainer(const QString &_name)
: QGraphicsItem(), name(_name), width(0), height(0)
DeckViewCardContainer::DeckViewCardContainer(const QString &_name) : QGraphicsItem(), name(_name), width(0), height(0)
{
setCacheMode(DeviceCoordinateCache);
}
@ -181,7 +182,8 @@ void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsI
f.setPixelSize(24);
f.setWeight(QFont::Bold);
painter->setFont(f);
painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size()));
painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine,
InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size()));
f.setPixelSize(16);
painter->setFont(f);
@ -212,12 +214,12 @@ void DeckViewCardContainer::addCard(DeckViewCard *card)
void DeckViewCardContainer::removeCard(DeckViewCard *card)
{
cards.removeAt(cards.indexOf(card));
cardsByType.remove(card->getInfo() ? card->getInfo()->getMainCardType(): "", card);
cardsByType.remove(card->getInfo() ? card->getInfo()->getMainCardType() : "", card);
}
QList<QPair<int, int> > DeckViewCardContainer::getRowsAndCols() const
QList<QPair<int, int>> DeckViewCardContainer::getRowsAndCols() const
{
QList<QPair<int, int> > result;
QList<QPair<int, int>> result;
QList<QString> cardTypeList = cardsByType.uniqueKeys();
for (int i = 0; i < cardTypeList.size(); ++i)
result.append(QPair<int, int>(1, cardsByType.count(cardTypeList[i])));
@ -243,7 +245,7 @@ int DeckViewCardContainer::getCardTypeTextWidth() const
return maxCardTypeWidth + 15;
}
QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const
QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int>> &rowsAndCols) const
{
qreal totalHeight = 0;
qreal totalWidth = 0;
@ -258,20 +260,20 @@ QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int>
return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY);
}
bool DeckViewCardContainer::sortCardsByName(DeckViewCard * c1, DeckViewCard * c2)
bool DeckViewCardContainer::sortCardsByName(DeckViewCard *c1, DeckViewCard *c2)
{
if (c1 && c2)
return c1->getName() < c2->getName();
return c1->getName() < c2->getName();
return false;
}
void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int> > &rowsAndCols)
void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int>> &rowsAndCols)
{
currentRowsAndCols = rowsAndCols;
int totalCols = 0, totalRows = 0;
qreal yUntilNow = separatorY + paddingY;
qreal x = (qreal) getCardTypeTextWidth();
qreal x = (qreal)getCardTypeTextWidth();
for (int i = 0; i < rowsAndCols.size(); ++i) {
const int tempRows = rowsAndCols[i].first;
const int tempCols = rowsAndCols[i].second;
@ -281,7 +283,7 @@ void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int> > &rowsAn
QList<QString> cardTypeList = cardsByType.uniqueKeys();
QList<DeckViewCard *> row = cardsByType.values(cardTypeList[i]);
qSort( row.begin(), row.end(), DeckViewCardContainer::sortCardsByName);
qSort(row.begin(), row.end(), DeckViewCardContainer::sortCardsByName);
for (int j = 0; j < row.size(); ++j) {
DeckViewCard *card = row[j];
card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT);
@ -302,8 +304,7 @@ void DeckViewCardContainer::setWidth(qreal _width)
update();
}
DeckViewScene::DeckViewScene(QObject *parent)
: QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
DeckViewScene::DeckViewScene(QObject *parent) : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
{
}
@ -395,10 +396,10 @@ void DeckViewScene::rearrangeItems()
QList<DeckViewCardContainer *> contList = cardContainers.values();
// Initialize space requirements
QList<QList<QPair<int, int> > > rowsAndColsList;
QList<QList<int> > cardCountList;
QList<QList<QPair<int, int>>> rowsAndColsList;
QList<QList<int>> cardCountList;
for (int i = 0; i < contList.size(); ++i) {
QList<QPair<int, int> > rowsAndCols = contList[i]->getRowsAndCols();
QList<QPair<int, int>> rowsAndCols = contList[i]->getRowsAndCols();
rowsAndColsList.append(rowsAndCols);
cardCountList.append(QList<int>());
@ -435,7 +436,8 @@ void DeckViewScene::rearrangeItems()
// Add row to category
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
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;
@ -484,14 +486,13 @@ void DeckViewScene::resetSideboardPlan()
rearrangeItems();
}
DeckView::DeckView(QWidget *parent)
: QGraphicsView(parent)
DeckView::DeckView(QWidget *parent) : QGraphicsView(parent)
{
deckViewScene = new DeckViewScene(this);
setBackgroundBrush(QBrush(QColor(0, 0, 0)));
setDragMode(RubberBandDrag);
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/);
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing /* | QPainter::SmoothPixmapTransform*/);
setScene(deckViewScene);
connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &)));
@ -502,7 +503,7 @@ DeckView::DeckView(QWidget *parent)
void DeckView::resizeEvent(QResizeEvent *event)
{
QGraphicsView::resizeEvent(event);
deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height());
deckViewScene->setOptimalAspectRatio((qreal)width() / (qreal)height());
deckViewScene->rearrangeItems();
}

View file

@ -1,12 +1,12 @@
#ifndef DECKVIEW_H
#define DECKVIEW_H
#include "abstractcarddragitem.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QMap>
#include <QMultiMap>
#include <QPixmap>
#include "abstractcarddragitem.h"
#include "pb/move_card_to_zone.pb.h"
@ -17,65 +17,90 @@ class DeckViewCardContainer;
class DeckViewCardDragItem;
class MoveCardToZone;
class DeckViewCard : public AbstractCardItem {
class DeckViewCard : public AbstractCardItem
{
private:
QString originZone;
DeckViewCardDragItem *dragItem;
public:
DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0);
~DeckViewCard();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
const QString &getOriginZone() const { return originZone; }
const QString &getOriginZone() const
{
return originZone;
}
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
};
class DeckViewCardDragItem : public AbstractCardDragItem {
class DeckViewCardDragItem : public AbstractCardDragItem
{
private:
DeckViewCardContainer *currentZone;
void handleDrop(DeckViewCardContainer *target);
public:
DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
void updatePosition(const QPointF &cursorScenePos);
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
};
class DeckViewCardContainer : public QGraphicsItem {
class DeckViewCardContainer : public QGraphicsItem
{
private:
static const int separatorY = 20;
static const int paddingY = 10;
static bool sortCardsByName(DeckViewCard * c1, DeckViewCard * c2);
static bool sortCardsByName(DeckViewCard *c1, DeckViewCard *c2);
QString name;
QList<DeckViewCard *> cards;
QMultiMap<QString, DeckViewCard *> cardsByType;
QList<QPair<int, int> > currentRowsAndCols;
QList<QPair<int, int>> currentRowsAndCols;
qreal width, height;
int getCardTypeTextWidth() const;
public:
enum { Type = typeDeckViewCardContainer };
int type() const { return Type; }
enum
{
Type = typeDeckViewCardContainer
};
int type() const
{
return Type;
}
DeckViewCardContainer(const QString &_name);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void addCard(DeckViewCard *card);
void removeCard(DeckViewCard *card);
const QList<DeckViewCard *> &getCards() const { return cards; }
const QString &getName() const { return name; }
const QList<DeckViewCard *> &getCards() const
{
return cards;
}
const QString &getName() const
{
return name;
}
void setWidth(qreal _width);
QList<QPair<int, int> > getRowsAndCols() const;
QSizeF calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const;
void rearrangeItems(const QList<QPair<int, int> > &rowsAndCols);
QList<QPair<int, int>> getRowsAndCols() const;
QSizeF calculateBoundingRect(const QList<QPair<int, int>> &rowsAndCols) const;
void rearrangeItems(const QList<QPair<int, int>> &rowsAndCols);
};
class DeckViewScene : public QGraphicsScene {
class DeckViewScene : public QGraphicsScene
{
Q_OBJECT
signals:
void newCardAdded(AbstractCardItem *card);
void sideboardPlanChanged();
private:
bool locked;
DeckList *deck;
@ -83,13 +108,23 @@ private:
qreal optimalAspectRatio;
void clearContents();
void rebuildTree();
public:
DeckViewScene(QObject *parent = 0);
~DeckViewScene();
void setLocked(bool _locked) { locked = _locked; }
bool getLocked() const { return locked; }
void setLocked(bool _locked)
{
locked = _locked;
}
bool getLocked() const
{
return locked;
}
void setDeck(const DeckList &_deck);
void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; }
void setOptimalAspectRatio(qreal _optimalAspectRatio)
{
optimalAspectRatio = _optimalAspectRatio;
}
void rearrangeItems();
void updateContents();
QList<MoveCard_ToZone> getSideboardPlan() const;
@ -97,10 +132,12 @@ public:
void applySideboardPlan(const QList<MoveCard_ToZone> &plan);
};
class DeckView : public QGraphicsView {
class DeckView : public QGraphicsView
{
Q_OBJECT
private:
DeckViewScene *deckViewScene;
protected:
void resizeEvent(QResizeEvent *event);
public slots:
@ -108,11 +145,18 @@ public slots:
signals:
void newCardAdded(AbstractCardItem *card);
void sideboardPlanChanged();
public:
DeckView(QWidget *parent = 0);
void setDeck(const DeckList &_deck);
void setLocked(bool _locked) { deckViewScene->setLocked(_locked); }
QList<MoveCard_ToZone> getSideboardPlan() const { return deckViewScene->getSideboardPlan(); }
void setLocked(bool _locked)
{
deckViewScene->setLocked(_locked);
}
QList<MoveCard_ToZone> getSideboardPlan() const
{
return deckViewScene->getSideboardPlan();
}
void mouseDoubleClickEvent(QMouseEvent *event);
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 "settingscache.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"
@ -52,7 +52,8 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
autoConnectCheckBox = new QCheckBox(tr("A&uto connect"));
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->setWordWrap(true);
publicServersLabel->setTextFormat(Qt::RichText);
@ -60,13 +61,10 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
publicServersLabel->setOpenExternalLinks(true);
publicServersLabel->setAlignment(Qt::AlignCenter);
if (savePasswordCheckBox->isChecked())
{
if (savePasswordCheckBox->isChecked()) {
autoConnectCheckBox->setChecked(static_cast<bool>(settingsCache->servers().getAutoConnect()));
autoConnectCheckBox->setEnabled(true);
}
else
{
} else {
settingsCache->servers().setAutoConnect(0);
autoConnectCheckBox->setChecked(false);
autoConnectCheckBox->setEnabled(false);
@ -140,7 +138,8 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
previousHostButton->setChecked(true);
connect(previousHosts, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(updateDisplayInfo(const QString &)));
connect(previousHosts, SIGNAL(currentIndexChanged(const QString &)), this,
SLOT(updateDisplayInfo(const QString &)));
playernameEdit->setFocus();
}
@ -148,24 +147,13 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
void DlgConnect::actSaveConfig()
{
bool updateSuccess = settingsCache->servers().updateExistingServer(
saveEdit->text().trimmed(),
hostEdit->text().trimmed(),
portEdit->text().trimmed(),
playernameEdit->text().trimmed(),
passwordEdit->text(),
savePasswordCheckBox->isChecked()
);
saveEdit->text().trimmed(), hostEdit->text().trimmed(), portEdit->text().trimmed(),
playernameEdit->text().trimmed(), passwordEdit->text(), savePasswordCheckBox->isChecked());
if (! updateSuccess)
{
settingsCache->servers().addNewServer(
saveEdit->text().trimmed(),
hostEdit->text().trimmed(),
portEdit->text().trimmed(),
playernameEdit->text().trimmed(),
passwordEdit->text(),
savePasswordCheckBox->isChecked()
);
if (!updateSuccess) {
settingsCache->servers().addNewServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(),
portEdit->text().trimmed(), playernameEdit->text().trimmed(),
passwordEdit->text(), savePasswordCheckBox->isChecked());
}
rebuildComboBoxList();
@ -178,8 +166,7 @@ void DlgConnect::rebuildComboBoxList()
UserConnection_Information uci;
savedHostList = uci.getServerInfo();
if (savedHostList.size() == 1)
{
if (savedHostList.size() == 1) {
settingsCache->servers().addNewServer("Woogerworks", "cockatrice.woogerworks.com", "4747", "", "", false);
settingsCache->servers().addNewServer("Chickatrice", "chickatrice.net", "4747", "", "", false);
settingsCache->servers().addNewServer("cockatric.es", "cockatric.es", "4747", "", "", false);
@ -188,15 +175,12 @@ void DlgConnect::rebuildComboBoxList()
savedHostList = uci.getServerInfo();
int i = 0;
for (UserConnection_Information tmp : savedHostList)
{
for (UserConnection_Information tmp : savedHostList) {
QString saveName = tmp.getSaveName();
if (saveName.size())
{
if (saveName.size()) {
previousHosts->addItem(saveName);
if (settingsCache->servers().getPrevioushostName() == saveName)
{
if (settingsCache->servers().getPrevioushostName() == saveName) {
previousHosts->setCurrentIndex(i);
}
@ -205,11 +189,9 @@ void DlgConnect::rebuildComboBoxList()
}
}
void DlgConnect::previousHostSelected(bool state)
{
if (state)
{
if (state) {
saveEdit->setDisabled(true);
previousHosts->setDisabled(false);
}
@ -217,8 +199,7 @@ void DlgConnect::previousHostSelected(bool state)
void DlgConnect::updateDisplayInfo(const QString &saveName)
{
if (saveEdit == nullptr)
{
if (saveEdit == nullptr) {
return;
}
@ -233,16 +214,14 @@ void DlgConnect::updateDisplayInfo(const QString &saveName)
playernameEdit->setText(data.at(3));
savePasswordCheckBox->setChecked(savePasswordStatus);
if (savePasswordStatus)
{
if (savePasswordStatus) {
passwordEdit->setText(data.at(4));
}
}
void DlgConnect::newHostSelected(bool state)
{
if (state)
{
if (state) {
previousHosts->setDisabled(true);
hostEdit->clear();
portEdit->clear();
@ -252,23 +231,17 @@ void DlgConnect::newHostSelected(bool state)
saveEdit->clear();
saveEdit->setPlaceholderText("New Menu Name");
saveEdit->setDisabled(false);
}
else
{
} else {
rebuildComboBoxList();
}
}
void DlgConnect::passwordSaved(int state)
{
Q_UNUSED(state);
if (savePasswordCheckBox->isChecked())
{
autoConnectCheckBox->setEnabled(true);
}
else
{
if (savePasswordCheckBox->isChecked()) {
autoConnectCheckBox->setEnabled(true);
} else {
autoConnectCheckBox->setChecked(false);
autoConnectCheckBox->setEnabled(false);
}
@ -276,40 +249,25 @@ void DlgConnect::passwordSaved(int state)
void DlgConnect::actOk()
{
if (newHostButton->isChecked())
{
if (saveEdit->text().isEmpty())
{
if (newHostButton->isChecked()) {
if (saveEdit->text().isEmpty()) {
QMessageBox::critical(this, tr("Connection Warning"), tr("You need to name your new connection profile."));
return;
}
settingsCache->servers().addNewServer(
saveEdit->text().trimmed(),
hostEdit->text().trimmed(),
portEdit->text().trimmed(),
playernameEdit->text().trimmed(),
passwordEdit->text(),
savePasswordCheckBox->isChecked()
);
}
else
{
settingsCache->servers().updateExistingServer(
saveEdit->text().trimmed(),
hostEdit->text().trimmed(),
portEdit->text().trimmed(),
playernameEdit->text().trimmed(),
passwordEdit->text(),
savePasswordCheckBox->isChecked()
);
settingsCache->servers().addNewServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(),
portEdit->text().trimmed(), playernameEdit->text().trimmed(),
passwordEdit->text(), savePasswordCheckBox->isChecked());
} else {
settingsCache->servers().updateExistingServer(saveEdit->text().trimmed(), hostEdit->text().trimmed(),
portEdit->text().trimmed(), playernameEdit->text().trimmed(),
passwordEdit->text(), savePasswordCheckBox->isChecked());
}
settingsCache->servers().setPrevioushostName(saveEdit->text());
settingsCache->servers().setAutoConnect(autoConnectCheckBox->isChecked());
if (playernameEdit->text().isEmpty())
{
if (playernameEdit->text().isEmpty()) {
QMessageBox::critical(this, tr("Connect Warning"), tr("The player name can't be empty."));
return;
}
@ -317,7 +275,6 @@ void DlgConnect::actOk()
accept();
}
QString DlgConnect::getHost() const
{
return hostEdit->text().trimmed();
@ -332,12 +289,10 @@ void DlgConnect::actCancel()
bool DeleteHighlightedItemWhenShiftDelPressedEventFilter::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
if (event->type() == QEvent::KeyPress) {
auto *keyEvent = dynamic_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Delete)
{
if (keyEvent->key() == Qt::Key_Delete) {
auto *combobox = reinterpret_cast<QComboBox *>(obj);
combobox->removeItem(combobox->currentIndex());
return true;

View file

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

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

View file

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

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

View file

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

View file

@ -10,15 +10,15 @@
#include "dlg_edit_avatar.h"
DlgEditAvatar::DlgEditAvatar(QWidget *parent)
: QDialog(parent)
DlgEditAvatar::DlgEditAvatar(QWidget *parent) : QDialog(parent)
{
imageLabel = new QLabel(tr("No image chosen."));
imageLabel->setFixedSize(400, 200);
imageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
imageLabel->setStyleSheet("border: 1px solid #000");
textLabel = new QLabel(tr("To change your avatar, choose a new image.\nTo remove your current avatar, confirm without choosing a new image."));
textLabel = new QLabel(tr("To change your avatar, choose a new image.\nTo remove your current avatar, confirm "
"without choosing a new image."));
browseButton = new QPushButton(tr("Browse..."));
connect(browseButton, SIGNAL(clicked()), this, SLOT(actBrowse()));
@ -53,9 +53,9 @@ void DlgEditAvatar::actCancel()
void DlgEditAvatar::actBrowse()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)"));
if(fileName.isEmpty())
{
QString fileName =
QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)"));
if (fileName.isEmpty()) {
imageLabel->setText(tr("No image chosen."));
return;
}
@ -64,8 +64,7 @@ void DlgEditAvatar::actBrowse()
QImageReader imgReader;
imgReader.setDecideFormatFromContent(true);
imgReader.setFileName(fileName);
if(!imgReader.read(&image))
{
if (!imgReader.read(&image)) {
qDebug() << "Avatar image loading failed for file:" << fileName;
imageLabel->setText(tr("Invalid image chosen."));
return;
@ -76,11 +75,11 @@ void DlgEditAvatar::actBrowse()
QByteArray DlgEditAvatar::getImage()
{
const QPixmap *pix = imageLabel->pixmap();
if(!pix || pix->isNull())
if (!pix || pix->isNull())
return QByteArray();
QImage image = pix->toImage();
if(image.isNull())
if (image.isNull())
return QByteArray();
QByteArray ba;

View file

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

View file

@ -4,17 +4,16 @@
#include <QLabel>
#include <QMessageBox>
#include "settingscache.h"
#include "dlg_edit_password.h"
#include "settingscache.h"
DlgEditPassword::DlgEditPassword(QWidget *parent)
: QDialog(parent)
DlgEditPassword::DlgEditPassword(QWidget *parent) : QDialog(parent)
{
oldPasswordLabel = new QLabel(tr("Old password:"));
oldPasswordEdit = new QLineEdit();
if(settingsCache->servers().getSavePassword())
if (settingsCache->servers().getSavePassword())
oldPasswordEdit->setText(settingsCache->servers().getPassword());
oldPasswordLabel->setBuddy(oldPasswordEdit);
@ -54,8 +53,7 @@ DlgEditPassword::DlgEditPassword(QWidget *parent)
void DlgEditPassword::actOk()
{
if(newPasswordEdit->text() != newPasswordEdit2->text())
{
if (newPasswordEdit->text() != newPasswordEdit2->text()) {
QMessageBox::warning(this, tr("Error"), tr("The new passwords don't match."));
return;
}

View file

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

View file

@ -2,23 +2,22 @@
#include "carddatabase.h"
#include "carddatabasemodel.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 <QComboBox>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QToolBar>
#include <QTreeView>
#include <QVBoxLayout>
DlgEditTokens::DlgEditTokens(QWidget *parent)
: QDialog(parent), currentCard(0)
DlgEditTokens::DlgEditTokens(QWidget *parent) : QDialog(parent), currentCard(0)
{
nameLabel = new QLabel(tr("&Name:"));
nameEdit = new QLineEdit;
@ -80,7 +79,8 @@ DlgEditTokens::DlgEditTokens(QWidget *parent)
chooseTokenView->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
chooseTokenView->header()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this,
SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
QAction *aAddToken = new QAction(tr("Add token"), this);
aAddToken->setIcon(QPixmap("theme:icons/increment"));
@ -118,8 +118,7 @@ void DlgEditTokens::tokenSelectionChanged(const QModelIndex &current, const QMod
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
currentCard = current.row() >= 0 ? databaseModel->getCard(realIndex.row()) : 0;
if(currentCard)
{
if (currentCard) {
nameEdit->setText(currentCard->getName());
const QChar cardColor = currentCard->getColorChar();
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
@ -139,16 +138,17 @@ void DlgEditTokens::actAddToken()
bool askAgain = true;
do {
name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:"));
if(name.isEmpty())
if (name.isEmpty())
return;
if (databaseModel->getDatabase()->getCard(name)) {
QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.\nMake sure to enable the 'Token' set in the \"Manage sets\" dialog to display them correctly."));
QMessageBox::critical(this, tr("Error"),
tr("The chosen name conflicts with an existing card or token.\nMake sure to enable "
"the 'Token' set in the \"Manage sets\" dialog to display them correctly."));
} else {
askAgain = false;
}
} while (askAgain);
CardInfo *card = new CardInfo(name, true);
card->addToSet(databaseModel->getDatabase()->getSet(CardDatabase::TOKENS_SETNAME));
card->setCardType("Token");

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,32 +1,36 @@
#include <QLabel>
#include <QCheckBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QDialogButtonBox>
#include <QLabel>
#include <QMessageBox>
#include <QDebug>
#include "dlg_forgotpasswordchallenge.h"
#include "settingscache.h"
DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent)
: QDialog(parent)
DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent) : QDialog(parent)
{
QString lastfphost; QString lastfpport; QString lastfpplayername;
QString lastfphost;
QString lastfpport;
QString lastfpplayername;
lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com");
lastfpport = settingsCache->servers().getPort("4747");
lastfpplayername = settingsCache->servers().getPlayerName("Player");
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) {
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() &&
!settingsCache->servers().getFPPlayerName().isEmpty()) {
lastfphost = settingsCache->servers().getFPHostname();
lastfpport = settingsCache->servers().getFPPort();
lastfpplayername = settingsCache->servers().getFPPlayerName();
}
if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() && settingsCache->servers().getFPPlayerName().isEmpty())
{
QMessageBox::warning(this, tr("Forgot Password Challenge Warning"), tr("Oops, looks like something has gone wrong. Please restart the forgot password process by using the forgot password button on the connection screen."));
if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() &&
settingsCache->servers().getFPPlayerName().isEmpty()) {
QMessageBox::warning(this, tr("Forgot Password Challenge Warning"),
tr("Oops, looks like something has gone wrong. Please restart the forgot password "
"process by using the forgot password button on the connection screen."));
actCancel();
}
@ -46,7 +50,8 @@ DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent)
emailEdit = new QLineEdit();
emailLabel->setBuddy(emailLabel);
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) {
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() &&
!settingsCache->servers().getFPPlayerName().isEmpty()) {
hostLabel->hide();
hostEdit->hide();
portLabel->hide();
@ -81,8 +86,7 @@ DlgForgotPasswordChallenge::DlgForgotPasswordChallenge(QWidget *parent)
void DlgForgotPasswordChallenge::actOk()
{
if (emailEdit->text().isEmpty())
{
if (emailEdit->text().isEmpty()) {
QMessageBox::critical(this, tr("Forgot Password Challenge Warning"), tr("The email address can't be empty."));
return;
}

View file

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

View file

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

View file

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

View file

@ -1,32 +1,36 @@
#include <QLabel>
#include <QCheckBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QDialogButtonBox>
#include <QLabel>
#include <QMessageBox>
#include <QDebug>
#include "dlg_forgotpasswordreset.h"
#include "settingscache.h"
DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent)
: QDialog(parent)
DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent) : QDialog(parent)
{
QString lastfphost; QString lastfpport; QString lastfpplayername;
QString lastfphost;
QString lastfpport;
QString lastfpplayername;
lastfphost = settingsCache->servers().getHostname("cockatrice.woogerworks.com");
lastfpport = settingsCache->servers().getPort("4747");
lastfpplayername = settingsCache->servers().getPlayerName("Player");
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) {
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() &&
!settingsCache->servers().getFPPlayerName().isEmpty()) {
lastfphost = settingsCache->servers().getFPHostname();
lastfpport = settingsCache->servers().getFPPort();
lastfpplayername = settingsCache->servers().getFPPlayerName();
}
if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() && settingsCache->servers().getFPPlayerName().isEmpty())
{
QMessageBox::warning(this, tr("Forgot Password Reset Warning"), tr("Opps, looks like something has gone wrong. Please re-start the forgot password process by using the forgot password button on the connection screen."));
if (settingsCache->servers().getFPHostname().isEmpty() && settingsCache->servers().getFPPort().isEmpty() &&
settingsCache->servers().getFPPlayerName().isEmpty()) {
QMessageBox::warning(this, tr("Forgot Password Reset Warning"),
tr("Opps, looks like something has gone wrong. Please re-start the forgot password "
"process by using the forgot password button on the connection screen."));
actCancel();
}
@ -56,7 +60,8 @@ DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent)
newpasswordverifyLabel->setBuddy(newpasswordEdit);
newpasswordverifyEdit->setEchoMode(QLineEdit::Password);
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() && !settingsCache->servers().getFPPlayerName().isEmpty()) {
if (!settingsCache->servers().getFPHostname().isEmpty() && !settingsCache->servers().getFPPort().isEmpty() &&
!settingsCache->servers().getFPPlayerName().isEmpty()) {
hostLabel->hide();
hostEdit->hide();
portLabel->hide();
@ -95,26 +100,22 @@ DlgForgotPasswordReset::DlgForgotPasswordReset(QWidget *parent)
void DlgForgotPasswordReset::actOk()
{
if(playernameEdit->text().isEmpty())
{
if (playernameEdit->text().isEmpty()) {
QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The player name can't be empty."));
return;
}
if (tokenEdit->text().isEmpty())
{
if (tokenEdit->text().isEmpty()) {
QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The token can't be empty."));
return;
}
if (newpasswordEdit->text().isEmpty())
{
if (newpasswordEdit->text().isEmpty()) {
QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The new password can't be empty."));
return;
}
if (newpasswordEdit->text() != newpasswordverifyEdit->text())
{
if (newpasswordEdit->text() != newpasswordverifyEdit->text()) {
QMessageBox::critical(this, tr("Forgot Password Reset Warning"), tr("The passwords do not match."));
return;
}

View file

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

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 "deck_loader.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)
{
@ -32,7 +32,7 @@ DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) : QDialog(pa
resize(500, 500);
actRefresh();
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts()));
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts()));
refreshShortcuts();
}
@ -52,26 +52,18 @@ void DlgLoadDeckFromClipboard::actOK()
QTextStream stream(&buffer);
auto *deckLoader = new DeckLoader;
if (buffer.contains("<cockatrice_deck version=\"1\">"))
{
if (deckLoader->loadFromString_Native(buffer))
{
if (buffer.contains("<cockatrice_deck version=\"1\">")) {
if (deckLoader->loadFromString_Native(buffer)) {
deckList = deckLoader;
accept();
}
else
{
} else {
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list."));
delete deckLoader;
}
}
else if (deckLoader->loadFromStream_Plain(stream))
{
} else if (deckLoader->loadFromStream_Plain(stream)) {
deckList = deckLoader;
accept();
}
else
{
} else {
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list."));
delete deckLoader;
}

View file

@ -10,19 +10,22 @@ class QPushButton;
class DlgLoadDeckFromClipboard : public QDialog
{
Q_OBJECT
private slots:
void actOK();
void actRefresh();
void refreshShortcuts();
private slots:
void actOK();
void actRefresh();
void refreshShortcuts();
private:
DeckLoader *deckList;
QPlainTextEdit *contentsEdit;
QPushButton *refreshButton;
private:
DeckLoader *deckList;
QPlainTextEdit *contentsEdit;
QPushButton *refreshButton;
public:
explicit DlgLoadDeckFromClipboard(QWidget *parent = nullptr);
DeckLoader *getDeckList() const { return deckList; }
public:
explicit DlgLoadDeckFromClipboard(QWidget *parent = nullptr);
DeckLoader *getDeckList() const
{
return deckList;
}
};
#endif

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 "main.h"
#include "remotedecklist_treewidget.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QPushButton>
#include <QVBoxLayout>
DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent)
: QDialog(parent), client(_client)
DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) : QDialog(parent), client(_client)
{
dirView = new RemoteDeckList_TreeWidget(client);
@ -26,15 +25,19 @@ DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent)
setMinimumWidth(sizeHint().width());
resize(400, 600);
connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &)));
connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this,
SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &)));
}
void DlgLoadRemoteDeck::currentItemChanged(const QModelIndex &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
{
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 QDialogButtonBox;
class DlgLoadRemoteDeck: public QDialog {
class DlgLoadRemoteDeck : public QDialog
{
Q_OBJECT
private:
AbstractClient *client;
@ -17,6 +18,7 @@ private:
QDialogButtonBox *buttonBox;
private slots:
void currentItemChanged(const QModelIndex &current, const QModelIndex &previous);
public:
DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0);
int getDeckId() const;

View file

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

View file

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

View file

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

View file

@ -1,8 +1,8 @@
#ifndef DLG_SETTINGS_H
#define DLG_SETTINGS_H
#include <QComboBox>
#include <QCheckBox>
#include <QComboBox>
#include <QDialog>
#include <QGroupBox>
#include <QLabel>
@ -28,225 +28,226 @@ class QSpinBox;
class AbstractSettingsPage : public QWidget
{
public:
virtual void retranslateUi() = 0;
public:
virtual void retranslateUi() = 0;
};
class GeneralSettingsPage : public AbstractSettingsPage
{
Q_OBJECT
public:
GeneralSettingsPage();
void retranslateUi() override;
public:
GeneralSettingsPage();
void retranslateUi() override;
private slots:
void deckPathButtonClicked();
void replaysPathButtonClicked();
void picsPathButtonClicked();
void clearDownloadedPicsButtonClicked();
void cardDatabasePathButtonClicked();
void tokenDatabasePathButtonClicked();
void languageBoxChanged(int index);
void setEnabledStatus(bool);
void defaultUrlRestoreButtonClicked();
void fallbackUrlRestoreButtonClicked();
private slots:
void deckPathButtonClicked();
void replaysPathButtonClicked();
void picsPathButtonClicked();
void clearDownloadedPicsButtonClicked();
void cardDatabasePathButtonClicked();
void tokenDatabasePathButtonClicked();
void languageBoxChanged(int index);
void setEnabledStatus(bool);
void defaultUrlRestoreButtonClicked();
void fallbackUrlRestoreButtonClicked();
private:
QStringList findQmFiles();
QString languageName(const QString &qmFile);
QLineEdit *deckPathEdit;
QLineEdit *replaysPathEdit;
QLineEdit *picsPathEdit;
QLineEdit *cardDatabasePathEdit;
QLineEdit *tokenDatabasePathEdit;
QLineEdit *defaultUrlEdit;
QLineEdit *fallbackUrlEdit;
QSpinBox pixmapCacheEdit;
QGroupBox *personalGroupBox;
QGroupBox *pathsGroupBox;
QComboBox languageBox;
QCheckBox picDownloadCheckBox;
QCheckBox updateNotificationCheckBox;
QComboBox updateReleaseChannelBox;
QLabel languageLabel;
QLabel pixmapCacheLabel;
QLabel deckPathLabel;
QLabel replaysPathLabel;
QLabel picsPathLabel;
QLabel cardDatabasePathLabel;
QLabel tokenDatabasePathLabel;
QLabel defaultUrlLabel;
QLabel fallbackUrlLabel;
QLabel urlLinkLabel;
QLabel updateReleaseChannelLabel;
QPushButton clearDownloadedPicsButton;
QPushButton defaultUrlRestoreButton;
QPushButton fallbackUrlRestoreButton;
private:
QStringList findQmFiles();
QString languageName(const QString &qmFile);
QLineEdit *deckPathEdit;
QLineEdit *replaysPathEdit;
QLineEdit *picsPathEdit;
QLineEdit *cardDatabasePathEdit;
QLineEdit *tokenDatabasePathEdit;
QLineEdit *defaultUrlEdit;
QLineEdit *fallbackUrlEdit;
QSpinBox pixmapCacheEdit;
QGroupBox *personalGroupBox;
QGroupBox *pathsGroupBox;
QComboBox languageBox;
QCheckBox picDownloadCheckBox;
QCheckBox updateNotificationCheckBox;
QComboBox updateReleaseChannelBox;
QLabel languageLabel;
QLabel pixmapCacheLabel;
QLabel deckPathLabel;
QLabel replaysPathLabel;
QLabel picsPathLabel;
QLabel cardDatabasePathLabel;
QLabel tokenDatabasePathLabel;
QLabel defaultUrlLabel;
QLabel fallbackUrlLabel;
QLabel urlLinkLabel;
QLabel updateReleaseChannelLabel;
QPushButton clearDownloadedPicsButton;
QPushButton defaultUrlRestoreButton;
QPushButton fallbackUrlRestoreButton;
};
class AppearanceSettingsPage : public AbstractSettingsPage
{
Q_OBJECT
private slots:
void themeBoxChanged(int index);
private slots:
void themeBoxChanged(int index);
private:
QLabel themeLabel;
QComboBox themeBox;
QLabel minPlayersForMultiColumnLayoutLabel;
QLabel maxFontSizeForCardsLabel;
QCheckBox displayCardNamesCheckBox;
QCheckBox cardScalingCheckBox;
QCheckBox horizontalHandCheckBox;
QCheckBox leftJustifiedHandCheckBox;
QCheckBox invertVerticalCoordinateCheckBox;
QGroupBox *themeGroupBox;
QGroupBox *cardsGroupBox;
QGroupBox *handGroupBox;
QGroupBox *tableGroupBox;
QSpinBox minPlayersForMultiColumnLayoutEdit;
QSpinBox maxFontSizeForCardsEdit;
private:
QLabel themeLabel;
QComboBox themeBox;
QLabel minPlayersForMultiColumnLayoutLabel;
QLabel maxFontSizeForCardsLabel;
QCheckBox displayCardNamesCheckBox;
QCheckBox cardScalingCheckBox;
QCheckBox horizontalHandCheckBox;
QCheckBox leftJustifiedHandCheckBox;
QCheckBox invertVerticalCoordinateCheckBox;
QGroupBox *themeGroupBox;
QGroupBox *cardsGroupBox;
QGroupBox *handGroupBox;
QGroupBox *tableGroupBox;
QSpinBox minPlayersForMultiColumnLayoutEdit;
QSpinBox maxFontSizeForCardsEdit;
public:
AppearanceSettingsPage();
void retranslateUi() override;
public:
AppearanceSettingsPage();
void retranslateUi() override;
};
class UserInterfaceSettingsPage : public AbstractSettingsPage
{
Q_OBJECT
private slots:
void setSpecNotificationEnabled(int);
private slots:
void setSpecNotificationEnabled(int);
private:
QCheckBox notificationsEnabledCheckBox;
QCheckBox specNotificationsEnabledCheckBox;
QCheckBox doubleClickToPlayCheckBox;
QCheckBox playToStackCheckBox;
QCheckBox annotateTokensCheckBox;
QCheckBox tapAnimationCheckBox;
QGroupBox *generalGroupBox;
QGroupBox *animationGroupBox;
private:
QCheckBox notificationsEnabledCheckBox;
QCheckBox specNotificationsEnabledCheckBox;
QCheckBox doubleClickToPlayCheckBox;
QCheckBox playToStackCheckBox;
QCheckBox annotateTokensCheckBox;
QCheckBox tapAnimationCheckBox;
QGroupBox *generalGroupBox;
QGroupBox *animationGroupBox;
public:
UserInterfaceSettingsPage();
void retranslateUi() override;
public:
UserInterfaceSettingsPage();
void retranslateUi() override;
};
class DeckEditorSettingsPage : public AbstractSettingsPage
{
Q_OBJECT
public:
DeckEditorSettingsPage();
void retranslateUi() override;
QString getLastUpdateTime();
public:
DeckEditorSettingsPage();
void retranslateUi() override;
QString getLastUpdateTime();
private slots:
void setSpoilersEnabled(bool);
void spoilerPathButtonClicked();
void updateSpoilers();
void unlockSettings();
private slots:
void setSpoilersEnabled(bool);
void spoilerPathButtonClicked();
void updateSpoilers();
void unlockSettings();
private:
QCheckBox mcDownloadSpoilersCheckBox;
QLabel msDownloadSpoilersLabel;
QGroupBox *mpGeneralGroupBox;
QGroupBox *mpSpoilerGroupBox;
QLineEdit *mpSpoilerSavePathLineEdit;
QLabel mcSpoilerSaveLabel;
QLabel mcGeneralMessageLabel;
QLabel infoOnSpoilersLabel;
QPushButton *mpSpoilerPathButton;
QPushButton *updateNowButton;
private:
QCheckBox mcDownloadSpoilersCheckBox;
QLabel msDownloadSpoilersLabel;
QGroupBox *mpGeneralGroupBox;
QGroupBox *mpSpoilerGroupBox;
QLineEdit *mpSpoilerSavePathLineEdit;
QLabel mcSpoilerSaveLabel;
QLabel mcGeneralMessageLabel;
QLabel infoOnSpoilersLabel;
QPushButton *mpSpoilerPathButton;
QPushButton *updateNowButton;
};
class MessagesSettingsPage : public AbstractSettingsPage
{
Q_OBJECT
public:
MessagesSettingsPage();
void retranslateUi() override;
public:
MessagesSettingsPage();
void retranslateUi() override;
private slots:
void actAdd();
void actRemove();
void updateColor(const QString &value);
void updateHighlightColor(const QString &value);
void updateTextColor(int value);
void updateTextHighlightColor(int value);
private slots:
void actAdd();
void actRemove();
void updateColor(const QString &value);
void updateHighlightColor(const QString &value);
void updateTextColor(int value);
void updateTextHighlightColor(int value);
private:
QListWidget *messageList;
QAction *aAdd;
QAction *aRemove;
QCheckBox chatMentionCheckBox;
QCheckBox chatMentionCompleterCheckbox;
QCheckBox invertMentionForeground;
QCheckBox invertHighlightForeground;
QCheckBox ignoreUnregUsersMainChat;
QCheckBox ignoreUnregUserMessages;
QCheckBox messagePopups;
QCheckBox mentionPopups;
QCheckBox roomHistory;
QGroupBox *chatGroupBox;
QGroupBox *highlightGroupBox;
QGroupBox *messageShortcuts;
QLineEdit *mentionColor;
QLineEdit *highlightColor;
QLineEdit *customAlertString;
QLabel hexLabel;
QLabel hexHighlightLabel;
QLabel customAlertStringLabel;
private:
QListWidget *messageList;
QAction *aAdd;
QAction *aRemove;
QCheckBox chatMentionCheckBox;
QCheckBox chatMentionCompleterCheckbox;
QCheckBox invertMentionForeground;
QCheckBox invertHighlightForeground;
QCheckBox ignoreUnregUsersMainChat;
QCheckBox ignoreUnregUserMessages;
QCheckBox messagePopups;
QCheckBox mentionPopups;
QCheckBox roomHistory;
QGroupBox *chatGroupBox;
QGroupBox *highlightGroupBox;
QGroupBox *messageShortcuts;
QLineEdit *mentionColor;
QLineEdit *highlightColor;
QLineEdit *customAlertString;
QLabel hexLabel;
QLabel hexHighlightLabel;
QLabel customAlertStringLabel;
void storeSettings();
void updateMentionPreview();
void updateHighlightPreview();
void storeSettings();
void updateMentionPreview();
void updateHighlightPreview();
};
class SoundSettingsPage : public AbstractSettingsPage
{
Q_OBJECT
public:
SoundSettingsPage();
void retranslateUi() override;
public:
SoundSettingsPage();
void retranslateUi() override;
private:
QLabel themeLabel;
QComboBox themeBox;
QGroupBox *soundGroupBox;
QPushButton soundTestButton;
QCheckBox soundEnabledCheckBox;
QLabel masterVolumeLabel;
QSlider *masterVolumeSlider;
QSpinBox *masterVolumeSpinBox;
private:
QLabel themeLabel;
QComboBox themeBox;
QGroupBox *soundGroupBox;
QPushButton soundTestButton;
QCheckBox soundEnabledCheckBox;
QLabel masterVolumeLabel;
QSlider *masterVolumeSlider;
QSpinBox *masterVolumeSpinBox;
private slots:
void masterVolumeChanged(int value);
void themeBoxChanged(int index);
private slots:
void masterVolumeChanged(int value);
void themeBoxChanged(int index);
};
class DlgSettings : public QDialog
{
Q_OBJECT
public:
explicit DlgSettings(QWidget *parent = nullptr);
void setTab(int index);
public:
explicit DlgSettings(QWidget *parent = nullptr);
void setTab(int index);
private slots:
void changePage(QListWidgetItem *current, QListWidgetItem *previous);
void updateLanguage();
private slots:
void changePage(QListWidgetItem *current, QListWidgetItem *previous);
void updateLanguage();
private:
QListWidget *contentsWidget;
QStackedWidget *pagesWidget;
QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton, *soundButton;
QListWidgetItem *shortcutsButton;
void createIcons();
void retranslateUi();
private:
QListWidget *contentsWidget;
QStackedWidget *pagesWidget;
QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton,
*soundButton;
QListWidgetItem *shortcutsButton;
void createIcons();
void retranslateUi();
protected:
void changeEvent(QEvent *event) override;
void closeEvent(QCloseEvent *event) override;
protected:
void changeEvent(QEvent *event) override;
void closeEvent(QCloseEvent *event) override;
};
#endif

View file

@ -1,13 +1,13 @@
#include <QtNetwork>
#include <QProgressDialog>
#include <QDesktopServices>
#include <QMessageBox>
#include <QProgressDialog>
#include <QVBoxLayout>
#include <QtNetwork>
#include <QPushButton>
#include <QApplication>
#include <QLabel>
#include <QProgressBar>
#include <QApplication>
#include <QPushButton>
#include <version_string.h>
#include "dlg_update.h"
@ -15,13 +15,17 @@
#include "settingscache.h"
#include "window_main.h"
DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) {
DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent)
{
//Handle layout
// Handle layout
statusLabel = new QLabel(this);
statusLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
statusLabel->setWordWrap(true);
descriptionLabel = new QLabel(tr("Current release channel") + QString(": %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8())), this);
descriptionLabel =
new QLabel(tr("Current release channel") +
QString(": %1").arg(tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8())),
this);
progress = new QProgressBar(this);
buttonBox = new QDialogButtonBox(this);
@ -33,7 +37,7 @@ DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) {
gotoDownload = new QPushButton(tr("Open Download Page"), this);
addStopDownloadAndRemoveOthers(false); // Add all buttons to box
enableUpdateButton(false); //Unless we know there's an update available, you can't install
enableUpdateButton(false); // Unless we know there's an update available, you can't install
buttonBox->addButton(ok, QDialogButtonBox::AcceptRole);
connect(gotoDownload, SIGNAL(clicked()), this, SLOT(gotoDownloadPage()));
@ -49,160 +53,180 @@ DlgUpdate::DlgUpdate(QWidget *parent) : QDialog(parent) {
setLayout(parentLayout);
//Check for SSL (this probably isn't necessary)
// Check for SSL (this probably isn't necessary)
if (!QSslSocket::supportsSsl()) {
enableUpdateButton(false);
QMessageBox::critical(this, tr("Error"),
tr("Cockatrice was not built with SSL support, therefore you cannot download updates automatically! \nPlease visit the download page to update manually."));
tr("Cockatrice was not built with SSL support, therefore you cannot download updates "
"automatically! \nPlease visit the download page to update manually."));
}
//Initialize the checker and downloader class
// Initialize the checker and downloader class
uDownloader = new UpdateDownloader(this);
connect(uDownloader, SIGNAL(downloadSuccessful(QUrl)), this, SLOT(downloadSuccessful(QUrl)));
connect(uDownloader, SIGNAL(progressMade(qint64, qint64)), this, SLOT(downloadProgressMade(qint64, qint64)));
connect(uDownloader, SIGNAL(error(QString)), this, SLOT(downloadError(QString)));
ReleaseChannel * channel = settingsCache->getUpdateReleaseChannel();
connect(channel, SIGNAL(finishedCheck(bool, bool, Release *)), this, SLOT(finishedUpdateCheck(bool, bool, Release *)));
ReleaseChannel *channel = settingsCache->getUpdateReleaseChannel();
connect(channel, SIGNAL(finishedCheck(bool, bool, Release *)), this,
SLOT(finishedUpdateCheck(bool, bool, Release *)));
connect(channel, SIGNAL(error(QString)), this, SLOT(updateCheckError(QString)));
//Check for updates
// Check for updates
beginUpdateCheck();
}
void DlgUpdate::closeDialog() {
void DlgUpdate::closeDialog()
{
accept();
}
void DlgUpdate::gotoDownloadPage() {
void DlgUpdate::gotoDownloadPage()
{
QDesktopServices::openUrl(settingsCache->getUpdateReleaseChannel()->getManualDownloadUrl());
}
void DlgUpdate::downloadUpdate() {
void DlgUpdate::downloadUpdate()
{
setLabel(tr("Downloading update..."));
addStopDownloadAndRemoveOthers(true); // Will remove all other buttons
uDownloader->beginDownload(updateUrl);
}
void DlgUpdate::cancelDownload() {
void DlgUpdate::cancelDownload()
{
emit uDownloader->stopDownload();
setLabel("Download canceled");
addStopDownloadAndRemoveOthers(false);
downloadProgressMade(0, 1);
}
void DlgUpdate::beginUpdateCheck() {
void DlgUpdate::beginUpdateCheck()
{
progress->setMinimum(0);
progress->setMaximum(0);
setLabel(tr("Checking for updates..."));
settingsCache->getUpdateReleaseChannel()->checkForUpdates();
}
void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Release *release) {
void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Release *release)
{
QString publishDate, versionName;
//Update the UI to say we've finished
// Update the UI to say we've finished
progress->setMaximum(100);
setLabel(tr("Finished checking for updates"));
//If there are no available builds, then they can't auto update.
// If there are no available builds, then they can't auto update.
enableUpdateButton(isCompatible);
//Give the user the appropriate message
// Give the user the appropriate message
if (!needToUpdate) {
//If there's no need to update, tell them that. However we still allow them to run the
//downloader themselves if there's a compatible build
QMessageBox::information(this, tr("No Update Available"),
tr("Cockatrice is up to date!") + "<br><br>"
+ tr("You are already running the latest version available in the chosen release channel.") + "<br>"
+ "<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())));
// If there's no need to update, tell them that. However we still allow them to run the
// downloader themselves if there's a compatible build
QMessageBox::information(
this, tr("No Update Available"),
tr("Cockatrice is up to date!") + "<br><br>" +
tr("You are already running the latest version available in the chosen release channel.") + "<br>" +
"<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;
}
publishDate = release->getPublishDate().toString(Qt::DefaultLocaleLongDate);
if (isCompatible) {
//If there is an update, save its URL and work out its name
// If there is an update, save its URL and work out its name
updateUrl = release->getDownloadUrl();
int reply;
reply = QMessageBox::question(this, tr("Update Available"),
tr("A new version of Cockatrice is available!") + "<br><br>"
+ "<b>" + tr("New version") + QString(":</b> %1<br>").arg(release->getName())
+ "<b>" + tr("Released") + QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + ")</a><br><br>"
+ tr("Do you want to update now?"),
reply = QMessageBox::question(
this, tr("Update Available"),
tr("A new version of Cockatrice is available!") + "<br><br>" + "<b>" + tr("New version") +
QString(":</b> %1<br>").arg(release->getName()) + "<b>" + tr("Released") +
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);
if (reply == QMessageBox::Yes)
downloadUpdate();
} else {
QMessageBox::information(this, tr("Update Available"),
tr("A new version of Cockatrice is available!") + "<br><br>"
+ "<b>" + tr("New version") + QString(":</b> %1<br>").arg(release->getName())
+ "<b>" + tr("Released") + QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") + ")</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."));
QMessageBox::information(
this, tr("Update Available"),
tr("A new version of Cockatrice is available!") + "<br><br>" + "<b>" + tr("New version") +
QString(":</b> %1<br>").arg(release->getName()) + "<b>" + tr("Released") +
QString(":</b> %1 <a href=\"%2\">(").arg(publishDate, release->getDescriptionUrl()) + tr("Changelog") +
")</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);
}
void DlgUpdate::addStopDownloadAndRemoveOthers(bool enable) {
void DlgUpdate::addStopDownloadAndRemoveOthers(bool enable)
{
if (enable) {
buttonBox->addButton(stopDownload, QDialogButtonBox::ActionRole);
buttonBox->removeButton(manualDownload);
buttonBox->removeButton(gotoDownload);
}
else {
} else {
buttonBox->removeButton(stopDownload);
buttonBox->addButton(manualDownload, QDialogButtonBox::ActionRole);
buttonBox->addButton(gotoDownload, QDialogButtonBox::ActionRole);
}
}
void DlgUpdate::enableOkButton(bool enable) {
void DlgUpdate::enableOkButton(bool enable)
{
ok->setEnabled(enable);
}
void DlgUpdate::setLabel(QString newText) {
void DlgUpdate::setLabel(QString newText)
{
statusLabel->setText(newText);
}
void DlgUpdate::updateCheckError(QString errorString) {
void DlgUpdate::updateCheckError(QString errorString)
{
setLabel(tr("Error"));
QMessageBox::critical(this, tr("Update Error"),
tr("An error occurred while checking for updates:") + QString(" ") + errorString);
tr("An error occurred while checking for updates:") + QString(" ") + errorString);
}
void DlgUpdate::downloadError(QString errorString) {
void DlgUpdate::downloadError(QString errorString)
{
setLabel(tr("Error"));
enableUpdateButton(true);
QMessageBox::critical(this, tr("Update Error"),
tr("An error occurred while downloading an update:") + QString(" ") + errorString);
tr("An error occurred while downloading an update:") + QString(" ") + errorString);
}
void DlgUpdate::downloadSuccessful(QUrl filepath) {
void DlgUpdate::downloadSuccessful(QUrl filepath)
{
setLabel(tr("Installing..."));
//Try to open the installer. If it opens, quit Cockatrice
if (QDesktopServices::openUrl(filepath))
{
// Try to open the installer. If it opens, quit Cockatrice
if (QDesktopServices::openUrl(filepath)) {
QMetaObject::invokeMethod(static_cast<MainWindow *>(parent()), "close", Qt::QueuedConnection);
qDebug() << "Opened downloaded update file successfully - closing Cockatrice";
close();
} else {
setLabel(tr("Error"));
QMessageBox::critical(this, tr("Update Error"),
tr("Cockatrice is unable to open the installer.") + "<br><br>"
+ tr("Try to update manually by closing Cockatrice and running the installer.") + "<br>"
+ tr("Download location") + QString(": %1").arg(filepath.toLocalFile()));
tr("Cockatrice is unable to open the installer.") + "<br><br>" +
tr("Try to update manually by closing Cockatrice and running the installer.") +
"<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->setValue(bytesRead);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,24 +1,19 @@
#include <QFont>
#include "filtertreemodel.h"
#include "filtertree.h"
#include "cardfilter.h"
#include "filtertree.h"
#include <QFont>
FilterTreeModel::FilterTreeModel(QObject *parent)
: QAbstractItemModel(parent)
FilterTreeModel::FilterTreeModel(QObject *parent) : QAbstractItemModel(parent)
{
fTree = new FilterTree;
connect(fTree,
SIGNAL(preInsertRow(const FilterTreeNode *, int)),
this, SLOT(proxyBeginInsertRow(const FilterTreeNode *, int)));
connect(fTree,
SIGNAL(postInsertRow(const FilterTreeNode *, int)),
this, SLOT(proxyEndInsertRow(const FilterTreeNode *, int)));
connect(fTree,
SIGNAL(preRemoveRow(const FilterTreeNode *, int)),
this, SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int)));
connect(fTree,
SIGNAL(postRemoveRow(const FilterTreeNode *, int)),
this, SLOT(proxyEndRemoveRow(const FilterTreeNode *, int)));
connect(fTree, SIGNAL(preInsertRow(const FilterTreeNode *, int)), this,
SLOT(proxyBeginInsertRow(const FilterTreeNode *, int)));
connect(fTree, SIGNAL(postInsertRow(const FilterTreeNode *, int)), this,
SLOT(proxyEndInsertRow(const FilterTreeNode *, int)));
connect(fTree, SIGNAL(preRemoveRow(const FilterTreeNode *, int)), this,
SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int)));
connect(fTree, SIGNAL(postRemoveRow(const FilterTreeNode *, int)), this,
SLOT(proxyEndRemoveRow(const FilterTreeNode *, int)));
}
FilterTreeModel::~FilterTreeModel()
@ -32,7 +27,7 @@ void FilterTreeModel::proxyBeginInsertRow(const FilterTreeNode *node, int i)
idx = node->index();
if (idx >= 0)
beginInsertRows(createIndex(idx, 0, (void *) node), i, i);
beginInsertRows(createIndex(idx, 0, (void *)node), i, i);
}
void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int)
@ -50,7 +45,7 @@ void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i)
idx = node->index();
if (idx >= 0)
beginRemoveRows(createIndex(idx, 0, (void *) node), i, i);
beginRemoveRows(createIndex(idx, 0, (void *)node), i, i);
}
void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int)
@ -102,7 +97,7 @@ int FilterTreeModel::rowCount(const QModelIndex &parent) const
return result;
}
int FilterTreeModel::columnCount(const QModelIndex &/*parent*/) const
int FilterTreeModel::columnCount(const QModelIndex & /*parent*/) const
{
return 1;
}
@ -133,7 +128,7 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
case Qt::ToolTipRole:
case Qt::StatusTipRole:
case Qt::WhatsThisRole:
if(!node->isLeaf())
if (!node->isLeaf())
return tr(node->textCStr());
else
return node->text();
@ -149,8 +144,7 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
return QVariant();
}
bool FilterTreeModel::setData(const QModelIndex &index,
const QVariant &value, int role)
bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
FilterTreeNode *node;
@ -158,7 +152,7 @@ bool FilterTreeModel::setData(const QModelIndex &index,
return false;
if (index.column() >= columnCount())
return false;
if (role != Qt::CheckStateRole )
if (role != Qt::CheckStateRole)
return false;
node = indexToNode(index);
@ -208,8 +202,7 @@ QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int
return createIndex(row, column, child);
}
QModelIndex FilterTreeModel::index(int row, int column,
const QModelIndex &parent) const
QModelIndex FilterTreeModel::index(int row, int column, const QModelIndex &parent) const
{
const FilterTreeNode *node;
@ -249,12 +242,12 @@ QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const
return QModelIndex();
}
bool FilterTreeModel::removeRows(int row, int count, const QModelIndex & parent)
bool FilterTreeModel::removeRows(int row, int count, const QModelIndex &parent)
{
FilterTreeNode *node;
int i, last;
last = row+count-1;
last = row + count - 1;
if (!parent.isValid() || count < 1 || row < 0)
return false;

View file

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

View file

@ -1,23 +1,20 @@
#include "gamescene.h"
#include "carditem.h"
#include "phasestoolbar.h"
#include "player.h"
#include "settingscache.h"
#include "zoneviewwidget.h"
#include "zoneviewzone.h"
#include "phasestoolbar.h"
#include "settingscache.h"
#include "carditem.h"
#include <math.h>
#include <QAction>
#include <QGraphicsSceneMouseEvent>
#include <QSet>
#include <QBasicTimer>
#include <QGraphicsView>
#include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <QSet>
#include <math.h>
GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent)
: QGraphicsScene(parent),
phasesToolbar(_phasesToolbar),
viewSize(QSize()),
playerRotation(0)
: QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()), playerRotation(0)
{
animationTimer = new QBasicTimer;
addItem(phasesToolbar);
@ -93,7 +90,7 @@ void GameScene::rearrange()
const int playersCount = playersPlaying.size();
const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2;
const int rows = ceil((qreal) playersCount / columns);
const int rows = ceil((qreal)playersCount / columns);
qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing;
QList<int> columnWidth;
@ -150,29 +147,32 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb
}
ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false);
zoneViews.append(item);
connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *)));
zoneViews.append(item);
connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *)));
addItem(item);
if (zoneName=="grave")
if (zoneName == "grave")
item->setPos(360, 100);
else if (zoneName=="rfg")
else if (zoneName == "rfg")
item->setPos(380, 120);
else
item->setPos(340, 80);
}
void GameScene::addRevealedZoneView(Player *player, CardZone *zone, const QList<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);
zoneViews.append(item);
connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *)));
connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *)));
addItem(item);
item->setPos(600, 80);
}
void GameScene::removeZoneView(ZoneViewWidget *item)
{
zoneViews.removeAt(zoneViews.indexOf(item));
zoneViews.removeAt(zoneViews.indexOf(item));
removeItem(item);
}
@ -202,7 +202,7 @@ void GameScene::processViewSizeChange(const QSize &newSize)
{
viewSize = newSize;
qreal newRatio = ((qreal) newSize.width()) / newSize.height();
qreal newRatio = ((qreal)newSize.width()) / newSize.height();
qreal minWidth = 0;
QList<qreal> minWidthByColumn;
for (int col = 0; col < playersByColumn.size(); ++col) {
@ -230,7 +230,7 @@ void GameScene::processViewSizeChange(const QSize &newSize)
qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size();
qreal newx = phasesToolbar->getWidth();
for (int col = 0; col < playersByColumn.size(); ++col) {
for (int row = 0; row < playersByColumn[col].size(); ++row){
for (int row = 0; row < playersByColumn[col].size(); ++row) {
playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn);
playersByColumn[col][row]->setPos(newx, playersByColumn[col][row]->y());
}
@ -240,7 +240,8 @@ void GameScene::processViewSizeChange(const QSize &newSize)
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.
CardZone *zone = 0;

View file

@ -15,14 +15,15 @@ class ServerInfo_Card;
class PhasesToolbar;
class QBasicTimer;
class GameScene : public QGraphicsScene {
class GameScene : public QGraphicsScene
{
Q_OBJECT
private:
static const int playerAreaSpacing = 5;
PhasesToolbar *phasesToolbar;
QList<Player *> players;
QList<QList<Player *> > playersByColumn;
QList<QList<Player *>> playersByColumn;
QList<ZoneViewWidget *> zoneViews;
QSize viewSize;
QPointer<CardItem> hoveredCard;
@ -30,6 +31,7 @@ private:
QSet<CardItem *> cardsToAnimate;
int playerRotation;
void updateHover(const QPointF &scenePos);
public:
GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0);
~GameScene();
@ -46,7 +48,10 @@ public:
void unregisterAnimationItem(AbstractCardItem *card);
public slots:
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 addPlayer(Player *player);
void removePlayer(Player *player);
@ -54,6 +59,7 @@ public slots:
void closeMostRecentZoneView();
void adjustPlayerRotation(int rotationAdjustment);
void rearrange();
protected:
bool event(QEvent *event);
void timerEvent(QTimerEvent *event);

View file

@ -1,30 +1,36 @@
#include <QTreeView>
#include <QCheckBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QHeaderView>
#include <QInputDialog>
#include <QDebug>
#include "tab_supervisor.h"
#include "gameselector.h"
#include "dlg_creategame.h"
#include "dlg_filter_games.h"
#include "gameselector.h"
#include "gamesmodel.h"
#include "tab_room.h"
#include "pending_command.h"
#include "pb/response.pb.h"
#include "pb/room_commands.pb.h"
#include "pb/serverinfo_game.pb.h"
#include "pb/response.pb.h"
#include "pending_command.h"
#include "tab_room.h"
#include "tab_supervisor.h"
#include <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)
{
gameListView = new QTreeView;
gameListModel = new GamesModel(_rooms, _gameTypes, this);
if(showfilters)
{
if (showfilters) {
gameListProxyModel = new GamesProxyModel(this, tabSupervisor->isOwnUserRegistered());
gameListProxyModel->setSourceModel(gameListModel);
gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
@ -53,7 +59,7 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup
gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId());
if (showfilters && restoresettings)
gameListProxyModel->loadFilterParameters(gameTypeMap);
gameListProxyModel->loadFilterParameters(gameTypeMap);
gameListView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
@ -74,8 +80,7 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup
spectateButton = new QPushButton;
QHBoxLayout *buttonLayout = new QHBoxLayout;
if(showfilters)
{
if (showfilters) {
buttonLayout->addWidget(filterButton);
buttonLayout->addWidget(clearFilterButton);
}
@ -93,12 +98,13 @@ GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSup
retranslateUi();
setLayout(mainLayout);
setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5);
setMinimumWidth((qreal)(gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5);
setMinimumHeight(200);
connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin()));
connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin()));
connect(gameListView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(actSelectedGameChanged(const QModelIndex &, const QModelIndex &)));
connect(gameListView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this,
SLOT(actSelectedGameChanged(const QModelIndex &, const QModelIndex &)));
connect(gameListView, SIGNAL(activated(const QModelIndex &)), this, SLOT(actJoin()));
}
@ -147,15 +153,31 @@ void GameSelector::checkResponse(const Response &response)
joinButton->setEnabled(true);
switch (response.response_code()) {
case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break;
case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break;
case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break;
case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break;
case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break;
case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break;
case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break;
case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break;
default: ;
case Response::RespNotInRoom:
QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first."));
break;
case Response::RespWrongPassword:
QMessageBox::critical(this, tr("Error"), tr("Wrong password."));
break;
case Response::RespSpectatorsNotAllowed:
QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game."));
break;
case Response::RespGameFull:
QMessageBox::critical(this, tr("Error"), tr("The game is already full."));
break;
case Response::RespNameNotFound:
QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more."));
break;
case Response::RespUserLevelTooLow:
QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users."));
break;
case Response::RespOnlyBuddies:
QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies."));
break;
case Response::RespInIgnoreList:
QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game."));
break;
default:;
}
if (response.response_code() != Response::RespSpectatorsNotAllowed)
@ -225,5 +247,5 @@ void GameSelector::actSelectedGameChanged(const QModelIndex &current, const QMod
bool overrideRestrictions = !tabSupervisor->getAdminLocked();
spectateButton->setEnabled(game.spectators_allowed() || overrideRestrictions);
joinButton->setEnabled( game.player_count() < game.max_players() || overrideRestrictions);
joinButton->setEnabled(game.player_count() < game.max_players() || overrideRestrictions);
}

View file

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

View file

@ -3,14 +3,25 @@
#include "pixmapgenerator.h"
#include "settingscache.h"
#include <QDateTime>
#include <QDebug>
#include <QIcon>
#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;
if (secs < SECS_PER_MIN * 2) // for first min we display "New"
@ -56,113 +67,119 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
int secs = then.secsTo(QDateTime::currentDateTime());
switch (role) {
case Qt::DisplayRole: return getGameCreatedString(secs);
case SORT_ROLE: return QVariant(secs);
case Qt::TextAlignmentRole: return Qt::AlignCenter;
default: return QVariant();
case Qt::DisplayRole:
return getGameCreatedString(secs);
case SORT_ROLE:
return QVariant(secs);
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
default:
return QVariant();
}
}
case DESCRIPTION:
switch(role) {
case SORT_ROLE:
case Qt::DisplayRole:
return QString::fromStdString(g.description());
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
switch (role) {
case SORT_ROLE:
case Qt::DisplayRole:
return QString::fromStdString(g.description());
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
case CREATOR: {
switch(role) {
case SORT_ROLE:
case Qt::DisplayRole:
return QString::fromStdString(g.creator_info().name());
case Qt::DecorationRole: {
QPixmap avatarPixmap = UserLevelPixmapGenerator::generatePixmap(13, (UserLevelFlags)g.creator_info().user_level(), false, QString::fromStdString(g.creator_info().privlevel()));
switch (role) {
case SORT_ROLE:
case Qt::DisplayRole:
return QString::fromStdString(g.creator_info().name());
case Qt::DecorationRole: {
QPixmap avatarPixmap = UserLevelPixmapGenerator::generatePixmap(
13, (UserLevelFlags)g.creator_info().user_level(), false,
QString::fromStdString(g.creator_info().privlevel()));
return QIcon(avatarPixmap);
}
default:
return QVariant();
default:
return QVariant();
}
}
case GAME_TYPE:
switch (role) {
case SORT_ROLE:
case Qt::DisplayRole: {
QStringList result;
GameTypeMap gameTypeMap = gameTypes.value(g.room_id());
for (int i = g.game_types_size() - 1; i >= 0; --i)
result.append(gameTypeMap.value(g.game_types(i)));
return result.join(", ");
case SORT_ROLE:
case Qt::DisplayRole: {
QStringList result;
GameTypeMap gameTypeMap = gameTypes.value(g.room_id());
for (int i = g.game_types_size() - 1; i >= 0; --i)
result.append(gameTypeMap.value(g.game_types(i)));
return result.join(", ");
}
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
case RESTRICTIONS:
switch(role) {
case SORT_ROLE:
case Qt::DisplayRole: {
QStringList result;
if (g.with_password())
result.append(tr("password"));
if (g.only_buddies())
result.append(tr("buddies only"));
if (g.only_registered())
result.append(tr("reg. users only"));
return result.join(", ");
}
case Qt::DecorationRole:{
return g.with_password() ? QIcon(LockPixmapGenerator::generatePixmap(13)) : QVariant();
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
switch (role) {
case SORT_ROLE:
case Qt::DisplayRole: {
QStringList result;
if (g.with_password())
result.append(tr("password"));
if (g.only_buddies())
result.append(tr("buddies only"));
if (g.only_registered())
result.append(tr("reg. users only"));
return result.join(", ");
}
case Qt::DecorationRole: {
return g.with_password() ? QIcon(LockPixmapGenerator::generatePixmap(13)) : QVariant();
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
}
case PLAYERS:
switch(role) {
case SORT_ROLE:
case Qt::DisplayRole:
return QString("%1/%2").arg(g.player_count()).arg(g.max_players());
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
default:
return QVariant();
switch (role) {
case SORT_ROLE:
case Qt::DisplayRole:
return QString("%1/%2").arg(g.player_count()).arg(g.max_players());
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
default:
return QVariant();
}
case SPECTATORS:
switch(role) {
case SORT_ROLE:
case Qt::DisplayRole: {
if (g.spectators_allowed()) {
QString result;
result.append(QString::number(g.spectators_count()));
switch (role) {
case SORT_ROLE:
case Qt::DisplayRole: {
if (g.spectators_allowed()) {
QString result;
result.append(QString::number(g.spectators_count()));
if (g.spectators_can_chat() && g.spectators_omniscient())
{
result.append(" (").append(tr("can chat")).append(" & ").append(tr("see hands")).append(")");
}
else if (g.spectators_can_chat())
{
result.append(" (").append(tr("can chat")).append(")");
}
else if (g.spectators_omniscient())
{
result.append(" (").append(tr("can see hands")).append(")");
}
if (g.spectators_can_chat() && g.spectators_omniscient()) {
result.append(" (")
.append(tr("can chat"))
.append(" & ")
.append(tr("see hands"))
.append(")");
} else if (g.spectators_can_chat()) {
result.append(" (").append(tr("can chat")).append(")");
} else if (g.spectators_omniscient()) {
result.append(" (").append(tr("can see hands")).append(")");
}
return result;
return result;
}
return QVariant(tr("not allowed"));
}
return QVariant(tr("not allowed"));
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
default:
return QVariant();
}
default: return QVariant();
default:
return QVariant();
}
}
@ -171,29 +188,36 @@ QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, in
if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole))
return QVariant();
switch (section) {
case ROOM: return tr("Room");
case CREATED: {
switch(role) {
case Qt::DisplayRole:
return tr("Age");
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
case ROOM:
return tr("Room");
case CREATED: {
switch (role) {
case Qt::DisplayRole:
return tr("Age");
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
}
}
}
case DESCRIPTION: return tr("Description");
case CREATOR: return tr("Creator");
case GAME_TYPE: return tr("Type");
case RESTRICTIONS: return tr("Restrictions");
case PLAYERS: {
switch(role) {
case Qt::DisplayRole:
return tr("Players");
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
case DESCRIPTION:
return tr("Description");
case CREATOR:
return tr("Creator");
case GAME_TYPE:
return tr("Type");
case RESTRICTIONS:
return tr("Restrictions");
case PLAYERS: {
switch (role) {
case Qt::DisplayRole:
return tr("Players");
case Qt::TextAlignmentRole:
return Qt::AlignCenter;
}
}
}
case SPECTATORS: return tr("Spectators");
default: return QVariant();
case SPECTATORS:
return tr("Spectators");
default:
return QVariant();
}
}
@ -213,7 +237,7 @@ void GamesModel::updateGameList(const ServerInfo_Game &game)
endRemoveRows();
} else {
gameList[i].MergeFrom(game);
emit dataChanged(index(i, 0), index(i, NUM_COLS-1));
emit dataChanged(index(i, 0), index(i, NUM_COLS - 1));
}
return;
}
@ -226,19 +250,15 @@ void GamesModel::updateGameList(const ServerInfo_Game &game)
}
GamesProxyModel::GamesProxyModel(QObject *parent, bool _ownUserIsRegistered)
: QSortFilterProxyModel(parent),
ownUserIsRegistered(_ownUserIsRegistered),
showBuddiesOnlyGames(false),
unavailableGamesVisible(false),
showPasswordProtectedGames(true),
maxPlayersFilterMin(-1),
maxPlayersFilterMax(-1)
: QSortFilterProxyModel(parent), ownUserIsRegistered(_ownUserIsRegistered), showBuddiesOnlyGames(false),
unavailableGamesVisible(false), showPasswordProtectedGames(true), maxPlayersFilterMin(-1), maxPlayersFilterMax(-1)
{
setSortRole(GamesModel::SORT_ROLE);
setDynamicSortFilter(true);
}
void GamesProxyModel::setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames) {
void GamesProxyModel::setShowBuddiesOnlyGames(bool _showBuddiesOnlyGames)
{
showBuddiesOnlyGames = _showBuddiesOnlyGames;
invalidateFilter();
}
@ -306,7 +326,7 @@ void GamesProxyModel::loadFilterParameters(const QMap<int, QString> &allGameType
QMapIterator<int, QString> gameTypesIterator(allGameTypes);
while (gameTypesIterator.hasNext()) {
gameTypesIterator.next();
if (settingsCache->gameFilters().isGameTypeEnabled(gameTypesIterator.value())){
if (settingsCache->gameFilters().isGameTypeEnabled(gameTypesIterator.value())) {
gameTypeFilter.insert(gameTypesIterator.key());
}
}
@ -325,14 +345,14 @@ void GamesProxyModel::saveFilterParameters(const QMap<int, QString> &allGameType
while (gameTypeIterator.hasNext()) {
gameTypeIterator.next();
bool enabled = gameTypeFilter.contains(gameTypeIterator.key());
settingsCache->gameFilters().setGameTypeEnabled(gameTypeIterator.value(),enabled);
settingsCache->gameFilters().setGameTypeEnabled(gameTypeIterator.value(), enabled);
}
settingsCache->gameFilters().setMinPlayers(maxPlayersFilterMin);
settingsCache->gameFilters().setMaxPlayers(maxPlayersFilterMax);
}
bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourceParent*/) const
bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const
{
GamesModel *model = qobject_cast<GamesModel *>(sourceModel());
if (!model)

View file

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

View file

@ -1,12 +1,11 @@
#include "gameview.h"
#include "gamescene.h"
#include "settingscache.h"
#include <QResizeEvent>
#include <QAction>
#include <QResizeEvent>
#include <QRubberBand>
GameView::GameView(QGraphicsScene *scene, QWidget *parent)
: QGraphicsView(scene, parent), rubberBand(0)
GameView::GameView(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent), rubberBand(0)
{
setBackgroundBrush(QBrush(QColor(0, 0, 0)));
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing);
@ -23,7 +22,7 @@ GameView::GameView(QGraphicsScene *scene, QWidget *parent)
connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView()));
addAction(aCloseMostRecentZoneView);
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts()));
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()), this, SLOT(refreshShortcuts()));
refreshShortcuts();
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
}

View file

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

View file

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

View file

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

View file

@ -1,10 +1,10 @@
#include <QPainter>
#include "handzone.h"
#include "settingscache.h"
#include "thememanager.h"
#include "player.h"
#include "carddragitem.h"
#include "carditem.h"
#include "player.h"
#include "settingscache.h"
#include "thememanager.h"
#include <QPainter>
#include "pb/command_move_card.pb.h"
@ -37,7 +37,7 @@ void HandZone::addCardImpl(CardItem *card, int x, int /*y*/)
card->update();
}
void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint & dropPoint)
void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint &dropPoint)
{
QPoint point = dropPoint + scenePos().toPoint();
int x = -1;
@ -86,17 +86,19 @@ void HandZone::reorganizeCards()
bool leftJustified = settingsCache->getLeftJustified();
qreal cardWidth = cards.at(0)->boundingRect().width();
const int xPadding = leftJustified ? cardWidth * 1.4 : 5;
qreal totalWidth = leftJustified? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding;
qreal totalWidth =
leftJustified ? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding;
for (int i = 0; i < cardCount; i++) {
CardItem *c = cards.at(i);
// If the total width of the cards is smaller than the available width,
// the cards do not need to overlap and are displayed in the center of the area.
if (cardWidth * cardCount > totalWidth)
c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
else {
qreal xPosition = leftJustified ? xPadding + ((qreal) i) * cardWidth :
xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2;
qreal xPosition =
leftJustified ? xPadding + ((qreal)i) * cardWidth
: xPadding + ((qreal)i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2;
c->setPos(xPosition, 5);
}
c->setRealZValue(i);
@ -116,9 +118,9 @@ void HandZone::reorganizeCards()
// If the total height of the cards is smaller than the available height,
// the cards do not need to overlap and are displayed in the center of the area.
if (cardHeight * cardCount > totalHeight)
c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1));
c->setPos(x, ((qreal)i) * (totalHeight - cardHeight) / (cardCount - 1));
else
c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2);
c->setPos(x, ((qreal)i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2);
c->setRealZValue(i);
}
}

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