Merge pull request #52 from mattkelly/whitespace
Convert rest of source to 4-space indent
This commit is contained in:
commit
ed5f02bf7a
146 changed files with 12810 additions and 12810 deletions
|
@ -5,47 +5,47 @@
|
|||
#include <QDebug>
|
||||
|
||||
AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag)
|
||||
: QGraphicsItem(), item(_item), hotSpot(_hotSpot)
|
||||
: QGraphicsItem(), item(_item), hotSpot(_hotSpot)
|
||||
{
|
||||
if (parentDrag) {
|
||||
parentDrag->addChildDrag(this);
|
||||
setZValue(2000000007 + hotSpot.x() * 1000000 + hotSpot.y() * 1000 + 1000);
|
||||
} else {
|
||||
if ((hotSpot.x() < 0) || (hotSpot.y() < 0)) {
|
||||
qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y();
|
||||
hotSpot = QPointF();
|
||||
} else if ((hotSpot.x() > CARD_WIDTH) || (hotSpot.y() > CARD_HEIGHT)) {
|
||||
qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y();
|
||||
hotSpot = QPointF(CARD_WIDTH, CARD_HEIGHT);
|
||||
}
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
setZValue(2000000007);
|
||||
}
|
||||
if (item->getTapped())
|
||||
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
|
||||
if (parentDrag) {
|
||||
parentDrag->addChildDrag(this);
|
||||
setZValue(2000000007 + hotSpot.x() * 1000000 + hotSpot.y() * 1000 + 1000);
|
||||
} else {
|
||||
if ((hotSpot.x() < 0) || (hotSpot.y() < 0)) {
|
||||
qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y();
|
||||
hotSpot = QPointF();
|
||||
} else if ((hotSpot.x() > CARD_WIDTH) || (hotSpot.y() > CARD_HEIGHT)) {
|
||||
qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y();
|
||||
hotSpot = QPointF(CARD_WIDTH, CARD_HEIGHT);
|
||||
}
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
setZValue(2000000007);
|
||||
}
|
||||
if (item->getTapped())
|
||||
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
|
||||
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
}
|
||||
|
||||
AbstractCardDragItem::~AbstractCardDragItem()
|
||||
{
|
||||
qDebug("CardDragItem destructor");
|
||||
for (int i = 0; i < childDrags.size(); i++)
|
||||
delete childDrags[i];
|
||||
qDebug("CardDragItem destructor");
|
||||
for (int i = 0; i < childDrags.size(); i++)
|
||||
delete childDrags[i];
|
||||
}
|
||||
|
||||
void AbstractCardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
|
||||
{
|
||||
item->paint(painter, option, widget);
|
||||
item->paint(painter, option, widget);
|
||||
}
|
||||
|
||||
void AbstractCardDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
event->accept();
|
||||
updatePosition(event->scenePos());
|
||||
event->accept();
|
||||
updatePosition(event->scenePos());
|
||||
}
|
||||
|
||||
void AbstractCardDragItem::addChildDrag(AbstractCardDragItem *child)
|
||||
{
|
||||
childDrags << child;
|
||||
childDrags << child;
|
||||
}
|
||||
|
|
|
@ -8,24 +8,24 @@ class CardZone;
|
|||
class CardInfo;
|
||||
|
||||
class AbstractCardDragItem : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
AbstractCardItem *item;
|
||||
QPointF hotSpot;
|
||||
QList<AbstractCardDragItem *> childDrags;
|
||||
AbstractCardItem *item;
|
||||
QPointF hotSpot;
|
||||
QList<AbstractCardDragItem *> childDrags;
|
||||
public:
|
||||
enum { Type = typeCardDrag };
|
||||
int type() const { return Type; }
|
||||
AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
|
||||
~AbstractCardDragItem();
|
||||
QRectF boundingRect() const { return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); }
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
AbstractCardItem *getItem() const { return item; }
|
||||
QPointF getHotSpot() const { return hotSpot; }
|
||||
void addChildDrag(AbstractCardDragItem *child);
|
||||
virtual void updatePosition(const QPointF &cursorScenePos) = 0;
|
||||
enum { Type = typeCardDrag };
|
||||
int type() const { return Type; }
|
||||
AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
|
||||
~AbstractCardDragItem();
|
||||
QRectF boundingRect() const { return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); }
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
AbstractCardItem *getItem() const { return item; }
|
||||
QPointF getHotSpot() const { return hotSpot; }
|
||||
void addChildDrag(AbstractCardDragItem *child);
|
||||
virtual void updatePosition(const QPointF &cursorScenePos) = 0;
|
||||
protected:
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -12,245 +12,245 @@
|
|||
#include <QDebug>
|
||||
|
||||
AbstractCardItem::AbstractCardItem(const QString &_name, Player *_owner, int _id, QGraphicsItem *parent)
|
||||
: ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0)
|
||||
: ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0)
|
||||
{
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
setFlag(ItemIsSelectable);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
setFlag(ItemIsSelectable);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
|
||||
connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated()));
|
||||
connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate()));
|
||||
cardInfoUpdated();
|
||||
connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated()));
|
||||
connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate()));
|
||||
cardInfoUpdated();
|
||||
}
|
||||
|
||||
AbstractCardItem::~AbstractCardItem()
|
||||
{
|
||||
emit deleteCardInfoPopup(name);
|
||||
emit deleteCardInfoPopup(name);
|
||||
}
|
||||
|
||||
QRectF AbstractCardItem::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT);
|
||||
return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT);
|
||||
}
|
||||
|
||||
void AbstractCardItem::pixmapUpdated()
|
||||
{
|
||||
update();
|
||||
emit sigPixmapUpdated();
|
||||
update();
|
||||
emit sigPixmapUpdated();
|
||||
}
|
||||
|
||||
void AbstractCardItem::cardInfoUpdated()
|
||||
{
|
||||
info = db->getCard(name);
|
||||
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated()));
|
||||
info = db->getCard(name);
|
||||
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated()));
|
||||
}
|
||||
|
||||
void AbstractCardItem::setRealZValue(qreal _zValue)
|
||||
{
|
||||
realZValue = _zValue;
|
||||
setZValue(_zValue);
|
||||
realZValue = _zValue;
|
||||
setZValue(_zValue);
|
||||
}
|
||||
|
||||
QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const
|
||||
{
|
||||
return QSizeF(
|
||||
painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(),
|
||||
painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length()
|
||||
);
|
||||
return QSizeF(
|
||||
painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(),
|
||||
painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length()
|
||||
);
|
||||
}
|
||||
|
||||
void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle)
|
||||
{
|
||||
QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect());
|
||||
QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect());
|
||||
|
||||
painter->resetTransform();
|
||||
painter->resetTransform();
|
||||
|
||||
QTransform pixmapTransform;
|
||||
pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2);
|
||||
pixmapTransform.rotate(angle);
|
||||
pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2);
|
||||
painter->setTransform(pixmapTransform);
|
||||
QTransform pixmapTransform;
|
||||
pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2);
|
||||
pixmapTransform.rotate(angle);
|
||||
pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2);
|
||||
painter->setTransform(pixmapTransform);
|
||||
|
||||
QFont f;
|
||||
int fontSize = round(translatedSize.height() / 8);
|
||||
if (fontSize < 9)
|
||||
fontSize = 9;
|
||||
if (fontSize > 10)
|
||||
fontSize = 10;
|
||||
f.setPixelSize(fontSize);
|
||||
QFont f;
|
||||
int fontSize = round(translatedSize.height() / 8);
|
||||
if (fontSize < 9)
|
||||
fontSize = 9;
|
||||
if (fontSize > 10)
|
||||
fontSize = 10;
|
||||
f.setPixelSize(fontSize);
|
||||
|
||||
painter->setFont(f);
|
||||
painter->setFont(f);
|
||||
}
|
||||
|
||||
void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle)
|
||||
{
|
||||
qreal scaleFactor = translatedSize.width() / boundingRect().width();
|
||||
qreal scaleFactor = translatedSize.width() / boundingRect().width();
|
||||
|
||||
CardInfo *imageSource = facedown ? db->getCard() : info;
|
||||
QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize());
|
||||
painter->save();
|
||||
QColor bgColor = Qt::transparent;
|
||||
if (translatedPixmap) {
|
||||
painter->save();
|
||||
transformPainter(painter, translatedSize, angle);
|
||||
painter->drawPixmap(QPointF(0, 0), *translatedPixmap);
|
||||
painter->restore();
|
||||
} else {
|
||||
QString colorStr;
|
||||
if (!color.isEmpty())
|
||||
colorStr = color;
|
||||
else if (info->getColors().size() > 1)
|
||||
colorStr = "m";
|
||||
else if (!info->getColors().isEmpty())
|
||||
colorStr = info->getColors().first().toLower();
|
||||
CardInfo *imageSource = facedown ? db->getCard() : info;
|
||||
QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize());
|
||||
painter->save();
|
||||
QColor bgColor = Qt::transparent;
|
||||
if (translatedPixmap) {
|
||||
painter->save();
|
||||
transformPainter(painter, translatedSize, angle);
|
||||
painter->drawPixmap(QPointF(0, 0), *translatedPixmap);
|
||||
painter->restore();
|
||||
} else {
|
||||
QString colorStr;
|
||||
if (!color.isEmpty())
|
||||
colorStr = color;
|
||||
else if (info->getColors().size() > 1)
|
||||
colorStr = "m";
|
||||
else if (!info->getColors().isEmpty())
|
||||
colorStr = info->getColors().first().toLower();
|
||||
|
||||
if (colorStr == "b")
|
||||
bgColor = QColor(0, 0, 0);
|
||||
else if (colorStr == "u")
|
||||
bgColor = QColor(0, 140, 180);
|
||||
else if (colorStr == "w")
|
||||
bgColor = QColor(255, 250, 140);
|
||||
else if (colorStr == "r")
|
||||
bgColor = QColor(230, 0, 0);
|
||||
else if (colorStr == "g")
|
||||
bgColor = QColor(0, 160, 0);
|
||||
else if (colorStr == "m")
|
||||
bgColor = QColor(250, 190, 30);
|
||||
else
|
||||
bgColor = QColor(230, 230, 230);
|
||||
}
|
||||
painter->setBrush(bgColor);
|
||||
QPen pen(Qt::black);
|
||||
pen.setWidth(2);
|
||||
painter->setPen(pen);
|
||||
painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2));
|
||||
if (colorStr == "b")
|
||||
bgColor = QColor(0, 0, 0);
|
||||
else if (colorStr == "u")
|
||||
bgColor = QColor(0, 140, 180);
|
||||
else if (colorStr == "w")
|
||||
bgColor = QColor(255, 250, 140);
|
||||
else if (colorStr == "r")
|
||||
bgColor = QColor(230, 0, 0);
|
||||
else if (colorStr == "g")
|
||||
bgColor = QColor(0, 160, 0);
|
||||
else if (colorStr == "m")
|
||||
bgColor = QColor(250, 190, 30);
|
||||
else
|
||||
bgColor = QColor(230, 230, 230);
|
||||
}
|
||||
painter->setBrush(bgColor);
|
||||
QPen pen(Qt::black);
|
||||
pen.setWidth(2);
|
||||
painter->setPen(pen);
|
||||
painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2));
|
||||
|
||||
if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) {
|
||||
painter->save();
|
||||
transformPainter(painter, translatedSize, angle);
|
||||
painter->setPen(Qt::white);
|
||||
painter->setBackground(Qt::black);
|
||||
painter->setBackgroundMode(Qt::OpaqueMode);
|
||||
QString nameStr;
|
||||
if (facedown)
|
||||
nameStr = "# " + QString::number(id);
|
||||
else
|
||||
nameStr = name;
|
||||
painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr);
|
||||
painter->restore();
|
||||
}
|
||||
if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) {
|
||||
painter->save();
|
||||
transformPainter(painter, translatedSize, angle);
|
||||
painter->setPen(Qt::white);
|
||||
painter->setBackground(Qt::black);
|
||||
painter->setBackgroundMode(Qt::OpaqueMode);
|
||||
QString nameStr;
|
||||
if (facedown)
|
||||
nameStr = "# " + QString::number(id);
|
||||
else
|
||||
nameStr = name;
|
||||
painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr);
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
painter->restore();
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/)
|
||||
{
|
||||
painter->save();
|
||||
painter->save();
|
||||
|
||||
QSizeF translatedSize = getTranslatedSize(painter);
|
||||
paintPicture(painter, translatedSize, tapAngle);
|
||||
QSizeF translatedSize = getTranslatedSize(painter);
|
||||
paintPicture(painter, translatedSize, tapAngle);
|
||||
|
||||
painter->save();
|
||||
painter->setRenderHint(QPainter::Antialiasing, false);
|
||||
transformPainter(painter, translatedSize, tapAngle);
|
||||
if (isSelected()) {
|
||||
painter->setPen(Qt::red);
|
||||
painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1));
|
||||
} else if (isHovered) {
|
||||
painter->setPen(Qt::yellow);
|
||||
painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1));
|
||||
}
|
||||
painter->restore();
|
||||
painter->save();
|
||||
painter->setRenderHint(QPainter::Antialiasing, false);
|
||||
transformPainter(painter, translatedSize, tapAngle);
|
||||
if (isSelected()) {
|
||||
painter->setPen(Qt::red);
|
||||
painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1));
|
||||
} else if (isHovered) {
|
||||
painter->setPen(Qt::yellow);
|
||||
painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1));
|
||||
}
|
||||
painter->restore();
|
||||
|
||||
painter->restore();
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
void AbstractCardItem::setName(const QString &_name)
|
||||
{
|
||||
if (name == _name)
|
||||
return;
|
||||
if (name == _name)
|
||||
return;
|
||||
|
||||
emit deleteCardInfoPopup(name);
|
||||
disconnect(info, 0, this, 0);
|
||||
name = _name;
|
||||
info = db->getCard(name);
|
||||
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated()));
|
||||
update();
|
||||
emit deleteCardInfoPopup(name);
|
||||
disconnect(info, 0, this, 0);
|
||||
name = _name;
|
||||
info = db->getCard(name);
|
||||
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated()));
|
||||
update();
|
||||
}
|
||||
|
||||
void AbstractCardItem::setHovered(bool _hovered)
|
||||
{
|
||||
if (isHovered == _hovered)
|
||||
return;
|
||||
if (isHovered == _hovered)
|
||||
return;
|
||||
|
||||
if (_hovered)
|
||||
processHoverEvent();
|
||||
isHovered = _hovered;
|
||||
setZValue(_hovered ? 2000000004 : realZValue);
|
||||
update();
|
||||
if (_hovered)
|
||||
processHoverEvent();
|
||||
isHovered = _hovered;
|
||||
setZValue(_hovered ? 2000000004 : realZValue);
|
||||
update();
|
||||
}
|
||||
|
||||
void AbstractCardItem::setColor(const QString &_color)
|
||||
{
|
||||
color = _color;
|
||||
update();
|
||||
color = _color;
|
||||
update();
|
||||
}
|
||||
|
||||
void AbstractCardItem::setTapped(bool _tapped, bool canAnimate)
|
||||
{
|
||||
if (tapped == _tapped)
|
||||
return;
|
||||
if (tapped == _tapped)
|
||||
return;
|
||||
|
||||
tapped = _tapped;
|
||||
if (settingsCache->getTapAnimation() && 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));
|
||||
update();
|
||||
}
|
||||
tapped = _tapped;
|
||||
if (settingsCache->getTapAnimation() && 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));
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractCardItem::setFaceDown(bool _facedown)
|
||||
{
|
||||
facedown = _facedown;
|
||||
update();
|
||||
emit updateCardMenu(this);
|
||||
facedown = _facedown;
|
||||
update();
|
||||
emit updateCardMenu(this);
|
||||
}
|
||||
|
||||
void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (!isSelected()) {
|
||||
scene()->clearSelection();
|
||||
setSelected(true);
|
||||
}
|
||||
if (event->button() == Qt::LeftButton)
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
else if (event->button() == Qt::MidButton)
|
||||
emit showCardInfoPopup(event->screenPos(), name);
|
||||
event->accept();
|
||||
if (!isSelected()) {
|
||||
scene()->clearSelection();
|
||||
setSelected(true);
|
||||
}
|
||||
if (event->button() == Qt::LeftButton)
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
else if (event->button() == Qt::MidButton)
|
||||
emit showCardInfoPopup(event->screenPos(), name);
|
||||
event->accept();
|
||||
}
|
||||
|
||||
void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::MidButton)
|
||||
emit deleteCardInfoPopup(name);
|
||||
if (event->button() == Qt::MidButton)
|
||||
emit deleteCardInfoPopup(name);
|
||||
|
||||
// This function ensures the parent function doesn't mess around with our selection.
|
||||
event->accept();
|
||||
// This function ensures the parent function doesn't mess around with our selection.
|
||||
event->accept();
|
||||
}
|
||||
|
||||
void AbstractCardItem::processHoverEvent()
|
||||
{
|
||||
emit hovered(this);
|
||||
emit hovered(this);
|
||||
}
|
||||
|
||||
QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
|
||||
{
|
||||
if (change == ItemSelectedHasChanged) {
|
||||
update();
|
||||
return value;
|
||||
} else
|
||||
return QGraphicsItem::itemChange(change, value);
|
||||
if (change == ItemSelectedHasChanged) {
|
||||
update();
|
||||
return value;
|
||||
} else
|
||||
return QGraphicsItem::itemChange(change, value);
|
||||
}
|
||||
|
||||
|
|
|
@ -12,59 +12,59 @@ const int CARD_WIDTH = 72;
|
|||
const int CARD_HEIGHT = 102;
|
||||
|
||||
class AbstractCardItem : public ArrowTarget {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
CardInfo *info;
|
||||
CardInfoWidget *infoWidget;
|
||||
int id;
|
||||
QString name;
|
||||
bool tapped;
|
||||
bool facedown;
|
||||
int tapAngle;
|
||||
QString color;
|
||||
CardInfo *info;
|
||||
CardInfoWidget *infoWidget;
|
||||
int id;
|
||||
QString name;
|
||||
bool tapped;
|
||||
bool facedown;
|
||||
int tapAngle;
|
||||
QString color;
|
||||
private:
|
||||
bool isHovered;
|
||||
qreal realZValue;
|
||||
bool isHovered;
|
||||
qreal realZValue;
|
||||
private slots:
|
||||
void pixmapUpdated();
|
||||
void cardInfoUpdated();
|
||||
void callUpdate() { update(); }
|
||||
void pixmapUpdated();
|
||||
void cardInfoUpdated();
|
||||
void callUpdate() { update(); }
|
||||
signals:
|
||||
void hovered(AbstractCardItem *card);
|
||||
void showCardInfoPopup(QPoint pos, QString cardName);
|
||||
void deleteCardInfoPopup(QString cardName);
|
||||
void updateCardMenu(AbstractCardItem *card);
|
||||
void sigPixmapUpdated();
|
||||
void hovered(AbstractCardItem *card);
|
||||
void showCardInfoPopup(QPoint pos, QString cardName);
|
||||
void deleteCardInfoPopup(QString cardName);
|
||||
void updateCardMenu(AbstractCardItem *card);
|
||||
void sigPixmapUpdated();
|
||||
public:
|
||||
enum { Type = typeCard };
|
||||
int type() const { return Type; }
|
||||
AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0);
|
||||
~AbstractCardItem();
|
||||
QRectF boundingRect() const;
|
||||
QSizeF getTranslatedSize(QPainter *painter) const;
|
||||
void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle);
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
CardInfo *getInfo() const { return info; }
|
||||
int getId() const { return id; }
|
||||
void setId(int _id) { id = _id; }
|
||||
QString getName() const { return name; }
|
||||
void setName(const QString &_name = QString());
|
||||
qreal getRealZValue() const { return realZValue; }
|
||||
void setRealZValue(qreal _zValue);
|
||||
void setHovered(bool _hovered);
|
||||
QString getColor() const { return color; }
|
||||
void setColor(const QString &_color);
|
||||
bool getTapped() const { return tapped; }
|
||||
void setTapped(bool _tapped, bool canAnimate = false);
|
||||
bool getFaceDown() const { return facedown; }
|
||||
void setFaceDown(bool _facedown);
|
||||
void processHoverEvent();
|
||||
void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); }
|
||||
enum { Type = typeCard };
|
||||
int type() const { return Type; }
|
||||
AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0);
|
||||
~AbstractCardItem();
|
||||
QRectF boundingRect() const;
|
||||
QSizeF getTranslatedSize(QPainter *painter) const;
|
||||
void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle);
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
CardInfo *getInfo() const { return info; }
|
||||
int getId() const { return id; }
|
||||
void setId(int _id) { id = _id; }
|
||||
QString getName() const { return name; }
|
||||
void setName(const QString &_name = QString());
|
||||
qreal getRealZValue() const { return realZValue; }
|
||||
void setRealZValue(qreal _zValue);
|
||||
void setHovered(bool _hovered);
|
||||
QString getColor() const { return color; }
|
||||
void setColor(const QString &_color);
|
||||
bool getTapped() const { return tapped; }
|
||||
void setTapped(bool _tapped, bool canAnimate = false);
|
||||
bool getFaceDown() const { return facedown; }
|
||||
void setFaceDown(bool _facedown);
|
||||
void processHoverEvent();
|
||||
void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); }
|
||||
protected:
|
||||
void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value);
|
||||
void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -26,67 +26,67 @@ class Event_ServerShutdown;
|
|||
class Event_ReplayAdded;
|
||||
|
||||
enum ClientStatus {
|
||||
StatusDisconnected,
|
||||
StatusDisconnecting,
|
||||
StatusConnecting,
|
||||
StatusAwaitingWelcome,
|
||||
StatusLoggingIn,
|
||||
StatusLoggedIn,
|
||||
StatusDisconnected,
|
||||
StatusDisconnecting,
|
||||
StatusConnecting,
|
||||
StatusAwaitingWelcome,
|
||||
StatusLoggingIn,
|
||||
StatusLoggedIn,
|
||||
};
|
||||
|
||||
class AbstractClient : public QObject {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void statusChanged(ClientStatus _status);
|
||||
void statusChanged(ClientStatus _status);
|
||||
|
||||
// Room events
|
||||
void roomEventReceived(const RoomEvent &event);
|
||||
// Game events
|
||||
void gameEventContainerReceived(const GameEventContainer &event);
|
||||
// Session events
|
||||
void serverIdentificationEventReceived(const Event_ServerIdentification &event);
|
||||
void connectionClosedEventReceived(const Event_ConnectionClosed &event);
|
||||
void serverShutdownEventReceived(const Event_ServerShutdown &event);
|
||||
void addToListEventReceived(const Event_AddToList &event);
|
||||
void removeFromListEventReceived(const Event_RemoveFromList &event);
|
||||
void userJoinedEventReceived(const Event_UserJoined &event);
|
||||
void userLeftEventReceived(const Event_UserLeft &event);
|
||||
void serverMessageEventReceived(const Event_ServerMessage &event);
|
||||
void listRoomsEventReceived(const Event_ListRooms &event);
|
||||
void gameJoinedEventReceived(const Event_GameJoined &event);
|
||||
void userMessageEventReceived(const Event_UserMessage &event);
|
||||
void userInfoChanged(const ServerInfo_User &userInfo);
|
||||
void buddyListReceived(const QList<ServerInfo_User> &buddyList);
|
||||
void ignoreListReceived(const QList<ServerInfo_User> &ignoreList);
|
||||
void replayAddedEventReceived(const Event_ReplayAdded &event);
|
||||
// Room events
|
||||
void roomEventReceived(const RoomEvent &event);
|
||||
// Game events
|
||||
void gameEventContainerReceived(const GameEventContainer &event);
|
||||
// Session events
|
||||
void serverIdentificationEventReceived(const Event_ServerIdentification &event);
|
||||
void connectionClosedEventReceived(const Event_ConnectionClosed &event);
|
||||
void serverShutdownEventReceived(const Event_ServerShutdown &event);
|
||||
void addToListEventReceived(const Event_AddToList &event);
|
||||
void removeFromListEventReceived(const Event_RemoveFromList &event);
|
||||
void userJoinedEventReceived(const Event_UserJoined &event);
|
||||
void userLeftEventReceived(const Event_UserLeft &event);
|
||||
void serverMessageEventReceived(const Event_ServerMessage &event);
|
||||
void listRoomsEventReceived(const Event_ListRooms &event);
|
||||
void gameJoinedEventReceived(const Event_GameJoined &event);
|
||||
void userMessageEventReceived(const Event_UserMessage &event);
|
||||
void userInfoChanged(const ServerInfo_User &userInfo);
|
||||
void buddyListReceived(const QList<ServerInfo_User> &buddyList);
|
||||
void ignoreListReceived(const QList<ServerInfo_User> &ignoreList);
|
||||
void replayAddedEventReceived(const Event_ReplayAdded &event);
|
||||
|
||||
void sigQueuePendingCommand(PendingCommand *pend);
|
||||
void sigQueuePendingCommand(PendingCommand *pend);
|
||||
private:
|
||||
int nextCmdId;
|
||||
mutable QMutex clientMutex;
|
||||
ClientStatus status;
|
||||
int nextCmdId;
|
||||
mutable QMutex clientMutex;
|
||||
ClientStatus status;
|
||||
private slots:
|
||||
void queuePendingCommand(PendingCommand *pend);
|
||||
void queuePendingCommand(PendingCommand *pend);
|
||||
protected slots:
|
||||
void processProtocolItem(const ServerMessage &item);
|
||||
void processProtocolItem(const ServerMessage &item);
|
||||
protected:
|
||||
QMap<int, PendingCommand *> pendingCommands;
|
||||
QString userName, password;
|
||||
void setStatus(ClientStatus _status);
|
||||
int getNewCmdId() { return nextCmdId++; }
|
||||
virtual void sendCommandContainer(const CommandContainer &cont) = 0;
|
||||
QMap<int, PendingCommand *> pendingCommands;
|
||||
QString userName, password;
|
||||
void setStatus(ClientStatus _status);
|
||||
int getNewCmdId() { return nextCmdId++; }
|
||||
virtual void sendCommandContainer(const CommandContainer &cont) = 0;
|
||||
public:
|
||||
AbstractClient(QObject *parent = 0);
|
||||
~AbstractClient();
|
||||
AbstractClient(QObject *parent = 0);
|
||||
~AbstractClient();
|
||||
|
||||
ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; }
|
||||
void sendCommand(const CommandContainer &cont);
|
||||
void sendCommand(PendingCommand *pend);
|
||||
ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; }
|
||||
void sendCommand(const CommandContainer &cont);
|
||||
void sendCommand(PendingCommand *pend);
|
||||
|
||||
static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd);
|
||||
static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId);
|
||||
static PendingCommand *prepareModeratorCommand(const ::google::protobuf::Message &cmd);
|
||||
static PendingCommand *prepareAdminCommand(const ::google::protobuf::Message &cmd);
|
||||
static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd);
|
||||
static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId);
|
||||
static PendingCommand *prepareModeratorCommand(const ::google::protobuf::Message &cmd);
|
||||
static PendingCommand *prepareAdminCommand(const ::google::protobuf::Message &cmd);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -9,137 +9,137 @@
|
|||
#include "pb/command_set_counter.pb.h"
|
||||
|
||||
AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent)
|
||||
: QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea)
|
||||
: QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea)
|
||||
{
|
||||
setAcceptsHoverEvents(true);
|
||||
setAcceptsHoverEvents(true);
|
||||
|
||||
if (player->getLocal()) {
|
||||
menu = new QMenu(name);
|
||||
aSet = new QAction(this);
|
||||
connect(aSet, SIGNAL(triggered()), this, SLOT(setCounter()));
|
||||
menu->addAction(aSet);
|
||||
menu->addSeparator();
|
||||
for (int i = -10; i <= 10; ++i)
|
||||
if (i == 0)
|
||||
menu->addSeparator();
|
||||
else {
|
||||
QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this);
|
||||
if (i == -1)
|
||||
aDec = aIncrement;
|
||||
else if (i == 1)
|
||||
aInc = aIncrement;
|
||||
aIncrement->setData(i);
|
||||
connect(aIncrement, SIGNAL(triggered()), this, SLOT(incrementCounter()));
|
||||
menu->addAction(aIncrement);
|
||||
}
|
||||
} else
|
||||
menu = 0;
|
||||
if (player->getLocal()) {
|
||||
menu = new QMenu(name);
|
||||
aSet = new QAction(this);
|
||||
connect(aSet, SIGNAL(triggered()), this, SLOT(setCounter()));
|
||||
menu->addAction(aSet);
|
||||
menu->addSeparator();
|
||||
for (int i = -10; i <= 10; ++i)
|
||||
if (i == 0)
|
||||
menu->addSeparator();
|
||||
else {
|
||||
QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this);
|
||||
if (i == -1)
|
||||
aDec = aIncrement;
|
||||
else if (i == 1)
|
||||
aInc = aIncrement;
|
||||
aIncrement->setData(i);
|
||||
connect(aIncrement, SIGNAL(triggered()), this, SLOT(incrementCounter()));
|
||||
menu->addAction(aIncrement);
|
||||
}
|
||||
} else
|
||||
menu = 0;
|
||||
|
||||
retranslateUi();
|
||||
retranslateUi();
|
||||
}
|
||||
|
||||
AbstractCounter::~AbstractCounter()
|
||||
{
|
||||
delete menu;
|
||||
delete menu;
|
||||
}
|
||||
|
||||
void AbstractCounter::delCounter()
|
||||
{
|
||||
if (dialogSemaphore)
|
||||
deleteAfterDialog = true;
|
||||
else
|
||||
deleteLater();
|
||||
if (dialogSemaphore)
|
||||
deleteAfterDialog = true;
|
||||
else
|
||||
deleteLater();
|
||||
}
|
||||
|
||||
void AbstractCounter::retranslateUi()
|
||||
{
|
||||
if (menu) {
|
||||
aSet->setText(tr("&Set counter..."));
|
||||
}
|
||||
if (menu) {
|
||||
aSet->setText(tr("&Set counter..."));
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractCounter::setShortcutsActive()
|
||||
{
|
||||
if (name == "life") {
|
||||
aSet->setShortcut(tr("Ctrl+L"));
|
||||
aDec->setShortcut(tr("F11"));
|
||||
aInc->setShortcut(tr("F12"));
|
||||
}
|
||||
if (name == "life") {
|
||||
aSet->setShortcut(tr("Ctrl+L"));
|
||||
aDec->setShortcut(tr("F11"));
|
||||
aInc->setShortcut(tr("F12"));
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractCounter::setShortcutsInactive()
|
||||
{
|
||||
if (name == "life") {
|
||||
aSet->setShortcut(QKeySequence());
|
||||
aDec->setShortcut(QKeySequence());
|
||||
aInc->setShortcut(QKeySequence());
|
||||
}
|
||||
if (name == "life") {
|
||||
aSet->setShortcut(QKeySequence());
|
||||
aDec->setShortcut(QKeySequence());
|
||||
aInc->setShortcut(QKeySequence());
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractCounter::setValue(int _value)
|
||||
{
|
||||
value = _value;
|
||||
update();
|
||||
value = _value;
|
||||
update();
|
||||
}
|
||||
|
||||
void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
Command_IncCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_delta(1);
|
||||
player->sendGameCommand(cmd);
|
||||
event->accept();
|
||||
} else if (event->button() == Qt::RightButton) {
|
||||
Command_IncCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_delta(-1);
|
||||
player->sendGameCommand(cmd);
|
||||
event->accept();
|
||||
} else if (event->button() == Qt::MidButton) {
|
||||
if (menu)
|
||||
menu->exec(event->screenPos());
|
||||
event->accept();
|
||||
} else
|
||||
event->ignore();
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
Command_IncCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_delta(1);
|
||||
player->sendGameCommand(cmd);
|
||||
event->accept();
|
||||
} else if (event->button() == Qt::RightButton) {
|
||||
Command_IncCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_delta(-1);
|
||||
player->sendGameCommand(cmd);
|
||||
event->accept();
|
||||
} else if (event->button() == Qt::MidButton) {
|
||||
if (menu)
|
||||
menu->exec(event->screenPos());
|
||||
event->accept();
|
||||
} else
|
||||
event->ignore();
|
||||
}
|
||||
|
||||
void AbstractCounter::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/)
|
||||
{
|
||||
hovered = true;
|
||||
update();
|
||||
hovered = true;
|
||||
update();
|
||||
}
|
||||
|
||||
void AbstractCounter::hoverLeaveEvent(QGraphicsSceneHoverEvent * /*event*/)
|
||||
{
|
||||
hovered = false;
|
||||
update();
|
||||
hovered = false;
|
||||
update();
|
||||
}
|
||||
|
||||
void AbstractCounter::incrementCounter()
|
||||
{
|
||||
const int delta = static_cast<QAction *>(sender())->data().toInt();
|
||||
Command_IncCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_delta(delta);
|
||||
player->sendGameCommand(cmd);
|
||||
const int delta = static_cast<QAction *>(sender())->data().toInt();
|
||||
Command_IncCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_delta(delta);
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
|
||||
void AbstractCounter::setCounter()
|
||||
{
|
||||
bool ok;
|
||||
dialogSemaphore = true;
|
||||
int newValue = QInputDialog::getInteger(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok);
|
||||
if (deleteAfterDialog) {
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
dialogSemaphore = false;
|
||||
if (!ok)
|
||||
return;
|
||||
bool ok;
|
||||
dialogSemaphore = true;
|
||||
int newValue = QInputDialog::getInteger(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok);
|
||||
if (deleteAfterDialog) {
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
dialogSemaphore = false;
|
||||
if (!ok)
|
||||
return;
|
||||
|
||||
Command_SetCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_value(newValue);
|
||||
player->sendGameCommand(cmd);
|
||||
Command_SetCounter cmd;
|
||||
cmd.set_counter_id(id);
|
||||
cmd.set_value(newValue);
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
|
|
|
@ -8,41 +8,41 @@ class QMenu;
|
|||
class QAction;
|
||||
|
||||
class AbstractCounter : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
Player *player;
|
||||
int id;
|
||||
QString name;
|
||||
int value;
|
||||
bool hovered;
|
||||
Player *player;
|
||||
int id;
|
||||
QString name;
|
||||
int value;
|
||||
bool hovered;
|
||||
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
|
||||
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
|
||||
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
|
||||
private:
|
||||
QAction *aSet, *aDec, *aInc;
|
||||
QMenu *menu;
|
||||
bool dialogSemaphore, deleteAfterDialog;
|
||||
bool shownInCounterArea;
|
||||
QAction *aSet, *aDec, *aInc;
|
||||
QMenu *menu;
|
||||
bool dialogSemaphore, deleteAfterDialog;
|
||||
bool shownInCounterArea;
|
||||
private slots:
|
||||
void incrementCounter();
|
||||
void setCounter();
|
||||
void incrementCounter();
|
||||
void setCounter();
|
||||
public:
|
||||
AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent = 0);
|
||||
~AbstractCounter();
|
||||
AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent = 0);
|
||||
~AbstractCounter();
|
||||
|
||||
QMenu *getMenu() const { return menu; }
|
||||
void retranslateUi();
|
||||
QMenu *getMenu() const { return menu; }
|
||||
void retranslateUi();
|
||||
|
||||
int getId() const { return id; }
|
||||
QString getName() const { return name; }
|
||||
bool getShownInCounterArea() const { return shownInCounterArea; }
|
||||
int getValue() const { return value; }
|
||||
void setValue(int _value);
|
||||
void delCounter();
|
||||
int getId() const { return id; }
|
||||
QString getName() const { return name; }
|
||||
bool getShownInCounterArea() const { return shownInCounterArea; }
|
||||
int getValue() const { return value; }
|
||||
void setValue(int _value);
|
||||
void delCounter();
|
||||
|
||||
void setShortcutsActive();
|
||||
void setShortcutsInactive();
|
||||
void setShortcutsActive();
|
||||
void setShortcutsInactive();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -3,48 +3,48 @@
|
|||
|
||||
void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QColor &color, int position, int count, QPainter *painter)
|
||||
{
|
||||
painter->save();
|
||||
painter->save();
|
||||
|
||||
QString numStr = QString::number(number);
|
||||
QFont font("Serif");
|
||||
font.setPixelSize(fontSize);
|
||||
font.setWeight(QFont::Bold);
|
||||
QString numStr = QString::number(number);
|
||||
QFont font("Serif");
|
||||
font.setPixelSize(fontSize);
|
||||
font.setWeight(QFont::Bold);
|
||||
|
||||
QFontMetrics fm(font);
|
||||
double w = fm.width(numStr) * 1.3;
|
||||
double h = fm.height() * 1.3;
|
||||
if (w < h)
|
||||
w = h;
|
||||
QFontMetrics fm(font);
|
||||
double w = fm.width(numStr) * 1.3;
|
||||
double h = fm.height() * 1.3;
|
||||
if (w < h)
|
||||
w = h;
|
||||
|
||||
painter->setPen(QColor(255, 255, 255, 0));
|
||||
QRadialGradient grad(QPointF(0.5, 0.5), 0.5);
|
||||
grad.setCoordinateMode(QGradient::ObjectBoundingMode);
|
||||
QColor color1(color), color2(color);
|
||||
color1.setAlpha(255);
|
||||
color2.setAlpha(0);
|
||||
grad.setColorAt(0, color1);
|
||||
grad.setColorAt(0.8, color1);
|
||||
grad.setColorAt(1, color2);
|
||||
painter->setBrush(QBrush(grad));
|
||||
painter->setPen(QColor(255, 255, 255, 0));
|
||||
QRadialGradient grad(QPointF(0.5, 0.5), 0.5);
|
||||
grad.setCoordinateMode(QGradient::ObjectBoundingMode);
|
||||
QColor color1(color), color2(color);
|
||||
color1.setAlpha(255);
|
||||
color2.setAlpha(0);
|
||||
grad.setColorAt(0, color1);
|
||||
grad.setColorAt(0.8, color1);
|
||||
grad.setColorAt(1, color2);
|
||||
painter->setBrush(QBrush(grad));
|
||||
|
||||
QRectF textRect;
|
||||
if (position == -1)
|
||||
textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h);
|
||||
else {
|
||||
qreal xOffset = 10;
|
||||
qreal yOffset = 20;
|
||||
qreal spacing = 2;
|
||||
if (position < 2)
|
||||
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h);
|
||||
else
|
||||
textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h);
|
||||
}
|
||||
QRectF textRect;
|
||||
if (position == -1)
|
||||
textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h);
|
||||
else {
|
||||
qreal xOffset = 10;
|
||||
qreal yOffset = 20;
|
||||
qreal spacing = 2;
|
||||
if (position < 2)
|
||||
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h);
|
||||
else
|
||||
textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h);
|
||||
}
|
||||
|
||||
painter->drawEllipse(textRect);
|
||||
painter->drawEllipse(textRect);
|
||||
|
||||
painter->setPen(Qt::black);
|
||||
painter->setFont(font);
|
||||
painter->drawText(textRect, Qt::AlignCenter, numStr);
|
||||
painter->setPen(Qt::black);
|
||||
painter->setFont(font);
|
||||
painter->drawText(textRect, Qt::AlignCenter, numStr);
|
||||
|
||||
painter->restore();
|
||||
painter->restore();
|
||||
}
|
||||
|
|
|
@ -4,20 +4,20 @@
|
|||
#include <QGraphicsItem>
|
||||
|
||||
enum GraphicsItemType {
|
||||
typeCard = QGraphicsItem::UserType + 1,
|
||||
typeCardDrag = QGraphicsItem::UserType + 2,
|
||||
typeZone = QGraphicsItem::UserType + 3,
|
||||
typePlayerTarget = QGraphicsItem::UserType + 4,
|
||||
typeDeckViewCardContainer = QGraphicsItem::UserType + 5,
|
||||
typeOther = QGraphicsItem::UserType + 6
|
||||
typeCard = QGraphicsItem::UserType + 1,
|
||||
typeCardDrag = QGraphicsItem::UserType + 2,
|
||||
typeZone = QGraphicsItem::UserType + 3,
|
||||
typePlayerTarget = QGraphicsItem::UserType + 4,
|
||||
typeDeckViewCardContainer = QGraphicsItem::UserType + 5,
|
||||
typeOther = QGraphicsItem::UserType + 6
|
||||
};
|
||||
|
||||
class AbstractGraphicsItem : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter);
|
||||
void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter);
|
||||
public:
|
||||
AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { }
|
||||
AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -17,127 +17,127 @@
|
|||
ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &_color)
|
||||
: QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color), fullColor(true)
|
||||
{
|
||||
qDebug() << "ArrowItem constructor: startItem=" << static_cast<QGraphicsItem *>(startItem);
|
||||
setZValue(2000000005);
|
||||
qDebug() << "ArrowItem constructor: startItem=" << static_cast<QGraphicsItem *>(startItem);
|
||||
setZValue(2000000005);
|
||||
|
||||
if (startItem)
|
||||
startItem->addArrowFrom(this);
|
||||
if (targetItem)
|
||||
targetItem->addArrowTo(this);
|
||||
if (startItem)
|
||||
startItem->addArrowFrom(this);
|
||||
if (targetItem)
|
||||
targetItem->addArrowTo(this);
|
||||
|
||||
if (startItem && targetItem)
|
||||
updatePath();
|
||||
if (startItem && targetItem)
|
||||
updatePath();
|
||||
}
|
||||
|
||||
ArrowItem::~ArrowItem()
|
||||
{
|
||||
qDebug() << "ArrowItem destructor";
|
||||
qDebug() << "ArrowItem destructor";
|
||||
}
|
||||
|
||||
void ArrowItem::delArrow()
|
||||
{
|
||||
if (startItem) {
|
||||
startItem->removeArrowFrom(this);
|
||||
startItem = 0;
|
||||
}
|
||||
if (startItem) {
|
||||
startItem->removeArrowFrom(this);
|
||||
startItem = 0;
|
||||
}
|
||||
|
||||
if (targetItem) {
|
||||
targetItem->setBeingPointedAt(false);
|
||||
targetItem->removeArrowTo(this);
|
||||
targetItem = 0;
|
||||
}
|
||||
if (targetItem) {
|
||||
targetItem->setBeingPointedAt(false);
|
||||
targetItem->removeArrowTo(this);
|
||||
targetItem = 0;
|
||||
}
|
||||
|
||||
player->removeArrow(this);
|
||||
deleteLater();
|
||||
player->removeArrow(this);
|
||||
deleteLater();
|
||||
}
|
||||
|
||||
void ArrowItem::updatePath()
|
||||
{
|
||||
if (!targetItem)
|
||||
return;
|
||||
if (!targetItem)
|
||||
return;
|
||||
|
||||
QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2));
|
||||
updatePath(endPoint);
|
||||
QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2));
|
||||
updatePath(endPoint);
|
||||
}
|
||||
|
||||
void ArrowItem::updatePath(const QPointF &endPoint)
|
||||
{
|
||||
const double arrowWidth = 15.0;
|
||||
const double headWidth = 40.0;
|
||||
const double headLength = headWidth / sqrt(2);
|
||||
const double phi = 15;
|
||||
const double arrowWidth = 15.0;
|
||||
const double headWidth = 40.0;
|
||||
const double headLength = headWidth / sqrt(2);
|
||||
const double phi = 15;
|
||||
|
||||
if (!startItem)
|
||||
return;
|
||||
if (!startItem)
|
||||
return;
|
||||
|
||||
QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2));
|
||||
QLineF line(startPoint, endPoint);
|
||||
qreal lineLength = line.length();
|
||||
QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2));
|
||||
QLineF line(startPoint, endPoint);
|
||||
qreal lineLength = line.length();
|
||||
|
||||
prepareGeometryChange();
|
||||
if (lineLength < 30)
|
||||
path = QPainterPath();
|
||||
else {
|
||||
QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength);
|
||||
prepareGeometryChange();
|
||||
if (lineLength < 30)
|
||||
path = QPainterPath();
|
||||
else {
|
||||
QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength);
|
||||
|
||||
QPainterPath centerLine;
|
||||
centerLine.moveTo(0, 0);
|
||||
centerLine.quadTo(c, QPointF(lineLength, 0));
|
||||
QPainterPath centerLine;
|
||||
centerLine.moveTo(0, 0);
|
||||
centerLine.quadTo(c, QPointF(lineLength, 0));
|
||||
|
||||
double percentage = 1 - headLength / lineLength;
|
||||
QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage);
|
||||
QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001));
|
||||
qreal alpha = testLine.angle() - 90;
|
||||
QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
|
||||
QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
|
||||
QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
|
||||
QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
|
||||
double percentage = 1 - headLength / lineLength;
|
||||
QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage);
|
||||
QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001));
|
||||
qreal alpha = testLine.angle() - 90;
|
||||
QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
|
||||
QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
|
||||
QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
|
||||
QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
|
||||
|
||||
path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
|
||||
path.quadTo(c, endPoint1);
|
||||
path.lineTo(point1);
|
||||
path.lineTo(QPointF(lineLength, 0));
|
||||
path.lineTo(point2);
|
||||
path.lineTo(endPoint2);
|
||||
path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
|
||||
path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
|
||||
}
|
||||
path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
|
||||
path.quadTo(c, endPoint1);
|
||||
path.lineTo(point1);
|
||||
path.lineTo(QPointF(lineLength, 0));
|
||||
path.lineTo(point2);
|
||||
path.lineTo(endPoint2);
|
||||
path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
|
||||
path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
|
||||
}
|
||||
|
||||
setPos(startPoint);
|
||||
setTransform(QTransform().rotate(-line.angle()));
|
||||
setPos(startPoint);
|
||||
setTransform(QTransform().rotate(-line.angle()));
|
||||
}
|
||||
|
||||
void ArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
QColor paintColor(color);
|
||||
if (fullColor)
|
||||
paintColor.setAlpha(200);
|
||||
else
|
||||
paintColor.setAlpha(150);
|
||||
painter->setBrush(paintColor);
|
||||
painter->drawPath(path);
|
||||
QColor paintColor(color);
|
||||
if (fullColor)
|
||||
paintColor.setAlpha(200);
|
||||
else
|
||||
paintColor.setAlpha(150);
|
||||
painter->setBrush(paintColor);
|
||||
painter->drawPath(path);
|
||||
}
|
||||
|
||||
void ArrowItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (!player->getLocal()) {
|
||||
event->ignore();
|
||||
return;
|
||||
}
|
||||
if (!player->getLocal()) {
|
||||
event->ignore();
|
||||
return;
|
||||
}
|
||||
|
||||
QList<QGraphicsItem *> colliding = scene()->items(event->scenePos());
|
||||
for (int i = 0; i < colliding.size(); ++i)
|
||||
if (qgraphicsitem_cast<CardItem *>(colliding[i])) {
|
||||
event->ignore();
|
||||
return;
|
||||
}
|
||||
QList<QGraphicsItem *> colliding = scene()->items(event->scenePos());
|
||||
for (int i = 0; i < colliding.size(); ++i)
|
||||
if (qgraphicsitem_cast<CardItem *>(colliding[i])) {
|
||||
event->ignore();
|
||||
return;
|
||||
}
|
||||
|
||||
event->accept();
|
||||
if (event->button() == Qt::RightButton) {
|
||||
Command_DeleteArrow cmd;
|
||||
cmd.set_arrow_id(id);
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
event->accept();
|
||||
if (event->button() == Qt::RightButton) {
|
||||
Command_DeleteArrow cmd;
|
||||
cmd.set_arrow_id(id);
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
ArrowDragItem::ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color)
|
||||
|
@ -147,85 +147,85 @@ ArrowDragItem::ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QCol
|
|||
|
||||
void ArrowDragItem::addChildArrow(ArrowDragItem *childArrow)
|
||||
{
|
||||
childArrows.append(childArrow);
|
||||
childArrows.append(childArrow);
|
||||
}
|
||||
|
||||
void ArrowDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
// This ensures that if a mouse move event happens after a call to delArrow(),
|
||||
// the event will be discarded as it would create some stray pointers.
|
||||
if (!startItem)
|
||||
return;
|
||||
// This ensures that if a mouse move event happens after a call to delArrow(),
|
||||
// the event will be discarded as it would create some stray pointers.
|
||||
if (!startItem)
|
||||
return;
|
||||
|
||||
QPointF endPos = event->scenePos();
|
||||
QPointF endPos = event->scenePos();
|
||||
|
||||
QList<QGraphicsItem *> colliding = scene()->items(endPos);
|
||||
ArrowTarget *cursorItem = 0;
|
||||
qreal cursorItemZ = -1;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--)
|
||||
if (qgraphicsitem_cast<PlayerTarget *>(colliding.at(i)) || qgraphicsitem_cast<CardItem *>(colliding.at(i)))
|
||||
if (colliding.at(i)->zValue() > cursorItemZ) {
|
||||
cursorItem = static_cast<ArrowTarget *>(colliding.at(i));
|
||||
cursorItemZ = cursorItem->zValue();
|
||||
}
|
||||
if ((cursorItem != targetItem) && targetItem) {
|
||||
targetItem->setBeingPointedAt(false);
|
||||
targetItem->removeArrowTo(this);
|
||||
}
|
||||
QList<QGraphicsItem *> colliding = scene()->items(endPos);
|
||||
ArrowTarget *cursorItem = 0;
|
||||
qreal cursorItemZ = -1;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--)
|
||||
if (qgraphicsitem_cast<PlayerTarget *>(colliding.at(i)) || qgraphicsitem_cast<CardItem *>(colliding.at(i)))
|
||||
if (colliding.at(i)->zValue() > cursorItemZ) {
|
||||
cursorItem = static_cast<ArrowTarget *>(colliding.at(i));
|
||||
cursorItemZ = cursorItem->zValue();
|
||||
}
|
||||
if ((cursorItem != targetItem) && targetItem) {
|
||||
targetItem->setBeingPointedAt(false);
|
||||
targetItem->removeArrowTo(this);
|
||||
}
|
||||
if (!cursorItem) {
|
||||
fullColor = false;
|
||||
targetItem = 0;
|
||||
updatePath(endPos);
|
||||
} else {
|
||||
if (cursorItem != targetItem) {
|
||||
fullColor = true;
|
||||
if (cursorItem != startItem) {
|
||||
cursorItem->setBeingPointedAt(true);
|
||||
cursorItem->addArrowTo(this);
|
||||
}
|
||||
targetItem = cursorItem;
|
||||
}
|
||||
updatePath();
|
||||
}
|
||||
update();
|
||||
fullColor = false;
|
||||
targetItem = 0;
|
||||
updatePath(endPos);
|
||||
} else {
|
||||
if (cursorItem != targetItem) {
|
||||
fullColor = true;
|
||||
if (cursorItem != startItem) {
|
||||
cursorItem->setBeingPointedAt(true);
|
||||
cursorItem->addArrowTo(this);
|
||||
}
|
||||
targetItem = cursorItem;
|
||||
}
|
||||
updatePath();
|
||||
}
|
||||
update();
|
||||
|
||||
for (int i = 0; i < childArrows.size(); ++i)
|
||||
childArrows[i]->mouseMoveEvent(event);
|
||||
for (int i = 0; i < childArrows.size(); ++i)
|
||||
childArrows[i]->mouseMoveEvent(event);
|
||||
}
|
||||
|
||||
void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (!startItem)
|
||||
return;
|
||||
if (!startItem)
|
||||
return;
|
||||
|
||||
if (targetItem && (targetItem != startItem)) {
|
||||
CardZone *startZone = static_cast<CardItem *>(startItem)->getZone();
|
||||
// For now, we can safely assume that the start item is always a card.
|
||||
// The target item can be a player as well.
|
||||
CardItem *startCard = qgraphicsitem_cast<CardItem *>(startItem);
|
||||
CardItem *targetCard = qgraphicsitem_cast<CardItem *>(targetItem);
|
||||
if (targetItem && (targetItem != startItem)) {
|
||||
CardZone *startZone = static_cast<CardItem *>(startItem)->getZone();
|
||||
// For now, we can safely assume that the start item is always a card.
|
||||
// The target item can be a player as well.
|
||||
CardItem *startCard = qgraphicsitem_cast<CardItem *>(startItem);
|
||||
CardItem *targetCard = qgraphicsitem_cast<CardItem *>(targetItem);
|
||||
|
||||
Command_CreateArrow cmd;
|
||||
cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color));
|
||||
cmd.set_start_player_id(startZone->getPlayer()->getId());
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_start_card_id(startCard->getId());
|
||||
Command_CreateArrow cmd;
|
||||
cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color));
|
||||
cmd.set_start_player_id(startZone->getPlayer()->getId());
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_start_card_id(startCard->getId());
|
||||
|
||||
if (targetCard) {
|
||||
CardZone *targetZone = targetCard->getZone();
|
||||
cmd.set_target_player_id(targetZone->getPlayer()->getId());
|
||||
cmd.set_target_zone(targetZone->getName().toStdString());
|
||||
cmd.set_target_card_id(targetCard->getId());
|
||||
} else {
|
||||
PlayerTarget *targetPlayer = qgraphicsitem_cast<PlayerTarget *>(targetItem);
|
||||
cmd.set_target_player_id(targetPlayer->getOwner()->getId());
|
||||
}
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
delArrow();
|
||||
if (targetCard) {
|
||||
CardZone *targetZone = targetCard->getZone();
|
||||
cmd.set_target_player_id(targetZone->getPlayer()->getId());
|
||||
cmd.set_target_zone(targetZone->getName().toStdString());
|
||||
cmd.set_target_card_id(targetCard->getId());
|
||||
} else {
|
||||
PlayerTarget *targetPlayer = qgraphicsitem_cast<PlayerTarget *>(targetItem);
|
||||
cmd.set_target_player_id(targetPlayer->getOwner()->getId());
|
||||
}
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
delArrow();
|
||||
|
||||
for (int i = 0; i < childArrows.size(); ++i)
|
||||
childArrows[i]->mouseReleaseEvent(event);
|
||||
for (int i = 0; i < childArrows.size(); ++i)
|
||||
childArrows[i]->mouseReleaseEvent(event);
|
||||
}
|
||||
|
||||
ArrowAttachItem::ArrowAttachItem(ArrowTarget *_startItem)
|
||||
|
@ -235,57 +235,57 @@ ArrowAttachItem::ArrowAttachItem(ArrowTarget *_startItem)
|
|||
|
||||
void ArrowAttachItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (!startItem)
|
||||
return;
|
||||
if (!startItem)
|
||||
return;
|
||||
|
||||
QPointF endPos = event->scenePos();
|
||||
QPointF endPos = event->scenePos();
|
||||
|
||||
QList<QGraphicsItem *> colliding = scene()->items(endPos);
|
||||
QList<QGraphicsItem *> colliding = scene()->items(endPos);
|
||||
ArrowTarget *cursorItem = 0;
|
||||
qreal cursorItemZ = -1;
|
||||
qreal cursorItemZ = -1;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--)
|
||||
if (qgraphicsitem_cast<CardItem *>(colliding.at(i)))
|
||||
if (colliding.at(i)->zValue() > cursorItemZ) {
|
||||
cursorItem = static_cast<ArrowTarget *>(colliding.at(i));
|
||||
cursorItemZ = cursorItem->zValue();
|
||||
}
|
||||
if (colliding.at(i)->zValue() > cursorItemZ) {
|
||||
cursorItem = static_cast<ArrowTarget *>(colliding.at(i));
|
||||
cursorItemZ = cursorItem->zValue();
|
||||
}
|
||||
|
||||
if ((cursorItem != targetItem) && targetItem)
|
||||
targetItem->setBeingPointedAt(false);
|
||||
if ((cursorItem != targetItem) && targetItem)
|
||||
targetItem->setBeingPointedAt(false);
|
||||
if (!cursorItem) {
|
||||
fullColor = false;
|
||||
targetItem = 0;
|
||||
updatePath(endPos);
|
||||
} else {
|
||||
fullColor = true;
|
||||
if (cursorItem != startItem)
|
||||
cursorItem->setBeingPointedAt(true);
|
||||
targetItem = cursorItem;
|
||||
updatePath();
|
||||
}
|
||||
update();
|
||||
fullColor = false;
|
||||
targetItem = 0;
|
||||
updatePath(endPos);
|
||||
} else {
|
||||
fullColor = true;
|
||||
if (cursorItem != startItem)
|
||||
cursorItem->setBeingPointedAt(true);
|
||||
targetItem = cursorItem;
|
||||
updatePath();
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void ArrowAttachItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * /*event*/)
|
||||
{
|
||||
if (!startItem)
|
||||
return;
|
||||
if (!startItem)
|
||||
return;
|
||||
|
||||
if (targetItem && (targetItem != startItem)) {
|
||||
CardItem *startCard = qgraphicsitem_cast<CardItem *>(startItem);
|
||||
CardZone *startZone = startCard->getZone();
|
||||
CardItem *targetCard = qgraphicsitem_cast<CardItem *>(targetItem);
|
||||
CardZone *targetZone = targetCard->getZone();
|
||||
if (targetItem && (targetItem != startItem)) {
|
||||
CardItem *startCard = qgraphicsitem_cast<CardItem *>(startItem);
|
||||
CardZone *startZone = startCard->getZone();
|
||||
CardItem *targetCard = qgraphicsitem_cast<CardItem *>(targetItem);
|
||||
CardZone *targetZone = targetCard->getZone();
|
||||
|
||||
Command_AttachCard cmd;
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_card_id(startCard->getId());
|
||||
cmd.set_target_player_id(targetZone->getPlayer()->getId());
|
||||
cmd.set_target_zone(targetZone->getName().toStdString());
|
||||
cmd.set_target_card_id(targetCard->getId());
|
||||
Command_AttachCard cmd;
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_card_id(startCard->getId());
|
||||
cmd.set_target_player_id(targetZone->getPlayer()->getId());
|
||||
cmd.set_target_zone(targetZone->getName().toStdString());
|
||||
cmd.set_target_card_id(targetCard->getId());
|
||||
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
|
||||
delArrow();
|
||||
delArrow();
|
||||
}
|
||||
|
|
|
@ -10,54 +10,54 @@ class Player;
|
|||
class ArrowTarget;
|
||||
|
||||
class ArrowItem : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QPainterPath path;
|
||||
QMenu *menu;
|
||||
QPainterPath path;
|
||||
QMenu *menu;
|
||||
protected:
|
||||
Player *player;
|
||||
int id;
|
||||
ArrowTarget *startItem, *targetItem;
|
||||
QColor color;
|
||||
bool fullColor;
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
Player *player;
|
||||
int id;
|
||||
ArrowTarget *startItem, *targetItem;
|
||||
QColor color;
|
||||
bool fullColor;
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
public:
|
||||
ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color);
|
||||
~ArrowItem();
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
QRectF boundingRect() const { return path.boundingRect(); }
|
||||
QPainterPath shape() const { return path; }
|
||||
void updatePath();
|
||||
void updatePath(const QPointF &endPoint);
|
||||
ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color);
|
||||
~ArrowItem();
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
QRectF boundingRect() const { return path.boundingRect(); }
|
||||
QPainterPath shape() const { return path; }
|
||||
void updatePath();
|
||||
void updatePath(const QPointF &endPoint);
|
||||
|
||||
int getId() const { return id; }
|
||||
Player *getPlayer() const { return player; }
|
||||
void setStartItem(ArrowTarget *_item) { startItem = _item; }
|
||||
void setTargetItem(ArrowTarget *_item) { targetItem = _item; }
|
||||
ArrowTarget *getStartItem() const { return startItem; }
|
||||
ArrowTarget *getTargetItem() const { return targetItem; }
|
||||
void delArrow();
|
||||
int getId() const { return id; }
|
||||
Player *getPlayer() const { return player; }
|
||||
void setStartItem(ArrowTarget *_item) { startItem = _item; }
|
||||
void setTargetItem(ArrowTarget *_item) { targetItem = _item; }
|
||||
ArrowTarget *getStartItem() const { return startItem; }
|
||||
ArrowTarget *getTargetItem() const { return targetItem; }
|
||||
void delArrow();
|
||||
};
|
||||
|
||||
class ArrowDragItem : public ArrowItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QList<ArrowDragItem *> childArrows;
|
||||
QList<ArrowDragItem *> childArrows;
|
||||
public:
|
||||
ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color);
|
||||
void addChildArrow(ArrowDragItem *childArrow);
|
||||
ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color);
|
||||
void addChildArrow(ArrowDragItem *childArrow);
|
||||
protected:
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
};
|
||||
|
||||
class ArrowAttachItem : public ArrowItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
ArrowAttachItem(ArrowTarget *_startItem);
|
||||
ArrowAttachItem(ArrowTarget *_startItem);
|
||||
protected:
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
};
|
||||
|
||||
#endif // ARROWITEM_H
|
||||
|
|
|
@ -3,24 +3,24 @@
|
|||
#include "player.h"
|
||||
|
||||
ArrowTarget::ArrowTarget(Player *_owner, QGraphicsItem *parent)
|
||||
: AbstractGraphicsItem(parent), owner(_owner), beingPointedAt(false)
|
||||
: AbstractGraphicsItem(parent), owner(_owner), beingPointedAt(false)
|
||||
{
|
||||
}
|
||||
|
||||
ArrowTarget::~ArrowTarget()
|
||||
{
|
||||
for (int i = 0; i < arrowsFrom.size(); ++i) {
|
||||
arrowsFrom[i]->setStartItem(0);
|
||||
arrowsFrom[i]->delArrow();
|
||||
}
|
||||
for (int i = 0; i < arrowsTo.size(); ++i) {
|
||||
arrowsTo[i]->setTargetItem(0);
|
||||
arrowsTo[i]->delArrow();
|
||||
}
|
||||
for (int i = 0; i < arrowsFrom.size(); ++i) {
|
||||
arrowsFrom[i]->setStartItem(0);
|
||||
arrowsFrom[i]->delArrow();
|
||||
}
|
||||
for (int i = 0; i < arrowsTo.size(); ++i) {
|
||||
arrowsTo[i]->setTargetItem(0);
|
||||
arrowsTo[i]->delArrow();
|
||||
}
|
||||
}
|
||||
|
||||
void ArrowTarget::setBeingPointedAt(bool _beingPointedAt)
|
||||
{
|
||||
beingPointedAt = _beingPointedAt;
|
||||
update();
|
||||
beingPointedAt = _beingPointedAt;
|
||||
update();
|
||||
}
|
||||
|
|
|
@ -8,28 +8,28 @@ class Player;
|
|||
class ArrowItem;
|
||||
|
||||
class ArrowTarget : public AbstractGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
Player *owner;
|
||||
Player *owner;
|
||||
private:
|
||||
bool beingPointedAt;
|
||||
QList<ArrowItem *> arrowsFrom, arrowsTo;
|
||||
bool beingPointedAt;
|
||||
QList<ArrowItem *> arrowsFrom, arrowsTo;
|
||||
public:
|
||||
ArrowTarget(Player *_owner, QGraphicsItem *parent = 0);
|
||||
~ArrowTarget();
|
||||
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; }
|
||||
void setBeingPointedAt(bool _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
|
@ -22,191 +22,191 @@ typedef QMap<QString, QString> QStringMap;
|
|||
|
||||
class CardSet : public QList<CardInfo *> {
|
||||
private:
|
||||
QString shortName, longName;
|
||||
unsigned int sortKey;
|
||||
QString shortName, longName;
|
||||
unsigned int sortKey;
|
||||
public:
|
||||
CardSet(const QString &_shortName = QString(), const QString &_longName = QString());
|
||||
QString getShortName() const { return shortName; }
|
||||
QString getLongName() const { return longName; }
|
||||
int getSortKey() const { return sortKey; }
|
||||
void setSortKey(unsigned int _sortKey);
|
||||
void updateSortKey();
|
||||
CardSet(const QString &_shortName = QString(), const QString &_longName = QString());
|
||||
QString getShortName() const { return shortName; }
|
||||
QString getLongName() const { return longName; }
|
||||
int getSortKey() const { return sortKey; }
|
||||
void setSortKey(unsigned int _sortKey);
|
||||
void updateSortKey();
|
||||
};
|
||||
|
||||
class SetList : public QList<CardSet *> {
|
||||
private:
|
||||
class CompareFunctor;
|
||||
class CompareFunctor;
|
||||
public:
|
||||
void sortByKey();
|
||||
void sortByKey();
|
||||
};
|
||||
|
||||
class PictureToLoad {
|
||||
private:
|
||||
CardInfo *card;
|
||||
bool stripped;
|
||||
SetList sortedSets;
|
||||
int setIndex;
|
||||
bool hq;
|
||||
CardInfo *card;
|
||||
bool stripped;
|
||||
SetList sortedSets;
|
||||
int setIndex;
|
||||
bool hq;
|
||||
public:
|
||||
PictureToLoad(CardInfo *_card = 0, bool _stripped = false, bool _hq = true);
|
||||
CardInfo *getCard() const { return card; }
|
||||
bool getStripped() const { return stripped; }
|
||||
QString getSetName() const { return sortedSets[setIndex]->getShortName(); }
|
||||
bool nextSet();
|
||||
PictureToLoad(CardInfo *_card = 0, bool _stripped = false, bool _hq = true);
|
||||
CardInfo *getCard() const { return card; }
|
||||
bool getStripped() const { return stripped; }
|
||||
QString getSetName() const { return sortedSets[setIndex]->getShortName(); }
|
||||
bool nextSet();
|
||||
|
||||
bool getHq() const { return hq; }
|
||||
void setHq(bool _hq) { hq = _hq; }
|
||||
bool getHq() const { return hq; }
|
||||
void setHq(bool _hq) { hq = _hq; }
|
||||
|
||||
};
|
||||
|
||||
class PictureLoader : public QObject {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QString _picsPath;
|
||||
QList<PictureToLoad> loadQueue;
|
||||
QMutex mutex;
|
||||
QNetworkAccessManager *networkManager;
|
||||
QList<PictureToLoad> cardsToDownload;
|
||||
PictureToLoad cardBeingDownloaded;
|
||||
bool picDownload, downloadRunning, loadQueueRunning;
|
||||
void startNextPicDownload();
|
||||
QString _picsPath;
|
||||
QList<PictureToLoad> loadQueue;
|
||||
QMutex mutex;
|
||||
QNetworkAccessManager *networkManager;
|
||||
QList<PictureToLoad> cardsToDownload;
|
||||
PictureToLoad cardBeingDownloaded;
|
||||
bool picDownload, downloadRunning, loadQueueRunning;
|
||||
void startNextPicDownload();
|
||||
public:
|
||||
PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent = 0);
|
||||
~PictureLoader();
|
||||
void setPicsPath(const QString &path);
|
||||
void setPicDownload(bool _picDownload);
|
||||
void loadImage(CardInfo *card, bool stripped);
|
||||
PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent = 0);
|
||||
~PictureLoader();
|
||||
void setPicsPath(const QString &path);
|
||||
void setPicDownload(bool _picDownload);
|
||||
void loadImage(CardInfo *card, bool stripped);
|
||||
private slots:
|
||||
void picDownloadFinished(QNetworkReply *reply);
|
||||
void picDownloadFinished(QNetworkReply *reply);
|
||||
public slots:
|
||||
void processLoadQueue();
|
||||
void processLoadQueue();
|
||||
signals:
|
||||
void startLoadQueue();
|
||||
void imageLoaded(CardInfo *card, const QImage &image);
|
||||
void startLoadQueue();
|
||||
void imageLoaded(CardInfo *card, const QImage &image);
|
||||
};
|
||||
|
||||
class CardInfo : public QObject {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
CardDatabase *db;
|
||||
CardDatabase *db;
|
||||
|
||||
QString name;
|
||||
bool isToken;
|
||||
SetList sets;
|
||||
QString manacost;
|
||||
QString cardtype;
|
||||
QString powtough;
|
||||
QString text;
|
||||
QStringList colors;
|
||||
int loyalty;
|
||||
QMap<QString, QString> picURLs, picURLsHq, picURLsSt;
|
||||
bool cipt;
|
||||
int tableRow;
|
||||
QPixmap *pixmap;
|
||||
QMap<int, QPixmap *> scaledPixmapCache;
|
||||
QString name;
|
||||
bool isToken;
|
||||
SetList sets;
|
||||
QString manacost;
|
||||
QString cardtype;
|
||||
QString powtough;
|
||||
QString text;
|
||||
QStringList colors;
|
||||
int loyalty;
|
||||
QMap<QString, QString> picURLs, picURLsHq, picURLsSt;
|
||||
bool cipt;
|
||||
int tableRow;
|
||||
QPixmap *pixmap;
|
||||
QMap<int, QPixmap *> scaledPixmapCache;
|
||||
public:
|
||||
CardInfo(CardDatabase *_db,
|
||||
const QString &_name = QString(),
|
||||
bool _isToken = false,
|
||||
const QString &_manacost = QString(),
|
||||
const QString &_cardtype = QString(),
|
||||
const QString &_powtough = QString(),
|
||||
const QString &_text = QString(),
|
||||
const QStringList &_colors = QStringList(),
|
||||
int _loyalty = 0,
|
||||
bool _cipt = false,
|
||||
int _tableRow = 0,
|
||||
const SetList &_sets = SetList(),
|
||||
const QStringMap &_picURLs = QStringMap(),
|
||||
const QStringMap &_picURLsHq = QStringMap(),
|
||||
const QStringMap &_picURLsSt = QStringMap());
|
||||
~CardInfo();
|
||||
const QString &getName() const { return name; }
|
||||
bool getIsToken() const { return isToken; }
|
||||
const SetList &getSets() const { return sets; }
|
||||
const QString &getManaCost() const { return manacost; }
|
||||
const QString &getCardType() const { return cardtype; }
|
||||
const QString &getPowTough() const { return powtough; }
|
||||
const QString &getText() const { return text; }
|
||||
const int &getLoyalty() const { return loyalty; }
|
||||
bool getCipt() const { return cipt; }
|
||||
void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); }
|
||||
void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); }
|
||||
void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); }
|
||||
void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); }
|
||||
void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); }
|
||||
const QStringList &getColors() const { return colors; }
|
||||
QString getPicURL(const QString &set) const { return picURLs.value(set); }
|
||||
QString getPicURLHq(const QString &set) const { return picURLsHq.value(set); }
|
||||
QString getPicURLSt(const QString &set) const { return picURLsSt.value(set); }
|
||||
QString getPicURL() const;
|
||||
const QMap<QString, QString> &getPicURLs() const { return picURLs; }
|
||||
QString getMainCardType() const;
|
||||
QString getCorrectedName() const;
|
||||
int getTableRow() const { return tableRow; }
|
||||
void setTableRow(int _tableRow) { tableRow = _tableRow; }
|
||||
void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); }
|
||||
void setPicURL(const QString &_set, const QString &_picURL) { picURLs.insert(_set, _picURL); }
|
||||
void setPicURLHq(const QString &_set, const QString &_picURL) { picURLsHq.insert(_set, _picURL); }
|
||||
void setPicURLSt(const QString &_set, const QString &_picURL) { picURLsSt.insert(_set, _picURL); }
|
||||
void addToSet(CardSet *set);
|
||||
QPixmap *loadPixmap();
|
||||
QPixmap *getPixmap(QSize size);
|
||||
void clearPixmapCache();
|
||||
void clearPixmapCacheMiss();
|
||||
void imageLoaded(const QImage &image);
|
||||
CardInfo(CardDatabase *_db,
|
||||
const QString &_name = QString(),
|
||||
bool _isToken = false,
|
||||
const QString &_manacost = QString(),
|
||||
const QString &_cardtype = QString(),
|
||||
const QString &_powtough = QString(),
|
||||
const QString &_text = QString(),
|
||||
const QStringList &_colors = QStringList(),
|
||||
int _loyalty = 0,
|
||||
bool _cipt = false,
|
||||
int _tableRow = 0,
|
||||
const SetList &_sets = SetList(),
|
||||
const QStringMap &_picURLs = QStringMap(),
|
||||
const QStringMap &_picURLsHq = QStringMap(),
|
||||
const QStringMap &_picURLsSt = QStringMap());
|
||||
~CardInfo();
|
||||
const QString &getName() const { return name; }
|
||||
bool getIsToken() const { return isToken; }
|
||||
const SetList &getSets() const { return sets; }
|
||||
const QString &getManaCost() const { return manacost; }
|
||||
const QString &getCardType() const { return cardtype; }
|
||||
const QString &getPowTough() const { return powtough; }
|
||||
const QString &getText() const { return text; }
|
||||
const int &getLoyalty() const { return loyalty; }
|
||||
bool getCipt() const { return cipt; }
|
||||
void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); }
|
||||
void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); }
|
||||
void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); }
|
||||
void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); }
|
||||
void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); }
|
||||
const QStringList &getColors() const { return colors; }
|
||||
QString getPicURL(const QString &set) const { return picURLs.value(set); }
|
||||
QString getPicURLHq(const QString &set) const { return picURLsHq.value(set); }
|
||||
QString getPicURLSt(const QString &set) const { return picURLsSt.value(set); }
|
||||
QString getPicURL() const;
|
||||
const QMap<QString, QString> &getPicURLs() const { return picURLs; }
|
||||
QString getMainCardType() const;
|
||||
QString getCorrectedName() const;
|
||||
int getTableRow() const { return tableRow; }
|
||||
void setTableRow(int _tableRow) { tableRow = _tableRow; }
|
||||
void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); }
|
||||
void setPicURL(const QString &_set, const QString &_picURL) { picURLs.insert(_set, _picURL); }
|
||||
void setPicURLHq(const QString &_set, const QString &_picURL) { picURLsHq.insert(_set, _picURL); }
|
||||
void setPicURLSt(const QString &_set, const QString &_picURL) { picURLsSt.insert(_set, _picURL); }
|
||||
void addToSet(CardSet *set);
|
||||
QPixmap *loadPixmap();
|
||||
QPixmap *getPixmap(QSize size);
|
||||
void clearPixmapCache();
|
||||
void clearPixmapCacheMiss();
|
||||
void imageLoaded(const QImage &image);
|
||||
public slots:
|
||||
void updatePixmapCache();
|
||||
void updatePixmapCache();
|
||||
signals:
|
||||
void pixmapUpdated();
|
||||
void cardInfoChanged(CardInfo *card);
|
||||
void pixmapUpdated();
|
||||
void cardInfoChanged(CardInfo *card);
|
||||
};
|
||||
|
||||
class CardDatabase : public QObject {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
QHash<QString, CardInfo *> cardHash;
|
||||
QHash<QString, CardSet *> setHash;
|
||||
bool loadSuccess;
|
||||
CardInfo *noCard;
|
||||
QHash<QString, CardInfo *> cardHash;
|
||||
QHash<QString, CardSet *> setHash;
|
||||
bool loadSuccess;
|
||||
CardInfo *noCard;
|
||||
|
||||
QThread *pictureLoaderThread;
|
||||
PictureLoader *pictureLoader;
|
||||
QThread *pictureLoaderThread;
|
||||
PictureLoader *pictureLoader;
|
||||
private:
|
||||
static const int versionNeeded;
|
||||
void loadCardsFromXml(QXmlStreamReader &xml);
|
||||
void loadSetsFromXml(QXmlStreamReader &xml);
|
||||
static const int versionNeeded;
|
||||
void loadCardsFromXml(QXmlStreamReader &xml);
|
||||
void loadSetsFromXml(QXmlStreamReader &xml);
|
||||
public:
|
||||
CardDatabase(QObject *parent = 0);
|
||||
~CardDatabase();
|
||||
void clear();
|
||||
void addCard(CardInfo *card);
|
||||
void removeCard(CardInfo *card);
|
||||
CardInfo *getCard(const QString &cardName = QString(), bool createIfNotFound = true);
|
||||
CardSet *getSet(const QString &setName);
|
||||
QList<CardInfo *> getCardList() const { return cardHash.values(); }
|
||||
SetList getSetList() const;
|
||||
bool loadFromFile(const QString &fileName, bool tokens = false);
|
||||
bool saveToFile(const QString &fileName, bool tokens = false);
|
||||
QStringList getAllColors() const;
|
||||
QStringList getAllMainCardTypes() const;
|
||||
bool getLoadSuccess() const { return loadSuccess; }
|
||||
void cacheCardPixmaps(const QStringList &cardNames);
|
||||
void loadImage(CardInfo *card);
|
||||
CardDatabase(QObject *parent = 0);
|
||||
~CardDatabase();
|
||||
void clear();
|
||||
void addCard(CardInfo *card);
|
||||
void removeCard(CardInfo *card);
|
||||
CardInfo *getCard(const QString &cardName = QString(), bool createIfNotFound = true);
|
||||
CardSet *getSet(const QString &setName);
|
||||
QList<CardInfo *> getCardList() const { return cardHash.values(); }
|
||||
SetList getSetList() const;
|
||||
bool loadFromFile(const QString &fileName, bool tokens = false);
|
||||
bool saveToFile(const QString &fileName, bool tokens = false);
|
||||
QStringList getAllColors() const;
|
||||
QStringList getAllMainCardTypes() const;
|
||||
bool getLoadSuccess() const { return loadSuccess; }
|
||||
void cacheCardPixmaps(const QStringList &cardNames);
|
||||
void loadImage(CardInfo *card);
|
||||
public slots:
|
||||
void clearPixmapCache();
|
||||
bool loadCardDatabase(const QString &path, bool tokens = false);
|
||||
void clearPixmapCache();
|
||||
bool loadCardDatabase(const QString &path, bool tokens = false);
|
||||
private slots:
|
||||
void imageLoaded(CardInfo *card, QImage image);
|
||||
void picDownloadChanged();
|
||||
void picsPathChanged();
|
||||
void imageLoaded(CardInfo *card, QImage image);
|
||||
void picDownloadChanged();
|
||||
void picsPathChanged();
|
||||
|
||||
void loadCardDatabase();
|
||||
void loadTokenDatabase();
|
||||
void loadCardDatabase();
|
||||
void loadTokenDatabase();
|
||||
signals:
|
||||
void cardListChanged();
|
||||
void cardAdded(CardInfo *card);
|
||||
void cardRemoved(CardInfo *card);
|
||||
void cardListChanged();
|
||||
void cardAdded(CardInfo *card);
|
||||
void cardRemoved(CardInfo *card);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
#include "carddatabasemodel.h"
|
||||
|
||||
CardDatabaseModel::CardDatabaseModel(CardDatabase *_db, QObject *parent)
|
||||
: QAbstractListModel(parent), db(_db)
|
||||
: QAbstractListModel(parent), db(_db)
|
||||
{
|
||||
connect(db, SIGNAL(cardListChanged()), this, SLOT(updateCardList()));
|
||||
connect(db, SIGNAL(cardAdded(CardInfo *)), this, SLOT(cardAdded(CardInfo *)));
|
||||
connect(db, SIGNAL(cardRemoved(CardInfo *)), this, SLOT(cardRemoved(CardInfo *)));
|
||||
updateCardList();
|
||||
connect(db, SIGNAL(cardListChanged()), this, SLOT(updateCardList()));
|
||||
connect(db, SIGNAL(cardAdded(CardInfo *)), this, SLOT(cardAdded(CardInfo *)));
|
||||
connect(db, SIGNAL(cardRemoved(CardInfo *)), this, SLOT(cardRemoved(CardInfo *)));
|
||||
updateCardList();
|
||||
}
|
||||
|
||||
CardDatabaseModel::~CardDatabaseModel()
|
||||
|
@ -15,143 +15,143 @@ CardDatabaseModel::~CardDatabaseModel()
|
|||
|
||||
int CardDatabaseModel::rowCount(const QModelIndex &/*parent*/) const
|
||||
{
|
||||
return cardList.size();
|
||||
return cardList.size();
|
||||
}
|
||||
|
||||
int CardDatabaseModel::columnCount(const QModelIndex &/*parent*/) const
|
||||
{
|
||||
return 5;
|
||||
return 5;
|
||||
}
|
||||
|
||||
QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if ((index.row() >= cardList.size()) || (index.column() >= 5))
|
||||
return QVariant();
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if ((index.row() >= cardList.size()) || (index.column() >= 5))
|
||||
return QVariant();
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
|
||||
CardInfo *card = cardList.at(index.row());
|
||||
switch (index.column()){
|
||||
case 0: return card->getName();
|
||||
case 1: {
|
||||
QStringList setList;
|
||||
const QList<CardSet *> &sets = card->getSets();
|
||||
for (int i = 0; i < sets.size(); i++)
|
||||
setList << sets[i]->getShortName();
|
||||
return setList.join(", ");
|
||||
}
|
||||
case 2: return card->getManaCost();
|
||||
case 3: return card->getCardType();
|
||||
case 4: return card->getPowTough();
|
||||
default: return QVariant();
|
||||
}
|
||||
CardInfo *card = cardList.at(index.row());
|
||||
switch (index.column()){
|
||||
case 0: return card->getName();
|
||||
case 1: {
|
||||
QStringList setList;
|
||||
const QList<CardSet *> &sets = card->getSets();
|
||||
for (int i = 0; i < sets.size(); i++)
|
||||
setList << sets[i]->getShortName();
|
||||
return setList.join(", ");
|
||||
}
|
||||
case 2: return card->getManaCost();
|
||||
case 3: return card->getCardType();
|
||||
case 4: return card->getPowTough();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
QVariant CardDatabaseModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
if (orientation != Qt::Horizontal)
|
||||
return QVariant();
|
||||
switch (section) {
|
||||
case 0: return QString(tr("Name"));
|
||||
case 1: return QString(tr("Sets"));
|
||||
case 2: return QString(tr("Mana cost"));
|
||||
case 3: return QString(tr("Card type"));
|
||||
case 4: return QString(tr("P/T"));
|
||||
default: return QVariant();
|
||||
}
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
if (orientation != Qt::Horizontal)
|
||||
return QVariant();
|
||||
switch (section) {
|
||||
case 0: return QString(tr("Name"));
|
||||
case 1: return QString(tr("Sets"));
|
||||
case 2: return QString(tr("Mana cost"));
|
||||
case 3: return QString(tr("Card type"));
|
||||
case 4: return QString(tr("P/T"));
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
void CardDatabaseModel::updateCardList()
|
||||
{
|
||||
for (int i = 0; i < cardList.size(); ++i)
|
||||
disconnect(cardList[i], 0, this, 0);
|
||||
for (int i = 0; i < cardList.size(); ++i)
|
||||
disconnect(cardList[i], 0, this, 0);
|
||||
|
||||
cardList = db->getCardList();
|
||||
for (int i = 0; i < cardList.size(); ++i)
|
||||
connect(cardList[i], SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *)));
|
||||
cardList = db->getCardList();
|
||||
for (int i = 0; i < cardList.size(); ++i)
|
||||
connect(cardList[i], SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *)));
|
||||
|
||||
reset();
|
||||
reset();
|
||||
}
|
||||
|
||||
void CardDatabaseModel::cardInfoChanged(CardInfo *card)
|
||||
{
|
||||
const int row = cardList.indexOf(card);
|
||||
if (row == -1)
|
||||
return;
|
||||
const int row = cardList.indexOf(card);
|
||||
if (row == -1)
|
||||
return;
|
||||
|
||||
emit dataChanged(index(row, 0), index(row, 4));
|
||||
emit dataChanged(index(row, 0), index(row, 4));
|
||||
}
|
||||
|
||||
void CardDatabaseModel::cardAdded(CardInfo *card)
|
||||
{
|
||||
beginInsertRows(QModelIndex(), cardList.size(), cardList.size());
|
||||
cardList.append(card);
|
||||
connect(card, SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *)));
|
||||
endInsertRows();
|
||||
beginInsertRows(QModelIndex(), cardList.size(), cardList.size());
|
||||
cardList.append(card);
|
||||
connect(card, SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *)));
|
||||
endInsertRows();
|
||||
}
|
||||
|
||||
void CardDatabaseModel::cardRemoved(CardInfo *card)
|
||||
{
|
||||
const int row = cardList.indexOf(card);
|
||||
if (row == -1)
|
||||
return;
|
||||
const int row = cardList.indexOf(card);
|
||||
if (row == -1)
|
||||
return;
|
||||
|
||||
beginRemoveRows(QModelIndex(), row, row);
|
||||
cardList.removeAt(row);
|
||||
endRemoveRows();
|
||||
beginRemoveRows(QModelIndex(), row, row);
|
||||
cardList.removeAt(row);
|
||||
endRemoveRows();
|
||||
}
|
||||
|
||||
CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent)
|
||||
: QSortFilterProxyModel(parent),
|
||||
isToken(ShowAll)
|
||||
: QSortFilterProxyModel(parent),
|
||||
isToken(ShowAll)
|
||||
{
|
||||
setFilterCaseSensitivity(Qt::CaseInsensitive);
|
||||
setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
setFilterCaseSensitivity(Qt::CaseInsensitive);
|
||||
setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
}
|
||||
|
||||
bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const
|
||||
{
|
||||
CardInfo const *info = static_cast<CardDatabaseModel *>(sourceModel())->getCard(sourceRow);
|
||||
CardInfo const *info = static_cast<CardDatabaseModel *>(sourceModel())->getCard(sourceRow);
|
||||
|
||||
if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken()))
|
||||
return false;
|
||||
if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken()))
|
||||
return false;
|
||||
|
||||
if (!cardNameBeginning.isEmpty())
|
||||
if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive))
|
||||
return false;
|
||||
if (!cardNameBeginning.isEmpty())
|
||||
if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive))
|
||||
return false;
|
||||
|
||||
if (!cardName.isEmpty())
|
||||
if (!info->getName().contains(cardName, Qt::CaseInsensitive))
|
||||
return false;
|
||||
if (!cardName.isEmpty())
|
||||
if (!info->getName().contains(cardName, Qt::CaseInsensitive))
|
||||
return false;
|
||||
|
||||
if (!cardNameSet.isEmpty())
|
||||
if (!cardNameSet.contains(info->getName()))
|
||||
return false;
|
||||
if (!cardNameSet.isEmpty())
|
||||
if (!cardNameSet.contains(info->getName()))
|
||||
return false;
|
||||
|
||||
if (!cardText.isEmpty())
|
||||
if (!info->getText().contains(cardText, Qt::CaseInsensitive))
|
||||
return false;
|
||||
if (!cardText.isEmpty())
|
||||
if (!info->getText().contains(cardText, Qt::CaseInsensitive))
|
||||
return false;
|
||||
|
||||
if (!cardColors.isEmpty())
|
||||
if (QSet<QString>::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X")))
|
||||
return false;
|
||||
if (!cardColors.isEmpty())
|
||||
if (QSet<QString>::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X")))
|
||||
return false;
|
||||
|
||||
if (!cardTypes.isEmpty())
|
||||
if (!cardTypes.contains(info->getMainCardType()))
|
||||
return false;
|
||||
if (!cardTypes.isEmpty())
|
||||
if (!cardTypes.contains(info->getMainCardType()))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void CardDatabaseDisplayModel::clearSearch()
|
||||
{
|
||||
cardName.clear();
|
||||
cardText.clear();
|
||||
cardTypes.clear();
|
||||
cardColors.clear();
|
||||
invalidateFilter();
|
||||
cardName.clear();
|
||||
cardText.clear();
|
||||
cardTypes.clear();
|
||||
cardColors.clear();
|
||||
invalidateFilter();
|
||||
}
|
||||
|
|
|
@ -8,46 +8,46 @@
|
|||
#include "carddatabase.h"
|
||||
|
||||
class CardDatabaseModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
CardDatabaseModel(CardDatabase *_db, 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]; }
|
||||
CardDatabaseModel(CardDatabase *_db, 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]; }
|
||||
private:
|
||||
QList<CardInfo *> cardList;
|
||||
CardDatabase *db;
|
||||
QList<CardInfo *> cardList;
|
||||
CardDatabase *db;
|
||||
private slots:
|
||||
void updateCardList();
|
||||
void cardAdded(CardInfo *card);
|
||||
void cardRemoved(CardInfo *card);
|
||||
void cardInfoChanged(CardInfo *card);
|
||||
void updateCardList();
|
||||
void cardAdded(CardInfo *card);
|
||||
void cardRemoved(CardInfo *card);
|
||||
void cardInfoChanged(CardInfo *card);
|
||||
};
|
||||
|
||||
class CardDatabaseDisplayModel : public QSortFilterProxyModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
enum FilterBool { ShowTrue, ShowFalse, ShowAll };
|
||||
enum FilterBool { ShowTrue, ShowFalse, ShowAll };
|
||||
private:
|
||||
FilterBool isToken;
|
||||
QString cardNameBeginning, cardName, cardText;
|
||||
QSet<QString> cardNameSet, cardTypes, cardColors;
|
||||
FilterBool isToken;
|
||||
QString cardNameBeginning, cardName, cardText;
|
||||
QSet<QString> cardNameSet, cardTypes, cardColors;
|
||||
public:
|
||||
CardDatabaseDisplayModel(QObject *parent = 0);
|
||||
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 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 clearSearch();
|
||||
CardDatabaseDisplayModel(QObject *parent = 0);
|
||||
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 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 clearSearch();
|
||||
protected:
|
||||
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
|
||||
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -9,82 +9,82 @@
|
|||
#include <QPainter>
|
||||
|
||||
CardDragItem::CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag)
|
||||
: AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0)
|
||||
: AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0)
|
||||
{
|
||||
}
|
||||
|
||||
void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
|
||||
{
|
||||
AbstractCardDragItem::paint(painter, option, widget);
|
||||
AbstractCardDragItem::paint(painter, option, widget);
|
||||
|
||||
if (occupied)
|
||||
painter->fillRect(boundingRect(), QColor(200, 0, 0, 100));
|
||||
if (occupied)
|
||||
painter->fillRect(boundingRect(), QColor(200, 0, 0, 100));
|
||||
}
|
||||
|
||||
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;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--) {
|
||||
CardZone *temp = qgraphicsitem_cast<CardZone *>(colliding.at(i));
|
||||
if (!cardZone)
|
||||
cardZone = temp;
|
||||
if (!zoneViewZone)
|
||||
zoneViewZone = qobject_cast<ZoneViewZone *>(temp);
|
||||
}
|
||||
CardZone *cursorZone = 0;
|
||||
if (zoneViewZone)
|
||||
cursorZone = zoneViewZone;
|
||||
else if (cardZone)
|
||||
cursorZone = cardZone;
|
||||
if (!cursorZone)
|
||||
return;
|
||||
currentZone = cursorZone;
|
||||
CardZone *cardZone = 0;
|
||||
ZoneViewZone *zoneViewZone = 0;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--) {
|
||||
CardZone *temp = qgraphicsitem_cast<CardZone *>(colliding.at(i));
|
||||
if (!cardZone)
|
||||
cardZone = temp;
|
||||
if (!zoneViewZone)
|
||||
zoneViewZone = qobject_cast<ZoneViewZone *>(temp);
|
||||
}
|
||||
CardZone *cursorZone = 0;
|
||||
if (zoneViewZone)
|
||||
cursorZone = zoneViewZone;
|
||||
else if (cardZone)
|
||||
cursorZone = cardZone;
|
||||
if (!cursorZone)
|
||||
return;
|
||||
currentZone = cursorZone;
|
||||
|
||||
QPointF zonePos = currentZone->scenePos();
|
||||
QPointF cursorPosInZone = cursorScenePos - zonePos;
|
||||
QPointF cardTopLeft = cursorPosInZone - hotSpot;
|
||||
QPointF closestGridPoint = cursorZone->closestGridPoint(cardTopLeft);
|
||||
QPointF newPos = zonePos + closestGridPoint;
|
||||
QPointF zonePos = currentZone->scenePos();
|
||||
QPointF cursorPosInZone = cursorScenePos - zonePos;
|
||||
QPointF cardTopLeft = cursorPosInZone - hotSpot;
|
||||
QPointF closestGridPoint = cursorZone->closestGridPoint(cardTopLeft);
|
||||
QPointF newPos = zonePos + closestGridPoint;
|
||||
|
||||
if (newPos != pos()) {
|
||||
for (int i = 0; i < childDrags.size(); i++)
|
||||
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
|
||||
setPos(newPos);
|
||||
if (newPos != pos()) {
|
||||
for (int i = 0; i < childDrags.size(); i++)
|
||||
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
|
||||
setPos(newPos);
|
||||
|
||||
bool newOccupied = false;
|
||||
TableZone *table = qobject_cast<TableZone *>(cursorZone);
|
||||
if (table)
|
||||
if (table->getCardFromCoords(closestGridPoint))
|
||||
newOccupied = true;
|
||||
if (newOccupied != occupied) {
|
||||
occupied = newOccupied;
|
||||
update();
|
||||
}
|
||||
}
|
||||
bool newOccupied = false;
|
||||
TableZone *table = qobject_cast<TableZone *>(cursorZone);
|
||||
if (table)
|
||||
if (table->getCardFromCoords(closestGridPoint))
|
||||
newOccupied = true;
|
||||
if (newOccupied != occupied) {
|
||||
occupied = newOccupied;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QGraphicsScene *sc = scene();
|
||||
QPointF sp = pos();
|
||||
sc->removeItem(this);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QGraphicsScene *sc = scene();
|
||||
QPointF sp = pos();
|
||||
sc->removeItem(this);
|
||||
|
||||
QList<CardDragItem *> dragItemList;
|
||||
CardZone *startZone = static_cast<CardItem *>(item)->getZone();
|
||||
if (currentZone && !(static_cast<CardItem *>(item)->getAttachedTo() && (startZone == currentZone))) {
|
||||
dragItemList.append(this);
|
||||
for (int i = 0; i < childDrags.size(); i++) {
|
||||
CardDragItem *c = static_cast<CardDragItem *>(childDrags[i]);
|
||||
if (!(static_cast<CardItem *>(c->item)->getAttachedTo() && (startZone == currentZone)) && !c->occupied)
|
||||
dragItemList.append(c);
|
||||
sc->removeItem(c);
|
||||
}
|
||||
}
|
||||
currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint());
|
||||
QList<CardDragItem *> dragItemList;
|
||||
CardZone *startZone = static_cast<CardItem *>(item)->getZone();
|
||||
if (currentZone && !(static_cast<CardItem *>(item)->getAttachedTo() && (startZone == currentZone))) {
|
||||
dragItemList.append(this);
|
||||
for (int i = 0; i < childDrags.size(); i++) {
|
||||
CardDragItem *c = static_cast<CardDragItem *>(childDrags[i]);
|
||||
if (!(static_cast<CardItem *>(c->item)->getAttachedTo() && (startZone == currentZone)) && !c->occupied)
|
||||
dragItemList.append(c);
|
||||
sc->removeItem(c);
|
||||
}
|
||||
}
|
||||
currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint());
|
||||
|
||||
event->accept();
|
||||
event->accept();
|
||||
}
|
||||
|
|
|
@ -6,20 +6,20 @@
|
|||
class CardItem;
|
||||
|
||||
class CardDragItem : public AbstractCardDragItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
int id;
|
||||
bool faceDown;
|
||||
bool occupied;
|
||||
CardZone *currentZone;
|
||||
int id;
|
||||
bool faceDown;
|
||||
bool occupied;
|
||||
CardZone *currentZone;
|
||||
public:
|
||||
CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0);
|
||||
int getId() const { return id; }
|
||||
bool getFaceDown() const { return faceDown; }
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void updatePosition(const QPointF &cursorScenePos);
|
||||
CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0);
|
||||
int getId() const { return id; }
|
||||
bool getFaceDown() const { return faceDown; }
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void updatePosition(const QPointF &cursorScenePos);
|
||||
protected:
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -12,209 +12,209 @@
|
|||
#include "settingscache.h"
|
||||
|
||||
CardInfoWidget::CardInfoWidget(ResizeMode _mode, const QString &cardName, QWidget *parent, Qt::WindowFlags flags)
|
||||
: QFrame(parent, flags)
|
||||
, pixmapWidth(0)
|
||||
, aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH)
|
||||
, minimized(settingsCache->getCardInfoMinimized()) // Initialize the cardinfo view status from cache.
|
||||
, mode(_mode)
|
||||
, info(0)
|
||||
: QFrame(parent, flags)
|
||||
, pixmapWidth(0)
|
||||
, aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH)
|
||||
, minimized(settingsCache->getCardInfoMinimized()) // Initialize the cardinfo view status from cache.
|
||||
, mode(_mode)
|
||||
, info(0)
|
||||
{
|
||||
if (mode == ModeGameTab) {
|
||||
// Create indexed list of status views for card.
|
||||
const QStringList cardInfoStatus = QStringList() << tr("Show card only") << tr("Show text only") << tr("Show full info");
|
||||
if (mode == ModeGameTab) {
|
||||
// Create indexed list of status views for card.
|
||||
const QStringList cardInfoStatus = QStringList() << tr("Show card only") << tr("Show text only") << tr("Show full info");
|
||||
|
||||
// Create droplist for cardinfo view selection, and set right current index.
|
||||
dropList = new QComboBox();
|
||||
dropList->addItems(cardInfoStatus);
|
||||
dropList->setCurrentIndex(minimized);
|
||||
connect(dropList, SIGNAL(currentIndexChanged(int)), this, SLOT(minimizeClicked(int)));
|
||||
}
|
||||
// Create droplist for cardinfo view selection, and set right current index.
|
||||
dropList = new QComboBox();
|
||||
dropList->addItems(cardInfoStatus);
|
||||
dropList->setCurrentIndex(minimized);
|
||||
connect(dropList, SIGNAL(currentIndexChanged(int)), this, SLOT(minimizeClicked(int)));
|
||||
}
|
||||
|
||||
cardPicture = new QLabel;
|
||||
cardPicture->setAlignment(Qt::AlignCenter);
|
||||
cardPicture = new QLabel;
|
||||
cardPicture->setAlignment(Qt::AlignCenter);
|
||||
|
||||
nameLabel1 = new QLabel;
|
||||
nameLabel2 = new QLabel;
|
||||
nameLabel2->setWordWrap(true);
|
||||
manacostLabel1 = new QLabel;
|
||||
manacostLabel2 = new QLabel;
|
||||
manacostLabel2->setWordWrap(true);
|
||||
cardtypeLabel1 = new QLabel;
|
||||
cardtypeLabel2 = new QLabel;
|
||||
cardtypeLabel2->setWordWrap(true);
|
||||
powtoughLabel1 = new QLabel;
|
||||
powtoughLabel2 = new QLabel;
|
||||
loyaltyLabel1 = new QLabel;
|
||||
loyaltyLabel2 = new QLabel;
|
||||
nameLabel1 = new QLabel;
|
||||
nameLabel2 = new QLabel;
|
||||
nameLabel2->setWordWrap(true);
|
||||
manacostLabel1 = new QLabel;
|
||||
manacostLabel2 = new QLabel;
|
||||
manacostLabel2->setWordWrap(true);
|
||||
cardtypeLabel1 = new QLabel;
|
||||
cardtypeLabel2 = new QLabel;
|
||||
cardtypeLabel2->setWordWrap(true);
|
||||
powtoughLabel1 = new QLabel;
|
||||
powtoughLabel2 = new QLabel;
|
||||
loyaltyLabel1 = new QLabel;
|
||||
loyaltyLabel2 = new QLabel;
|
||||
|
||||
textLabel = new QTextEdit();
|
||||
textLabel->setReadOnly(true);
|
||||
textLabel = new QTextEdit();
|
||||
textLabel->setReadOnly(true);
|
||||
|
||||
QGridLayout *grid = new QGridLayout(this);
|
||||
int row = 0;
|
||||
if (mode == ModeGameTab)
|
||||
grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight);
|
||||
grid->addWidget(cardPicture, row++, 0, 1, 2);
|
||||
grid->addWidget(nameLabel1, row, 0);
|
||||
grid->addWidget(nameLabel2, row++, 1);
|
||||
grid->addWidget(manacostLabel1, row, 0);
|
||||
grid->addWidget(manacostLabel2, row++, 1);
|
||||
grid->addWidget(cardtypeLabel1, row, 0);
|
||||
grid->addWidget(cardtypeLabel2, row++, 1);
|
||||
grid->addWidget(powtoughLabel1, row, 0);
|
||||
grid->addWidget(powtoughLabel2, row++, 1);
|
||||
grid->addWidget(loyaltyLabel1, row, 0);
|
||||
grid->addWidget(loyaltyLabel2, row++, 1);
|
||||
grid->addWidget(textLabel, row, 0, -1, 2);
|
||||
grid->setRowStretch(row, 1);
|
||||
grid->setColumnStretch(1, 1);
|
||||
QGridLayout *grid = new QGridLayout(this);
|
||||
int row = 0;
|
||||
if (mode == ModeGameTab)
|
||||
grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight);
|
||||
grid->addWidget(cardPicture, row++, 0, 1, 2);
|
||||
grid->addWidget(nameLabel1, row, 0);
|
||||
grid->addWidget(nameLabel2, row++, 1);
|
||||
grid->addWidget(manacostLabel1, row, 0);
|
||||
grid->addWidget(manacostLabel2, row++, 1);
|
||||
grid->addWidget(cardtypeLabel1, row, 0);
|
||||
grid->addWidget(cardtypeLabel2, row++, 1);
|
||||
grid->addWidget(powtoughLabel1, row, 0);
|
||||
grid->addWidget(powtoughLabel2, row++, 1);
|
||||
grid->addWidget(loyaltyLabel1, row, 0);
|
||||
grid->addWidget(loyaltyLabel2, row++, 1);
|
||||
grid->addWidget(textLabel, row, 0, -1, 2);
|
||||
grid->setRowStretch(row, 1);
|
||||
grid->setColumnStretch(1, 1);
|
||||
|
||||
retranslateUi();
|
||||
setFrameStyle(QFrame::Panel | QFrame::Raised);
|
||||
if (mode == ModeGameTab) {
|
||||
textLabel->setMinimumHeight(100);
|
||||
setFixedWidth(sizeHint().width());
|
||||
} else if (mode == ModePopUp) {
|
||||
QDesktopWidget desktopWidget;
|
||||
pixmapWidth = desktopWidget.screenGeometry().height() / 3 / aspectRatio;
|
||||
setFixedWidth(pixmapWidth + 150);
|
||||
} else
|
||||
setFixedWidth(250);
|
||||
retranslateUi();
|
||||
setFrameStyle(QFrame::Panel | QFrame::Raised);
|
||||
if (mode == ModeGameTab) {
|
||||
textLabel->setMinimumHeight(100);
|
||||
setFixedWidth(sizeHint().width());
|
||||
} else if (mode == ModePopUp) {
|
||||
QDesktopWidget desktopWidget;
|
||||
pixmapWidth = desktopWidget.screenGeometry().height() / 3 / aspectRatio;
|
||||
setFixedWidth(pixmapWidth + 150);
|
||||
} else
|
||||
setFixedWidth(250);
|
||||
|
||||
setCard(db->getCard(cardName));
|
||||
setMinimized(settingsCache->getCardInfoMinimized());
|
||||
setCard(db->getCard(cardName));
|
||||
setMinimized(settingsCache->getCardInfoMinimized());
|
||||
}
|
||||
|
||||
void CardInfoWidget::minimizeClicked(int newMinimized)
|
||||
{
|
||||
// Set new status, and store it in the settings cache.
|
||||
setMinimized(newMinimized);
|
||||
settingsCache->setCardInfoMinimized(newMinimized);
|
||||
// Set new status, and store it in the settings cache.
|
||||
setMinimized(newMinimized);
|
||||
settingsCache->setCardInfoMinimized(newMinimized);
|
||||
}
|
||||
|
||||
bool CardInfoWidget::shouldShowPowTough()
|
||||
{
|
||||
// return (!info->getPowTough().isEmpty() && (minimized != 0));
|
||||
return (minimized != 0);
|
||||
// return (!info->getPowTough().isEmpty() && (minimized != 0));
|
||||
return (minimized != 0);
|
||||
}
|
||||
|
||||
bool CardInfoWidget::shouldShowLoyalty()
|
||||
{
|
||||
// return ((info->getLoyalty() > 0) && (minimized != 0));
|
||||
return (minimized != 0);
|
||||
// return ((info->getLoyalty() > 0) && (minimized != 0));
|
||||
return (minimized != 0);
|
||||
}
|
||||
|
||||
void CardInfoWidget::setMinimized(int _minimized)
|
||||
{
|
||||
minimized = _minimized;
|
||||
minimized = _minimized;
|
||||
|
||||
// Toggle oracle fields according to selected view.
|
||||
bool showAll = ((minimized == 1) || (minimized == 2));
|
||||
bool showPowTough = info ? (showAll && shouldShowPowTough()) : true;
|
||||
bool showLoyalty = info ? (showAll && shouldShowLoyalty()) : true;
|
||||
if (mode == ModeGameTab) {
|
||||
nameLabel1->setVisible(showAll);
|
||||
nameLabel2->setVisible(showAll);
|
||||
manacostLabel1->setVisible(showAll);
|
||||
manacostLabel2->setVisible(showAll);
|
||||
cardtypeLabel1->setVisible(showAll);
|
||||
cardtypeLabel2->setVisible(showAll);
|
||||
powtoughLabel1->setVisible(showPowTough);
|
||||
powtoughLabel2->setVisible(showPowTough);
|
||||
loyaltyLabel1->setVisible(showLoyalty);
|
||||
loyaltyLabel2->setVisible(showLoyalty);
|
||||
textLabel->setVisible(showAll);
|
||||
}
|
||||
// Toggle oracle fields according to selected view.
|
||||
bool showAll = ((minimized == 1) || (minimized == 2));
|
||||
bool showPowTough = info ? (showAll && shouldShowPowTough()) : true;
|
||||
bool showLoyalty = info ? (showAll && shouldShowLoyalty()) : true;
|
||||
if (mode == ModeGameTab) {
|
||||
nameLabel1->setVisible(showAll);
|
||||
nameLabel2->setVisible(showAll);
|
||||
manacostLabel1->setVisible(showAll);
|
||||
manacostLabel2->setVisible(showAll);
|
||||
cardtypeLabel1->setVisible(showAll);
|
||||
cardtypeLabel2->setVisible(showAll);
|
||||
powtoughLabel1->setVisible(showPowTough);
|
||||
powtoughLabel2->setVisible(showPowTough);
|
||||
loyaltyLabel1->setVisible(showLoyalty);
|
||||
loyaltyLabel2->setVisible(showLoyalty);
|
||||
textLabel->setVisible(showAll);
|
||||
}
|
||||
|
||||
cardPicture->hide();
|
||||
cardHeightOffset = minimumSizeHint().height() + 10;
|
||||
cardPicture->hide();
|
||||
cardHeightOffset = minimumSizeHint().height() + 10;
|
||||
|
||||
// Set the picture to be shown only at "card only" (0) and "full info" (2)
|
||||
if (mode == ModeGameTab) {
|
||||
cardPicture->setVisible((minimized == 0) || (minimized == 2));
|
||||
// Set the picture to be shown only at "card only" (0) and "full info" (2)
|
||||
if (mode == ModeGameTab) {
|
||||
cardPicture->setVisible((minimized == 0) || (minimized == 2));
|
||||
|
||||
if (minimized == 0)
|
||||
setMaximumHeight(cardHeightOffset + width() * aspectRatio);
|
||||
else
|
||||
setMaximumHeight(1000000);
|
||||
} else
|
||||
cardPicture->show();
|
||||
resize(width(), sizeHint().height());
|
||||
if (minimized == 0)
|
||||
setMaximumHeight(cardHeightOffset + width() * aspectRatio);
|
||||
else
|
||||
setMaximumHeight(1000000);
|
||||
} else
|
||||
cardPicture->show();
|
||||
resize(width(), sizeHint().height());
|
||||
}
|
||||
|
||||
void CardInfoWidget::setCard(CardInfo *card)
|
||||
{
|
||||
if (info)
|
||||
disconnect(info, 0, this, 0);
|
||||
info = card;
|
||||
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap()));
|
||||
connect(info, SIGNAL(destroyed()), this, SLOT(clear()));
|
||||
if (info)
|
||||
disconnect(info, 0, this, 0);
|
||||
info = card;
|
||||
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap()));
|
||||
connect(info, SIGNAL(destroyed()), this, SLOT(clear()));
|
||||
|
||||
updatePixmap();
|
||||
nameLabel2->setText(card->getName());
|
||||
manacostLabel2->setText(card->getManaCost());
|
||||
cardtypeLabel2->setText(card->getCardType());
|
||||
powtoughLabel2->setText(card->getPowTough());
|
||||
loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString());
|
||||
textLabel->setText(card->getText());
|
||||
updatePixmap();
|
||||
nameLabel2->setText(card->getName());
|
||||
manacostLabel2->setText(card->getManaCost());
|
||||
cardtypeLabel2->setText(card->getCardType());
|
||||
powtoughLabel2->setText(card->getPowTough());
|
||||
loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString());
|
||||
textLabel->setText(card->getText());
|
||||
|
||||
powtoughLabel1->setVisible(shouldShowPowTough());
|
||||
powtoughLabel2->setVisible(shouldShowPowTough());
|
||||
loyaltyLabel1->setVisible(shouldShowLoyalty());
|
||||
loyaltyLabel2->setVisible(shouldShowLoyalty());
|
||||
powtoughLabel1->setVisible(shouldShowPowTough());
|
||||
powtoughLabel2->setVisible(shouldShowPowTough());
|
||||
loyaltyLabel1->setVisible(shouldShowLoyalty());
|
||||
loyaltyLabel2->setVisible(shouldShowLoyalty());
|
||||
}
|
||||
|
||||
void CardInfoWidget::setCard(const QString &cardName)
|
||||
{
|
||||
setCard(db->getCard(cardName));
|
||||
setCard(db->getCard(cardName));
|
||||
}
|
||||
|
||||
void CardInfoWidget::setCard(AbstractCardItem *card)
|
||||
{
|
||||
setCard(card->getInfo());
|
||||
setCard(card->getInfo());
|
||||
}
|
||||
|
||||
void CardInfoWidget::clear()
|
||||
{
|
||||
setCard(db->getCard());
|
||||
setCard(db->getCard());
|
||||
}
|
||||
|
||||
void CardInfoWidget::updatePixmap()
|
||||
{
|
||||
if (pixmapWidth == 0)
|
||||
return;
|
||||
if (pixmapWidth == 0)
|
||||
return;
|
||||
|
||||
QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio));
|
||||
if (resizedPixmap)
|
||||
cardPicture->setPixmap(*resizedPixmap);
|
||||
else
|
||||
cardPicture->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio))));
|
||||
QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio));
|
||||
if (resizedPixmap)
|
||||
cardPicture->setPixmap(*resizedPixmap);
|
||||
else
|
||||
cardPicture->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio))));
|
||||
}
|
||||
|
||||
void CardInfoWidget::retranslateUi()
|
||||
{
|
||||
nameLabel1->setText(tr("Name:"));
|
||||
manacostLabel1->setText(tr("Mana cost:"));
|
||||
cardtypeLabel1->setText(tr("Card type:"));
|
||||
powtoughLabel1->setText(tr("P / T:"));
|
||||
loyaltyLabel1->setText(tr("Loyalty:"));
|
||||
nameLabel1->setText(tr("Name:"));
|
||||
manacostLabel1->setText(tr("Mana cost:"));
|
||||
cardtypeLabel1->setText(tr("Card type:"));
|
||||
powtoughLabel1->setText(tr("P / T:"));
|
||||
loyaltyLabel1->setText(tr("Loyalty:"));
|
||||
}
|
||||
void CardInfoWidget::resizeEvent(QResizeEvent * /*event*/)
|
||||
{
|
||||
if (mode == ModePopUp)
|
||||
return;
|
||||
if ((minimized == 1) && (mode == ModeGameTab)) {
|
||||
pixmapWidth = 0;
|
||||
return;
|
||||
}
|
||||
qreal newPixmapWidth = qMax((qreal) 100.0, qMin((qreal) cardPicture->width(), (qreal) ((height() - cardHeightOffset) / aspectRatio)));
|
||||
if (newPixmapWidth != pixmapWidth) {
|
||||
pixmapWidth = newPixmapWidth;
|
||||
updatePixmap();
|
||||
}
|
||||
if (mode == ModePopUp)
|
||||
return;
|
||||
if ((minimized == 1) && (mode == ModeGameTab)) {
|
||||
pixmapWidth = 0;
|
||||
return;
|
||||
}
|
||||
qreal newPixmapWidth = qMax((qreal) 100.0, qMin((qreal) cardPicture->width(), (qreal) ((height() - cardHeightOffset) / aspectRatio)));
|
||||
if (newPixmapWidth != pixmapWidth) {
|
||||
pixmapWidth = newPixmapWidth;
|
||||
updatePixmap();
|
||||
}
|
||||
}
|
||||
|
||||
QString CardInfoWidget::getCardName() const
|
||||
{
|
||||
return nameLabel2->text();
|
||||
return nameLabel2->text();
|
||||
}
|
||||
|
|
|
@ -14,51 +14,51 @@ class QResizeEvent;
|
|||
class QMouseEvent;
|
||||
|
||||
class CardInfoWidget : public QFrame {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp };
|
||||
enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp };
|
||||
|
||||
private:
|
||||
int pixmapWidth;
|
||||
qreal cardHeightOffset;
|
||||
qreal aspectRatio;
|
||||
// XXX: Why isn't this an eunm?
|
||||
int minimized; // 0 - card, 1 - oracle only, 2 - full
|
||||
ResizeMode mode;
|
||||
int pixmapWidth;
|
||||
qreal cardHeightOffset;
|
||||
qreal aspectRatio;
|
||||
// XXX: Why isn't this an eunm?
|
||||
int minimized; // 0 - card, 1 - oracle only, 2 - full
|
||||
ResizeMode mode;
|
||||
|
||||
QComboBox *dropList;
|
||||
QLabel *cardPicture;
|
||||
QLabel *nameLabel1, *nameLabel2;
|
||||
QLabel *manacostLabel1, *manacostLabel2;
|
||||
QLabel *cardtypeLabel1, *cardtypeLabel2;
|
||||
QLabel *powtoughLabel1, *powtoughLabel2;
|
||||
QLabel *loyaltyLabel1, *loyaltyLabel2;
|
||||
QTextEdit *textLabel;
|
||||
QComboBox *dropList;
|
||||
QLabel *cardPicture;
|
||||
QLabel *nameLabel1, *nameLabel2;
|
||||
QLabel *manacostLabel1, *manacostLabel2;
|
||||
QLabel *cardtypeLabel1, *cardtypeLabel2;
|
||||
QLabel *powtoughLabel1, *powtoughLabel2;
|
||||
QLabel *loyaltyLabel1, *loyaltyLabel2;
|
||||
QTextEdit *textLabel;
|
||||
|
||||
bool shouldShowPowTough();
|
||||
bool shouldShowLoyalty();
|
||||
bool shouldShowPowTough();
|
||||
bool shouldShowLoyalty();
|
||||
|
||||
CardInfo *info;
|
||||
void setMinimized(int _minimized);
|
||||
CardInfo *info;
|
||||
void setMinimized(int _minimized);
|
||||
|
||||
public:
|
||||
CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0);
|
||||
void retranslateUi();
|
||||
QString getCardName() const;
|
||||
CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0);
|
||||
void retranslateUi();
|
||||
QString getCardName() const;
|
||||
|
||||
public slots:
|
||||
void setCard(CardInfo *card);
|
||||
void setCard(const QString &cardName);
|
||||
void setCard(AbstractCardItem *card);
|
||||
void setCard(CardInfo *card);
|
||||
void setCard(const QString &cardName);
|
||||
void setCard(AbstractCardItem *card);
|
||||
|
||||
private slots:
|
||||
void clear();
|
||||
void updatePixmap();
|
||||
void minimizeClicked(int newMinimized);
|
||||
void clear();
|
||||
void updatePixmap();
|
||||
void minimizeClicked(int newMinimized);
|
||||
|
||||
protected:
|
||||
void resizeEvent(QResizeEvent *event);
|
||||
void resizeEvent(QResizeEvent *event);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -18,374 +18,374 @@
|
|||
#include "pb/serverinfo_card.pb.h"
|
||||
|
||||
CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _revealedCard, QGraphicsItem *parent)
|
||||
: AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0)
|
||||
: AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0)
|
||||
{
|
||||
owner->addCard(this);
|
||||
owner->addCard(this);
|
||||
|
||||
cardMenu = new QMenu;
|
||||
ptMenu = new QMenu;
|
||||
moveMenu = new QMenu;
|
||||
cardMenu = new QMenu;
|
||||
ptMenu = new QMenu;
|
||||
moveMenu = new QMenu;
|
||||
|
||||
retranslateUi();
|
||||
emit updateCardMenu(this);
|
||||
retranslateUi();
|
||||
emit updateCardMenu(this);
|
||||
}
|
||||
|
||||
CardItem::~CardItem()
|
||||
{
|
||||
prepareDelete();
|
||||
prepareDelete();
|
||||
|
||||
if (scene())
|
||||
static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
|
||||
if (scene())
|
||||
static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
|
||||
|
||||
delete cardMenu;
|
||||
delete ptMenu;
|
||||
delete moveMenu;
|
||||
delete cardMenu;
|
||||
delete ptMenu;
|
||||
delete moveMenu;
|
||||
|
||||
deleteDragItem();
|
||||
deleteDragItem();
|
||||
}
|
||||
|
||||
void CardItem::prepareDelete()
|
||||
{
|
||||
if (owner) {
|
||||
if (owner->getCardMenu() == cardMenu) {
|
||||
owner->setCardMenu(0);
|
||||
owner->getGame()->setActiveCard(0);
|
||||
}
|
||||
owner = 0;
|
||||
}
|
||||
if (owner) {
|
||||
if (owner->getCardMenu() == cardMenu) {
|
||||
owner->setCardMenu(0);
|
||||
owner->getGame()->setActiveCard(0);
|
||||
}
|
||||
owner = 0;
|
||||
}
|
||||
|
||||
while (!attachedCards.isEmpty()) {
|
||||
attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards()
|
||||
attachedCards.first()->setAttachedTo(0);
|
||||
}
|
||||
while (!attachedCards.isEmpty()) {
|
||||
attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards()
|
||||
attachedCards.first()->setAttachedTo(0);
|
||||
}
|
||||
|
||||
if (attachedTo) {
|
||||
attachedTo->removeAttachedCard(this);
|
||||
attachedTo = 0;
|
||||
}
|
||||
if (attachedTo) {
|
||||
attachedTo->removeAttachedCard(this);
|
||||
attachedTo = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void CardItem::deleteLater()
|
||||
{
|
||||
prepareDelete();
|
||||
AbstractCardItem::deleteLater();
|
||||
prepareDelete();
|
||||
AbstractCardItem::deleteLater();
|
||||
}
|
||||
|
||||
void CardItem::setZone(CardZone *_zone)
|
||||
{
|
||||
zone = _zone;
|
||||
emit updateCardMenu(this);
|
||||
zone = _zone;
|
||||
emit updateCardMenu(this);
|
||||
}
|
||||
|
||||
void CardItem::retranslateUi()
|
||||
{
|
||||
moveMenu->setTitle(tr("&Move to"));
|
||||
ptMenu->setTitle(tr("&Power / toughness"));
|
||||
moveMenu->setTitle(tr("&Move to"));
|
||||
ptMenu->setTitle(tr("&Power / toughness"));
|
||||
}
|
||||
|
||||
void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
|
||||
{
|
||||
painter->save();
|
||||
AbstractCardItem::paint(painter, option, widget);
|
||||
painter->save();
|
||||
AbstractCardItem::paint(painter, option, widget);
|
||||
|
||||
int i = 0;
|
||||
QMapIterator<int, int> counterIterator(counters);
|
||||
while (counterIterator.hasNext()) {
|
||||
counterIterator.next();
|
||||
QColor color;
|
||||
color.setHsv(counterIterator.key() * 60, 150, 255);
|
||||
int i = 0;
|
||||
QMapIterator<int, int> counterIterator(counters);
|
||||
while (counterIterator.hasNext()) {
|
||||
counterIterator.next();
|
||||
QColor color;
|
||||
color.setHsv(counterIterator.key() * 60, 150, 255);
|
||||
|
||||
paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter);
|
||||
++i;
|
||||
}
|
||||
paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter);
|
||||
++i;
|
||||
}
|
||||
|
||||
QSizeF translatedSize = getTranslatedSize(painter);
|
||||
qreal scaleFactor = translatedSize.width() / boundingRect().width();
|
||||
QSizeF translatedSize = getTranslatedSize(painter);
|
||||
qreal scaleFactor = translatedSize.width() / boundingRect().width();
|
||||
|
||||
if (!pt.isEmpty()) {
|
||||
painter->save();
|
||||
if (!pt.isEmpty()) {
|
||||
painter->save();
|
||||
|
||||
transformPainter(painter, translatedSize, tapAngle);
|
||||
painter->setBackground(Qt::black);
|
||||
painter->setBackgroundMode(Qt::OpaqueMode);
|
||||
painter->setPen(Qt::white);
|
||||
transformPainter(painter, translatedSize, tapAngle);
|
||||
painter->setBackground(Qt::black);
|
||||
painter->setBackgroundMode(Qt::OpaqueMode);
|
||||
painter->setPen(Qt::white);
|
||||
|
||||
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt);
|
||||
painter->restore();
|
||||
}
|
||||
if (!annotation.isEmpty()) {
|
||||
painter->save();
|
||||
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt);
|
||||
painter->restore();
|
||||
}
|
||||
if (!annotation.isEmpty()) {
|
||||
painter->save();
|
||||
|
||||
transformPainter(painter, translatedSize, tapAngle);
|
||||
painter->setBackground(Qt::black);
|
||||
painter->setBackgroundMode(Qt::OpaqueMode);
|
||||
painter->setPen(Qt::white);
|
||||
transformPainter(painter, translatedSize, tapAngle);
|
||||
painter->setBackground(Qt::black);
|
||||
painter->setBackgroundMode(Qt::OpaqueMode);
|
||||
painter->setPen(Qt::white);
|
||||
|
||||
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation);
|
||||
painter->restore();
|
||||
}
|
||||
if (getBeingPointedAt())
|
||||
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
|
||||
painter->restore();
|
||||
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation);
|
||||
painter->restore();
|
||||
}
|
||||
if (getBeingPointedAt())
|
||||
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
void CardItem::setAttacking(bool _attacking)
|
||||
{
|
||||
attacking = _attacking;
|
||||
update();
|
||||
attacking = _attacking;
|
||||
update();
|
||||
}
|
||||
|
||||
void CardItem::setCounter(int _id, int _value)
|
||||
{
|
||||
if (_value)
|
||||
counters.insert(_id, _value);
|
||||
else
|
||||
counters.remove(_id);
|
||||
update();
|
||||
if (_value)
|
||||
counters.insert(_id, _value);
|
||||
else
|
||||
counters.remove(_id);
|
||||
update();
|
||||
}
|
||||
|
||||
void CardItem::setAnnotation(const QString &_annotation)
|
||||
{
|
||||
annotation = _annotation;
|
||||
update();
|
||||
annotation = _annotation;
|
||||
update();
|
||||
}
|
||||
|
||||
void CardItem::setDoesntUntap(bool _doesntUntap)
|
||||
{
|
||||
doesntUntap = _doesntUntap;
|
||||
doesntUntap = _doesntUntap;
|
||||
}
|
||||
|
||||
void CardItem::setPT(const QString &_pt)
|
||||
{
|
||||
pt = _pt;
|
||||
update();
|
||||
pt = _pt;
|
||||
update();
|
||||
}
|
||||
|
||||
void CardItem::setAttachedTo(CardItem *_attachedTo)
|
||||
{
|
||||
if (attachedTo)
|
||||
attachedTo->removeAttachedCard(this);
|
||||
if (attachedTo)
|
||||
attachedTo->removeAttachedCard(this);
|
||||
|
||||
gridPoint.setX(-1);
|
||||
attachedTo = _attachedTo;
|
||||
if (attachedTo) {
|
||||
setParentItem(attachedTo->getZone());
|
||||
attachedTo->addAttachedCard(this);
|
||||
if (zone != attachedTo->getZone())
|
||||
attachedTo->getZone()->reorganizeCards();
|
||||
} else
|
||||
setParentItem(zone);
|
||||
gridPoint.setX(-1);
|
||||
attachedTo = _attachedTo;
|
||||
if (attachedTo) {
|
||||
setParentItem(attachedTo->getZone());
|
||||
attachedTo->addAttachedCard(this);
|
||||
if (zone != attachedTo->getZone())
|
||||
attachedTo->getZone()->reorganizeCards();
|
||||
} else
|
||||
setParentItem(zone);
|
||||
|
||||
if (zone)
|
||||
zone->reorganizeCards();
|
||||
if (zone)
|
||||
zone->reorganizeCards();
|
||||
|
||||
emit updateCardMenu(this);
|
||||
emit updateCardMenu(this);
|
||||
}
|
||||
|
||||
void CardItem::resetState()
|
||||
{
|
||||
attacking = false;
|
||||
facedown = false;
|
||||
counters.clear();
|
||||
pt.clear();
|
||||
annotation.clear();
|
||||
attachedTo = 0;
|
||||
attachedCards.clear();
|
||||
setTapped(false, false);
|
||||
setDoesntUntap(false);
|
||||
if (scene())
|
||||
static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
|
||||
update();
|
||||
attacking = false;
|
||||
facedown = false;
|
||||
counters.clear();
|
||||
pt.clear();
|
||||
annotation.clear();
|
||||
attachedTo = 0;
|
||||
attachedCards.clear();
|
||||
setTapped(false, false);
|
||||
setDoesntUntap(false);
|
||||
if (scene())
|
||||
static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
|
||||
update();
|
||||
}
|
||||
|
||||
void CardItem::processCardInfo(const ServerInfo_Card &info)
|
||||
{
|
||||
counters.clear();
|
||||
const int counterListSize = info.counter_list_size();
|
||||
for (int i = 0; i < counterListSize; ++i) {
|
||||
const ServerInfo_CardCounter &counterInfo = info.counter_list(i);
|
||||
counters.insert(counterInfo.id(), counterInfo.value());
|
||||
}
|
||||
counters.clear();
|
||||
const int counterListSize = info.counter_list_size();
|
||||
for (int i = 0; i < counterListSize; ++i) {
|
||||
const ServerInfo_CardCounter &counterInfo = info.counter_list(i);
|
||||
counters.insert(counterInfo.id(), counterInfo.value());
|
||||
}
|
||||
|
||||
setId(info.id());
|
||||
setName(QString::fromStdString(info.name()));
|
||||
setAttacking(info.attacking());
|
||||
setFaceDown(info.face_down());
|
||||
setPT(QString::fromStdString(info.pt()));
|
||||
setAnnotation(QString::fromStdString(info.annotation()));
|
||||
setColor(QString::fromStdString(info.color()));
|
||||
setTapped(info.tapped());
|
||||
setDestroyOnZoneChange(info.destroy_on_zone_change());
|
||||
setDoesntUntap(info.doesnt_untap());
|
||||
setId(info.id());
|
||||
setName(QString::fromStdString(info.name()));
|
||||
setAttacking(info.attacking());
|
||||
setFaceDown(info.face_down());
|
||||
setPT(QString::fromStdString(info.pt()));
|
||||
setAnnotation(QString::fromStdString(info.annotation()));
|
||||
setColor(QString::fromStdString(info.color()));
|
||||
setTapped(info.tapped());
|
||||
setDestroyOnZoneChange(info.destroy_on_zone_change());
|
||||
setDoesntUntap(info.doesnt_untap());
|
||||
}
|
||||
|
||||
CardDragItem *CardItem::createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown)
|
||||
{
|
||||
deleteDragItem();
|
||||
dragItem = new CardDragItem(this, _id, _pos, faceDown);
|
||||
dragItem->setVisible(false);
|
||||
scene()->addItem(dragItem);
|
||||
dragItem->updatePosition(_scenePos);
|
||||
dragItem->setVisible(true);
|
||||
deleteDragItem();
|
||||
dragItem = new CardDragItem(this, _id, _pos, faceDown);
|
||||
dragItem->setVisible(false);
|
||||
scene()->addItem(dragItem);
|
||||
dragItem->updatePosition(_scenePos);
|
||||
dragItem->setVisible(true);
|
||||
|
||||
return dragItem;
|
||||
return dragItem;
|
||||
}
|
||||
|
||||
void CardItem::deleteDragItem()
|
||||
{
|
||||
dragItem->deleteLater();
|
||||
dragItem = NULL;
|
||||
dragItem->deleteLater();
|
||||
dragItem = NULL;
|
||||
}
|
||||
|
||||
void CardItem::drawArrow(const QColor &arrowColor)
|
||||
{
|
||||
if (static_cast<TabGame *>(owner->parent())->getSpectator())
|
||||
return;
|
||||
if (static_cast<TabGame *>(owner->parent())->getSpectator())
|
||||
return;
|
||||
|
||||
Player *arrowOwner = static_cast<TabGame *>(owner->parent())->getActiveLocalPlayer();
|
||||
ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor);
|
||||
scene()->addItem(arrow);
|
||||
arrow->grabMouse();
|
||||
Player *arrowOwner = static_cast<TabGame *>(owner->parent())->getActiveLocalPlayer();
|
||||
ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor);
|
||||
scene()->addItem(arrow);
|
||||
arrow->grabMouse();
|
||||
|
||||
QListIterator<QGraphicsItem *> itemIterator(scene()->selectedItems());
|
||||
while (itemIterator.hasNext()) {
|
||||
CardItem *c = qgraphicsitem_cast<CardItem *>(itemIterator.next());
|
||||
if (!c || (c == this))
|
||||
continue;
|
||||
if (c->getZone() != zone)
|
||||
continue;
|
||||
QListIterator<QGraphicsItem *> itemIterator(scene()->selectedItems());
|
||||
while (itemIterator.hasNext()) {
|
||||
CardItem *c = qgraphicsitem_cast<CardItem *>(itemIterator.next());
|
||||
if (!c || (c == this))
|
||||
continue;
|
||||
if (c->getZone() != zone)
|
||||
continue;
|
||||
|
||||
ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor);
|
||||
scene()->addItem(childArrow);
|
||||
arrow->addChildArrow(childArrow);
|
||||
}
|
||||
ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor);
|
||||
scene()->addItem(childArrow);
|
||||
arrow->addChildArrow(childArrow);
|
||||
}
|
||||
}
|
||||
|
||||
void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->buttons().testFlag(Qt::RightButton)) {
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance())
|
||||
return;
|
||||
if (event->buttons().testFlag(Qt::RightButton)) {
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance())
|
||||
return;
|
||||
|
||||
QColor arrowColor = Qt::red;
|
||||
if (event->modifiers().testFlag(Qt::ControlModifier))
|
||||
arrowColor = Qt::yellow;
|
||||
else if (event->modifiers().testFlag(Qt::AltModifier))
|
||||
arrowColor = Qt::blue;
|
||||
else if (event->modifiers().testFlag(Qt::ShiftModifier))
|
||||
arrowColor = Qt::green;
|
||||
QColor arrowColor = Qt::red;
|
||||
if (event->modifiers().testFlag(Qt::ControlModifier))
|
||||
arrowColor = Qt::yellow;
|
||||
else if (event->modifiers().testFlag(Qt::AltModifier))
|
||||
arrowColor = Qt::blue;
|
||||
else if (event->modifiers().testFlag(Qt::ShiftModifier))
|
||||
arrowColor = Qt::green;
|
||||
|
||||
drawArrow(arrowColor);
|
||||
} else if (event->buttons().testFlag(Qt::LeftButton)) {
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
|
||||
return;
|
||||
if (zone->getIsView()) {
|
||||
const ZoneViewZone *const view = static_cast<const ZoneViewZone *const>(zone);
|
||||
if (view->getRevealZone() && !view->getWriteableRevealZone())
|
||||
return;
|
||||
} else if (!owner->getLocal())
|
||||
return;
|
||||
drawArrow(arrowColor);
|
||||
} else if (event->buttons().testFlag(Qt::LeftButton)) {
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
|
||||
return;
|
||||
if (zone->getIsView()) {
|
||||
const ZoneViewZone *const view = static_cast<const ZoneViewZone *const>(zone);
|
||||
if (view->getRevealZone() && !view->getWriteableRevealZone())
|
||||
return;
|
||||
} else if (!owner->getLocal())
|
||||
return;
|
||||
|
||||
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
|
||||
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
|
||||
|
||||
createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown);
|
||||
dragItem->grabMouse();
|
||||
createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown);
|
||||
dragItem->grabMouse();
|
||||
|
||||
QList<QGraphicsItem *> sel = scene()->selectedItems();
|
||||
int j = 0;
|
||||
for (int i = 0; i < sel.size(); i++) {
|
||||
CardItem *c = (CardItem *) sel.at(i);
|
||||
if ((c == this) || (c->getZone() != zone))
|
||||
continue;
|
||||
++j;
|
||||
QPointF childPos;
|
||||
if (zone->getHasCardAttr())
|
||||
childPos = c->pos() - pos();
|
||||
else
|
||||
childPos = QPointF(j * CARD_WIDTH / 2, 0);
|
||||
CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem);
|
||||
drag->setPos(dragItem->pos() + childPos);
|
||||
scene()->addItem(drag);
|
||||
}
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QList<QGraphicsItem *> sel = scene()->selectedItems();
|
||||
int j = 0;
|
||||
for (int i = 0; i < sel.size(); i++) {
|
||||
CardItem *c = (CardItem *) sel.at(i);
|
||||
if ((c == this) || (c->getZone() != zone))
|
||||
continue;
|
||||
++j;
|
||||
QPointF childPos;
|
||||
if (zone->getHasCardAttr())
|
||||
childPos = c->pos() - pos();
|
||||
else
|
||||
childPos = QPointF(j * CARD_WIDTH / 2, 0);
|
||||
CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem);
|
||||
drag->setPos(dragItem->pos() + childPos);
|
||||
scene()->addItem(drag);
|
||||
}
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
}
|
||||
|
||||
void CardItem::playCard(bool faceDown)
|
||||
{
|
||||
// Do nothing if the card belongs to another player
|
||||
if (!owner->getLocal())
|
||||
return;
|
||||
// Do nothing if the card belongs to another player
|
||||
if (!owner->getLocal())
|
||||
return;
|
||||
|
||||
TableZone *tz = qobject_cast<TableZone *>(zone);
|
||||
if (tz)
|
||||
tz->toggleTapped();
|
||||
else
|
||||
zone->getPlayer()->playCard(this, faceDown, info->getCipt());
|
||||
TableZone *tz = qobject_cast<TableZone *>(zone);
|
||||
if (tz)
|
||||
tz->toggleTapped();
|
||||
else
|
||||
zone->getPlayer()->playCard(this, faceDown, info->getCipt());
|
||||
}
|
||||
|
||||
void CardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::RightButton) {
|
||||
if (cardMenu)
|
||||
if (!cardMenu->isEmpty())
|
||||
cardMenu->exec(event->screenPos());
|
||||
} else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) {
|
||||
if (event->button() == Qt::RightButton) {
|
||||
if (cardMenu)
|
||||
if (!cardMenu->isEmpty())
|
||||
cardMenu->exec(event->screenPos());
|
||||
} else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) {
|
||||
|
||||
bool hideCard = false;
|
||||
if (zone->getIsView()) {
|
||||
ZoneViewZone *view = static_cast<ZoneViewZone *>(zone);
|
||||
if (view->getRevealZone() && !view->getWriteableRevealZone())
|
||||
hideCard = true;
|
||||
}
|
||||
if (hideCard)
|
||||
zone->removeCard(this);
|
||||
else
|
||||
playCard(event->modifiers().testFlag(Qt::ShiftModifier));
|
||||
}
|
||||
bool hideCard = false;
|
||||
if (zone->getIsView()) {
|
||||
ZoneViewZone *view = static_cast<ZoneViewZone *>(zone);
|
||||
if (view->getRevealZone() && !view->getWriteableRevealZone())
|
||||
hideCard = true;
|
||||
}
|
||||
if (hideCard)
|
||||
zone->removeCard(this);
|
||||
else
|
||||
playCard(event->modifiers().testFlag(Qt::ShiftModifier));
|
||||
}
|
||||
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
AbstractCardItem::mouseReleaseEvent(event);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
AbstractCardItem::mouseReleaseEvent(event);
|
||||
}
|
||||
|
||||
void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (settingsCache->getDoubleClickToPlay()) {
|
||||
if (revealedCard)
|
||||
zone->removeCard(this);
|
||||
else
|
||||
playCard(event->modifiers().testFlag(Qt::ShiftModifier));
|
||||
}
|
||||
event->accept();
|
||||
if (settingsCache->getDoubleClickToPlay()) {
|
||||
if (revealedCard)
|
||||
zone->removeCard(this);
|
||||
else
|
||||
playCard(event->modifiers().testFlag(Qt::ShiftModifier));
|
||||
}
|
||||
event->accept();
|
||||
}
|
||||
|
||||
bool CardItem::animationEvent()
|
||||
{
|
||||
int delta = 18;
|
||||
if (!tapped)
|
||||
delta *= -1;
|
||||
int delta = 18;
|
||||
if (!tapped)
|
||||
delta *= -1;
|
||||
|
||||
tapAngle += delta;
|
||||
tapAngle += delta;
|
||||
|
||||
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
|
||||
setHovered(false);
|
||||
update();
|
||||
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
|
||||
setHovered(false);
|
||||
update();
|
||||
|
||||
if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0)))
|
||||
return false;
|
||||
return true;
|
||||
if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0)))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
QVariant CardItem::itemChange(GraphicsItemChange change, const QVariant &value)
|
||||
{
|
||||
if ((change == ItemSelectedHasChanged) && owner) {
|
||||
if (value == true) {
|
||||
owner->setCardMenu(cardMenu);
|
||||
owner->getGame()->setActiveCard(this);
|
||||
} else if (owner->getCardMenu() == cardMenu) {
|
||||
owner->setCardMenu(0);
|
||||
owner->getGame()->setActiveCard(0);
|
||||
}
|
||||
}
|
||||
return QGraphicsItem::itemChange(change, value);
|
||||
if ((change == ItemSelectedHasChanged) && owner) {
|
||||
if (value == true) {
|
||||
owner->setCardMenu(cardMenu);
|
||||
owner->getGame()->setActiveCard(this);
|
||||
} else if (owner->getCardMenu() == cardMenu) {
|
||||
owner->setCardMenu(0);
|
||||
owner->getGame()->setActiveCard(0);
|
||||
}
|
||||
}
|
||||
return QGraphicsItem::itemChange(change, value);
|
||||
}
|
||||
|
|
|
@ -14,75 +14,75 @@ class QColor;
|
|||
const int MAX_COUNTERS_ON_CARD = 999;
|
||||
|
||||
class CardItem : public AbstractCardItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
CardZone *zone;
|
||||
bool revealedCard;
|
||||
bool attacking;
|
||||
QMap<int, int> counters;
|
||||
QString annotation;
|
||||
QString pt;
|
||||
bool destroyOnZoneChange;
|
||||
bool doesntUntap;
|
||||
QPoint gridPoint;
|
||||
CardDragItem *dragItem;
|
||||
CardItem *attachedTo;
|
||||
QList<CardItem *> attachedCards;
|
||||
CardZone *zone;
|
||||
bool revealedCard;
|
||||
bool attacking;
|
||||
QMap<int, int> counters;
|
||||
QString annotation;
|
||||
QString pt;
|
||||
bool destroyOnZoneChange;
|
||||
bool doesntUntap;
|
||||
QPoint gridPoint;
|
||||
CardDragItem *dragItem;
|
||||
CardItem *attachedTo;
|
||||
QList<CardItem *> attachedCards;
|
||||
|
||||
QMenu *cardMenu, *ptMenu, *moveMenu;
|
||||
QMenu *cardMenu, *ptMenu, *moveMenu;
|
||||
|
||||
void prepareDelete();
|
||||
void prepareDelete();
|
||||
public slots:
|
||||
void deleteLater();
|
||||
void deleteLater();
|
||||
public:
|
||||
enum { Type = typeCard };
|
||||
int type() const { return Type; }
|
||||
CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0);
|
||||
~CardItem();
|
||||
void retranslateUi();
|
||||
CardZone *getZone() const { return zone; }
|
||||
void setZone(CardZone *_zone);
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
QPoint getGridPoint() const { return gridPoint; }
|
||||
void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; }
|
||||
QPoint getGridPos() const { return gridPoint; }
|
||||
Player *getOwner() const { return owner; }
|
||||
void setOwner(Player *_owner) { owner = _owner; }
|
||||
bool getRevealedCard() const { return revealedCard; }
|
||||
bool getAttacking() const { return attacking; }
|
||||
void setAttacking(bool _attacking);
|
||||
const QMap<int, int> &getCounters() const { return counters; }
|
||||
void setCounter(int _id, int _value);
|
||||
QString getAnnotation() const { return annotation; }
|
||||
void setAnnotation(const QString &_annotation);
|
||||
bool getDoesntUntap() const { return doesntUntap; }
|
||||
void setDoesntUntap(bool _doesntUntap);
|
||||
QString getPT() const { return pt; }
|
||||
void setPT(const QString &_pt);
|
||||
bool getDestroyOnZoneChange() const { return destroyOnZoneChange; }
|
||||
void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; }
|
||||
CardItem *getAttachedTo() const { return attachedTo; }
|
||||
void setAttachedTo(CardItem *_attachedTo);
|
||||
void addAttachedCard(CardItem *card) { attachedCards.append(card); }
|
||||
void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); }
|
||||
const QList<CardItem *> &getAttachedCards() const { return attachedCards; }
|
||||
void resetState();
|
||||
void processCardInfo(const ServerInfo_Card &info);
|
||||
enum { Type = typeCard };
|
||||
int type() const { return Type; }
|
||||
CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0);
|
||||
~CardItem();
|
||||
void retranslateUi();
|
||||
CardZone *getZone() const { return zone; }
|
||||
void setZone(CardZone *_zone);
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
QPoint getGridPoint() const { return gridPoint; }
|
||||
void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; }
|
||||
QPoint getGridPos() const { return gridPoint; }
|
||||
Player *getOwner() const { return owner; }
|
||||
void setOwner(Player *_owner) { owner = _owner; }
|
||||
bool getRevealedCard() const { return revealedCard; }
|
||||
bool getAttacking() const { return attacking; }
|
||||
void setAttacking(bool _attacking);
|
||||
const QMap<int, int> &getCounters() const { return counters; }
|
||||
void setCounter(int _id, int _value);
|
||||
QString getAnnotation() const { return annotation; }
|
||||
void setAnnotation(const QString &_annotation);
|
||||
bool getDoesntUntap() const { return doesntUntap; }
|
||||
void setDoesntUntap(bool _doesntUntap);
|
||||
QString getPT() const { return pt; }
|
||||
void setPT(const QString &_pt);
|
||||
bool getDestroyOnZoneChange() const { return destroyOnZoneChange; }
|
||||
void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; }
|
||||
CardItem *getAttachedTo() const { return attachedTo; }
|
||||
void setAttachedTo(CardItem *_attachedTo);
|
||||
void addAttachedCard(CardItem *card) { attachedCards.append(card); }
|
||||
void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); }
|
||||
const QList<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);
|
||||
bool animationEvent();
|
||||
CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown);
|
||||
void deleteDragItem();
|
||||
void drawArrow(const QColor &arrowColor);
|
||||
void playCard(bool faceDown);
|
||||
protected:
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
|
||||
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
|
||||
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -3,57 +3,57 @@
|
|||
#include "carddatabase.h"
|
||||
|
||||
CardList::CardList(bool _contentsKnown)
|
||||
: QList<CardItem *>(), contentsKnown(_contentsKnown)
|
||||
: QList<CardItem *>(), contentsKnown(_contentsKnown)
|
||||
{
|
||||
}
|
||||
|
||||
CardItem *CardList::findCard(const int id, const bool remove, int *position)
|
||||
{
|
||||
if (!contentsKnown) {
|
||||
if (empty())
|
||||
return 0;
|
||||
CardItem *temp = at(0);
|
||||
if (remove)
|
||||
removeAt(0);
|
||||
if (position)
|
||||
*position = id;
|
||||
return temp;
|
||||
} else
|
||||
for (int i = 0; i < size(); i++) {
|
||||
CardItem *temp = at(i);
|
||||
if (temp->getId() == id) {
|
||||
if (remove)
|
||||
removeAt(i);
|
||||
if (position)
|
||||
*position = i;
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
if (!contentsKnown) {
|
||||
if (empty())
|
||||
return 0;
|
||||
CardItem *temp = at(0);
|
||||
if (remove)
|
||||
removeAt(0);
|
||||
if (position)
|
||||
*position = id;
|
||||
return temp;
|
||||
} else
|
||||
for (int i = 0; i < size(); i++) {
|
||||
CardItem *temp = at(i);
|
||||
if (temp->getId() == id) {
|
||||
if (remove)
|
||||
removeAt(i);
|
||||
if (position)
|
||||
*position = i;
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
class CardList::compareFunctor {
|
||||
private:
|
||||
int flags;
|
||||
int flags;
|
||||
public:
|
||||
compareFunctor(int _flags) : flags(_flags)
|
||||
{
|
||||
}
|
||||
inline bool operator()(CardItem *a, CardItem *b) const
|
||||
{
|
||||
if (flags & SortByType) {
|
||||
QString t1 = a->getInfo()->getMainCardType();
|
||||
QString t2 = b->getInfo()->getMainCardType();
|
||||
if ((t1 == t2) && (flags & SortByName))
|
||||
return a->getName() < b->getName();
|
||||
return t1 < t2;
|
||||
} else
|
||||
return a->getName() < b->getName();
|
||||
}
|
||||
compareFunctor(int _flags) : flags(_flags)
|
||||
{
|
||||
}
|
||||
inline bool operator()(CardItem *a, CardItem *b) const
|
||||
{
|
||||
if (flags & SortByType) {
|
||||
QString t1 = a->getInfo()->getMainCardType();
|
||||
QString t2 = b->getInfo()->getMainCardType();
|
||||
if ((t1 == t2) && (flags & SortByName))
|
||||
return a->getName() < b->getName();
|
||||
return t1 < t2;
|
||||
} else
|
||||
return a->getName() < b->getName();
|
||||
}
|
||||
};
|
||||
|
||||
void CardList::sort(int flags)
|
||||
{
|
||||
compareFunctor cf(flags);
|
||||
qSort(begin(), end(), cf);
|
||||
compareFunctor cf(flags);
|
||||
qSort(begin(), end(), cf);
|
||||
}
|
||||
|
|
|
@ -7,15 +7,15 @@ class CardItem;
|
|||
|
||||
class CardList : public QList<CardItem *> {
|
||||
private:
|
||||
class compareFunctor;
|
||||
class compareFunctor;
|
||||
protected:
|
||||
bool contentsKnown;
|
||||
bool contentsKnown;
|
||||
public:
|
||||
enum SortFlags { SortByName = 1, SortByType = 2 };
|
||||
CardList(bool _contentsKnown);
|
||||
CardItem *findCard(const int id, const bool remove, int *position = NULL);
|
||||
bool getContentsKnown() const { return contentsKnown; }
|
||||
void sort(int flags = SortByName);
|
||||
enum SortFlags { SortByName = 1, SortByType = 2 };
|
||||
CardList(bool _contentsKnown);
|
||||
CardItem *findCard(const int id, const bool remove, int *position = NULL);
|
||||
bool getContentsKnown() const { return contentsKnown; }
|
||||
void sort(int flags = SortByName);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -14,56 +14,56 @@ class QPainter;
|
|||
class CardDragItem;
|
||||
|
||||
class CardZone : public AbstractGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
Player *player;
|
||||
QString name;
|
||||
CardList cards;
|
||||
ZoneViewZone *view;
|
||||
QMenu *menu;
|
||||
QAction *doubleClickAction;
|
||||
bool hasCardAttr;
|
||||
bool isShufflable;
|
||||
bool isView;
|
||||
bool alwaysRevealTopCard;
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
virtual void addCardImpl(CardItem *card, int x, int y) = 0;
|
||||
Player *player;
|
||||
QString name;
|
||||
CardList cards;
|
||||
ZoneViewZone *view;
|
||||
QMenu *menu;
|
||||
QAction *doubleClickAction;
|
||||
bool hasCardAttr;
|
||||
bool isShufflable;
|
||||
bool isView;
|
||||
bool alwaysRevealTopCard;
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
virtual void addCardImpl(CardItem *card, int x, int y) = 0;
|
||||
signals:
|
||||
void cardCountChanged();
|
||||
void cardCountChanged();
|
||||
public slots:
|
||||
void moveAllToZone();
|
||||
bool showContextMenu(const QPoint &screenPos);
|
||||
void moveAllToZone();
|
||||
bool showContextMenu(const QPoint &screenPos);
|
||||
public:
|
||||
enum { Type = typeZone };
|
||||
int type() const { return Type; }
|
||||
virtual void handleDropEvent(const QList<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; }
|
||||
QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const;
|
||||
Player *getPlayer() const { return player; }
|
||||
bool contentsKnown() const { return cards.getContentsKnown(); }
|
||||
const CardList &getCards() const { return cards; }
|
||||
void addCard(CardItem *card, bool reorganize, int x, int y = -1);
|
||||
// getCard() finds a card by id.
|
||||
CardItem *getCard(int cardId, const QString &cardName);
|
||||
// takeCard() finds a card by position and removes it from the zone and from all of its views.
|
||||
virtual CardItem *takeCard(int position, int cardId, bool canResize = true);
|
||||
void removeCard(CardItem *card);
|
||||
ZoneViewZone *getView() const { return view; }
|
||||
void setView(ZoneViewZone *_view) { view = _view; }
|
||||
virtual void reorganizeCards() = 0;
|
||||
virtual QPointF closestGridPoint(const QPointF &point);
|
||||
bool getIsView() const { return isView; }
|
||||
bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; }
|
||||
void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; }
|
||||
enum { Type = typeZone };
|
||||
int type() const { return Type; }
|
||||
virtual void handleDropEvent(const QList<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; }
|
||||
QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const;
|
||||
Player *getPlayer() const { return player; }
|
||||
bool contentsKnown() const { return cards.getContentsKnown(); }
|
||||
const CardList &getCards() const { return cards; }
|
||||
void addCard(CardItem *card, bool reorganize, int x, int y = -1);
|
||||
// getCard() finds a card by id.
|
||||
CardItem *getCard(int cardId, const QString &cardName);
|
||||
// takeCard() finds a card by position and removes it from the zone and from all of its views.
|
||||
virtual CardItem *takeCard(int position, int cardId, bool canResize = true);
|
||||
void removeCard(CardItem *card);
|
||||
ZoneViewZone *getView() const { return view; }
|
||||
void setView(ZoneViewZone *_view) { view = _view; }
|
||||
virtual void reorganizeCards() = 0;
|
||||
virtual QPointF closestGridPoint(const QPointF &point);
|
||||
bool getIsView() const { return isView; }
|
||||
bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; }
|
||||
void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -10,256 +10,256 @@
|
|||
#include "pixmapgenerator.h"
|
||||
|
||||
ChatView::ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent)
|
||||
: QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing)
|
||||
: QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing)
|
||||
{
|
||||
document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }");
|
||||
userContextMenu = new UserContextMenu(tabSupervisor, this, game);
|
||||
connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
|
||||
document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }");
|
||||
userContextMenu = new UserContextMenu(tabSupervisor, this, game);
|
||||
connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
|
||||
|
||||
viewport()->setCursor(Qt::IBeamCursor);
|
||||
setReadOnly(true);
|
||||
setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse);
|
||||
setOpenLinks(false);
|
||||
connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &)));
|
||||
viewport()->setCursor(Qt::IBeamCursor);
|
||||
setReadOnly(true);
|
||||
setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse);
|
||||
setOpenLinks(false);
|
||||
connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &)));
|
||||
}
|
||||
|
||||
void ChatView::retranslateUi()
|
||||
{
|
||||
userContextMenu->retranslateUi();
|
||||
userContextMenu->retranslateUi();
|
||||
}
|
||||
|
||||
QTextCursor ChatView::prepareBlock(bool same)
|
||||
{
|
||||
lastSender.clear();
|
||||
lastSender.clear();
|
||||
|
||||
QTextCursor cursor(document()->lastBlock());
|
||||
cursor.movePosition(QTextCursor::End);
|
||||
if (!same) {
|
||||
QTextBlockFormat blockFormat;
|
||||
if ((evenNumber = !evenNumber))
|
||||
blockFormat.setBackground(palette().alternateBase());
|
||||
blockFormat.setBottomMargin(2);
|
||||
cursor.insertBlock(blockFormat);
|
||||
} else
|
||||
cursor.insertHtml("<br>");
|
||||
QTextCursor cursor(document()->lastBlock());
|
||||
cursor.movePosition(QTextCursor::End);
|
||||
if (!same) {
|
||||
QTextBlockFormat blockFormat;
|
||||
if ((evenNumber = !evenNumber))
|
||||
blockFormat.setBackground(palette().alternateBase());
|
||||
blockFormat.setBottomMargin(2);
|
||||
cursor.insertBlock(blockFormat);
|
||||
} else
|
||||
cursor.insertHtml("<br>");
|
||||
|
||||
return cursor;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
void ChatView::appendHtml(const QString &html)
|
||||
{
|
||||
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
|
||||
prepareBlock().insertHtml(html);
|
||||
if (atBottom)
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
|
||||
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
|
||||
prepareBlock().insertHtml(html);
|
||||
if (atBottom)
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
|
||||
}
|
||||
|
||||
void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName)
|
||||
{
|
||||
QTextCharFormat oldFormat = cursor.charFormat();
|
||||
QTextCharFormat anchorFormat = oldFormat;
|
||||
anchorFormat.setForeground(Qt::blue);
|
||||
anchorFormat.setAnchor(true);
|
||||
anchorFormat.setAnchorHref("card://" + cardName);
|
||||
QTextCharFormat oldFormat = cursor.charFormat();
|
||||
QTextCharFormat anchorFormat = oldFormat;
|
||||
anchorFormat.setForeground(Qt::blue);
|
||||
anchorFormat.setAnchor(true);
|
||||
anchorFormat.setAnchorHref("card://" + cardName);
|
||||
|
||||
cursor.setCharFormat(anchorFormat);
|
||||
cursor.insertText(cardName);
|
||||
cursor.setCharFormat(oldFormat);
|
||||
cursor.setCharFormat(anchorFormat);
|
||||
cursor.insertText(cardName);
|
||||
cursor.setCharFormat(oldFormat);
|
||||
}
|
||||
|
||||
void ChatView::appendUrlTag(QTextCursor &cursor, QString url)
|
||||
{
|
||||
if (!url.contains("://"))
|
||||
url.prepend("http://");
|
||||
if (!url.contains("://"))
|
||||
url.prepend("http://");
|
||||
|
||||
QTextCharFormat oldFormat = cursor.charFormat();
|
||||
QTextCharFormat anchorFormat = oldFormat;
|
||||
anchorFormat.setForeground(Qt::blue);
|
||||
anchorFormat.setAnchor(true);
|
||||
anchorFormat.setAnchorHref(url);
|
||||
QTextCharFormat oldFormat = cursor.charFormat();
|
||||
QTextCharFormat anchorFormat = oldFormat;
|
||||
anchorFormat.setForeground(Qt::blue);
|
||||
anchorFormat.setAnchor(true);
|
||||
anchorFormat.setAnchorHref(url);
|
||||
|
||||
cursor.setCharFormat(anchorFormat);
|
||||
cursor.insertText(url);
|
||||
cursor.setCharFormat(oldFormat);
|
||||
cursor.setCharFormat(anchorFormat);
|
||||
cursor.insertText(url);
|
||||
cursor.setCharFormat(oldFormat);
|
||||
}
|
||||
|
||||
void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold)
|
||||
{
|
||||
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
|
||||
bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
|
||||
QTextCursor cursor = prepareBlock(sameSender);
|
||||
lastSender = sender;
|
||||
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
|
||||
bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
|
||||
QTextCursor cursor = prepareBlock(sameSender);
|
||||
lastSender = sender;
|
||||
|
||||
if (showTimestamps && !sameSender) {
|
||||
QTextCharFormat timeFormat;
|
||||
timeFormat.setForeground(Qt::black);
|
||||
cursor.setCharFormat(timeFormat);
|
||||
cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] "));
|
||||
}
|
||||
if (showTimestamps && !sameSender) {
|
||||
QTextCharFormat timeFormat;
|
||||
timeFormat.setForeground(Qt::black);
|
||||
cursor.setCharFormat(timeFormat);
|
||||
cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] "));
|
||||
}
|
||||
|
||||
QTextCharFormat senderFormat;
|
||||
if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
|
||||
senderFormat.setFontWeight(QFont::Bold);
|
||||
senderFormat.setForeground(Qt::red);
|
||||
} else {
|
||||
senderFormat.setForeground(Qt::blue);
|
||||
if (playerBold)
|
||||
senderFormat.setFontWeight(QFont::Bold);
|
||||
}
|
||||
senderFormat.setAnchor(true);
|
||||
senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
|
||||
if (!sameSender) {
|
||||
if (!sender.isEmpty()) {
|
||||
const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
|
||||
cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel));
|
||||
cursor.insertText(" ");
|
||||
}
|
||||
cursor.setCharFormat(senderFormat);
|
||||
if (!sender.isEmpty())
|
||||
sender.append(": ");
|
||||
cursor.insertText(sender);
|
||||
} else
|
||||
cursor.insertText(" ");
|
||||
QTextCharFormat senderFormat;
|
||||
if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
|
||||
senderFormat.setFontWeight(QFont::Bold);
|
||||
senderFormat.setForeground(Qt::red);
|
||||
} else {
|
||||
senderFormat.setForeground(Qt::blue);
|
||||
if (playerBold)
|
||||
senderFormat.setFontWeight(QFont::Bold);
|
||||
}
|
||||
senderFormat.setAnchor(true);
|
||||
senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
|
||||
if (!sameSender) {
|
||||
if (!sender.isEmpty()) {
|
||||
const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
|
||||
cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel));
|
||||
cursor.insertText(" ");
|
||||
}
|
||||
cursor.setCharFormat(senderFormat);
|
||||
if (!sender.isEmpty())
|
||||
sender.append(": ");
|
||||
cursor.insertText(sender);
|
||||
} else
|
||||
cursor.insertText(" ");
|
||||
|
||||
QTextCharFormat messageFormat;
|
||||
if (sender.isEmpty())
|
||||
messageFormat.setForeground(Qt::darkGreen);
|
||||
cursor.setCharFormat(messageFormat);
|
||||
QTextCharFormat messageFormat;
|
||||
if (sender.isEmpty())
|
||||
messageFormat.setForeground(Qt::darkGreen);
|
||||
cursor.setCharFormat(messageFormat);
|
||||
|
||||
int from = 0, index = 0;
|
||||
while ((index = message.indexOf('[', from)) != -1) {
|
||||
cursor.insertText(message.left(index));
|
||||
message = message.mid(index);
|
||||
if (message.isEmpty())
|
||||
break;
|
||||
int from = 0, index = 0;
|
||||
while ((index = message.indexOf('[', from)) != -1) {
|
||||
cursor.insertText(message.left(index));
|
||||
message = message.mid(index);
|
||||
if (message.isEmpty())
|
||||
break;
|
||||
|
||||
if (message.startsWith("[card]")) {
|
||||
message = message.mid(6);
|
||||
int closeTagIndex = message.indexOf("[/card]");
|
||||
QString cardName = message.left(closeTagIndex);
|
||||
if (closeTagIndex == -1)
|
||||
message.clear();
|
||||
else
|
||||
message = message.mid(closeTagIndex + 7);
|
||||
if (message.startsWith("[card]")) {
|
||||
message = message.mid(6);
|
||||
int closeTagIndex = message.indexOf("[/card]");
|
||||
QString cardName = message.left(closeTagIndex);
|
||||
if (closeTagIndex == -1)
|
||||
message.clear();
|
||||
else
|
||||
message = message.mid(closeTagIndex + 7);
|
||||
|
||||
appendCardTag(cursor, cardName);
|
||||
} else if (message.startsWith("[[")) {
|
||||
message = message.mid(2);
|
||||
int closeTagIndex = message.indexOf("]]");
|
||||
QString cardName = message.left(closeTagIndex);
|
||||
if (closeTagIndex == -1)
|
||||
message.clear();
|
||||
else
|
||||
message = message.mid(closeTagIndex + 2);
|
||||
appendCardTag(cursor, cardName);
|
||||
} else if (message.startsWith("[[")) {
|
||||
message = message.mid(2);
|
||||
int closeTagIndex = message.indexOf("]]");
|
||||
QString cardName = message.left(closeTagIndex);
|
||||
if (closeTagIndex == -1)
|
||||
message.clear();
|
||||
else
|
||||
message = message.mid(closeTagIndex + 2);
|
||||
|
||||
appendCardTag(cursor, cardName);
|
||||
} else if (message.startsWith("[url]")) {
|
||||
message = message.mid(5);
|
||||
int closeTagIndex = message.indexOf("[/url]");
|
||||
QString url = message.left(closeTagIndex);
|
||||
if (closeTagIndex == -1)
|
||||
message.clear();
|
||||
else
|
||||
message = message.mid(closeTagIndex + 6);
|
||||
appendCardTag(cursor, cardName);
|
||||
} else if (message.startsWith("[url]")) {
|
||||
message = message.mid(5);
|
||||
int closeTagIndex = message.indexOf("[/url]");
|
||||
QString url = message.left(closeTagIndex);
|
||||
if (closeTagIndex == -1)
|
||||
message.clear();
|
||||
else
|
||||
message = message.mid(closeTagIndex + 6);
|
||||
|
||||
appendUrlTag(cursor, url);
|
||||
} else
|
||||
from = 1;
|
||||
}
|
||||
if (!message.isEmpty())
|
||||
cursor.insertText(message);
|
||||
appendUrlTag(cursor, url);
|
||||
} else
|
||||
from = 1;
|
||||
}
|
||||
if (!message.isEmpty())
|
||||
cursor.insertText(message);
|
||||
|
||||
if (atBottom)
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
|
||||
if (atBottom)
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
|
||||
}
|
||||
|
||||
void ChatView::enterEvent(QEvent * /*event*/)
|
||||
{
|
||||
setMouseTracking(true);
|
||||
setMouseTracking(true);
|
||||
}
|
||||
|
||||
void ChatView::leaveEvent(QEvent * /*event*/)
|
||||
{
|
||||
setMouseTracking(false);
|
||||
setMouseTracking(false);
|
||||
}
|
||||
|
||||
QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const
|
||||
{
|
||||
QTextCursor cursor(cursorForPosition(pos));
|
||||
QTextBlock block(cursor.block());
|
||||
QTextBlock::iterator it;
|
||||
for (it = block.begin(); !(it.atEnd()); ++it) {
|
||||
QTextFragment frag = it.fragment();
|
||||
if (frag.contains(cursor.position()))
|
||||
return frag;
|
||||
}
|
||||
return QTextFragment();
|
||||
QTextCursor cursor(cursorForPosition(pos));
|
||||
QTextBlock block(cursor.block());
|
||||
QTextBlock::iterator it;
|
||||
for (it = block.begin(); !(it.atEnd()); ++it) {
|
||||
QTextFragment frag = it.fragment();
|
||||
if (frag.contains(cursor.position()))
|
||||
return frag;
|
||||
}
|
||||
return QTextFragment();
|
||||
}
|
||||
|
||||
void ChatView::mouseMoveEvent(QMouseEvent *event)
|
||||
{
|
||||
QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref();
|
||||
if (!anchorHref.isEmpty()) {
|
||||
const int delimiterIndex = anchorHref.indexOf("://");
|
||||
if (delimiterIndex != -1) {
|
||||
const QString scheme = anchorHref.left(delimiterIndex);
|
||||
hoveredContent = anchorHref.mid(delimiterIndex + 3);
|
||||
if (scheme == "card") {
|
||||
hoveredItemType = HoveredCard;
|
||||
emit cardNameHovered(hoveredContent);
|
||||
} else if (scheme == "user")
|
||||
hoveredItemType = HoveredUser;
|
||||
else
|
||||
hoveredItemType = HoveredUrl;
|
||||
viewport()->setCursor(Qt::PointingHandCursor);
|
||||
} else {
|
||||
hoveredItemType = HoveredNothing;
|
||||
viewport()->setCursor(Qt::IBeamCursor);
|
||||
}
|
||||
} else {
|
||||
hoveredItemType = HoveredNothing;
|
||||
viewport()->setCursor(Qt::IBeamCursor);
|
||||
}
|
||||
QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref();
|
||||
if (!anchorHref.isEmpty()) {
|
||||
const int delimiterIndex = anchorHref.indexOf("://");
|
||||
if (delimiterIndex != -1) {
|
||||
const QString scheme = anchorHref.left(delimiterIndex);
|
||||
hoveredContent = anchorHref.mid(delimiterIndex + 3);
|
||||
if (scheme == "card") {
|
||||
hoveredItemType = HoveredCard;
|
||||
emit cardNameHovered(hoveredContent);
|
||||
} else if (scheme == "user")
|
||||
hoveredItemType = HoveredUser;
|
||||
else
|
||||
hoveredItemType = HoveredUrl;
|
||||
viewport()->setCursor(Qt::PointingHandCursor);
|
||||
} else {
|
||||
hoveredItemType = HoveredNothing;
|
||||
viewport()->setCursor(Qt::IBeamCursor);
|
||||
}
|
||||
} else {
|
||||
hoveredItemType = HoveredNothing;
|
||||
viewport()->setCursor(Qt::IBeamCursor);
|
||||
}
|
||||
|
||||
QTextBrowser::mouseMoveEvent(event);
|
||||
QTextBrowser::mouseMoveEvent(event);
|
||||
}
|
||||
|
||||
void ChatView::mousePressEvent(QMouseEvent *event)
|
||||
{
|
||||
switch (hoveredItemType) {
|
||||
case HoveredCard: {
|
||||
if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton))
|
||||
emit showCardInfoPopup(event->globalPos(), hoveredContent);
|
||||
break;
|
||||
}
|
||||
case HoveredUser: {
|
||||
if (event->button() == Qt::RightButton) {
|
||||
const int delimiterIndex = hoveredContent.indexOf("_");
|
||||
UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt());
|
||||
const QString userName = hoveredContent.mid(delimiterIndex + 1);
|
||||
switch (hoveredItemType) {
|
||||
case HoveredCard: {
|
||||
if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton))
|
||||
emit showCardInfoPopup(event->globalPos(), hoveredContent);
|
||||
break;
|
||||
}
|
||||
case HoveredUser: {
|
||||
if (event->button() == Qt::RightButton) {
|
||||
const int delimiterIndex = hoveredContent.indexOf("_");
|
||||
UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt());
|
||||
const QString userName = hoveredContent.mid(delimiterIndex + 1);
|
||||
|
||||
userContextMenu->showContextMenu(event->globalPos(), userName, userLevel);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
QTextBrowser::mousePressEvent(event);
|
||||
}
|
||||
}
|
||||
userContextMenu->showContextMenu(event->globalPos(), userName, userLevel);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
QTextBrowser::mousePressEvent(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChatView::mouseReleaseEvent(QMouseEvent *event)
|
||||
{
|
||||
if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton))
|
||||
emit deleteCardInfoPopup(QString("_"));
|
||||
if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton))
|
||||
emit deleteCardInfoPopup(QString("_"));
|
||||
|
||||
QTextBrowser::mouseReleaseEvent(event);
|
||||
QTextBrowser::mouseReleaseEvent(event);
|
||||
}
|
||||
|
||||
void ChatView::openLink(const QUrl &link)
|
||||
{
|
||||
if ((link.scheme() == "card") || (link.scheme() == "user"))
|
||||
return;
|
||||
if ((link.scheme() == "card") || (link.scheme() == "user"))
|
||||
return;
|
||||
|
||||
QDesktopServices::openUrl(link);
|
||||
QDesktopServices::openUrl(link);
|
||||
}
|
||||
|
|
|
@ -14,40 +14,40 @@ class TabSupervisor;
|
|||
class TabGame;
|
||||
|
||||
class ChatView : public QTextBrowser {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
protected:
|
||||
const TabSupervisor * const tabSupervisor;
|
||||
TabGame * const game;
|
||||
const TabSupervisor * const tabSupervisor;
|
||||
TabGame * const game;
|
||||
private:
|
||||
enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser };
|
||||
UserContextMenu *userContextMenu;
|
||||
QString lastSender;
|
||||
bool evenNumber;
|
||||
bool showTimestamps;
|
||||
HoveredItemType hoveredItemType;
|
||||
QString hoveredContent;
|
||||
QTextFragment getFragmentUnderMouse(const QPoint &pos) const;
|
||||
QTextCursor prepareBlock(bool same = false);
|
||||
void appendCardTag(QTextCursor &cursor, const QString &cardName);
|
||||
void appendUrlTag(QTextCursor &cursor, QString url);
|
||||
enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser };
|
||||
UserContextMenu *userContextMenu;
|
||||
QString lastSender;
|
||||
bool evenNumber;
|
||||
bool showTimestamps;
|
||||
HoveredItemType hoveredItemType;
|
||||
QString hoveredContent;
|
||||
QTextFragment getFragmentUnderMouse(const QPoint &pos) const;
|
||||
QTextCursor prepareBlock(bool same = false);
|
||||
void appendCardTag(QTextCursor &cursor, const QString &cardName);
|
||||
void appendUrlTag(QTextCursor &cursor, QString url);
|
||||
private slots:
|
||||
void openLink(const QUrl &link);
|
||||
void openLink(const QUrl &link);
|
||||
public:
|
||||
ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0);
|
||||
void retranslateUi();
|
||||
void appendHtml(const QString &html);
|
||||
void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false);
|
||||
ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0);
|
||||
void retranslateUi();
|
||||
void appendHtml(const QString &html);
|
||||
void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false);
|
||||
protected:
|
||||
void enterEvent(QEvent *event);
|
||||
void leaveEvent(QEvent *event);
|
||||
void mouseMoveEvent(QMouseEvent *event);
|
||||
void mousePressEvent(QMouseEvent *event);
|
||||
void mouseReleaseEvent(QMouseEvent *event);
|
||||
void enterEvent(QEvent *event);
|
||||
void leaveEvent(QEvent *event);
|
||||
void mouseMoveEvent(QMouseEvent *event);
|
||||
void mousePressEvent(QMouseEvent *event);
|
||||
void mouseReleaseEvent(QMouseEvent *event);
|
||||
signals:
|
||||
void openMessageDialog(const QString &userName, bool focus);
|
||||
void cardNameHovered(QString cardName);
|
||||
void showCardInfoPopup(QPoint pos, QString cardName);
|
||||
void deleteCardInfoPopup(QString cardName);
|
||||
void openMessageDialog(const QString &userName, bool focus);
|
||||
void cardNameHovered(QString cardName);
|
||||
void showCardInfoPopup(QPoint pos, QString cardName);
|
||||
void deleteCardInfoPopup(QString cardName);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -3,34 +3,34 @@
|
|||
#include <QPainter>
|
||||
|
||||
GeneralCounter::GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent)
|
||||
: AbstractCounter(_player, _id, _name, true, _value, parent), color(_color), radius(_radius)
|
||||
: AbstractCounter(_player, _id, _name, true, _value, parent), color(_color), radius(_radius)
|
||||
{
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
}
|
||||
|
||||
QRectF GeneralCounter::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, radius * 2, radius * 2);
|
||||
return QRectF(0, 0, radius * 2, radius * 2);
|
||||
}
|
||||
|
||||
void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/)
|
||||
{
|
||||
QRectF mapRect = painter->combinedTransform().mapRect(boundingRect());
|
||||
int translatedHeight = mapRect.size().height();
|
||||
qreal scaleFactor = translatedHeight / boundingRect().height();
|
||||
QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered);
|
||||
QRectF mapRect = painter->combinedTransform().mapRect(boundingRect());
|
||||
int translatedHeight = mapRect.size().height();
|
||||
qreal scaleFactor = translatedHeight / boundingRect().height();
|
||||
QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered);
|
||||
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->drawPixmap(QPoint(0, 0), pixmap);
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->drawPixmap(QPoint(0, 0), pixmap);
|
||||
|
||||
if (value) {
|
||||
QFont f("Serif");
|
||||
f.setPixelSize(qMax((int) (radius * scaleFactor), 10));
|
||||
f.setWeight(QFont::Bold);
|
||||
painter->setPen(Qt::black);
|
||||
painter->setFont(f);
|
||||
painter->drawText(mapRect, Qt::AlignCenter, QString::number(value));
|
||||
}
|
||||
painter->restore();
|
||||
if (value) {
|
||||
QFont f("Serif");
|
||||
f.setPixelSize(qMax((int) (radius * scaleFactor), 10));
|
||||
f.setWeight(QFont::Bold);
|
||||
painter->setPen(Qt::black);
|
||||
painter->setFont(f);
|
||||
painter->drawText(mapRect, Qt::AlignCenter, QString::number(value));
|
||||
}
|
||||
painter->restore();
|
||||
}
|
||||
|
|
|
@ -4,14 +4,14 @@
|
|||
#include "abstractcounter.h"
|
||||
|
||||
class GeneralCounter : public AbstractCounter {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QColor color;
|
||||
int radius;
|
||||
QColor color;
|
||||
int radius;
|
||||
public:
|
||||
GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -4,96 +4,96 @@
|
|||
#include "decklist.h"
|
||||
|
||||
const QStringList DeckLoader::fileNameFilters = QStringList()
|
||||
<< QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)")
|
||||
<< QObject::tr("All files (*.*)");
|
||||
<< QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)")
|
||||
<< QObject::tr("All files (*.*)");
|
||||
|
||||
DeckLoader::DeckLoader()
|
||||
: DeckList(),
|
||||
lastFileName(QString()),
|
||||
lastFileFormat(CockatriceFormat),
|
||||
lastRemoteDeckId(-1)
|
||||
: DeckList(),
|
||||
lastFileName(QString()),
|
||||
lastFileFormat(CockatriceFormat),
|
||||
lastRemoteDeckId(-1)
|
||||
{
|
||||
}
|
||||
|
||||
DeckLoader::DeckLoader(const QString &nativeString)
|
||||
: DeckList(nativeString),
|
||||
lastFileName(QString()),
|
||||
lastFileFormat(CockatriceFormat),
|
||||
lastRemoteDeckId(-1)
|
||||
: DeckList(nativeString),
|
||||
lastFileName(QString()),
|
||||
lastFileFormat(CockatriceFormat),
|
||||
lastRemoteDeckId(-1)
|
||||
{
|
||||
}
|
||||
|
||||
DeckLoader::DeckLoader(const DeckList &other)
|
||||
: DeckList(other),
|
||||
lastFileName(QString()),
|
||||
lastFileFormat(CockatriceFormat),
|
||||
lastRemoteDeckId(-1)
|
||||
: DeckList(other),
|
||||
lastFileName(QString()),
|
||||
lastFileFormat(CockatriceFormat),
|
||||
lastRemoteDeckId(-1)
|
||||
{
|
||||
}
|
||||
|
||||
DeckLoader::DeckLoader(const DeckLoader &other)
|
||||
: DeckList(other),
|
||||
lastFileName(other.lastFileName),
|
||||
lastFileFormat(other.lastFileFormat),
|
||||
lastRemoteDeckId(other.lastRemoteDeckId)
|
||||
: DeckList(other),
|
||||
lastFileName(other.lastFileName),
|
||||
lastFileFormat(other.lastFileFormat),
|
||||
lastRemoteDeckId(other.lastRemoteDeckId)
|
||||
{
|
||||
}
|
||||
|
||||
bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
|
||||
{
|
||||
QFile file(fileName);
|
||||
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
|
||||
return false;
|
||||
QFile file(fileName);
|
||||
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
|
||||
return false;
|
||||
|
||||
bool result = false;
|
||||
switch (fmt) {
|
||||
case PlainTextFormat: result = loadFromFile_Plain(&file); break;
|
||||
case CockatriceFormat: result = loadFromFile_Native(&file); break;
|
||||
}
|
||||
if (result) {
|
||||
lastFileName = fileName;
|
||||
lastFileFormat = fmt;
|
||||
bool result = false;
|
||||
switch (fmt) {
|
||||
case PlainTextFormat: result = loadFromFile_Plain(&file); break;
|
||||
case CockatriceFormat: result = loadFromFile_Native(&file); break;
|
||||
}
|
||||
if (result) {
|
||||
lastFileName = fileName;
|
||||
lastFileFormat = fmt;
|
||||
|
||||
emit deckLoaded();
|
||||
}
|
||||
return result;
|
||||
emit deckLoaded();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
|
||||
{
|
||||
bool result = loadFromString_Native(nativeString);
|
||||
if (result) {
|
||||
lastFileName = QString();
|
||||
lastFileFormat = CockatriceFormat;
|
||||
lastRemoteDeckId = remoteDeckId;
|
||||
bool result = loadFromString_Native(nativeString);
|
||||
if (result) {
|
||||
lastFileName = QString();
|
||||
lastFileFormat = CockatriceFormat;
|
||||
lastRemoteDeckId = remoteDeckId;
|
||||
|
||||
emit deckLoaded();
|
||||
}
|
||||
return result;
|
||||
emit deckLoaded();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt)
|
||||
{
|
||||
QFile file(fileName);
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
|
||||
return false;
|
||||
QFile file(fileName);
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
|
||||
return false;
|
||||
|
||||
bool result = false;
|
||||
switch (fmt) {
|
||||
case PlainTextFormat: result = saveToFile_Plain(&file); break;
|
||||
case CockatriceFormat: result = saveToFile_Native(&file); break;
|
||||
}
|
||||
if (result) {
|
||||
lastFileName = fileName;
|
||||
lastFileFormat = fmt;
|
||||
}
|
||||
return result;
|
||||
bool result = false;
|
||||
switch (fmt) {
|
||||
case PlainTextFormat: result = saveToFile_Plain(&file); break;
|
||||
case CockatriceFormat: result = saveToFile_Native(&file); break;
|
||||
}
|
||||
if (result) {
|
||||
lastFileName = fileName;
|
||||
lastFileFormat = fmt;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName)
|
||||
{
|
||||
if (fileName.endsWith(".cod", Qt::CaseInsensitive)) {
|
||||
return CockatriceFormat;
|
||||
}
|
||||
return PlainTextFormat;
|
||||
if (fileName.endsWith(".cod", Qt::CaseInsensitive)) {
|
||||
return CockatriceFormat;
|
||||
}
|
||||
return PlainTextFormat;
|
||||
}
|
||||
|
|
|
@ -4,30 +4,30 @@
|
|||
#include "decklist.h"
|
||||
|
||||
class DeckLoader : public DeckList {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void deckLoaded();
|
||||
void deckLoaded();
|
||||
public:
|
||||
enum FileFormat { PlainTextFormat, CockatriceFormat };
|
||||
static const QStringList fileNameFilters;
|
||||
enum FileFormat { PlainTextFormat, CockatriceFormat };
|
||||
static const QStringList fileNameFilters;
|
||||
private:
|
||||
QString lastFileName;
|
||||
FileFormat lastFileFormat;
|
||||
int lastRemoteDeckId;
|
||||
QString lastFileName;
|
||||
FileFormat lastFileFormat;
|
||||
int lastRemoteDeckId;
|
||||
public:
|
||||
DeckLoader();
|
||||
DeckLoader(const QString &nativeString);
|
||||
DeckLoader(const DeckList &other);
|
||||
DeckLoader(const DeckLoader &other);
|
||||
const QString &getLastFileName() const { return lastFileName; }
|
||||
FileFormat getLastFileFormat() const { return lastFileFormat; }
|
||||
int getLastRemoteDeckId() const { return lastRemoteDeckId; }
|
||||
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);
|
||||
bool loadFromFile(const QString &fileName, FileFormat fmt);
|
||||
bool loadFromRemote(const QString &nativeString, int remoteDeckId);
|
||||
bool saveToFile(const QString &fileName, FileFormat fmt);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -14,423 +14,423 @@
|
|||
#include "deck_loader.h"
|
||||
|
||||
DeckListModel::DeckListModel(QObject *parent)
|
||||
: QAbstractItemModel(parent)
|
||||
: QAbstractItemModel(parent)
|
||||
{
|
||||
deckList = new DeckLoader;
|
||||
connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree()));
|
||||
connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged()));
|
||||
root = new InnerDecklistNode;
|
||||
deckList = new DeckLoader;
|
||||
connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree()));
|
||||
connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged()));
|
||||
root = new InnerDecklistNode;
|
||||
}
|
||||
|
||||
DeckListModel::~DeckListModel()
|
||||
{
|
||||
delete root;
|
||||
delete deckList;
|
||||
delete root;
|
||||
delete deckList;
|
||||
}
|
||||
|
||||
void DeckListModel::rebuildTree()
|
||||
{
|
||||
root->clearTree();
|
||||
InnerDecklistNode *listRoot = deckList->getRoot();
|
||||
for (int i = 0; i < listRoot->size(); i++) {
|
||||
InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
|
||||
InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root);
|
||||
for (int j = 0; j < currentZone->size(); j++) {
|
||||
DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
|
||||
// XXX better sanity checking
|
||||
if (!currentCard)
|
||||
continue;
|
||||
root->clearTree();
|
||||
InnerDecklistNode *listRoot = deckList->getRoot();
|
||||
for (int i = 0; i < listRoot->size(); i++) {
|
||||
InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
|
||||
InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root);
|
||||
for (int j = 0; j < currentZone->size(); j++) {
|
||||
DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
|
||||
// XXX better sanity checking
|
||||
if (!currentCard)
|
||||
continue;
|
||||
|
||||
CardInfo *info = db->getCard(currentCard->getName());
|
||||
QString cardType;
|
||||
if (!info)
|
||||
cardType = "unknown";
|
||||
else
|
||||
cardType = info->getMainCardType();
|
||||
InnerDecklistNode *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType));
|
||||
if (!cardTypeNode)
|
||||
cardTypeNode = new InnerDecklistNode(cardType, node);
|
||||
CardInfo *info = db->getCard(currentCard->getName());
|
||||
QString cardType;
|
||||
if (!info)
|
||||
cardType = "unknown";
|
||||
else
|
||||
cardType = info->getMainCardType();
|
||||
InnerDecklistNode *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType));
|
||||
if (!cardTypeNode)
|
||||
cardTypeNode = new InnerDecklistNode(cardType, node);
|
||||
|
||||
new DecklistModelCardNode(currentCard, cardTypeNode);
|
||||
}
|
||||
}
|
||||
new DecklistModelCardNode(currentCard, cardTypeNode);
|
||||
}
|
||||
}
|
||||
|
||||
reset();
|
||||
reset();
|
||||
}
|
||||
|
||||
int DeckListModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
// debugIndexInfo("rowCount", parent);
|
||||
InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent);
|
||||
if (node)
|
||||
return node->size();
|
||||
else
|
||||
return 0;
|
||||
// debugIndexInfo("rowCount", parent);
|
||||
InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent);
|
||||
if (node)
|
||||
return node->size();
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
int DeckListModel::columnCount(const QModelIndex &/*parent*/) const
|
||||
{
|
||||
if (settingsCache->getPriceTagFeature())
|
||||
return 3;
|
||||
else
|
||||
return 2;
|
||||
if (settingsCache->getPriceTagFeature())
|
||||
return 3;
|
||||
else
|
||||
return 2;
|
||||
}
|
||||
|
||||
QVariant DeckListModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
// debugIndexInfo("data", index);
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
// debugIndexInfo("data", index);
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (index.column() >= columnCount())
|
||||
return QVariant();
|
||||
return QVariant();
|
||||
|
||||
AbstractDecklistNode *temp = static_cast<AbstractDecklistNode *>(index.internalPointer());
|
||||
DecklistModelCardNode *card = dynamic_cast<DecklistModelCardNode *>(temp);
|
||||
if (!card) {
|
||||
InnerDecklistNode *node = dynamic_cast<InnerDecklistNode *>(temp);
|
||||
switch (role) {
|
||||
case Qt::FontRole: {
|
||||
QFont f;
|
||||
f.setBold(true);
|
||||
return f;
|
||||
}
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole:
|
||||
switch (index.column()) {
|
||||
AbstractDecklistNode *temp = static_cast<AbstractDecklistNode *>(index.internalPointer());
|
||||
DecklistModelCardNode *card = dynamic_cast<DecklistModelCardNode *>(temp);
|
||||
if (!card) {
|
||||
InnerDecklistNode *node = dynamic_cast<InnerDecklistNode *>(temp);
|
||||
switch (role) {
|
||||
case Qt::FontRole: {
|
||||
QFont f;
|
||||
f.setBold(true);
|
||||
return f;
|
||||
}
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole:
|
||||
switch (index.column()) {
|
||||
case 0: return node->recursiveCount(true);
|
||||
case 1: return node->getVisibleName();
|
||||
case 2: return QString().sprintf("$%.2f", node->recursivePrice(true));
|
||||
default: return QVariant();
|
||||
}
|
||||
case Qt::BackgroundRole: {
|
||||
int color = 90 + 60 * node->depth();
|
||||
return QBrush(QColor(color, 255, color));
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
} else {
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole: {
|
||||
switch (index.column()) {
|
||||
default: return QVariant();
|
||||
}
|
||||
case Qt::BackgroundRole: {
|
||||
int color = 90 + 60 * node->depth();
|
||||
return QBrush(QColor(color, 255, color));
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
} else {
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return card->getNumber();
|
||||
case 1: return card->getName();
|
||||
case 2: return QString().sprintf("$%.2f", card->getTotalPrice());
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::BackgroundRole: {
|
||||
int color = 255 - (index.row() % 2) * 30;
|
||||
return QBrush(QColor(color, color, color));
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::BackgroundRole: {
|
||||
int color = 255 - (index.row() % 2) * 30;
|
||||
return QBrush(QColor(color, color, color));
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal))
|
||||
return QVariant();
|
||||
if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal))
|
||||
return QVariant();
|
||||
if (section >= columnCount())
|
||||
return QVariant();
|
||||
switch (section) {
|
||||
return QVariant();
|
||||
switch (section) {
|
||||
case 0: return tr("Number");
|
||||
case 1: return tr("Card");
|
||||
case 2: return tr("Price");
|
||||
default: return QVariant();
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const
|
||||
{
|
||||
// debugIndexInfo("index", parent);
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
// debugIndexInfo("index", parent);
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
|
||||
InnerDecklistNode *parentNode = getNode<InnerDecklistNode *>(parent);
|
||||
if (row >= parentNode->size())
|
||||
return QModelIndex();
|
||||
InnerDecklistNode *parentNode = getNode<InnerDecklistNode *>(parent);
|
||||
if (row >= parentNode->size())
|
||||
return QModelIndex();
|
||||
|
||||
return createIndex(row, column, parentNode->at(row));
|
||||
return createIndex(row, column, parentNode->at(row));
|
||||
}
|
||||
|
||||
QModelIndex DeckListModel::parent(const QModelIndex &ind) const
|
||||
{
|
||||
if (!ind.isValid())
|
||||
return QModelIndex();
|
||||
if (!ind.isValid())
|
||||
return QModelIndex();
|
||||
|
||||
return nodeToIndex(static_cast<AbstractDecklistNode *>(ind.internalPointer())->getParent());
|
||||
return nodeToIndex(static_cast<AbstractDecklistNode *>(ind.internalPointer())->getParent());
|
||||
}
|
||||
|
||||
Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
Qt::ItemFlags result = Qt::ItemIsEnabled;
|
||||
if (getNode<DecklistModelCardNode *>(index))
|
||||
result |= Qt::ItemIsSelectable;
|
||||
Qt::ItemFlags result = Qt::ItemIsEnabled;
|
||||
if (getNode<DecklistModelCardNode *>(index))
|
||||
result |= Qt::ItemIsSelectable;
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
void DeckListModel::emitRecursiveUpdates(const QModelIndex &index)
|
||||
{
|
||||
if (!index.isValid())
|
||||
return;
|
||||
emit dataChanged(index, index);
|
||||
emitRecursiveUpdates(index.parent());
|
||||
if (!index.isValid())
|
||||
return;
|
||||
emit dataChanged(index, index);
|
||||
emitRecursiveUpdates(index.parent());
|
||||
}
|
||||
|
||||
bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role)
|
||||
{
|
||||
DecklistModelCardNode *node = getNode<DecklistModelCardNode *>(index);
|
||||
if (!node || (role != Qt::EditRole))
|
||||
return false;
|
||||
DecklistModelCardNode *node = getNode<DecklistModelCardNode *>(index);
|
||||
if (!node || (role != Qt::EditRole))
|
||||
return false;
|
||||
|
||||
switch (index.column()) {
|
||||
switch (index.column()) {
|
||||
case 0: node->setNumber(value.toInt()); break;
|
||||
case 1: node->setName(value.toString()); break;
|
||||
case 2: node->setPrice(value.toFloat()); break;
|
||||
default: return false;
|
||||
}
|
||||
emitRecursiveUpdates(index);
|
||||
deckList->updateDeckHash();
|
||||
return true;
|
||||
default: return false;
|
||||
}
|
||||
emitRecursiveUpdates(index);
|
||||
deckList->updateDeckHash();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent)
|
||||
{
|
||||
InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent);
|
||||
if (!node)
|
||||
return false;
|
||||
if (row + count > node->size())
|
||||
return false;
|
||||
InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent);
|
||||
if (!node)
|
||||
return false;
|
||||
if (row + count > node->size())
|
||||
return false;
|
||||
|
||||
beginRemoveRows(parent, row, row + count - 1);
|
||||
for (int i = 0; i < count; i++) {
|
||||
AbstractDecklistNode *toDelete = node->takeAt(row);
|
||||
if (DecklistModelCardNode *temp = dynamic_cast<DecklistModelCardNode *>(toDelete))
|
||||
deckList->deleteNode(temp->getDataNode());
|
||||
delete toDelete;
|
||||
}
|
||||
endRemoveRows();
|
||||
beginRemoveRows(parent, row, row + count - 1);
|
||||
for (int i = 0; i < count; i++) {
|
||||
AbstractDecklistNode *toDelete = node->takeAt(row);
|
||||
if (DecklistModelCardNode *temp = dynamic_cast<DecklistModelCardNode *>(toDelete))
|
||||
deckList->deleteNode(temp->getDataNode());
|
||||
delete toDelete;
|
||||
}
|
||||
endRemoveRows();
|
||||
|
||||
if (!node->size() && (node != root))
|
||||
removeRows(parent.row(), 1, parent.parent());
|
||||
else
|
||||
emitRecursiveUpdates(parent);
|
||||
if (!node->size() && (node != root))
|
||||
removeRows(parent.row(), 1, parent.parent());
|
||||
else
|
||||
emitRecursiveUpdates(parent);
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent)
|
||||
{
|
||||
InnerDecklistNode *newNode = dynamic_cast<InnerDecklistNode *>(parent->findChild(name));
|
||||
if (!newNode) {
|
||||
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
|
||||
newNode = new InnerDecklistNode(name, parent);
|
||||
endInsertRows();
|
||||
}
|
||||
return newNode;
|
||||
InnerDecklistNode *newNode = dynamic_cast<InnerDecklistNode *>(parent->findChild(name));
|
||||
if (!newNode) {
|
||||
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
|
||||
newNode = new InnerDecklistNode(name, parent);
|
||||
endInsertRows();
|
||||
}
|
||||
return newNode;
|
||||
}
|
||||
|
||||
QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName)
|
||||
{
|
||||
InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root);
|
||||
InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root);
|
||||
|
||||
CardInfo *info = db->getCard(cardName);
|
||||
QString cardType = info->getMainCardType();
|
||||
InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode);
|
||||
CardInfo *info = db->getCard(cardName);
|
||||
QString cardType = info->getMainCardType();
|
||||
InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode);
|
||||
|
||||
DecklistModelCardNode *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName));
|
||||
if (!cardNode) {
|
||||
DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName);
|
||||
QModelIndex parentIndex = nodeToIndex(cardTypeNode);
|
||||
beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size());
|
||||
cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode);
|
||||
endInsertRows();
|
||||
sort(1);
|
||||
emitRecursiveUpdates(parentIndex);
|
||||
return nodeToIndex(cardNode);
|
||||
} else {
|
||||
cardNode->setNumber(cardNode->getNumber() + 1);
|
||||
QModelIndex ind = nodeToIndex(cardNode);
|
||||
emitRecursiveUpdates(ind);
|
||||
deckList->updateDeckHash();
|
||||
return ind;
|
||||
}
|
||||
DecklistModelCardNode *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName));
|
||||
if (!cardNode) {
|
||||
DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName);
|
||||
QModelIndex parentIndex = nodeToIndex(cardTypeNode);
|
||||
beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size());
|
||||
cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode);
|
||||
endInsertRows();
|
||||
sort(1);
|
||||
emitRecursiveUpdates(parentIndex);
|
||||
return nodeToIndex(cardNode);
|
||||
} else {
|
||||
cardNode->setNumber(cardNode->getNumber() + 1);
|
||||
QModelIndex ind = nodeToIndex(cardNode);
|
||||
emitRecursiveUpdates(ind);
|
||||
deckList->updateDeckHash();
|
||||
return ind;
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const
|
||||
{
|
||||
if (node == root)
|
||||
return QModelIndex();
|
||||
return createIndex(node->getParent()->indexOf(node), 0, node);
|
||||
if (node == root)
|
||||
return QModelIndex();
|
||||
return createIndex(node->getParent()->indexOf(node), 0, node);
|
||||
}
|
||||
|
||||
void 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);
|
||||
// Sort children of node and save the information needed to
|
||||
// update the list of persistent indexes.
|
||||
QVector<QPair<int, int> > sortResult = node->sort(order);
|
||||
|
||||
QModelIndexList from, to;
|
||||
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 = columnCount(); j; --j) {
|
||||
from << createIndex(fromRow, 0, temp);
|
||||
to << createIndex(toRow, 0, temp);
|
||||
}
|
||||
}
|
||||
changePersistentIndexList(from, to);
|
||||
QModelIndexList from, to;
|
||||
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 = columnCount(); j; --j) {
|
||||
from << createIndex(fromRow, 0, temp);
|
||||
to << createIndex(toRow, 0, temp);
|
||||
}
|
||||
}
|
||||
changePersistentIndexList(from, to);
|
||||
|
||||
// Recursion
|
||||
for (int i = node->size() - 1; i >= 0; --i) {
|
||||
InnerDecklistNode *subNode = dynamic_cast<InnerDecklistNode *>(node->at(i));
|
||||
if (subNode)
|
||||
sortHelper(subNode, order);
|
||||
}
|
||||
// Recursion
|
||||
for (int i = node->size() - 1; i >= 0; --i) {
|
||||
InnerDecklistNode *subNode = dynamic_cast<InnerDecklistNode *>(node->at(i));
|
||||
if (subNode)
|
||||
sortHelper(subNode, order);
|
||||
}
|
||||
}
|
||||
|
||||
void DeckListModel::sort(int /*column*/, Qt::SortOrder order)
|
||||
{
|
||||
emit layoutAboutToBeChanged();
|
||||
sortHelper(root, order);
|
||||
emit layoutChanged();
|
||||
emit layoutAboutToBeChanged();
|
||||
sortHelper(root, order);
|
||||
emit layoutChanged();
|
||||
}
|
||||
|
||||
void DeckListModel::cleanList()
|
||||
{
|
||||
setDeckList(new DeckLoader);
|
||||
setDeckList(new DeckLoader);
|
||||
}
|
||||
|
||||
void DeckListModel::setDeckList(DeckLoader *_deck)
|
||||
{
|
||||
delete deckList;
|
||||
deckList = _deck;
|
||||
connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree()));
|
||||
connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged()));
|
||||
rebuildTree();
|
||||
delete deckList;
|
||||
deckList = _deck;
|
||||
connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree()));
|
||||
connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged()));
|
||||
rebuildTree();
|
||||
}
|
||||
|
||||
void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node)
|
||||
{
|
||||
const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2;
|
||||
const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2;
|
||||
|
||||
if (node->height() == 1) {
|
||||
QTextBlockFormat blockFormat;
|
||||
QTextCharFormat charFormat;
|
||||
charFormat.setFontPointSize(11);
|
||||
charFormat.setFontWeight(QFont::Bold);
|
||||
cursor->insertBlock(blockFormat, charFormat);
|
||||
QString priceStr;
|
||||
if (settingsCache->getPriceTagFeature())
|
||||
priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
|
||||
if (node->height() == 1) {
|
||||
QTextBlockFormat blockFormat;
|
||||
QTextCharFormat charFormat;
|
||||
charFormat.setFontPointSize(11);
|
||||
charFormat.setFontWeight(QFont::Bold);
|
||||
cursor->insertBlock(blockFormat, charFormat);
|
||||
QString priceStr;
|
||||
if (settingsCache->getPriceTagFeature())
|
||||
priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
|
||||
cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr));
|
||||
|
||||
QTextTableFormat tableFormat;
|
||||
tableFormat.setCellPadding(0);
|
||||
tableFormat.setCellSpacing(0);
|
||||
tableFormat.setBorder(0);
|
||||
QTextTableFormat tableFormat;
|
||||
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++) {
|
||||
AbstractDecklistCardNode *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i));
|
||||
for (int i = 0; i < node->size(); i++) {
|
||||
AbstractDecklistCardNode *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i));
|
||||
|
||||
QTextCharFormat cellCharFormat;
|
||||
cellCharFormat.setFontPointSize(9);
|
||||
QTextCharFormat cellCharFormat;
|
||||
cellCharFormat.setFontPointSize(9);
|
||||
|
||||
QTextTableCell cell = table->cellAt(i, 0);
|
||||
cell.setFormat(cellCharFormat);
|
||||
QTextCursor cellCursor = cell.firstCursorPosition();
|
||||
cellCursor.insertText(QString("%1 ").arg(card->getNumber()));
|
||||
QTextTableCell cell = table->cellAt(i, 0);
|
||||
cell.setFormat(cellCharFormat);
|
||||
QTextCursor cellCursor = cell.firstCursorPosition();
|
||||
cellCursor.insertText(QString("%1 ").arg(card->getNumber()));
|
||||
|
||||
cell = table->cellAt(i, 1);
|
||||
cell.setFormat(cellCharFormat);
|
||||
cellCursor = cell.firstCursorPosition();
|
||||
cellCursor.insertText(card->getName());
|
||||
cell = table->cellAt(i, 1);
|
||||
cell.setFormat(cellCharFormat);
|
||||
cellCursor = cell.firstCursorPosition();
|
||||
cellCursor.insertText(card->getName());
|
||||
|
||||
if (settingsCache->getPriceTagFeature()) {
|
||||
cell = table->cellAt(i, 2);
|
||||
cell.setFormat(cellCharFormat);
|
||||
cellCursor = cell.firstCursorPosition();
|
||||
cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice()));
|
||||
}
|
||||
}
|
||||
} else if (node->height() == 2) {
|
||||
QTextBlockFormat blockFormat;
|
||||
QTextCharFormat charFormat;
|
||||
charFormat.setFontPointSize(14);
|
||||
charFormat.setFontWeight(QFont::Bold);
|
||||
if (settingsCache->getPriceTagFeature()) {
|
||||
cell = table->cellAt(i, 2);
|
||||
cell.setFormat(cellCharFormat);
|
||||
cellCursor = cell.firstCursorPosition();
|
||||
cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice()));
|
||||
}
|
||||
}
|
||||
} else if (node->height() == 2) {
|
||||
QTextBlockFormat blockFormat;
|
||||
QTextCharFormat charFormat;
|
||||
charFormat.setFontPointSize(14);
|
||||
charFormat.setFontWeight(QFont::Bold);
|
||||
|
||||
cursor->insertBlock(blockFormat, charFormat);
|
||||
QString priceStr;
|
||||
if (settingsCache->getPriceTagFeature())
|
||||
priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
|
||||
cursor->insertBlock(blockFormat, charFormat);
|
||||
QString priceStr;
|
||||
if (settingsCache->getPriceTagFeature())
|
||||
priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
|
||||
cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr));
|
||||
|
||||
QTextTableFormat tableFormat;
|
||||
tableFormat.setCellPadding(10);
|
||||
tableFormat.setCellSpacing(0);
|
||||
tableFormat.setBorder(0);
|
||||
QVector<QTextLength> constraints;
|
||||
for (int i = 0; i < totalColumns; i++)
|
||||
constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns);
|
||||
tableFormat.setColumnWidthConstraints(constraints);
|
||||
QTextTableFormat tableFormat;
|
||||
tableFormat.setCellPadding(10);
|
||||
tableFormat.setCellSpacing(0);
|
||||
tableFormat.setBorder(0);
|
||||
QVector<QTextLength> constraints;
|
||||
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++) {
|
||||
QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition();
|
||||
printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i)));
|
||||
}
|
||||
}
|
||||
cursor->movePosition(QTextCursor::End);
|
||||
QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat);
|
||||
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)));
|
||||
}
|
||||
}
|
||||
cursor->movePosition(QTextCursor::End);
|
||||
}
|
||||
|
||||
void DeckListModel::printDeckList(QPrinter *printer)
|
||||
{
|
||||
QTextDocument doc;
|
||||
QTextDocument doc;
|
||||
|
||||
QFont font("Serif");
|
||||
font.setStyleHint(QFont::Serif);
|
||||
doc.setDefaultFont(font);
|
||||
QFont font("Serif");
|
||||
font.setStyleHint(QFont::Serif);
|
||||
doc.setDefaultFont(font);
|
||||
|
||||
QTextCursor cursor(&doc);
|
||||
QTextCursor cursor(&doc);
|
||||
|
||||
QTextBlockFormat headerBlockFormat;
|
||||
QTextCharFormat headerCharFormat;
|
||||
headerCharFormat.setFontPointSize(16);
|
||||
headerCharFormat.setFontWeight(QFont::Bold);
|
||||
QTextBlockFormat headerBlockFormat;
|
||||
QTextCharFormat headerCharFormat;
|
||||
headerCharFormat.setFontPointSize(16);
|
||||
headerCharFormat.setFontWeight(QFont::Bold);
|
||||
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
cursor.insertText(deckList->getName());
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
cursor.insertText(deckList->getName());
|
||||
|
||||
headerCharFormat.setFontPointSize(12);
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
cursor.insertText(deckList->getComments());
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
headerCharFormat.setFontPointSize(12);
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
cursor.insertText(deckList->getComments());
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
|
||||
for (int i = 0; i < root->size(); i++) {
|
||||
cursor.insertHtml("<br><img src=:/resources/hr.jpg>");
|
||||
//cursor.insertHtml("<hr>");
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
for (int i = 0; i < root->size(); i++) {
|
||||
cursor.insertHtml("<br><img src=:/resources/hr.jpg>");
|
||||
//cursor.insertHtml("<hr>");
|
||||
cursor.insertBlock(headerBlockFormat, headerCharFormat);
|
||||
|
||||
printDeckListNode(&cursor, dynamic_cast<InnerDecklistNode *>(root->at(i)));
|
||||
}
|
||||
printDeckListNode(&cursor, dynamic_cast<InnerDecklistNode *>(root->at(i)));
|
||||
}
|
||||
|
||||
doc.print(printer);
|
||||
doc.print(printer);
|
||||
}
|
||||
|
||||
void DeckListModel::pricesUpdated(InnerDecklistNode *node)
|
||||
{
|
||||
if (!node)
|
||||
node = root;
|
||||
if (!node)
|
||||
node = root;
|
||||
|
||||
if (node->isEmpty())
|
||||
return;
|
||||
if (node->isEmpty())
|
||||
return;
|
||||
|
||||
emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last()));
|
||||
emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last()));
|
||||
}
|
||||
|
|
|
@ -13,60 +13,60 @@ class QTextCursor;
|
|||
|
||||
class DecklistModelCardNode : public AbstractDecklistCardNode {
|
||||
private:
|
||||
DecklistCardNode *dataNode;
|
||||
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); }
|
||||
DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { }
|
||||
int getNumber() const { return dataNode->getNumber(); }
|
||||
void setNumber(int _number) { dataNode->setNumber(_number); }
|
||||
float getPrice() const { return dataNode->getPrice(); }
|
||||
void setPrice(float _price) { dataNode->setPrice(_price); }
|
||||
QString getName() const { return dataNode->getName(); }
|
||||
void setName(const QString &_name) { dataNode->setName(_name); }
|
||||
DecklistCardNode *getDataNode() const { return dataNode; }
|
||||
QString getName() const { return dataNode->getName(); }
|
||||
void setName(const QString &_name) { dataNode->setName(_name); }
|
||||
DecklistCardNode *getDataNode() const { return dataNode; }
|
||||
};
|
||||
|
||||
class DeckListModel : public QAbstractItemModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void rebuildTree();
|
||||
void rebuildTree();
|
||||
public slots:
|
||||
void printDeckList(QPrinter *printer);
|
||||
void printDeckList(QPrinter *printer);
|
||||
signals:
|
||||
void deckHashChanged();
|
||||
void deckHashChanged();
|
||||
public:
|
||||
DeckListModel(QObject *parent = 0);
|
||||
~DeckListModel();
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
DeckListModel(QObject *parent = 0);
|
||||
~DeckListModel();
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const;
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
bool setData(const QModelIndex &index, const QVariant &value, int role);
|
||||
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
|
||||
QModelIndex addCard(const QString &cardName, const QString &zoneName);
|
||||
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
|
||||
void cleanList();
|
||||
DeckLoader *getDeckList() const { return deckList; }
|
||||
void setDeckList(DeckLoader *_deck);
|
||||
void pricesUpdated(InnerDecklistNode *node = 0);
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
bool setData(const QModelIndex &index, const QVariant &value, int role);
|
||||
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
|
||||
QModelIndex addCard(const QString &cardName, const QString &zoneName);
|
||||
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
|
||||
void cleanList();
|
||||
DeckLoader *getDeckList() const { return deckList; }
|
||||
void setDeckList(DeckLoader *_deck);
|
||||
void pricesUpdated(InnerDecklistNode *node = 0);
|
||||
private:
|
||||
DeckLoader *deckList;
|
||||
InnerDecklistNode *root;
|
||||
InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent);
|
||||
QModelIndex nodeToIndex(AbstractDecklistNode *node) const;
|
||||
void emitRecursiveUpdates(const QModelIndex &index);
|
||||
void sortHelper(InnerDecklistNode *node, Qt::SortOrder order);
|
||||
DeckLoader *deckList;
|
||||
InnerDecklistNode *root;
|
||||
InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent);
|
||||
QModelIndex nodeToIndex(AbstractDecklistNode *node) const;
|
||||
void emitRecursiveUpdates(const QModelIndex &index);
|
||||
void sortHelper(InnerDecklistNode *node, Qt::SortOrder order);
|
||||
|
||||
void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node);
|
||||
void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node);
|
||||
|
||||
template<typename T> T getNode(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return dynamic_cast<T>(root);
|
||||
return dynamic_cast<T>(static_cast<AbstractDecklistNode *>(index.internalPointer()));
|
||||
}
|
||||
template<typename T> T getNode(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return dynamic_cast<T>(root);
|
||||
return dynamic_cast<T>(static_cast<AbstractDecklistNode *>(index.internalPointer()));
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -8,46 +8,46 @@
|
|||
#include <QDesktopServices>
|
||||
|
||||
DeckStatsInterface::DeckStatsInterface(QObject *parent)
|
||||
: QObject(parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
manager = new QNetworkAccessManager(this);
|
||||
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *)));
|
||||
manager = new QNetworkAccessManager(this);
|
||||
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *)));
|
||||
}
|
||||
|
||||
void DeckStatsInterface::queryFinished(QNetworkReply *reply)
|
||||
{
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
QMessageBox::critical(0, tr("Error"), reply->errorString());
|
||||
reply->deleteLater();
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
QMessageBox::critical(0, tr("Error"), reply->errorString());
|
||||
reply->deleteLater();
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
QString data(reply->readAll());
|
||||
reply->deleteLater();
|
||||
QString data(reply->readAll());
|
||||
reply->deleteLater();
|
||||
|
||||
QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\"");
|
||||
if (!rx.indexIn(data)) {
|
||||
QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed."));
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\"");
|
||||
if (!rx.indexIn(data)) {
|
||||
QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed."));
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
QString deckUrl = rx.cap(1);
|
||||
QDesktopServices::openUrl(deckUrl);
|
||||
QString deckUrl = rx.cap(1);
|
||||
QDesktopServices::openUrl(deckUrl);
|
||||
|
||||
deleteLater();
|
||||
deleteLater();
|
||||
}
|
||||
|
||||
void DeckStatsInterface::analyzeDeck(DeckList *deck)
|
||||
{
|
||||
QUrl params;
|
||||
params.addQueryItem("deck", deck->writeToString_Plain());
|
||||
QByteArray data;
|
||||
data.append(params.encodedQuery());
|
||||
QUrl params;
|
||||
params.addQueryItem("deck", deck->writeToString_Plain());
|
||||
QByteArray data;
|
||||
data.append(params.encodedQuery());
|
||||
|
||||
QNetworkRequest request(QUrl("http://deckstats.net/index.php"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||||
QNetworkRequest request(QUrl("http://deckstats.net/index.php"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||||
|
||||
manager->post(request, data);
|
||||
manager->post(request, data);
|
||||
}
|
||||
|
|
|
@ -8,14 +8,14 @@ class QNetworkReply;
|
|||
class DeckList;
|
||||
|
||||
class DeckStatsInterface : public QObject {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QNetworkAccessManager *manager;
|
||||
QNetworkAccessManager *manager;
|
||||
private slots:
|
||||
void queryFinished(QNetworkReply *reply);
|
||||
void queryFinished(QNetworkReply *reply);
|
||||
public:
|
||||
DeckStatsInterface(QObject *parent = 0);
|
||||
void analyzeDeck(DeckList *deck);
|
||||
DeckStatsInterface(QObject *parent = 0);
|
||||
void analyzeDeck(DeckList *deck);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -8,479 +8,479 @@
|
|||
#include "main.h"
|
||||
|
||||
DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag)
|
||||
: AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0)
|
||||
: AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0)
|
||||
{
|
||||
}
|
||||
|
||||
void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
|
||||
{
|
||||
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos);
|
||||
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos);
|
||||
|
||||
DeckViewCardContainer *cursorZone = 0;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--)
|
||||
if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i))))
|
||||
break;
|
||||
if (!cursorZone)
|
||||
return;
|
||||
currentZone = cursorZone;
|
||||
DeckViewCardContainer *cursorZone = 0;
|
||||
for (int i = colliding.size() - 1; i >= 0; i--)
|
||||
if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i))))
|
||||
break;
|
||||
if (!cursorZone)
|
||||
return;
|
||||
currentZone = cursorZone;
|
||||
|
||||
QPointF newPos = cursorScenePos;
|
||||
if (newPos != pos()) {
|
||||
for (int i = 0; i < childDrags.size(); i++)
|
||||
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
|
||||
setPos(newPos);
|
||||
}
|
||||
QPointF newPos = cursorScenePos;
|
||||
if (newPos != pos()) {
|
||||
for (int i = 0; i < childDrags.size(); i++)
|
||||
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
|
||||
setPos(newPos);
|
||||
}
|
||||
}
|
||||
|
||||
void DeckViewCardDragItem::handleDrop(DeckViewCardContainer *target)
|
||||
{
|
||||
DeckViewCard *card = static_cast<DeckViewCard *>(item);
|
||||
DeckViewCardContainer *start = static_cast<DeckViewCardContainer *>(item->parentItem());
|
||||
start->removeCard(card);
|
||||
target->addCard(card);
|
||||
card->setParentItem(target);
|
||||
DeckViewCard *card = static_cast<DeckViewCard *>(item);
|
||||
DeckViewCardContainer *start = static_cast<DeckViewCardContainer *>(item->parentItem());
|
||||
start->removeCard(card);
|
||||
target->addCard(card);
|
||||
card->setParentItem(target);
|
||||
}
|
||||
|
||||
void DeckViewCardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
DeckViewScene *sc = static_cast<DeckViewScene *>(scene());
|
||||
sc->removeItem(this);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
DeckViewScene *sc = static_cast<DeckViewScene *>(scene());
|
||||
sc->removeItem(this);
|
||||
|
||||
if (currentZone) {
|
||||
handleDrop(currentZone);
|
||||
for (int i = 0; i < childDrags.size(); i++) {
|
||||
DeckViewCardDragItem *c = static_cast<DeckViewCardDragItem *>(childDrags[i]);
|
||||
c->handleDrop(currentZone);
|
||||
sc->removeItem(c);
|
||||
}
|
||||
if (currentZone) {
|
||||
handleDrop(currentZone);
|
||||
for (int i = 0; i < childDrags.size(); i++) {
|
||||
DeckViewCardDragItem *c = static_cast<DeckViewCardDragItem *>(childDrags[i]);
|
||||
c->handleDrop(currentZone);
|
||||
sc->removeItem(c);
|
||||
}
|
||||
|
||||
sc->updateContents();
|
||||
}
|
||||
sc->updateContents();
|
||||
}
|
||||
|
||||
event->accept();
|
||||
event->accept();
|
||||
}
|
||||
|
||||
DeckViewCard::DeckViewCard(const QString &_name, const QString &_originZone, QGraphicsItem *parent)
|
||||
: AbstractCardItem(_name, 0, -1, parent), originZone(_originZone), dragItem(0)
|
||||
: AbstractCardItem(_name, 0, -1, parent), originZone(_originZone), dragItem(0)
|
||||
{
|
||||
setAcceptsHoverEvents(true);
|
||||
setAcceptsHoverEvents(true);
|
||||
}
|
||||
|
||||
DeckViewCard::~DeckViewCard()
|
||||
{
|
||||
delete dragItem;
|
||||
delete dragItem;
|
||||
}
|
||||
|
||||
void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
|
||||
{
|
||||
AbstractCardItem::paint(painter, option, widget);
|
||||
AbstractCardItem::paint(painter, option, widget);
|
||||
|
||||
painter->save();
|
||||
QPen pen;//(Qt::DotLine);
|
||||
pen.setWidth(3);
|
||||
if (originZone == "main")
|
||||
pen.setColor(QColor(0, 255, 0));
|
||||
else
|
||||
pen.setColor(QColor(255, 0, 0));
|
||||
painter->setPen(pen);
|
||||
painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3));
|
||||
painter->restore();
|
||||
painter->save();
|
||||
QPen pen;//(Qt::DotLine);
|
||||
pen.setWidth(3);
|
||||
if (originZone == "main")
|
||||
pen.setColor(QColor(0, 255, 0));
|
||||
else
|
||||
pen.setColor(QColor(255, 0, 0));
|
||||
painter->setPen(pen);
|
||||
painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3));
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
|
||||
return;
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
|
||||
return;
|
||||
|
||||
if (static_cast<DeckViewScene *>(scene())->getLocked())
|
||||
return;
|
||||
if (static_cast<DeckViewScene *>(scene())->getLocked())
|
||||
return;
|
||||
|
||||
delete dragItem;
|
||||
dragItem = new DeckViewCardDragItem(this, event->pos());
|
||||
scene()->addItem(dragItem);
|
||||
dragItem->updatePosition(event->scenePos());
|
||||
dragItem->grabMouse();
|
||||
delete dragItem;
|
||||
dragItem = new DeckViewCardDragItem(this, event->pos());
|
||||
scene()->addItem(dragItem);
|
||||
dragItem->updatePosition(event->scenePos());
|
||||
dragItem->grabMouse();
|
||||
|
||||
QList<QGraphicsItem *> sel = scene()->selectedItems();
|
||||
int j = 0;
|
||||
for (int i = 0; i < sel.size(); i++) {
|
||||
DeckViewCard *c = static_cast<DeckViewCard *>(sel.at(i));
|
||||
if (c == this)
|
||||
continue;
|
||||
++j;
|
||||
QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0);
|
||||
DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem);
|
||||
drag->setPos(dragItem->pos() + childPos);
|
||||
scene()->addItem(drag);
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QList<QGraphicsItem *> sel = scene()->selectedItems();
|
||||
int j = 0;
|
||||
for (int i = 0; i < sel.size(); i++) {
|
||||
DeckViewCard *c = static_cast<DeckViewCard *>(sel.at(i));
|
||||
if (c == this)
|
||||
continue;
|
||||
++j;
|
||||
QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0);
|
||||
DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem);
|
||||
drag->setPos(dragItem->pos() + childPos);
|
||||
scene()->addItem(drag);
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
}
|
||||
|
||||
void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
|
||||
{
|
||||
event->accept();
|
||||
processHoverEvent();
|
||||
event->accept();
|
||||
processHoverEvent();
|
||||
}
|
||||
|
||||
DeckViewCardContainer::DeckViewCardContainer(const QString &_name)
|
||||
: QGraphicsItem(), name(_name), width(0), height(0)
|
||||
: QGraphicsItem(), name(_name), width(0), height(0)
|
||||
{
|
||||
QString bgPath = settingsCache->getTableBgPath();
|
||||
if (!bgPath.isEmpty())
|
||||
bgPixmap.load(bgPath);
|
||||
QString bgPath = settingsCache->getTableBgPath();
|
||||
if (!bgPath.isEmpty())
|
||||
bgPixmap.load(bgPath);
|
||||
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
}
|
||||
|
||||
QRectF DeckViewCardContainer::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, width, height);
|
||||
return QRectF(0, 0, width, height);
|
||||
}
|
||||
|
||||
void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
qreal totalTextWidth = getCardTypeTextWidth();
|
||||
qreal totalTextWidth = getCardTypeTextWidth();
|
||||
|
||||
if (bgPixmap.isNull())
|
||||
painter->fillRect(boundingRect(), QColor(0, 0, 100));
|
||||
else
|
||||
painter->fillRect(boundingRect(), QBrush(bgPixmap));
|
||||
painter->setPen(QColor(255, 255, 255, 100));
|
||||
painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY));
|
||||
if (bgPixmap.isNull())
|
||||
painter->fillRect(boundingRect(), QColor(0, 0, 100));
|
||||
else
|
||||
painter->fillRect(boundingRect(), QBrush(bgPixmap));
|
||||
painter->setPen(QColor(255, 255, 255, 100));
|
||||
painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY));
|
||||
|
||||
painter->setPen(QColor(Qt::white));
|
||||
QFont f("Serif");
|
||||
f.setStyleHint(QFont::Serif);
|
||||
f.setPixelSize(24);
|
||||
f.setWeight(QFont::Bold);
|
||||
painter->setFont(f);
|
||||
painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size()));
|
||||
painter->setPen(QColor(Qt::white));
|
||||
QFont f("Serif");
|
||||
f.setStyleHint(QFont::Serif);
|
||||
f.setPixelSize(24);
|
||||
f.setWeight(QFont::Bold);
|
||||
painter->setFont(f);
|
||||
painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size()));
|
||||
|
||||
f.setPixelSize(16);
|
||||
painter->setFont(f);
|
||||
QList<QString> cardTypeList = cardsByType.uniqueKeys();
|
||||
qreal yUntilNow = separatorY + paddingY;
|
||||
for (int i = 0; i < cardTypeList.size(); ++i) {
|
||||
if (i != 0) {
|
||||
painter->setPen(QColor(255, 255, 255, 100));
|
||||
painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2));
|
||||
}
|
||||
qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first;
|
||||
QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight);
|
||||
yUntilNow += thisRowHeight + paddingY;
|
||||
f.setPixelSize(16);
|
||||
painter->setFont(f);
|
||||
QList<QString> cardTypeList = cardsByType.uniqueKeys();
|
||||
qreal yUntilNow = separatorY + paddingY;
|
||||
for (int i = 0; i < cardTypeList.size(); ++i) {
|
||||
if (i != 0) {
|
||||
painter->setPen(QColor(255, 255, 255, 100));
|
||||
painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2));
|
||||
}
|
||||
qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first;
|
||||
QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight);
|
||||
yUntilNow += thisRowHeight + paddingY;
|
||||
|
||||
painter->setPen(Qt::white);
|
||||
painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]);
|
||||
}
|
||||
painter->setPen(Qt::white);
|
||||
painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void DeckViewCardContainer::addCard(DeckViewCard *card)
|
||||
{
|
||||
cards.append(card);
|
||||
cardsByType.insert(card->getInfo()->getMainCardType(), card);
|
||||
cards.append(card);
|
||||
cardsByType.insert(card->getInfo()->getMainCardType(), card);
|
||||
}
|
||||
|
||||
void DeckViewCardContainer::removeCard(DeckViewCard *card)
|
||||
{
|
||||
cards.removeAt(cards.indexOf(card));
|
||||
cardsByType.remove(card->getInfo()->getMainCardType(), card);
|
||||
cards.removeAt(cards.indexOf(card));
|
||||
cardsByType.remove(card->getInfo()->getMainCardType(), card);
|
||||
}
|
||||
|
||||
QList<QPair<int, int> > DeckViewCardContainer::getRowsAndCols() const
|
||||
{
|
||||
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])));
|
||||
return 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])));
|
||||
return result;
|
||||
}
|
||||
|
||||
int DeckViewCardContainer::getCardTypeTextWidth() const
|
||||
{
|
||||
QFont f("Serif");
|
||||
f.setStyleHint(QFont::Serif);
|
||||
f.setPixelSize(16);
|
||||
f.setWeight(QFont::Bold);
|
||||
QFontMetrics fm(f);
|
||||
QFont f("Serif");
|
||||
f.setStyleHint(QFont::Serif);
|
||||
f.setPixelSize(16);
|
||||
f.setWeight(QFont::Bold);
|
||||
QFontMetrics fm(f);
|
||||
|
||||
int maxCardTypeWidth = 0;
|
||||
QMapIterator<QString, DeckViewCard *> i(cardsByType);
|
||||
while (i.hasNext()) {
|
||||
int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width();
|
||||
if (cardTypeWidth > maxCardTypeWidth)
|
||||
maxCardTypeWidth = cardTypeWidth;
|
||||
}
|
||||
int maxCardTypeWidth = 0;
|
||||
QMapIterator<QString, DeckViewCard *> i(cardsByType);
|
||||
while (i.hasNext()) {
|
||||
int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width();
|
||||
if (cardTypeWidth > maxCardTypeWidth)
|
||||
maxCardTypeWidth = cardTypeWidth;
|
||||
}
|
||||
|
||||
return maxCardTypeWidth + 15;
|
||||
return maxCardTypeWidth + 15;
|
||||
}
|
||||
|
||||
QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const
|
||||
{
|
||||
qreal totalHeight = 0;
|
||||
qreal totalWidth = 0;
|
||||
qreal totalHeight = 0;
|
||||
qreal totalWidth = 0;
|
||||
|
||||
// Calculate space needed for cards
|
||||
for (int i = 0; i < rowsAndCols.size(); ++i) {
|
||||
totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY;
|
||||
if (CARD_WIDTH * rowsAndCols[i].second > totalWidth)
|
||||
totalWidth = CARD_WIDTH * rowsAndCols[i].second;
|
||||
}
|
||||
// Calculate space needed for cards
|
||||
for (int i = 0; i < rowsAndCols.size(); ++i) {
|
||||
totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY;
|
||||
if (CARD_WIDTH * rowsAndCols[i].second > totalWidth)
|
||||
totalWidth = CARD_WIDTH * rowsAndCols[i].second;
|
||||
}
|
||||
|
||||
return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY);
|
||||
return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY);
|
||||
}
|
||||
|
||||
void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int> > &rowsAndCols)
|
||||
{
|
||||
currentRowsAndCols = rowsAndCols;
|
||||
currentRowsAndCols = rowsAndCols;
|
||||
|
||||
int totalCols = 0, totalRows = 0;
|
||||
qreal yUntilNow = separatorY + paddingY;
|
||||
qreal x = (qreal) getCardTypeTextWidth();
|
||||
for (int i = 0; i < rowsAndCols.size(); ++i) {
|
||||
const int tempRows = rowsAndCols[i].first;
|
||||
const int tempCols = rowsAndCols[i].second;
|
||||
totalRows += tempRows;
|
||||
if (tempCols > totalCols)
|
||||
totalCols = tempCols;
|
||||
int totalCols = 0, totalRows = 0;
|
||||
qreal yUntilNow = separatorY + paddingY;
|
||||
qreal x = (qreal) getCardTypeTextWidth();
|
||||
for (int i = 0; i < rowsAndCols.size(); ++i) {
|
||||
const int tempRows = rowsAndCols[i].first;
|
||||
const int tempCols = rowsAndCols[i].second;
|
||||
totalRows += tempRows;
|
||||
if (tempCols > totalCols)
|
||||
totalCols = tempCols;
|
||||
|
||||
QList<QString> cardTypeList = cardsByType.uniqueKeys();
|
||||
QList<DeckViewCard *> row = cardsByType.values(cardTypeList[i]);
|
||||
for (int j = 0; j < row.size(); ++j) {
|
||||
DeckViewCard *card = row[j];
|
||||
card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT);
|
||||
}
|
||||
yUntilNow += tempRows * CARD_HEIGHT + paddingY;
|
||||
}
|
||||
QList<QString> cardTypeList = cardsByType.uniqueKeys();
|
||||
QList<DeckViewCard *> row = cardsByType.values(cardTypeList[i]);
|
||||
for (int j = 0; j < row.size(); ++j) {
|
||||
DeckViewCard *card = row[j];
|
||||
card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT);
|
||||
}
|
||||
yUntilNow += tempRows * CARD_HEIGHT + paddingY;
|
||||
}
|
||||
|
||||
prepareGeometryChange();
|
||||
QSizeF bRect = calculateBoundingRect(rowsAndCols);
|
||||
width = bRect.width();
|
||||
height = bRect.height();
|
||||
prepareGeometryChange();
|
||||
QSizeF bRect = calculateBoundingRect(rowsAndCols);
|
||||
width = bRect.width();
|
||||
height = bRect.height();
|
||||
}
|
||||
|
||||
void DeckViewCardContainer::setWidth(qreal _width)
|
||||
{
|
||||
prepareGeometryChange();
|
||||
width = _width;
|
||||
update();
|
||||
prepareGeometryChange();
|
||||
width = _width;
|
||||
update();
|
||||
}
|
||||
|
||||
DeckViewScene::DeckViewScene(QObject *parent)
|
||||
: QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
|
||||
: QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
|
||||
{
|
||||
}
|
||||
|
||||
DeckViewScene::~DeckViewScene()
|
||||
{
|
||||
clearContents();
|
||||
delete deck;
|
||||
clearContents();
|
||||
delete deck;
|
||||
}
|
||||
|
||||
void DeckViewScene::clearContents()
|
||||
{
|
||||
QMapIterator<QString, DeckViewCardContainer *> i(cardContainers);
|
||||
while (i.hasNext())
|
||||
delete i.next().value();
|
||||
cardContainers.clear();
|
||||
QMapIterator<QString, DeckViewCardContainer *> i(cardContainers);
|
||||
while (i.hasNext())
|
||||
delete i.next().value();
|
||||
cardContainers.clear();
|
||||
}
|
||||
|
||||
void DeckViewScene::setDeck(const DeckList &_deck)
|
||||
{
|
||||
if (deck)
|
||||
delete deck;
|
||||
if (deck)
|
||||
delete deck;
|
||||
|
||||
deck = new DeckList(_deck);
|
||||
rebuildTree();
|
||||
applySideboardPlan(deck->getCurrentSideboardPlan());
|
||||
rearrangeItems();
|
||||
deck = new DeckList(_deck);
|
||||
rebuildTree();
|
||||
applySideboardPlan(deck->getCurrentSideboardPlan());
|
||||
rearrangeItems();
|
||||
}
|
||||
|
||||
void DeckViewScene::rebuildTree()
|
||||
{
|
||||
clearContents();
|
||||
clearContents();
|
||||
|
||||
if (!deck)
|
||||
return;
|
||||
if (!deck)
|
||||
return;
|
||||
|
||||
InnerDecklistNode *listRoot = deck->getRoot();
|
||||
for (int i = 0; i < listRoot->size(); i++) {
|
||||
InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
|
||||
InnerDecklistNode *listRoot = deck->getRoot();
|
||||
for (int i = 0; i < listRoot->size(); i++) {
|
||||
InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
|
||||
|
||||
DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0);
|
||||
if (!container) {
|
||||
container = new DeckViewCardContainer(currentZone->getName());
|
||||
cardContainers.insert(currentZone->getName(), container);
|
||||
addItem(container);
|
||||
}
|
||||
DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0);
|
||||
if (!container) {
|
||||
container = new DeckViewCardContainer(currentZone->getName());
|
||||
cardContainers.insert(currentZone->getName(), container);
|
||||
addItem(container);
|
||||
}
|
||||
|
||||
for (int j = 0; j < currentZone->size(); j++) {
|
||||
DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
|
||||
if (!currentCard)
|
||||
continue;
|
||||
for (int j = 0; j < currentZone->size(); j++) {
|
||||
DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
|
||||
if (!currentCard)
|
||||
continue;
|
||||
|
||||
for (int k = 0; k < currentCard->getNumber(); ++k) {
|
||||
DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container);
|
||||
container->addCard(newCard);
|
||||
emit newCardAdded(newCard);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < currentCard->getNumber(); ++k) {
|
||||
DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container);
|
||||
container->addCard(newCard);
|
||||
emit newCardAdded(newCard);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DeckViewScene::applySideboardPlan(const QList<MoveCard_ToZone> &plan)
|
||||
{
|
||||
for (int i = 0; i < plan.size(); ++i) {
|
||||
const MoveCard_ToZone &m = plan[i];
|
||||
DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone()));
|
||||
DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone()));
|
||||
if (!start || !target)
|
||||
continue;
|
||||
for (int i = 0; i < plan.size(); ++i) {
|
||||
const MoveCard_ToZone &m = plan[i];
|
||||
DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone()));
|
||||
DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone()));
|
||||
if (!start || !target)
|
||||
continue;
|
||||
|
||||
DeckViewCard *card = 0;
|
||||
const QList<DeckViewCard *> &cardList = start->getCards();
|
||||
for (int j = 0; j < cardList.size(); ++j)
|
||||
if (cardList[j]->getName() == QString::fromStdString(m.card_name())) {
|
||||
card = cardList[j];
|
||||
break;
|
||||
}
|
||||
if (!card)
|
||||
continue;
|
||||
DeckViewCard *card = 0;
|
||||
const QList<DeckViewCard *> &cardList = start->getCards();
|
||||
for (int j = 0; j < cardList.size(); ++j)
|
||||
if (cardList[j]->getName() == QString::fromStdString(m.card_name())) {
|
||||
card = cardList[j];
|
||||
break;
|
||||
}
|
||||
if (!card)
|
||||
continue;
|
||||
|
||||
start->removeCard(card);
|
||||
target->addCard(card);
|
||||
card->setParentItem(target);
|
||||
}
|
||||
start->removeCard(card);
|
||||
target->addCard(card);
|
||||
card->setParentItem(target);
|
||||
}
|
||||
}
|
||||
|
||||
void DeckViewScene::rearrangeItems()
|
||||
{
|
||||
const int spacing = CARD_HEIGHT / 3;
|
||||
QList<DeckViewCardContainer *> contList = cardContainers.values();
|
||||
const int spacing = CARD_HEIGHT / 3;
|
||||
QList<DeckViewCardContainer *> contList = cardContainers.values();
|
||||
|
||||
// Initialize space requirements
|
||||
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();
|
||||
rowsAndColsList.append(rowsAndCols);
|
||||
// Initialize space requirements
|
||||
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();
|
||||
rowsAndColsList.append(rowsAndCols);
|
||||
|
||||
cardCountList.append(QList<int>());
|
||||
for (int j = 0; j < rowsAndCols.size(); ++j)
|
||||
cardCountList[i].append(rowsAndCols[j].second);
|
||||
}
|
||||
cardCountList.append(QList<int>());
|
||||
for (int j = 0; j < rowsAndCols.size(); ++j)
|
||||
cardCountList[i].append(rowsAndCols[j].second);
|
||||
}
|
||||
|
||||
qreal totalHeight, totalWidth;
|
||||
for (;;) {
|
||||
// Calculate total size before this iteration
|
||||
totalHeight = -spacing;
|
||||
totalWidth = 0;
|
||||
for (int i = 0; i < contList.size(); ++i) {
|
||||
QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]);
|
||||
totalHeight += contSize.height() + spacing;
|
||||
if (contSize.width() > totalWidth)
|
||||
totalWidth = contSize.width();
|
||||
}
|
||||
qreal totalHeight, totalWidth;
|
||||
for (;;) {
|
||||
// Calculate total size before this iteration
|
||||
totalHeight = -spacing;
|
||||
totalWidth = 0;
|
||||
for (int i = 0; i < contList.size(); ++i) {
|
||||
QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]);
|
||||
totalHeight += contSize.height() + spacing;
|
||||
if (contSize.width() > totalWidth)
|
||||
totalWidth = contSize.width();
|
||||
}
|
||||
|
||||
// We're done when the aspect ratio shifts from too high to too low.
|
||||
if (totalWidth / totalHeight <= optimalAspectRatio)
|
||||
break;
|
||||
// We're done when the aspect ratio shifts from too high to too low.
|
||||
if (totalWidth / totalHeight <= optimalAspectRatio)
|
||||
break;
|
||||
|
||||
// Find category with highest column count
|
||||
int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0;
|
||||
for (int i = 0; i < rowsAndColsList.size(); ++i)
|
||||
for (int j = 0; j < rowsAndColsList[i].size(); ++j)
|
||||
if (rowsAndColsList[i][j].second > maxCols) {
|
||||
maxIndex1 = i;
|
||||
maxIndex2 = j;
|
||||
maxCols = rowsAndColsList[i][j].second;
|
||||
}
|
||||
// Find category with highest column count
|
||||
int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0;
|
||||
for (int i = 0; i < rowsAndColsList.size(); ++i)
|
||||
for (int j = 0; j < rowsAndColsList[i].size(); ++j)
|
||||
if (rowsAndColsList[i][j].second > maxCols) {
|
||||
maxIndex1 = i;
|
||||
maxIndex2 = j;
|
||||
maxCols = rowsAndColsList[i][j].second;
|
||||
}
|
||||
|
||||
// Add row to category
|
||||
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
|
||||
const int maxCardCount = cardCountList[maxIndex1][maxIndex2];
|
||||
rowsAndColsList[maxIndex1][maxIndex2] = QPair<int, int>(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1)));
|
||||
}
|
||||
// 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)));
|
||||
}
|
||||
|
||||
totalHeight = -spacing;
|
||||
for (int i = 0; i < contList.size(); ++i) {
|
||||
DeckViewCardContainer *c = contList[i];
|
||||
c->rearrangeItems(rowsAndColsList[i]);
|
||||
c->setPos(0, totalHeight + spacing);
|
||||
totalHeight += c->boundingRect().height() + spacing;
|
||||
}
|
||||
totalHeight = -spacing;
|
||||
for (int i = 0; i < contList.size(); ++i) {
|
||||
DeckViewCardContainer *c = contList[i];
|
||||
c->rearrangeItems(rowsAndColsList[i]);
|
||||
c->setPos(0, totalHeight + spacing);
|
||||
totalHeight += c->boundingRect().height() + spacing;
|
||||
}
|
||||
|
||||
totalWidth = totalHeight * optimalAspectRatio;
|
||||
for (int i = 0; i < contList.size(); ++i)
|
||||
contList[i]->setWidth(totalWidth);
|
||||
totalWidth = totalHeight * optimalAspectRatio;
|
||||
for (int i = 0; i < contList.size(); ++i)
|
||||
contList[i]->setWidth(totalWidth);
|
||||
|
||||
setSceneRect(QRectF(0, 0, totalWidth, totalHeight));
|
||||
setSceneRect(QRectF(0, 0, totalWidth, totalHeight));
|
||||
}
|
||||
|
||||
void DeckViewScene::updateContents()
|
||||
{
|
||||
rearrangeItems();
|
||||
emit sideboardPlanChanged();
|
||||
rearrangeItems();
|
||||
emit sideboardPlanChanged();
|
||||
}
|
||||
|
||||
QList<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const
|
||||
{
|
||||
QList<MoveCard_ToZone> result;
|
||||
QMapIterator<QString, DeckViewCardContainer *> containerIterator(cardContainers);
|
||||
while (containerIterator.hasNext()) {
|
||||
DeckViewCardContainer *cont = containerIterator.next().value();
|
||||
const QList<DeckViewCard *> cardList = cont->getCards();
|
||||
for (int i = 0; i < cardList.size(); ++i)
|
||||
if (cardList[i]->getOriginZone() != cont->getName()) {
|
||||
MoveCard_ToZone m;
|
||||
m.set_card_name(cardList[i]->getName().toStdString());
|
||||
m.set_start_zone(cardList[i]->getOriginZone().toStdString());
|
||||
m.set_target_zone(cont->getName().toStdString());
|
||||
result.append(m);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
QList<MoveCard_ToZone> result;
|
||||
QMapIterator<QString, DeckViewCardContainer *> containerIterator(cardContainers);
|
||||
while (containerIterator.hasNext()) {
|
||||
DeckViewCardContainer *cont = containerIterator.next().value();
|
||||
const QList<DeckViewCard *> cardList = cont->getCards();
|
||||
for (int i = 0; i < cardList.size(); ++i)
|
||||
if (cardList[i]->getOriginZone() != cont->getName()) {
|
||||
MoveCard_ToZone m;
|
||||
m.set_card_name(cardList[i]->getName().toStdString());
|
||||
m.set_start_zone(cardList[i]->getOriginZone().toStdString());
|
||||
m.set_target_zone(cont->getName().toStdString());
|
||||
result.append(m);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void DeckViewScene::resetSideboardPlan()
|
||||
{
|
||||
rebuildTree();
|
||||
rearrangeItems();
|
||||
rebuildTree();
|
||||
rearrangeItems();
|
||||
}
|
||||
|
||||
DeckView::DeckView(QWidget *parent)
|
||||
: QGraphicsView(parent)
|
||||
: QGraphicsView(parent)
|
||||
{
|
||||
deckViewScene = new DeckViewScene(this);
|
||||
deckViewScene = new DeckViewScene(this);
|
||||
|
||||
setBackgroundBrush(QBrush(QColor(0, 0, 0)));
|
||||
setDragMode(RubberBandDrag);
|
||||
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/);
|
||||
setScene(deckViewScene);
|
||||
setBackgroundBrush(QBrush(QColor(0, 0, 0)));
|
||||
setDragMode(RubberBandDrag);
|
||||
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/);
|
||||
setScene(deckViewScene);
|
||||
|
||||
connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &)));
|
||||
connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *)));
|
||||
connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged()));
|
||||
connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &)));
|
||||
connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *)));
|
||||
connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged()));
|
||||
}
|
||||
|
||||
void DeckView::resizeEvent(QResizeEvent *event)
|
||||
{
|
||||
QGraphicsView::resizeEvent(event);
|
||||
deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height());
|
||||
deckViewScene->rearrangeItems();
|
||||
QGraphicsView::resizeEvent(event);
|
||||
deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height());
|
||||
deckViewScene->rearrangeItems();
|
||||
}
|
||||
|
||||
void DeckView::updateSceneRect(const QRectF &rect)
|
||||
{
|
||||
fitInView(rect, Qt::KeepAspectRatio);
|
||||
fitInView(rect, Qt::KeepAspectRatio);
|
||||
}
|
||||
|
||||
void DeckView::setDeck(const DeckList &_deck)
|
||||
{
|
||||
deckViewScene->setDeck(_deck);
|
||||
deckViewScene->setDeck(_deck);
|
||||
}
|
||||
|
||||
void DeckView::resetSideboardPlan()
|
||||
{
|
||||
deckViewScene->resetSideboardPlan();
|
||||
deckViewScene->resetSideboardPlan();
|
||||
}
|
||||
|
|
|
@ -19,101 +19,101 @@ class MoveCardToZone;
|
|||
|
||||
class DeckViewCard : public AbstractCardItem {
|
||||
private:
|
||||
QString originZone;
|
||||
DeckViewCardDragItem *dragItem;
|
||||
QString originZone;
|
||||
DeckViewCardDragItem *dragItem;
|
||||
public:
|
||||
DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0);
|
||||
~DeckViewCard();
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
const QString &getOriginZone() const { return originZone; }
|
||||
DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0);
|
||||
~DeckViewCard();
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
const QString &getOriginZone() const { return originZone; }
|
||||
protected:
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
|
||||
};
|
||||
|
||||
class DeckViewCardDragItem : public AbstractCardDragItem {
|
||||
private:
|
||||
DeckViewCardContainer *currentZone;
|
||||
void handleDrop(DeckViewCardContainer *target);
|
||||
DeckViewCardContainer *currentZone;
|
||||
void handleDrop(DeckViewCardContainer *target);
|
||||
public:
|
||||
DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
|
||||
void updatePosition(const QPointF &cursorScenePos);
|
||||
DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
|
||||
void updatePosition(const QPointF &cursorScenePos);
|
||||
protected:
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
};
|
||||
|
||||
class DeckViewCardContainer : public QGraphicsItem {
|
||||
private:
|
||||
static const int separatorY = 20;
|
||||
static const int paddingY = 10;
|
||||
static const int separatorY = 20;
|
||||
static const int paddingY = 10;
|
||||
|
||||
QString name;
|
||||
QList<DeckViewCard *> cards;
|
||||
QMultiMap<QString, DeckViewCard *> cardsByType;
|
||||
QList<QPair<int, int> > currentRowsAndCols;
|
||||
qreal width, height;
|
||||
QPixmap bgPixmap;
|
||||
int getCardTypeTextWidth() const;
|
||||
QString name;
|
||||
QList<DeckViewCard *> cards;
|
||||
QMultiMap<QString, DeckViewCard *> cardsByType;
|
||||
QList<QPair<int, int> > currentRowsAndCols;
|
||||
qreal width, height;
|
||||
QPixmap bgPixmap;
|
||||
int getCardTypeTextWidth() const;
|
||||
public:
|
||||
enum { Type = typeDeckViewCardContainer };
|
||||
int type() const { return Type; }
|
||||
DeckViewCardContainer(const QString &_name);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void addCard(DeckViewCard *card);
|
||||
void removeCard(DeckViewCard *card);
|
||||
const QList<DeckViewCard *> &getCards() const { return cards; }
|
||||
const QString &getName() const { return name; }
|
||||
void setWidth(qreal _width);
|
||||
enum { Type = typeDeckViewCardContainer };
|
||||
int type() const { return Type; }
|
||||
DeckViewCardContainer(const QString &_name);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void addCard(DeckViewCard *card);
|
||||
void removeCard(DeckViewCard *card);
|
||||
const QList<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 {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void newCardAdded(AbstractCardItem *card);
|
||||
void sideboardPlanChanged();
|
||||
void newCardAdded(AbstractCardItem *card);
|
||||
void sideboardPlanChanged();
|
||||
private:
|
||||
bool locked;
|
||||
DeckList *deck;
|
||||
QMap<QString, DeckViewCardContainer *> cardContainers;
|
||||
qreal optimalAspectRatio;
|
||||
void clearContents();
|
||||
void rebuildTree();
|
||||
void applySideboardPlan(const QList<MoveCard_ToZone> &plan);
|
||||
bool locked;
|
||||
DeckList *deck;
|
||||
QMap<QString, DeckViewCardContainer *> cardContainers;
|
||||
qreal optimalAspectRatio;
|
||||
void clearContents();
|
||||
void rebuildTree();
|
||||
void applySideboardPlan(const QList<MoveCard_ToZone> &plan);
|
||||
public:
|
||||
DeckViewScene(QObject *parent = 0);
|
||||
~DeckViewScene();
|
||||
void setLocked(bool _locked) { locked = _locked; }
|
||||
bool getLocked() const { return locked; }
|
||||
void setDeck(const DeckList &_deck);
|
||||
void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; }
|
||||
void rearrangeItems();
|
||||
void updateContents();
|
||||
QList<MoveCard_ToZone> getSideboardPlan() const;
|
||||
void resetSideboardPlan();
|
||||
DeckViewScene(QObject *parent = 0);
|
||||
~DeckViewScene();
|
||||
void setLocked(bool _locked) { locked = _locked; }
|
||||
bool getLocked() const { return locked; }
|
||||
void setDeck(const DeckList &_deck);
|
||||
void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; }
|
||||
void rearrangeItems();
|
||||
void updateContents();
|
||||
QList<MoveCard_ToZone> getSideboardPlan() const;
|
||||
void resetSideboardPlan();
|
||||
};
|
||||
|
||||
class DeckView : public QGraphicsView {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
DeckViewScene *deckViewScene;
|
||||
DeckViewScene *deckViewScene;
|
||||
protected:
|
||||
void resizeEvent(QResizeEvent *event);
|
||||
void resizeEvent(QResizeEvent *event);
|
||||
public slots:
|
||||
void updateSceneRect(const QRectF &rect);
|
||||
void updateSceneRect(const QRectF &rect);
|
||||
signals:
|
||||
void newCardAdded(AbstractCardItem *card);
|
||||
void sideboardPlanChanged();
|
||||
void newCardAdded(AbstractCardItem *card);
|
||||
void sideboardPlanChanged();
|
||||
public:
|
||||
DeckView(QWidget *parent = 0);
|
||||
void setDeck(const DeckList &_deck);
|
||||
void setLocked(bool _locked) { deckViewScene->setLocked(_locked); }
|
||||
QList<MoveCard_ToZone> getSideboardPlan() const { return deckViewScene->getSideboardPlan(); }
|
||||
void resetSideboardPlan();
|
||||
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 resetSideboardPlan();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -10,86 +10,86 @@
|
|||
#include "main.h"
|
||||
|
||||
DlgCardSearch::DlgCardSearch(QWidget *parent)
|
||||
: QDialog(parent)
|
||||
: QDialog(parent)
|
||||
{
|
||||
QLabel *cardNameLabel = new QLabel(tr("Card name:"));
|
||||
cardNameEdit = new QLineEdit;
|
||||
QLabel *cardNameLabel = new QLabel(tr("Card name:"));
|
||||
cardNameEdit = new QLineEdit;
|
||||
|
||||
QLabel *cardTextLabel = new QLabel(tr("Card text:"));
|
||||
cardTextEdit = new QLineEdit;
|
||||
QLabel *cardTextLabel = new QLabel(tr("Card text:"));
|
||||
cardTextEdit = new QLineEdit;
|
||||
|
||||
QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):"));
|
||||
const QStringList &cardTypes = db->getAllMainCardTypes();
|
||||
QVBoxLayout *cardTypesLayout = new QVBoxLayout;
|
||||
for (int i = 0; i < cardTypes.size(); ++i) {
|
||||
QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]);
|
||||
cardTypeCheckBox->setChecked(true);
|
||||
cardTypeCheckBoxes.append(cardTypeCheckBox);
|
||||
cardTypesLayout->addWidget(cardTypeCheckBox);
|
||||
}
|
||||
QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):"));
|
||||
const QStringList &cardTypes = db->getAllMainCardTypes();
|
||||
QVBoxLayout *cardTypesLayout = new QVBoxLayout;
|
||||
for (int i = 0; i < cardTypes.size(); ++i) {
|
||||
QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]);
|
||||
cardTypeCheckBox->setChecked(true);
|
||||
cardTypeCheckBoxes.append(cardTypeCheckBox);
|
||||
cardTypesLayout->addWidget(cardTypeCheckBox);
|
||||
}
|
||||
|
||||
QLabel *cardColorsLabel = new QLabel(tr("Color (OR):"));
|
||||
const QStringList &cardColors = db->getAllColors();
|
||||
QHBoxLayout *cardColorsLayout = new QHBoxLayout;
|
||||
for (int i = 0; i < cardColors.size(); ++i) {
|
||||
QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]);
|
||||
cardColorCheckBox->setChecked(true);
|
||||
cardColorCheckBoxes.append(cardColorCheckBox);
|
||||
cardColorsLayout->addWidget(cardColorCheckBox);
|
||||
}
|
||||
QLabel *cardColorsLabel = new QLabel(tr("Color (OR):"));
|
||||
const QStringList &cardColors = db->getAllColors();
|
||||
QHBoxLayout *cardColorsLayout = new QHBoxLayout;
|
||||
for (int i = 0; i < cardColors.size(); ++i) {
|
||||
QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]);
|
||||
cardColorCheckBox->setChecked(true);
|
||||
cardColorCheckBoxes.append(cardColorCheckBox);
|
||||
cardColorsLayout->addWidget(cardColorCheckBox);
|
||||
}
|
||||
|
||||
QPushButton *okButton = new QPushButton(tr("O&K"));
|
||||
okButton->setDefault(true);
|
||||
okButton->setAutoDefault(true);
|
||||
QPushButton *cancelButton = new QPushButton(tr("&Cancel"));
|
||||
connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
|
||||
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
|
||||
QHBoxLayout *buttonHBox = new QHBoxLayout;
|
||||
buttonHBox->addStretch();
|
||||
buttonHBox->addWidget(okButton);
|
||||
buttonHBox->addWidget(cancelButton);
|
||||
QPushButton *okButton = new QPushButton(tr("O&K"));
|
||||
okButton->setDefault(true);
|
||||
okButton->setAutoDefault(true);
|
||||
QPushButton *cancelButton = new QPushButton(tr("&Cancel"));
|
||||
connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
|
||||
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
|
||||
QHBoxLayout *buttonHBox = new QHBoxLayout;
|
||||
buttonHBox->addStretch();
|
||||
buttonHBox->addWidget(okButton);
|
||||
buttonHBox->addWidget(cancelButton);
|
||||
|
||||
QGridLayout *optionsLayout = new QGridLayout;
|
||||
optionsLayout->addWidget(cardNameLabel, 0, 0);
|
||||
optionsLayout->addWidget(cardNameEdit, 0, 1);
|
||||
optionsLayout->addWidget(cardTextLabel, 1, 0);
|
||||
optionsLayout->addWidget(cardTextEdit, 1, 1);
|
||||
optionsLayout->addWidget(cardTypesLabel, 2, 0);
|
||||
optionsLayout->addLayout(cardTypesLayout, 2, 1);
|
||||
optionsLayout->addWidget(cardColorsLabel, 3, 0);
|
||||
optionsLayout->addLayout(cardColorsLayout, 3, 1);
|
||||
QGridLayout *optionsLayout = new QGridLayout;
|
||||
optionsLayout->addWidget(cardNameLabel, 0, 0);
|
||||
optionsLayout->addWidget(cardNameEdit, 0, 1);
|
||||
optionsLayout->addWidget(cardTextLabel, 1, 0);
|
||||
optionsLayout->addWidget(cardTextEdit, 1, 1);
|
||||
optionsLayout->addWidget(cardTypesLabel, 2, 0);
|
||||
optionsLayout->addLayout(cardTypesLayout, 2, 1);
|
||||
optionsLayout->addWidget(cardColorsLabel, 3, 0);
|
||||
optionsLayout->addLayout(cardColorsLayout, 3, 1);
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(optionsLayout);
|
||||
mainLayout->addLayout(buttonHBox);
|
||||
setLayout(mainLayout);
|
||||
setWindowTitle(tr("Card search"));
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(optionsLayout);
|
||||
mainLayout->addLayout(buttonHBox);
|
||||
setLayout(mainLayout);
|
||||
setWindowTitle(tr("Card search"));
|
||||
}
|
||||
|
||||
QString DlgCardSearch::getCardName() const
|
||||
{
|
||||
return cardNameEdit->text();
|
||||
return cardNameEdit->text();
|
||||
}
|
||||
|
||||
QString DlgCardSearch::getCardText() const
|
||||
{
|
||||
return cardTextEdit->text();
|
||||
return cardTextEdit->text();
|
||||
}
|
||||
|
||||
QSet<QString> DlgCardSearch::getCardTypes() const
|
||||
{
|
||||
QStringList result;
|
||||
for (int i = 0; i < cardTypeCheckBoxes.size(); ++i)
|
||||
if (cardTypeCheckBoxes[i]->isChecked())
|
||||
result.append(cardTypeCheckBoxes[i]->text());
|
||||
return QSet<QString>::fromList(result);
|
||||
QStringList result;
|
||||
for (int i = 0; i < cardTypeCheckBoxes.size(); ++i)
|
||||
if (cardTypeCheckBoxes[i]->isChecked())
|
||||
result.append(cardTypeCheckBoxes[i]->text());
|
||||
return QSet<QString>::fromList(result);
|
||||
}
|
||||
|
||||
QSet<QString> DlgCardSearch::getCardColors() const
|
||||
{
|
||||
QStringList result;
|
||||
for (int i = 0; i < cardColorCheckBoxes.size(); ++i)
|
||||
if (cardColorCheckBoxes[i]->isChecked())
|
||||
result.append(cardColorCheckBoxes[i]->text());
|
||||
return QSet<QString>::fromList(result);
|
||||
QStringList result;
|
||||
for (int i = 0; i < cardColorCheckBoxes.size(); ++i)
|
||||
if (cardColorCheckBoxes[i]->isChecked())
|
||||
result.append(cardColorCheckBoxes[i]->text());
|
||||
return QSet<QString>::fromList(result);
|
||||
}
|
||||
|
|
|
@ -9,16 +9,16 @@ class QLineEdit;
|
|||
class QCheckBox;
|
||||
|
||||
class DlgCardSearch : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QLineEdit *cardNameEdit, *cardTextEdit;
|
||||
QList<QCheckBox *> cardTypeCheckBoxes, cardColorCheckBoxes;
|
||||
QLineEdit *cardNameEdit, *cardTextEdit;
|
||||
QList<QCheckBox *> cardTypeCheckBoxes, cardColorCheckBoxes;
|
||||
public:
|
||||
DlgCardSearch(QWidget *parent = 0);
|
||||
QString getCardName() const;
|
||||
QString getCardText() const;
|
||||
QSet<QString> getCardTypes() const;
|
||||
QSet<QString> getCardColors() const;
|
||||
DlgCardSearch(QWidget *parent = 0);
|
||||
QString getCardName() const;
|
||||
QString getCardText() const;
|
||||
QSet<QString> getCardTypes() const;
|
||||
QSet<QString> getCardColors() const;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -7,66 +7,66 @@
|
|||
#include "dlg_connect.h"
|
||||
|
||||
DlgConnect::DlgConnect(QWidget *parent)
|
||||
: QDialog(parent)
|
||||
: QDialog(parent)
|
||||
{
|
||||
QSettings settings;
|
||||
settings.beginGroup("server");
|
||||
QSettings settings;
|
||||
settings.beginGroup("server");
|
||||
|
||||
hostLabel = new QLabel(tr("&Host:"));
|
||||
hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString());
|
||||
hostLabel->setBuddy(hostEdit);
|
||||
hostLabel = new QLabel(tr("&Host:"));
|
||||
hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString());
|
||||
hostLabel->setBuddy(hostEdit);
|
||||
|
||||
portLabel = new QLabel(tr("&Port:"));
|
||||
portEdit = new QLineEdit(settings.value("port", "4747").toString());
|
||||
portLabel->setBuddy(portEdit);
|
||||
portLabel = new QLabel(tr("&Port:"));
|
||||
portEdit = new QLineEdit(settings.value("port", "4747").toString());
|
||||
portLabel->setBuddy(portEdit);
|
||||
|
||||
playernameLabel = new QLabel(tr("Player &name:"));
|
||||
playernameEdit = new QLineEdit(settings.value("playername", "Player").toString());
|
||||
playernameLabel->setBuddy(playernameEdit);
|
||||
playernameLabel = new QLabel(tr("Player &name:"));
|
||||
playernameEdit = new QLineEdit(settings.value("playername", "Player").toString());
|
||||
playernameLabel->setBuddy(playernameEdit);
|
||||
|
||||
passwordLabel = new QLabel(tr("P&assword:"));
|
||||
passwordEdit = new QLineEdit(settings.value("password").toString());
|
||||
passwordLabel->setBuddy(passwordEdit);
|
||||
passwordEdit->setEchoMode(QLineEdit::Password);
|
||||
passwordLabel = new QLabel(tr("P&assword:"));
|
||||
passwordEdit = new QLineEdit(settings.value("password").toString());
|
||||
passwordLabel->setBuddy(passwordEdit);
|
||||
passwordEdit->setEchoMode(QLineEdit::Password);
|
||||
|
||||
savePasswordCheckBox = new QCheckBox(tr("&Save password"));
|
||||
savePasswordCheckBox->setChecked(settings.value("save_password", 1).toInt());
|
||||
savePasswordCheckBox = new QCheckBox(tr("&Save password"));
|
||||
savePasswordCheckBox->setChecked(settings.value("save_password", 1).toInt());
|
||||
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addWidget(hostLabel, 0, 0);
|
||||
grid->addWidget(hostEdit, 0, 1);
|
||||
grid->addWidget(portLabel, 1, 0);
|
||||
grid->addWidget(portEdit, 1, 1);
|
||||
grid->addWidget(playernameLabel, 2, 0);
|
||||
grid->addWidget(playernameEdit, 2, 1);
|
||||
grid->addWidget(passwordLabel, 3, 0);
|
||||
grid->addWidget(passwordEdit, 3, 1);
|
||||
grid->addWidget(savePasswordCheckBox, 4, 0, 1, 2);
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addWidget(hostLabel, 0, 0);
|
||||
grid->addWidget(hostEdit, 0, 1);
|
||||
grid->addWidget(portLabel, 1, 0);
|
||||
grid->addWidget(portEdit, 1, 1);
|
||||
grid->addWidget(playernameLabel, 2, 0);
|
||||
grid->addWidget(playernameEdit, 2, 1);
|
||||
grid->addWidget(passwordLabel, 3, 0);
|
||||
grid->addWidget(passwordEdit, 3, 1);
|
||||
grid->addWidget(savePasswordCheckBox, 4, 0, 1, 2);
|
||||
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(grid);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
setLayout(mainLayout);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(grid);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
setLayout(mainLayout);
|
||||
|
||||
setWindowTitle(tr("Connect to server"));
|
||||
setFixedHeight(sizeHint().height());
|
||||
setMinimumWidth(300);
|
||||
setWindowTitle(tr("Connect to server"));
|
||||
setFixedHeight(sizeHint().height());
|
||||
setMinimumWidth(300);
|
||||
}
|
||||
|
||||
void DlgConnect::actOk()
|
||||
{
|
||||
QSettings settings;
|
||||
settings.beginGroup("server");
|
||||
settings.setValue("hostname", hostEdit->text());
|
||||
settings.setValue("port", portEdit->text());
|
||||
settings.setValue("playername", playernameEdit->text());
|
||||
settings.setValue("password", savePasswordCheckBox->isChecked() ? passwordEdit->text() : QString());
|
||||
settings.setValue("save_password", savePasswordCheckBox->isChecked() ? 1 : 0);
|
||||
settings.endGroup();
|
||||
QSettings settings;
|
||||
settings.beginGroup("server");
|
||||
settings.setValue("hostname", hostEdit->text());
|
||||
settings.setValue("port", portEdit->text());
|
||||
settings.setValue("playername", playernameEdit->text());
|
||||
settings.setValue("password", savePasswordCheckBox->isChecked() ? passwordEdit->text() : QString());
|
||||
settings.setValue("save_password", savePasswordCheckBox->isChecked() ? 1 : 0);
|
||||
settings.endGroup();
|
||||
|
||||
accept();
|
||||
accept();
|
||||
}
|
||||
|
|
|
@ -9,19 +9,19 @@ class QPushButton;
|
|||
class QCheckBox;
|
||||
|
||||
class DlgConnect : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
DlgConnect(QWidget *parent = 0);
|
||||
QString getHost() const { return hostEdit->text(); }
|
||||
int getPort() const { return portEdit->text().toInt(); }
|
||||
QString getPlayerName() const { return playernameEdit->text(); }
|
||||
QString getPassword() const { return passwordEdit->text(); }
|
||||
DlgConnect(QWidget *parent = 0);
|
||||
QString getHost() const { return hostEdit->text(); }
|
||||
int getPort() const { return portEdit->text().toInt(); }
|
||||
QString getPlayerName() const { return playernameEdit->text(); }
|
||||
QString getPassword() const { return passwordEdit->text(); }
|
||||
private slots:
|
||||
void actOk();
|
||||
void actOk();
|
||||
private:
|
||||
QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel;
|
||||
QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit;
|
||||
QCheckBox *savePasswordCheckBox;
|
||||
QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel;
|
||||
QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit;
|
||||
QCheckBox *savePasswordCheckBox;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -16,160 +16,160 @@
|
|||
#include "main.h"
|
||||
|
||||
DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent)
|
||||
: QDialog(parent), predefinedTokens(_predefinedTokens)
|
||||
: QDialog(parent), predefinedTokens(_predefinedTokens)
|
||||
{
|
||||
nameLabel = new QLabel(tr("&Name:"));
|
||||
nameEdit = new QLineEdit(tr("Token"));
|
||||
nameEdit->selectAll();
|
||||
nameLabel->setBuddy(nameEdit);
|
||||
nameLabel = new QLabel(tr("&Name:"));
|
||||
nameEdit = new QLineEdit(tr("Token"));
|
||||
nameEdit->selectAll();
|
||||
nameLabel->setBuddy(nameEdit);
|
||||
|
||||
colorLabel = new QLabel(tr("C&olor:"));
|
||||
colorEdit = new QComboBox;
|
||||
colorEdit->addItem(tr("white"), "w");
|
||||
colorEdit->addItem(tr("blue"), "u");
|
||||
colorEdit->addItem(tr("black"), "b");
|
||||
colorEdit->addItem(tr("red"), "r");
|
||||
colorEdit->addItem(tr("green"), "g");
|
||||
colorEdit->addItem(tr("multicolor"), "m");
|
||||
colorEdit->addItem(tr("colorless"), QString());
|
||||
colorLabel->setBuddy(colorEdit);
|
||||
colorLabel = new QLabel(tr("C&olor:"));
|
||||
colorEdit = new QComboBox;
|
||||
colorEdit->addItem(tr("white"), "w");
|
||||
colorEdit->addItem(tr("blue"), "u");
|
||||
colorEdit->addItem(tr("black"), "b");
|
||||
colorEdit->addItem(tr("red"), "r");
|
||||
colorEdit->addItem(tr("green"), "g");
|
||||
colorEdit->addItem(tr("multicolor"), "m");
|
||||
colorEdit->addItem(tr("colorless"), QString());
|
||||
colorLabel->setBuddy(colorEdit);
|
||||
|
||||
ptLabel = new QLabel(tr("&P/T:"));
|
||||
ptEdit = new QLineEdit;
|
||||
ptLabel->setBuddy(ptEdit);
|
||||
ptLabel = new QLabel(tr("&P/T:"));
|
||||
ptEdit = new QLineEdit;
|
||||
ptLabel->setBuddy(ptEdit);
|
||||
|
||||
annotationLabel = new QLabel(tr("&Annotation:"));
|
||||
annotationEdit = new QLineEdit;
|
||||
annotationLabel->setBuddy(annotationEdit);
|
||||
annotationLabel = new QLabel(tr("&Annotation:"));
|
||||
annotationEdit = new QLineEdit;
|
||||
annotationLabel->setBuddy(annotationEdit);
|
||||
|
||||
destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table"));
|
||||
destroyCheckBox->setChecked(true);
|
||||
destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table"));
|
||||
destroyCheckBox->setChecked(true);
|
||||
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addWidget(nameLabel, 0, 0);
|
||||
grid->addWidget(nameEdit, 0, 1);
|
||||
grid->addWidget(colorLabel, 1, 0);
|
||||
grid->addWidget(colorEdit, 1, 1);
|
||||
grid->addWidget(ptLabel, 2, 0);
|
||||
grid->addWidget(ptEdit, 2, 1);
|
||||
grid->addWidget(annotationLabel, 3, 0);
|
||||
grid->addWidget(annotationEdit, 3, 1);
|
||||
grid->addWidget(destroyCheckBox, 4, 0, 1, 2);
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addWidget(nameLabel, 0, 0);
|
||||
grid->addWidget(nameEdit, 0, 1);
|
||||
grid->addWidget(colorLabel, 1, 0);
|
||||
grid->addWidget(colorEdit, 1, 1);
|
||||
grid->addWidget(ptLabel, 2, 0);
|
||||
grid->addWidget(ptEdit, 2, 1);
|
||||
grid->addWidget(annotationLabel, 3, 0);
|
||||
grid->addWidget(annotationEdit, 3, 1);
|
||||
grid->addWidget(destroyCheckBox, 4, 0, 1, 2);
|
||||
|
||||
QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
|
||||
tokenDataGroupBox->setLayout(grid);
|
||||
QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
|
||||
tokenDataGroupBox->setLayout(grid);
|
||||
|
||||
cardDatabaseModel = new CardDatabaseModel(db, this);
|
||||
cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this);
|
||||
cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel);
|
||||
cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
|
||||
cardDatabaseModel = new CardDatabaseModel(db, this);
|
||||
cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this);
|
||||
cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel);
|
||||
cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
|
||||
|
||||
chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens"));
|
||||
connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool)));
|
||||
chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck"));
|
||||
connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool)));
|
||||
QTreeView *chooseTokenView = new QTreeView;
|
||||
chooseTokenView->setModel(cardDatabaseDisplayModel);
|
||||
chooseTokenView->setUniformRowHeights(true);
|
||||
chooseTokenView->setRootIsDecorated(false);
|
||||
chooseTokenView->setAlternatingRowColors(true);
|
||||
chooseTokenView->setSortingEnabled(true);
|
||||
chooseTokenView->sortByColumn(0, Qt::AscendingOrder);
|
||||
chooseTokenView->resizeColumnToContents(0);
|
||||
chooseTokenView->header()->setStretchLastSection(false);
|
||||
chooseTokenView->header()->hideSection(1);
|
||||
chooseTokenView->header()->hideSection(2);
|
||||
chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents);
|
||||
chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents);
|
||||
connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
|
||||
chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens"));
|
||||
connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool)));
|
||||
chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck"));
|
||||
connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool)));
|
||||
QTreeView *chooseTokenView = new QTreeView;
|
||||
chooseTokenView->setModel(cardDatabaseDisplayModel);
|
||||
chooseTokenView->setUniformRowHeights(true);
|
||||
chooseTokenView->setRootIsDecorated(false);
|
||||
chooseTokenView->setAlternatingRowColors(true);
|
||||
chooseTokenView->setSortingEnabled(true);
|
||||
chooseTokenView->sortByColumn(0, Qt::AscendingOrder);
|
||||
chooseTokenView->resizeColumnToContents(0);
|
||||
chooseTokenView->header()->setStretchLastSection(false);
|
||||
chooseTokenView->header()->hideSection(1);
|
||||
chooseTokenView->header()->hideSection(2);
|
||||
chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents);
|
||||
chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents);
|
||||
connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
|
||||
|
||||
if (predefinedTokens.isEmpty())
|
||||
chooseTokenFromAllRadioButton->setChecked(true);
|
||||
else {
|
||||
chooseTokenFromDeckRadioButton->setChecked(true);
|
||||
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens));
|
||||
}
|
||||
if (predefinedTokens.isEmpty())
|
||||
chooseTokenFromAllRadioButton->setChecked(true);
|
||||
else {
|
||||
chooseTokenFromDeckRadioButton->setChecked(true);
|
||||
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens));
|
||||
}
|
||||
|
||||
QVBoxLayout *tokenChooseLayout = new QVBoxLayout;
|
||||
tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton);
|
||||
tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton);
|
||||
tokenChooseLayout->addWidget(chooseTokenView);
|
||||
QVBoxLayout *tokenChooseLayout = new QVBoxLayout;
|
||||
tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton);
|
||||
tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton);
|
||||
tokenChooseLayout->addWidget(chooseTokenView);
|
||||
|
||||
QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list"));
|
||||
tokenChooseGroupBox->setLayout(tokenChooseLayout);
|
||||
QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list"));
|
||||
tokenChooseGroupBox->setLayout(tokenChooseLayout);
|
||||
|
||||
QVBoxLayout *leftVBox = new QVBoxLayout;
|
||||
leftVBox->addWidget(tokenDataGroupBox);
|
||||
leftVBox->addStretch();
|
||||
QVBoxLayout *leftVBox = new QVBoxLayout;
|
||||
leftVBox->addWidget(tokenDataGroupBox);
|
||||
leftVBox->addStretch();
|
||||
|
||||
QHBoxLayout *hbox = new QHBoxLayout;
|
||||
hbox->addLayout(leftVBox);
|
||||
hbox->addWidget(tokenChooseGroupBox);
|
||||
QHBoxLayout *hbox = new QHBoxLayout;
|
||||
hbox->addLayout(leftVBox);
|
||||
hbox->addWidget(tokenChooseGroupBox);
|
||||
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(hbox);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
setLayout(mainLayout);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(hbox);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
setLayout(mainLayout);
|
||||
|
||||
setWindowTitle(tr("Create token"));
|
||||
setFixedHeight(sizeHint().height());
|
||||
setMinimumWidth(300);
|
||||
setWindowTitle(tr("Create token"));
|
||||
setFixedHeight(sizeHint().height());
|
||||
setMinimumWidth(300);
|
||||
}
|
||||
|
||||
void DlgCreateToken::tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/)
|
||||
{
|
||||
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
|
||||
const CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : db->getCard();
|
||||
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
|
||||
const CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : db->getCard();
|
||||
|
||||
nameEdit->setText(cardInfo->getName());
|
||||
const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first());
|
||||
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
|
||||
ptEdit->setText(cardInfo->getPowTough());
|
||||
annotationEdit->setText(cardInfo->getText());
|
||||
nameEdit->setText(cardInfo->getName());
|
||||
const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first());
|
||||
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
|
||||
ptEdit->setText(cardInfo->getPowTough());
|
||||
annotationEdit->setText(cardInfo->getText());
|
||||
}
|
||||
|
||||
void DlgCreateToken::actChooseTokenFromAll(bool checked)
|
||||
{
|
||||
if (checked)
|
||||
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>());
|
||||
if (checked)
|
||||
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>());
|
||||
}
|
||||
|
||||
void DlgCreateToken::actChooseTokenFromDeck(bool checked)
|
||||
{
|
||||
if (checked)
|
||||
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens));
|
||||
if (checked)
|
||||
cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens));
|
||||
}
|
||||
|
||||
void DlgCreateToken::actOk()
|
||||
{
|
||||
accept();
|
||||
accept();
|
||||
}
|
||||
|
||||
QString DlgCreateToken::getName() const
|
||||
{
|
||||
return nameEdit->text();
|
||||
return nameEdit->text();
|
||||
}
|
||||
|
||||
QString DlgCreateToken::getColor() const
|
||||
{
|
||||
return colorEdit->itemData(colorEdit->currentIndex()).toString();
|
||||
return colorEdit->itemData(colorEdit->currentIndex()).toString();
|
||||
}
|
||||
|
||||
QString DlgCreateToken::getPT() const
|
||||
{
|
||||
return ptEdit->text();
|
||||
return ptEdit->text();
|
||||
}
|
||||
|
||||
QString DlgCreateToken::getAnnotation() const
|
||||
{
|
||||
return annotationEdit->text();
|
||||
return annotationEdit->text();
|
||||
}
|
||||
|
||||
bool DlgCreateToken::getDestroy() const
|
||||
{
|
||||
return destroyCheckBox->isChecked();
|
||||
return destroyCheckBox->isChecked();
|
||||
}
|
||||
|
|
|
@ -15,28 +15,28 @@ class CardDatabaseModel;
|
|||
class CardDatabaseDisplayModel;
|
||||
|
||||
class DlgCreateToken : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0);
|
||||
QString getName() const;
|
||||
QString getColor() const;
|
||||
QString getPT() const;
|
||||
QString getAnnotation() const;
|
||||
bool getDestroy() const;
|
||||
DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0);
|
||||
QString getName() const;
|
||||
QString getColor() const;
|
||||
QString getPT() const;
|
||||
QString getAnnotation() const;
|
||||
bool getDestroy() const;
|
||||
private slots:
|
||||
void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous);
|
||||
void actChooseTokenFromAll(bool checked);
|
||||
void actChooseTokenFromDeck(bool checked);
|
||||
void actOk();
|
||||
void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous);
|
||||
void actChooseTokenFromAll(bool checked);
|
||||
void actChooseTokenFromDeck(bool checked);
|
||||
void actOk();
|
||||
private:
|
||||
CardDatabaseModel *cardDatabaseModel;
|
||||
CardDatabaseDisplayModel *cardDatabaseDisplayModel;
|
||||
QStringList predefinedTokens;
|
||||
QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel;
|
||||
QComboBox *colorEdit;
|
||||
QLineEdit *nameEdit, *ptEdit, *annotationEdit;
|
||||
QCheckBox *destroyCheckBox;
|
||||
QRadioButton *chooseTokenFromAllRadioButton, *chooseTokenFromDeckRadioButton;
|
||||
CardDatabaseModel *cardDatabaseModel;
|
||||
CardDatabaseDisplayModel *cardDatabaseDisplayModel;
|
||||
QStringList predefinedTokens;
|
||||
QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel;
|
||||
QComboBox *colorEdit;
|
||||
QLineEdit *nameEdit, *ptEdit, *annotationEdit;
|
||||
QCheckBox *destroyCheckBox;
|
||||
QRadioButton *chooseTokenFromAllRadioButton, *chooseTokenFromDeckRadioButton;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -20,180 +20,180 @@
|
|||
|
||||
void DlgCreateGame::sharedCtor()
|
||||
{
|
||||
descriptionLabel = new QLabel(tr("&Description:"));
|
||||
descriptionEdit = new QLineEdit;
|
||||
descriptionLabel->setBuddy(descriptionEdit);
|
||||
descriptionEdit->setMaxLength(60);
|
||||
descriptionLabel = new QLabel(tr("&Description:"));
|
||||
descriptionEdit = new QLineEdit;
|
||||
descriptionLabel->setBuddy(descriptionEdit);
|
||||
descriptionEdit->setMaxLength(60);
|
||||
|
||||
maxPlayersLabel = new QLabel(tr("P&layers:"));
|
||||
maxPlayersEdit = new QSpinBox();
|
||||
maxPlayersEdit->setMinimum(1);
|
||||
maxPlayersEdit->setMaximum(100);
|
||||
maxPlayersEdit->setValue(2);
|
||||
maxPlayersLabel->setBuddy(maxPlayersEdit);
|
||||
maxPlayersLabel = new QLabel(tr("P&layers:"));
|
||||
maxPlayersEdit = new QSpinBox();
|
||||
maxPlayersEdit->setMinimum(1);
|
||||
maxPlayersEdit->setMaximum(100);
|
||||
maxPlayersEdit->setValue(2);
|
||||
maxPlayersLabel->setBuddy(maxPlayersEdit);
|
||||
|
||||
QGridLayout *generalGrid = new QGridLayout;
|
||||
generalGrid->addWidget(descriptionLabel, 0, 0);
|
||||
generalGrid->addWidget(descriptionEdit, 0, 1);
|
||||
generalGrid->addWidget(maxPlayersLabel, 1, 0);
|
||||
generalGrid->addWidget(maxPlayersEdit, 1, 1);
|
||||
QGridLayout *generalGrid = new QGridLayout;
|
||||
generalGrid->addWidget(descriptionLabel, 0, 0);
|
||||
generalGrid->addWidget(descriptionEdit, 0, 1);
|
||||
generalGrid->addWidget(maxPlayersLabel, 1, 0);
|
||||
generalGrid->addWidget(maxPlayersEdit, 1, 1);
|
||||
|
||||
QVBoxLayout *gameTypeLayout = new QVBoxLayout;
|
||||
QMapIterator<int, QString> gameTypeIterator(gameTypes);
|
||||
while (gameTypeIterator.hasNext()) {
|
||||
gameTypeIterator.next();
|
||||
QCheckBox *gameTypeCheckBox = new QCheckBox(gameTypeIterator.value());
|
||||
gameTypeLayout->addWidget(gameTypeCheckBox);
|
||||
gameTypeCheckBoxes.insert(gameTypeIterator.key(), gameTypeCheckBox);
|
||||
}
|
||||
QGroupBox *gameTypeGroupBox = new QGroupBox(tr("Game type"));
|
||||
gameTypeGroupBox->setLayout(gameTypeLayout);
|
||||
QVBoxLayout *gameTypeLayout = new QVBoxLayout;
|
||||
QMapIterator<int, QString> gameTypeIterator(gameTypes);
|
||||
while (gameTypeIterator.hasNext()) {
|
||||
gameTypeIterator.next();
|
||||
QCheckBox *gameTypeCheckBox = new QCheckBox(gameTypeIterator.value());
|
||||
gameTypeLayout->addWidget(gameTypeCheckBox);
|
||||
gameTypeCheckBoxes.insert(gameTypeIterator.key(), gameTypeCheckBox);
|
||||
}
|
||||
QGroupBox *gameTypeGroupBox = new QGroupBox(tr("Game type"));
|
||||
gameTypeGroupBox->setLayout(gameTypeLayout);
|
||||
|
||||
passwordLabel = new QLabel(tr("&Password:"));
|
||||
passwordEdit = new QLineEdit;
|
||||
passwordLabel->setBuddy(passwordEdit);
|
||||
passwordLabel = new QLabel(tr("&Password:"));
|
||||
passwordEdit = new QLineEdit;
|
||||
passwordLabel->setBuddy(passwordEdit);
|
||||
|
||||
onlyBuddiesCheckBox = new QCheckBox(tr("Only &buddies can join"));
|
||||
onlyRegisteredCheckBox = new QCheckBox(tr("Only ®istered users can join"));
|
||||
if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsRegistered)
|
||||
onlyRegisteredCheckBox->setChecked(true);
|
||||
onlyBuddiesCheckBox = new QCheckBox(tr("Only &buddies can join"));
|
||||
onlyRegisteredCheckBox = new QCheckBox(tr("Only ®istered users can join"));
|
||||
if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsRegistered)
|
||||
onlyRegisteredCheckBox->setChecked(true);
|
||||
|
||||
QGridLayout *joinRestrictionsLayout = new QGridLayout;
|
||||
joinRestrictionsLayout->addWidget(passwordLabel, 0, 0);
|
||||
joinRestrictionsLayout->addWidget(passwordEdit, 0, 1);
|
||||
joinRestrictionsLayout->addWidget(onlyBuddiesCheckBox, 1, 0, 1, 2);
|
||||
joinRestrictionsLayout->addWidget(onlyRegisteredCheckBox, 2, 0, 1, 2);
|
||||
QGridLayout *joinRestrictionsLayout = new QGridLayout;
|
||||
joinRestrictionsLayout->addWidget(passwordLabel, 0, 0);
|
||||
joinRestrictionsLayout->addWidget(passwordEdit, 0, 1);
|
||||
joinRestrictionsLayout->addWidget(onlyBuddiesCheckBox, 1, 0, 1, 2);
|
||||
joinRestrictionsLayout->addWidget(onlyRegisteredCheckBox, 2, 0, 1, 2);
|
||||
|
||||
QGroupBox *joinRestrictionsGroupBox = new QGroupBox(tr("Joining restrictions"));
|
||||
joinRestrictionsGroupBox->setLayout(joinRestrictionsLayout);
|
||||
QGroupBox *joinRestrictionsGroupBox = new QGroupBox(tr("Joining restrictions"));
|
||||
joinRestrictionsGroupBox->setLayout(joinRestrictionsLayout);
|
||||
|
||||
spectatorsAllowedCheckBox = new QCheckBox(tr("&Spectators allowed"));
|
||||
spectatorsAllowedCheckBox->setChecked(true);
|
||||
connect(spectatorsAllowedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(spectatorsAllowedChanged(int)));
|
||||
spectatorsNeedPasswordCheckBox = new QCheckBox(tr("Spectators &need a password to join"));
|
||||
spectatorsCanTalkCheckBox = new QCheckBox(tr("Spectators can &chat"));
|
||||
spectatorsSeeEverythingCheckBox = new QCheckBox(tr("Spectators see &everything"));
|
||||
QVBoxLayout *spectatorsLayout = new QVBoxLayout;
|
||||
spectatorsLayout->addWidget(spectatorsAllowedCheckBox);
|
||||
spectatorsLayout->addWidget(spectatorsNeedPasswordCheckBox);
|
||||
spectatorsLayout->addWidget(spectatorsCanTalkCheckBox);
|
||||
spectatorsLayout->addWidget(spectatorsSeeEverythingCheckBox);
|
||||
spectatorsGroupBox = new QGroupBox(tr("Spectators"));
|
||||
spectatorsGroupBox->setLayout(spectatorsLayout);
|
||||
spectatorsAllowedCheckBox = new QCheckBox(tr("&Spectators allowed"));
|
||||
spectatorsAllowedCheckBox->setChecked(true);
|
||||
connect(spectatorsAllowedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(spectatorsAllowedChanged(int)));
|
||||
spectatorsNeedPasswordCheckBox = new QCheckBox(tr("Spectators &need a password to join"));
|
||||
spectatorsCanTalkCheckBox = new QCheckBox(tr("Spectators can &chat"));
|
||||
spectatorsSeeEverythingCheckBox = new QCheckBox(tr("Spectators see &everything"));
|
||||
QVBoxLayout *spectatorsLayout = new QVBoxLayout;
|
||||
spectatorsLayout->addWidget(spectatorsAllowedCheckBox);
|
||||
spectatorsLayout->addWidget(spectatorsNeedPasswordCheckBox);
|
||||
spectatorsLayout->addWidget(spectatorsCanTalkCheckBox);
|
||||
spectatorsLayout->addWidget(spectatorsSeeEverythingCheckBox);
|
||||
spectatorsGroupBox = new QGroupBox(tr("Spectators"));
|
||||
spectatorsGroupBox->setLayout(spectatorsLayout);
|
||||
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addLayout(generalGrid, 0, 0);
|
||||
grid->addWidget(spectatorsGroupBox, 1, 0);
|
||||
grid->addWidget(joinRestrictionsGroupBox, 0, 1);
|
||||
grid->addWidget(gameTypeGroupBox, 1, 1);
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addLayout(generalGrid, 0, 0);
|
||||
grid->addWidget(spectatorsGroupBox, 1, 0);
|
||||
grid->addWidget(joinRestrictionsGroupBox, 0, 1);
|
||||
grid->addWidget(gameTypeGroupBox, 1, 1);
|
||||
|
||||
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok);
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok);
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(grid);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(grid);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
|
||||
setLayout(mainLayout);
|
||||
setLayout(mainLayout);
|
||||
|
||||
setFixedHeight(sizeHint().height());
|
||||
setFixedHeight(sizeHint().height());
|
||||
}
|
||||
|
||||
DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent)
|
||||
: QDialog(parent), room(_room), gameTypes(_gameTypes)
|
||||
: QDialog(parent), room(_room), gameTypes(_gameTypes)
|
||||
{
|
||||
sharedCtor();
|
||||
sharedCtor();
|
||||
|
||||
buttonBox->addButton(QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK()));
|
||||
buttonBox->addButton(QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK()));
|
||||
|
||||
setWindowTitle(tr("Create game"));
|
||||
setWindowTitle(tr("Create game"));
|
||||
}
|
||||
|
||||
DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QString> &_gameTypes, QWidget *parent)
|
||||
: QDialog(parent), room(0), gameTypes(_gameTypes)
|
||||
: QDialog(parent), room(0), gameTypes(_gameTypes)
|
||||
{
|
||||
sharedCtor();
|
||||
sharedCtor();
|
||||
|
||||
descriptionEdit->setEnabled(false);
|
||||
maxPlayersEdit->setEnabled(false);
|
||||
passwordEdit->setEnabled(false);
|
||||
onlyBuddiesCheckBox->setEnabled(false);
|
||||
onlyRegisteredCheckBox->setEnabled(false);
|
||||
spectatorsAllowedCheckBox->setEnabled(false);
|
||||
spectatorsNeedPasswordCheckBox->setEnabled(false);
|
||||
spectatorsCanTalkCheckBox->setEnabled(false);
|
||||
spectatorsSeeEverythingCheckBox->setEnabled(false);
|
||||
descriptionEdit->setEnabled(false);
|
||||
maxPlayersEdit->setEnabled(false);
|
||||
passwordEdit->setEnabled(false);
|
||||
onlyBuddiesCheckBox->setEnabled(false);
|
||||
onlyRegisteredCheckBox->setEnabled(false);
|
||||
spectatorsAllowedCheckBox->setEnabled(false);
|
||||
spectatorsNeedPasswordCheckBox->setEnabled(false);
|
||||
spectatorsCanTalkCheckBox->setEnabled(false);
|
||||
spectatorsSeeEverythingCheckBox->setEnabled(false);
|
||||
|
||||
descriptionEdit->setText(QString::fromStdString(gameInfo.description()));
|
||||
maxPlayersEdit->setValue(gameInfo.max_players());
|
||||
onlyBuddiesCheckBox->setChecked(gameInfo.only_buddies());
|
||||
onlyRegisteredCheckBox->setChecked(gameInfo.only_registered());
|
||||
spectatorsAllowedCheckBox->setChecked(gameInfo.spectators_allowed());
|
||||
spectatorsNeedPasswordCheckBox->setChecked(gameInfo.spectators_need_password());
|
||||
spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat());
|
||||
spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient());
|
||||
descriptionEdit->setText(QString::fromStdString(gameInfo.description()));
|
||||
maxPlayersEdit->setValue(gameInfo.max_players());
|
||||
onlyBuddiesCheckBox->setChecked(gameInfo.only_buddies());
|
||||
onlyRegisteredCheckBox->setChecked(gameInfo.only_registered());
|
||||
spectatorsAllowedCheckBox->setChecked(gameInfo.spectators_allowed());
|
||||
spectatorsNeedPasswordCheckBox->setChecked(gameInfo.spectators_need_password());
|
||||
spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat());
|
||||
spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient());
|
||||
|
||||
QSet<int> types;
|
||||
for (int i = 0; i < gameInfo.game_types_size(); ++i)
|
||||
types.insert(gameInfo.game_types(i));
|
||||
QSet<int> types;
|
||||
for (int i = 0; i < gameInfo.game_types_size(); ++i)
|
||||
types.insert(gameInfo.game_types(i));
|
||||
|
||||
QMapIterator<int, QString> gameTypeIterator(gameTypes);
|
||||
while (gameTypeIterator.hasNext()) {
|
||||
gameTypeIterator.next();
|
||||
QMapIterator<int, QString> gameTypeIterator(gameTypes);
|
||||
while (gameTypeIterator.hasNext()) {
|
||||
gameTypeIterator.next();
|
||||
|
||||
QCheckBox *gameTypeCheckBox = gameTypeCheckBoxes.value(gameTypeIterator.key());
|
||||
gameTypeCheckBox->setEnabled(false);
|
||||
gameTypeCheckBox->setChecked(types.contains(gameTypeIterator.key()));
|
||||
}
|
||||
QCheckBox *gameTypeCheckBox = gameTypeCheckBoxes.value(gameTypeIterator.key());
|
||||
gameTypeCheckBox->setEnabled(false);
|
||||
gameTypeCheckBox->setChecked(types.contains(gameTypeIterator.key()));
|
||||
}
|
||||
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
|
||||
setWindowTitle(tr("Game information"));
|
||||
setWindowTitle(tr("Game information"));
|
||||
}
|
||||
|
||||
void DlgCreateGame::actOK()
|
||||
{
|
||||
Command_CreateGame cmd;
|
||||
cmd.set_description(descriptionEdit->text().toStdString());
|
||||
cmd.set_password(passwordEdit->text().toStdString());
|
||||
cmd.set_max_players(maxPlayersEdit->value());
|
||||
cmd.set_only_buddies(onlyBuddiesCheckBox->isChecked());
|
||||
cmd.set_only_registered(onlyRegisteredCheckBox->isChecked());
|
||||
cmd.set_spectators_allowed(spectatorsAllowedCheckBox->isChecked());
|
||||
cmd.set_spectators_need_password(spectatorsNeedPasswordCheckBox->isChecked());
|
||||
cmd.set_spectators_can_talk(spectatorsCanTalkCheckBox->isChecked());
|
||||
cmd.set_spectators_see_everything(spectatorsSeeEverythingCheckBox->isChecked());
|
||||
Command_CreateGame cmd;
|
||||
cmd.set_description(descriptionEdit->text().toStdString());
|
||||
cmd.set_password(passwordEdit->text().toStdString());
|
||||
cmd.set_max_players(maxPlayersEdit->value());
|
||||
cmd.set_only_buddies(onlyBuddiesCheckBox->isChecked());
|
||||
cmd.set_only_registered(onlyRegisteredCheckBox->isChecked());
|
||||
cmd.set_spectators_allowed(spectatorsAllowedCheckBox->isChecked());
|
||||
cmd.set_spectators_need_password(spectatorsNeedPasswordCheckBox->isChecked());
|
||||
cmd.set_spectators_can_talk(spectatorsCanTalkCheckBox->isChecked());
|
||||
cmd.set_spectators_see_everything(spectatorsSeeEverythingCheckBox->isChecked());
|
||||
|
||||
QMapIterator<int, QCheckBox *> gameTypeCheckBoxIterator(gameTypeCheckBoxes);
|
||||
while (gameTypeCheckBoxIterator.hasNext()) {
|
||||
gameTypeCheckBoxIterator.next();
|
||||
if (gameTypeCheckBoxIterator.value()->isChecked())
|
||||
cmd.add_game_type_ids(gameTypeCheckBoxIterator.key());
|
||||
}
|
||||
QMapIterator<int, QCheckBox *> gameTypeCheckBoxIterator(gameTypeCheckBoxes);
|
||||
while (gameTypeCheckBoxIterator.hasNext()) {
|
||||
gameTypeCheckBoxIterator.next();
|
||||
if (gameTypeCheckBoxIterator.value()->isChecked())
|
||||
cmd.add_game_type_ids(gameTypeCheckBoxIterator.key());
|
||||
}
|
||||
|
||||
PendingCommand *pend = room->prepareRoomCommand(cmd);
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response)));
|
||||
room->sendRoomCommand(pend);
|
||||
PendingCommand *pend = room->prepareRoomCommand(cmd);
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response)));
|
||||
room->sendRoomCommand(pend);
|
||||
|
||||
buttonBox->setEnabled(false);
|
||||
buttonBox->setEnabled(false);
|
||||
}
|
||||
|
||||
void DlgCreateGame::checkResponse(const Response &response)
|
||||
{
|
||||
buttonBox->setEnabled(true);
|
||||
buttonBox->setEnabled(true);
|
||||
|
||||
if (response.response_code() == Response::RespOk)
|
||||
accept();
|
||||
else {
|
||||
QMessageBox::critical(this, tr("Error"), tr("Server error."));
|
||||
return;
|
||||
}
|
||||
if (response.response_code() == Response::RespOk)
|
||||
accept();
|
||||
else {
|
||||
QMessageBox::critical(this, tr("Error"), tr("Server error."));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void DlgCreateGame::spectatorsAllowedChanged(int state)
|
||||
{
|
||||
spectatorsNeedPasswordCheckBox->setEnabled(state);
|
||||
spectatorsCanTalkCheckBox->setEnabled(state);
|
||||
spectatorsSeeEverythingCheckBox->setEnabled(state);
|
||||
spectatorsNeedPasswordCheckBox->setEnabled(state);
|
||||
spectatorsCanTalkCheckBox->setEnabled(state);
|
||||
spectatorsSeeEverythingCheckBox->setEnabled(state);
|
||||
}
|
||||
|
|
|
@ -17,28 +17,28 @@ class Response;
|
|||
class ServerInfo_Game;
|
||||
|
||||
class DlgCreateGame : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent = 0);
|
||||
DlgCreateGame(const ServerInfo_Game &game, const QMap<int, QString> &_gameTypes, QWidget *parent = 0);
|
||||
DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameTypes, QWidget *parent = 0);
|
||||
DlgCreateGame(const ServerInfo_Game &game, const QMap<int, QString> &_gameTypes, QWidget *parent = 0);
|
||||
private slots:
|
||||
void actOK();
|
||||
void checkResponse(const Response &response);
|
||||
void spectatorsAllowedChanged(int state);
|
||||
void actOK();
|
||||
void checkResponse(const Response &response);
|
||||
void spectatorsAllowedChanged(int state);
|
||||
private:
|
||||
TabRoom *room;
|
||||
QMap<int, QString> gameTypes;
|
||||
QMap<int, QCheckBox *> gameTypeCheckBoxes;
|
||||
TabRoom *room;
|
||||
QMap<int, QString> gameTypes;
|
||||
QMap<int, QCheckBox *> gameTypeCheckBoxes;
|
||||
|
||||
QGroupBox *spectatorsGroupBox;
|
||||
QLabel *descriptionLabel, *passwordLabel, *maxPlayersLabel;
|
||||
QLineEdit *descriptionEdit, *passwordEdit;
|
||||
QSpinBox *maxPlayersEdit;
|
||||
QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox;
|
||||
QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox;
|
||||
QDialogButtonBox *buttonBox;
|
||||
QGroupBox *spectatorsGroupBox;
|
||||
QLabel *descriptionLabel, *passwordLabel, *maxPlayersLabel;
|
||||
QLineEdit *descriptionEdit, *passwordEdit;
|
||||
QSpinBox *maxPlayersEdit;
|
||||
QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox;
|
||||
QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox;
|
||||
QDialogButtonBox *buttonBox;
|
||||
|
||||
void sharedCtor();
|
||||
void sharedCtor();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -16,160 +16,160 @@
|
|||
#include <QMessageBox>
|
||||
|
||||
DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent)
|
||||
: QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel)
|
||||
: QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel)
|
||||
{
|
||||
nameLabel = new QLabel(tr("&Name:"));
|
||||
nameEdit = new QLineEdit;
|
||||
nameEdit->setEnabled(false);
|
||||
nameLabel->setBuddy(nameEdit);
|
||||
nameLabel = new QLabel(tr("&Name:"));
|
||||
nameEdit = new QLineEdit;
|
||||
nameEdit->setEnabled(false);
|
||||
nameLabel->setBuddy(nameEdit);
|
||||
|
||||
colorLabel = new QLabel(tr("C&olor:"));
|
||||
colorEdit = new QComboBox;
|
||||
colorEdit->addItem(tr("white"), "w");
|
||||
colorEdit->addItem(tr("blue"), "u");
|
||||
colorEdit->addItem(tr("black"), "b");
|
||||
colorEdit->addItem(tr("red"), "r");
|
||||
colorEdit->addItem(tr("green"), "g");
|
||||
colorEdit->addItem(tr("multicolor"), "m");
|
||||
colorEdit->addItem(tr("colorless"), QString());
|
||||
colorLabel->setBuddy(colorEdit);
|
||||
connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int)));
|
||||
colorLabel = new QLabel(tr("C&olor:"));
|
||||
colorEdit = new QComboBox;
|
||||
colorEdit->addItem(tr("white"), "w");
|
||||
colorEdit->addItem(tr("blue"), "u");
|
||||
colorEdit->addItem(tr("black"), "b");
|
||||
colorEdit->addItem(tr("red"), "r");
|
||||
colorEdit->addItem(tr("green"), "g");
|
||||
colorEdit->addItem(tr("multicolor"), "m");
|
||||
colorEdit->addItem(tr("colorless"), QString());
|
||||
colorLabel->setBuddy(colorEdit);
|
||||
connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int)));
|
||||
|
||||
ptLabel = new QLabel(tr("&P/T:"));
|
||||
ptEdit = new QLineEdit;
|
||||
ptLabel->setBuddy(ptEdit);
|
||||
connect(ptEdit, SIGNAL(textChanged(QString)), this, SLOT(ptChanged(QString)));
|
||||
ptLabel = new QLabel(tr("&P/T:"));
|
||||
ptEdit = new QLineEdit;
|
||||
ptLabel->setBuddy(ptEdit);
|
||||
connect(ptEdit, SIGNAL(textChanged(QString)), this, SLOT(ptChanged(QString)));
|
||||
|
||||
annotationLabel = new QLabel(tr("&Annotation:"));
|
||||
annotationEdit = new QLineEdit;
|
||||
annotationLabel->setBuddy(annotationEdit);
|
||||
connect(annotationEdit, SIGNAL(textChanged(QString)), this, SLOT(annotationChanged(QString)));
|
||||
annotationLabel = new QLabel(tr("&Annotation:"));
|
||||
annotationEdit = new QLineEdit;
|
||||
annotationLabel->setBuddy(annotationEdit);
|
||||
connect(annotationEdit, SIGNAL(textChanged(QString)), this, SLOT(annotationChanged(QString)));
|
||||
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addWidget(nameLabel, 0, 0);
|
||||
grid->addWidget(nameEdit, 0, 1);
|
||||
grid->addWidget(colorLabel, 1, 0);
|
||||
grid->addWidget(colorEdit, 1, 1);
|
||||
grid->addWidget(ptLabel, 2, 0);
|
||||
grid->addWidget(ptEdit, 2, 1);
|
||||
grid->addWidget(annotationLabel, 3, 0);
|
||||
grid->addWidget(annotationEdit, 3, 1);
|
||||
QGridLayout *grid = new QGridLayout;
|
||||
grid->addWidget(nameLabel, 0, 0);
|
||||
grid->addWidget(nameEdit, 0, 1);
|
||||
grid->addWidget(colorLabel, 1, 0);
|
||||
grid->addWidget(colorEdit, 1, 1);
|
||||
grid->addWidget(ptLabel, 2, 0);
|
||||
grid->addWidget(ptEdit, 2, 1);
|
||||
grid->addWidget(annotationLabel, 3, 0);
|
||||
grid->addWidget(annotationEdit, 3, 1);
|
||||
|
||||
QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
|
||||
tokenDataGroupBox->setLayout(grid);
|
||||
QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
|
||||
tokenDataGroupBox->setLayout(grid);
|
||||
|
||||
cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this);
|
||||
cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel);
|
||||
cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
|
||||
cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this);
|
||||
cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel);
|
||||
cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
|
||||
|
||||
chooseTokenView = new QTreeView;
|
||||
chooseTokenView->setModel(cardDatabaseDisplayModel);
|
||||
chooseTokenView->setUniformRowHeights(true);
|
||||
chooseTokenView->setRootIsDecorated(false);
|
||||
chooseTokenView->setAlternatingRowColors(true);
|
||||
chooseTokenView->setSortingEnabled(true);
|
||||
chooseTokenView->sortByColumn(0, Qt::AscendingOrder);
|
||||
chooseTokenView->resizeColumnToContents(0);
|
||||
chooseTokenView->header()->setStretchLastSection(false);
|
||||
chooseTokenView->header()->hideSection(1);
|
||||
chooseTokenView->header()->hideSection(2);
|
||||
chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents);
|
||||
chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents);
|
||||
connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
|
||||
chooseTokenView = new QTreeView;
|
||||
chooseTokenView->setModel(cardDatabaseDisplayModel);
|
||||
chooseTokenView->setUniformRowHeights(true);
|
||||
chooseTokenView->setRootIsDecorated(false);
|
||||
chooseTokenView->setAlternatingRowColors(true);
|
||||
chooseTokenView->setSortingEnabled(true);
|
||||
chooseTokenView->sortByColumn(0, Qt::AscendingOrder);
|
||||
chooseTokenView->resizeColumnToContents(0);
|
||||
chooseTokenView->header()->setStretchLastSection(false);
|
||||
chooseTokenView->header()->hideSection(1);
|
||||
chooseTokenView->header()->hideSection(2);
|
||||
chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents);
|
||||
chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents);
|
||||
connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
|
||||
|
||||
QAction *aAddToken = new QAction(tr("Add token"), this);
|
||||
aAddToken->setIcon(QIcon(":/resources/increment.svg"));
|
||||
connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken()));
|
||||
QAction *aRemoveToken = new QAction(tr("Remove token"), this);
|
||||
aRemoveToken->setIcon(QIcon(":/resources/decrement.svg"));
|
||||
connect(aRemoveToken, SIGNAL(triggered()), this, SLOT(actRemoveToken()));
|
||||
QAction *aAddToken = new QAction(tr("Add token"), this);
|
||||
aAddToken->setIcon(QIcon(":/resources/increment.svg"));
|
||||
connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken()));
|
||||
QAction *aRemoveToken = new QAction(tr("Remove token"), this);
|
||||
aRemoveToken->setIcon(QIcon(":/resources/decrement.svg"));
|
||||
connect(aRemoveToken, SIGNAL(triggered()), this, SLOT(actRemoveToken()));
|
||||
|
||||
QToolBar *databaseToolBar = new QToolBar;
|
||||
databaseToolBar->addAction(aAddToken);
|
||||
databaseToolBar->addAction(aRemoveToken);
|
||||
QToolBar *databaseToolBar = new QToolBar;
|
||||
databaseToolBar->addAction(aAddToken);
|
||||
databaseToolBar->addAction(aRemoveToken);
|
||||
|
||||
QVBoxLayout *leftVBox = new QVBoxLayout;
|
||||
leftVBox->addWidget(chooseTokenView);
|
||||
leftVBox->addWidget(databaseToolBar);
|
||||
QVBoxLayout *leftVBox = new QVBoxLayout;
|
||||
leftVBox->addWidget(chooseTokenView);
|
||||
leftVBox->addWidget(databaseToolBar);
|
||||
|
||||
QHBoxLayout *hbox = new QHBoxLayout;
|
||||
hbox->addLayout(leftVBox);
|
||||
hbox->addWidget(tokenDataGroupBox);
|
||||
QHBoxLayout *hbox = new QHBoxLayout;
|
||||
hbox->addLayout(leftVBox);
|
||||
hbox->addWidget(tokenDataGroupBox);
|
||||
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(hbox);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(hbox);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
|
||||
setLayout(mainLayout);
|
||||
setWindowTitle(tr("Edit tokens"));
|
||||
setLayout(mainLayout);
|
||||
setWindowTitle(tr("Edit tokens"));
|
||||
}
|
||||
|
||||
void DlgEditTokens::tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous)
|
||||
{
|
||||
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
|
||||
CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard();
|
||||
if (!cardInfo->getName().isEmpty())
|
||||
currentCard = cardInfo;
|
||||
else
|
||||
currentCard = 0;
|
||||
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
|
||||
CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard();
|
||||
if (!cardInfo->getName().isEmpty())
|
||||
currentCard = cardInfo;
|
||||
else
|
||||
currentCard = 0;
|
||||
|
||||
nameEdit->setText(cardInfo->getName());
|
||||
const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first());
|
||||
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
|
||||
ptEdit->setText(cardInfo->getPowTough());
|
||||
annotationEdit->setText(cardInfo->getText());
|
||||
nameEdit->setText(cardInfo->getName());
|
||||
const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first());
|
||||
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
|
||||
ptEdit->setText(cardInfo->getPowTough());
|
||||
annotationEdit->setText(cardInfo->getText());
|
||||
}
|
||||
|
||||
void DlgEditTokens::actAddToken()
|
||||
{
|
||||
QString name;
|
||||
bool askAgain;
|
||||
do {
|
||||
name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:"));
|
||||
if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) {
|
||||
QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token."));
|
||||
askAgain = true;
|
||||
} else
|
||||
askAgain = false;
|
||||
} while (askAgain);
|
||||
QString name;
|
||||
bool askAgain;
|
||||
do {
|
||||
name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:"));
|
||||
if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) {
|
||||
QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token."));
|
||||
askAgain = true;
|
||||
} else
|
||||
askAgain = false;
|
||||
} while (askAgain);
|
||||
|
||||
if (name.isEmpty())
|
||||
return;
|
||||
if (name.isEmpty())
|
||||
return;
|
||||
|
||||
CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true);
|
||||
card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK"));
|
||||
card->setCardType("Token");
|
||||
cardDatabaseModel->getDatabase()->addCard(card);
|
||||
CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true);
|
||||
card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK"));
|
||||
card->setCardType("Token");
|
||||
cardDatabaseModel->getDatabase()->addCard(card);
|
||||
}
|
||||
|
||||
void DlgEditTokens::actRemoveToken()
|
||||
{
|
||||
if (currentCard) {
|
||||
CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard()
|
||||
currentCard = 0;
|
||||
cardDatabaseModel->getDatabase()->removeCard(cardToRemove);
|
||||
delete cardToRemove;
|
||||
}
|
||||
if (currentCard) {
|
||||
CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard()
|
||||
currentCard = 0;
|
||||
cardDatabaseModel->getDatabase()->removeCard(cardToRemove);
|
||||
delete cardToRemove;
|
||||
}
|
||||
}
|
||||
|
||||
void DlgEditTokens::colorChanged(int colorIndex)
|
||||
{
|
||||
if (currentCard)
|
||||
currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString());
|
||||
if (currentCard)
|
||||
currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString());
|
||||
}
|
||||
|
||||
void DlgEditTokens::ptChanged(const QString &_pt)
|
||||
{
|
||||
if (currentCard)
|
||||
currentCard->setPowTough(_pt);
|
||||
if (currentCard)
|
||||
currentCard->setPowTough(_pt);
|
||||
}
|
||||
|
||||
void DlgEditTokens::annotationChanged(const QString &_annotation)
|
||||
{
|
||||
if (currentCard)
|
||||
currentCard->setText(_annotation);
|
||||
if (currentCard)
|
||||
currentCard->setText(_annotation);
|
||||
}
|
||||
|
|
|
@ -13,26 +13,26 @@ class QTreeView;
|
|||
class CardInfo;
|
||||
|
||||
class DlgEditTokens : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous);
|
||||
void colorChanged(int _colorIndex);
|
||||
void ptChanged(const QString &_pt);
|
||||
void annotationChanged(const QString &_annotation);
|
||||
void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous);
|
||||
void colorChanged(int _colorIndex);
|
||||
void ptChanged(const QString &_pt);
|
||||
void annotationChanged(const QString &_annotation);
|
||||
|
||||
void actAddToken();
|
||||
void actRemoveToken();
|
||||
void actAddToken();
|
||||
void actRemoveToken();
|
||||
private:
|
||||
CardInfo *currentCard;
|
||||
CardDatabaseModel *cardDatabaseModel;
|
||||
CardDatabaseDisplayModel *cardDatabaseDisplayModel;
|
||||
QStringList predefinedTokens;
|
||||
QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel;
|
||||
QComboBox *colorEdit;
|
||||
QLineEdit *nameEdit, *ptEdit, *annotationEdit;
|
||||
QTreeView *chooseTokenView;
|
||||
CardInfo *currentCard;
|
||||
CardDatabaseModel *cardDatabaseModel;
|
||||
CardDatabaseDisplayModel *cardDatabaseDisplayModel;
|
||||
QStringList predefinedTokens;
|
||||
QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel;
|
||||
QComboBox *colorEdit;
|
||||
QLineEdit *nameEdit, *ptEdit, *annotationEdit;
|
||||
QTreeView *chooseTokenView;
|
||||
public:
|
||||
DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0);
|
||||
DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -11,162 +11,162 @@
|
|||
#include <QDialogButtonBox>
|
||||
|
||||
DlgFilterGames::DlgFilterGames(const QMap<int, QString> &allGameTypes, QWidget *parent)
|
||||
: QDialog(parent)
|
||||
: QDialog(parent)
|
||||
{
|
||||
unavailableGamesVisibleCheckBox = new QCheckBox(tr("Show &unavailable games"));
|
||||
passwordProtectedGamesVisibleCheckBox = new QCheckBox(tr("Show &password protected games"));
|
||||
unavailableGamesVisibleCheckBox = new QCheckBox(tr("Show &unavailable games"));
|
||||
passwordProtectedGamesVisibleCheckBox = new QCheckBox(tr("Show &password protected games"));
|
||||
|
||||
QLabel *gameNameFilterLabel = new QLabel(tr("Game &description:"));
|
||||
gameNameFilterEdit = new QLineEdit;
|
||||
gameNameFilterLabel->setBuddy(gameNameFilterEdit);
|
||||
QLabel *gameNameFilterLabel = new QLabel(tr("Game &description:"));
|
||||
gameNameFilterEdit = new QLineEdit;
|
||||
gameNameFilterLabel->setBuddy(gameNameFilterEdit);
|
||||
|
||||
QLabel *creatorNameFilterLabel = new QLabel(tr("&Creator name:"));
|
||||
creatorNameFilterEdit = new QLineEdit;
|
||||
creatorNameFilterLabel->setBuddy(creatorNameFilterEdit);
|
||||
QLabel *creatorNameFilterLabel = new QLabel(tr("&Creator name:"));
|
||||
creatorNameFilterEdit = new QLineEdit;
|
||||
creatorNameFilterLabel->setBuddy(creatorNameFilterEdit);
|
||||
|
||||
QVBoxLayout *gameTypeFilterLayout = new QVBoxLayout;
|
||||
QMapIterator<int, QString> gameTypesIterator(allGameTypes);
|
||||
while (gameTypesIterator.hasNext()) {
|
||||
gameTypesIterator.next();
|
||||
QCheckBox *temp = new QCheckBox(gameTypesIterator.value());
|
||||
gameTypeFilterCheckBoxes.insert(gameTypesIterator.key(), temp);
|
||||
gameTypeFilterLayout->addWidget(temp);
|
||||
}
|
||||
QGroupBox *gameTypeFilterGroupBox;
|
||||
if (!allGameTypes.isEmpty()) {
|
||||
gameTypeFilterGroupBox = new QGroupBox(tr("&Game types"));
|
||||
gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout);
|
||||
} else
|
||||
gameTypeFilterGroupBox = 0;
|
||||
QVBoxLayout *gameTypeFilterLayout = new QVBoxLayout;
|
||||
QMapIterator<int, QString> gameTypesIterator(allGameTypes);
|
||||
while (gameTypesIterator.hasNext()) {
|
||||
gameTypesIterator.next();
|
||||
QCheckBox *temp = new QCheckBox(gameTypesIterator.value());
|
||||
gameTypeFilterCheckBoxes.insert(gameTypesIterator.key(), temp);
|
||||
gameTypeFilterLayout->addWidget(temp);
|
||||
}
|
||||
QGroupBox *gameTypeFilterGroupBox;
|
||||
if (!allGameTypes.isEmpty()) {
|
||||
gameTypeFilterGroupBox = new QGroupBox(tr("&Game types"));
|
||||
gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout);
|
||||
} else
|
||||
gameTypeFilterGroupBox = 0;
|
||||
|
||||
QLabel *maxPlayersFilterMinLabel = new QLabel(tr("at &least:"));
|
||||
maxPlayersFilterMinSpinBox = new QSpinBox;
|
||||
maxPlayersFilterMinSpinBox->setMinimum(1);
|
||||
maxPlayersFilterMinSpinBox->setMaximum(99);
|
||||
maxPlayersFilterMinSpinBox->setValue(1);
|
||||
maxPlayersFilterMinLabel->setBuddy(maxPlayersFilterMinSpinBox);
|
||||
QLabel *maxPlayersFilterMinLabel = new QLabel(tr("at &least:"));
|
||||
maxPlayersFilterMinSpinBox = new QSpinBox;
|
||||
maxPlayersFilterMinSpinBox->setMinimum(1);
|
||||
maxPlayersFilterMinSpinBox->setMaximum(99);
|
||||
maxPlayersFilterMinSpinBox->setValue(1);
|
||||
maxPlayersFilterMinLabel->setBuddy(maxPlayersFilterMinSpinBox);
|
||||
|
||||
QLabel *maxPlayersFilterMaxLabel = new QLabel(tr("at &most:"));
|
||||
maxPlayersFilterMaxSpinBox = new QSpinBox;
|
||||
maxPlayersFilterMaxSpinBox->setMinimum(1);
|
||||
maxPlayersFilterMaxSpinBox->setMaximum(99);
|
||||
maxPlayersFilterMaxSpinBox->setValue(99);
|
||||
maxPlayersFilterMaxLabel->setBuddy(maxPlayersFilterMaxSpinBox);
|
||||
QLabel *maxPlayersFilterMaxLabel = new QLabel(tr("at &most:"));
|
||||
maxPlayersFilterMaxSpinBox = new QSpinBox;
|
||||
maxPlayersFilterMaxSpinBox->setMinimum(1);
|
||||
maxPlayersFilterMaxSpinBox->setMaximum(99);
|
||||
maxPlayersFilterMaxSpinBox->setValue(99);
|
||||
maxPlayersFilterMaxLabel->setBuddy(maxPlayersFilterMaxSpinBox);
|
||||
|
||||
QGridLayout *maxPlayersFilterLayout = new QGridLayout;
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMinLabel, 0, 0);
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMinSpinBox, 0, 1);
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxLabel, 1, 0);
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxSpinBox, 1, 1);
|
||||
QGridLayout *maxPlayersFilterLayout = new QGridLayout;
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMinLabel, 0, 0);
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMinSpinBox, 0, 1);
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxLabel, 1, 0);
|
||||
maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxSpinBox, 1, 1);
|
||||
|
||||
QGroupBox *maxPlayersGroupBox = new QGroupBox(tr("Maximum player count"));
|
||||
maxPlayersGroupBox->setLayout(maxPlayersFilterLayout);
|
||||
QGroupBox *maxPlayersGroupBox = new QGroupBox(tr("Maximum player count"));
|
||||
maxPlayersGroupBox->setLayout(maxPlayersFilterLayout);
|
||||
|
||||
QGridLayout *leftGrid = new QGridLayout;
|
||||
leftGrid->addWidget(gameNameFilterLabel, 0, 0);
|
||||
leftGrid->addWidget(gameNameFilterEdit, 0, 1);
|
||||
leftGrid->addWidget(creatorNameFilterLabel, 1, 0);
|
||||
leftGrid->addWidget(creatorNameFilterEdit, 1, 1);
|
||||
leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2);
|
||||
leftGrid->addWidget(unavailableGamesVisibleCheckBox, 3, 0, 1, 2);
|
||||
leftGrid->addWidget(passwordProtectedGamesVisibleCheckBox, 4, 0, 1, 2);
|
||||
QGridLayout *leftGrid = new QGridLayout;
|
||||
leftGrid->addWidget(gameNameFilterLabel, 0, 0);
|
||||
leftGrid->addWidget(gameNameFilterEdit, 0, 1);
|
||||
leftGrid->addWidget(creatorNameFilterLabel, 1, 0);
|
||||
leftGrid->addWidget(creatorNameFilterEdit, 1, 1);
|
||||
leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2);
|
||||
leftGrid->addWidget(unavailableGamesVisibleCheckBox, 3, 0, 1, 2);
|
||||
leftGrid->addWidget(passwordProtectedGamesVisibleCheckBox, 4, 0, 1, 2);
|
||||
|
||||
QVBoxLayout *leftColumn = new QVBoxLayout;
|
||||
leftColumn->addLayout(leftGrid);
|
||||
leftColumn->addStretch();
|
||||
QVBoxLayout *leftColumn = new QVBoxLayout;
|
||||
leftColumn->addLayout(leftGrid);
|
||||
leftColumn->addStretch();
|
||||
|
||||
QVBoxLayout *rightColumn = new QVBoxLayout;
|
||||
rightColumn->addWidget(gameTypeFilterGroupBox);
|
||||
QVBoxLayout *rightColumn = new QVBoxLayout;
|
||||
rightColumn->addWidget(gameTypeFilterGroupBox);
|
||||
|
||||
QHBoxLayout *hbox = new QHBoxLayout;
|
||||
hbox->addLayout(leftColumn);
|
||||
hbox->addLayout(rightColumn);
|
||||
QHBoxLayout *hbox = new QHBoxLayout;
|
||||
hbox->addLayout(leftColumn);
|
||||
hbox->addLayout(rightColumn);
|
||||
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(hbox);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addLayout(hbox);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
|
||||
setLayout(mainLayout);
|
||||
setWindowTitle(tr("Filter games"));
|
||||
setLayout(mainLayout);
|
||||
setWindowTitle(tr("Filter games"));
|
||||
}
|
||||
|
||||
bool DlgFilterGames::getUnavailableGamesVisible() const
|
||||
{
|
||||
return unavailableGamesVisibleCheckBox->isChecked();
|
||||
return unavailableGamesVisibleCheckBox->isChecked();
|
||||
}
|
||||
|
||||
void DlgFilterGames::setUnavailableGamesVisible(bool _unavailableGamesVisible)
|
||||
{
|
||||
unavailableGamesVisibleCheckBox->setChecked(_unavailableGamesVisible);
|
||||
unavailableGamesVisibleCheckBox->setChecked(_unavailableGamesVisible);
|
||||
}
|
||||
|
||||
bool DlgFilterGames::getPasswordProtectedGamesVisible() const
|
||||
{
|
||||
return passwordProtectedGamesVisibleCheckBox->isChecked();
|
||||
return passwordProtectedGamesVisibleCheckBox->isChecked();
|
||||
}
|
||||
|
||||
void DlgFilterGames::setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible)
|
||||
{
|
||||
passwordProtectedGamesVisibleCheckBox->setChecked(_passwordProtectedGamesVisible);
|
||||
passwordProtectedGamesVisibleCheckBox->setChecked(_passwordProtectedGamesVisible);
|
||||
}
|
||||
|
||||
QString DlgFilterGames::getGameNameFilter() const
|
||||
{
|
||||
return gameNameFilterEdit->text();
|
||||
return gameNameFilterEdit->text();
|
||||
}
|
||||
|
||||
void DlgFilterGames::setGameNameFilter(const QString &_gameNameFilter)
|
||||
{
|
||||
gameNameFilterEdit->setText(_gameNameFilter);
|
||||
gameNameFilterEdit->setText(_gameNameFilter);
|
||||
}
|
||||
|
||||
QString DlgFilterGames::getCreatorNameFilter() const
|
||||
{
|
||||
return creatorNameFilterEdit->text();
|
||||
return creatorNameFilterEdit->text();
|
||||
}
|
||||
|
||||
void DlgFilterGames::setCreatorNameFilter(const QString &_creatorNameFilter)
|
||||
{
|
||||
creatorNameFilterEdit->setText(_creatorNameFilter);
|
||||
creatorNameFilterEdit->setText(_creatorNameFilter);
|
||||
}
|
||||
|
||||
QSet<int> DlgFilterGames::getGameTypeFilter() const
|
||||
{
|
||||
QSet<int> result;
|
||||
QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
if (i.value()->isChecked())
|
||||
result.insert(i.key());
|
||||
}
|
||||
return result;
|
||||
QSet<int> result;
|
||||
QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
if (i.value()->isChecked())
|
||||
result.insert(i.key());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void DlgFilterGames::setGameTypeFilter(const QSet<int> &_gameTypeFilter)
|
||||
{
|
||||
QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
i.value()->setChecked(_gameTypeFilter.contains(i.key()));
|
||||
}
|
||||
QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
i.value()->setChecked(_gameTypeFilter.contains(i.key()));
|
||||
}
|
||||
}
|
||||
|
||||
int DlgFilterGames::getMaxPlayersFilterMin() const
|
||||
{
|
||||
return maxPlayersFilterMinSpinBox->value();
|
||||
return maxPlayersFilterMinSpinBox->value();
|
||||
}
|
||||
|
||||
int DlgFilterGames::getMaxPlayersFilterMax() const
|
||||
{
|
||||
return maxPlayersFilterMaxSpinBox->value();
|
||||
return maxPlayersFilterMaxSpinBox->value();
|
||||
}
|
||||
|
||||
void DlgFilterGames::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax)
|
||||
{
|
||||
maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin);
|
||||
maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax);
|
||||
maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin);
|
||||
maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax);
|
||||
}
|
||||
|
|
|
@ -10,31 +10,31 @@ class QLineEdit;
|
|||
class QSpinBox;
|
||||
|
||||
class DlgFilterGames : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QCheckBox *unavailableGamesVisibleCheckBox;
|
||||
QCheckBox *passwordProtectedGamesVisibleCheckBox;
|
||||
QLineEdit *gameNameFilterEdit;
|
||||
QLineEdit *creatorNameFilterEdit;
|
||||
QMap<int, QCheckBox *> gameTypeFilterCheckBoxes;
|
||||
QSpinBox *maxPlayersFilterMinSpinBox;
|
||||
QSpinBox *maxPlayersFilterMaxSpinBox;
|
||||
QCheckBox *unavailableGamesVisibleCheckBox;
|
||||
QCheckBox *passwordProtectedGamesVisibleCheckBox;
|
||||
QLineEdit *gameNameFilterEdit;
|
||||
QLineEdit *creatorNameFilterEdit;
|
||||
QMap<int, QCheckBox *> gameTypeFilterCheckBoxes;
|
||||
QSpinBox *maxPlayersFilterMinSpinBox;
|
||||
QSpinBox *maxPlayersFilterMaxSpinBox;
|
||||
public:
|
||||
DlgFilterGames(const QMap<int, QString> &allGameTypes, QWidget *parent = 0);
|
||||
DlgFilterGames(const QMap<int, QString> &allGameTypes, QWidget *parent = 0);
|
||||
|
||||
bool getUnavailableGamesVisible() const;
|
||||
void setUnavailableGamesVisible(bool _unavailableGamesVisible);
|
||||
bool getPasswordProtectedGamesVisible() const;
|
||||
void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible);
|
||||
QString getGameNameFilter() const;
|
||||
void setGameNameFilter(const QString &_gameNameFilter);
|
||||
QString getCreatorNameFilter() const;
|
||||
void setCreatorNameFilter(const QString &_creatorNameFilter);
|
||||
QSet<int> getGameTypeFilter() const;
|
||||
void setGameTypeFilter(const QSet<int> &_gameTypeFilter);
|
||||
int getMaxPlayersFilterMin() const;
|
||||
int getMaxPlayersFilterMax() const;
|
||||
void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax);
|
||||
bool getUnavailableGamesVisible() const;
|
||||
void setUnavailableGamesVisible(bool _unavailableGamesVisible);
|
||||
bool getPasswordProtectedGamesVisible() const;
|
||||
void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible);
|
||||
QString getGameNameFilter() const;
|
||||
void setGameNameFilter(const QString &_gameNameFilter);
|
||||
QString getCreatorNameFilter() const;
|
||||
void setCreatorNameFilter(const QString &_creatorNameFilter);
|
||||
QSet<int> getGameTypeFilter() const;
|
||||
void setGameTypeFilter(const QSet<int> &_gameTypeFilter);
|
||||
int getMaxPlayersFilterMin() const;
|
||||
int getMaxPlayersFilterMax() const;
|
||||
void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -12,47 +12,47 @@
|
|||
#include "deck_loader.h"
|
||||
|
||||
DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent)
|
||||
: QDialog(parent), deckList(0)
|
||||
: QDialog(parent), deckList(0)
|
||||
{
|
||||
contentsEdit = new QPlainTextEdit;
|
||||
contentsEdit = new QPlainTextEdit;
|
||||
|
||||
refreshButton = new QPushButton(tr("&Refresh"));
|
||||
refreshButton->setShortcut(QKeySequence("F5"));
|
||||
connect(refreshButton, SIGNAL(clicked()), this, SLOT(actRefresh()));
|
||||
refreshButton = new QPushButton(tr("&Refresh"));
|
||||
refreshButton->setShortcut(QKeySequence("F5"));
|
||||
connect(refreshButton, SIGNAL(clicked()), this, SLOT(actRefresh()));
|
||||
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addWidget(contentsEdit);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addWidget(contentsEdit);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
|
||||
setLayout(mainLayout);
|
||||
setLayout(mainLayout);
|
||||
|
||||
setWindowTitle(tr("Load deck from clipboard"));
|
||||
resize(500, 500);
|
||||
setWindowTitle(tr("Load deck from clipboard"));
|
||||
resize(500, 500);
|
||||
|
||||
actRefresh();
|
||||
actRefresh();
|
||||
}
|
||||
|
||||
void DlgLoadDeckFromClipboard::actRefresh()
|
||||
{
|
||||
contentsEdit->setPlainText(QApplication::clipboard()->text());
|
||||
contentsEdit->setPlainText(QApplication::clipboard()->text());
|
||||
}
|
||||
|
||||
void DlgLoadDeckFromClipboard::actOK()
|
||||
{
|
||||
QString buffer = contentsEdit->toPlainText();
|
||||
QTextStream stream(&buffer);
|
||||
QString buffer = contentsEdit->toPlainText();
|
||||
QTextStream stream(&buffer);
|
||||
|
||||
DeckLoader *l = new DeckLoader;
|
||||
if (l->loadFromStream_Plain(stream)) {
|
||||
deckList = l;
|
||||
accept();
|
||||
} else {
|
||||
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list."));
|
||||
delete l;
|
||||
}
|
||||
DeckLoader *l = new DeckLoader;
|
||||
if (l->loadFromStream_Plain(stream)) {
|
||||
deckList = l;
|
||||
accept();
|
||||
} else {
|
||||
QMessageBox::critical(this, tr("Error"), tr("Invalid deck list."));
|
||||
delete l;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,18 +8,18 @@ class QPlainTextEdit;
|
|||
class QPushButton;
|
||||
|
||||
class DlgLoadDeckFromClipboard : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void actOK();
|
||||
void actRefresh();
|
||||
void actOK();
|
||||
void actRefresh();
|
||||
private:
|
||||
DeckLoader *deckList;
|
||||
DeckLoader *deckList;
|
||||
public:
|
||||
DlgLoadDeckFromClipboard(QWidget *parent = 0);
|
||||
DeckLoader *getDeckList() const { return deckList; }
|
||||
DlgLoadDeckFromClipboard(QWidget *parent = 0);
|
||||
DeckLoader *getDeckList() const { return deckList; }
|
||||
private:
|
||||
QPlainTextEdit *contentsEdit;
|
||||
QPushButton *refreshButton;
|
||||
QPlainTextEdit *contentsEdit;
|
||||
QPushButton *refreshButton;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -7,34 +7,34 @@
|
|||
#include "main.h"
|
||||
|
||||
DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent)
|
||||
: QDialog(parent), client(_client)
|
||||
: QDialog(parent), client(_client)
|
||||
{
|
||||
dirView = new RemoteDeckList_TreeWidget(client);
|
||||
dirView = new RemoteDeckList_TreeWidget(client);
|
||||
|
||||
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
|
||||
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
|
||||
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addWidget(dirView);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addWidget(dirView);
|
||||
mainLayout->addWidget(buttonBox);
|
||||
|
||||
setLayout(mainLayout);
|
||||
setLayout(mainLayout);
|
||||
|
||||
setWindowTitle(tr("Load deck"));
|
||||
setMinimumWidth(sizeHint().width());
|
||||
resize(400, 600);
|
||||
setWindowTitle(tr("Load deck"));
|
||||
setMinimumWidth(sizeHint().width());
|
||||
resize(400, 600);
|
||||
|
||||
connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &)));
|
||||
connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &)));
|
||||
}
|
||||
|
||||
void DlgLoadRemoteDeck::currentItemChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/)
|
||||
{
|
||||
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(dynamic_cast<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();
|
||||
}
|
||||
|
|
|
@ -10,16 +10,16 @@ class QPushButton;
|
|||
class QDialogButtonBox;
|
||||
|
||||
class DlgLoadRemoteDeck: public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
AbstractClient *client;
|
||||
RemoteDeckList_TreeWidget *dirView;
|
||||
QDialogButtonBox *buttonBox;
|
||||
AbstractClient *client;
|
||||
RemoteDeckList_TreeWidget *dirView;
|
||||
QDialogButtonBox *buttonBox;
|
||||
private slots:
|
||||
void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous);
|
||||
void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous);
|
||||
public:
|
||||
DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0);
|
||||
int getDeckId() const;
|
||||
DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0);
|
||||
int getDeckId() const;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -18,123 +18,123 @@ class QSpinBox;
|
|||
|
||||
class AbstractSettingsPage : public QWidget {
|
||||
public:
|
||||
virtual void retranslateUi() = 0;
|
||||
virtual void retranslateUi() = 0;
|
||||
};
|
||||
|
||||
class GeneralSettingsPage : public AbstractSettingsPage {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
GeneralSettingsPage();
|
||||
void retranslateUi();
|
||||
GeneralSettingsPage();
|
||||
void retranslateUi();
|
||||
private slots:
|
||||
void deckPathButtonClicked();
|
||||
void replaysPathButtonClicked();
|
||||
void picsPathButtonClicked();
|
||||
void cardDatabasePathButtonClicked();
|
||||
void tokenDatabasePathButtonClicked();
|
||||
void languageBoxChanged(int index);
|
||||
void deckPathButtonClicked();
|
||||
void replaysPathButtonClicked();
|
||||
void picsPathButtonClicked();
|
||||
void cardDatabasePathButtonClicked();
|
||||
void tokenDatabasePathButtonClicked();
|
||||
void languageBoxChanged(int index);
|
||||
private:
|
||||
QStringList findQmFiles();
|
||||
QString languageName(const QString &qmFile);
|
||||
QLineEdit *deckPathEdit, *replaysPathEdit, *picsPathEdit, *cardDatabasePathEdit, *tokenDatabasePathEdit;
|
||||
QGroupBox *personalGroupBox, *pathsGroupBox;
|
||||
QComboBox *languageBox;
|
||||
QCheckBox *picDownloadCheckBox;
|
||||
QLabel *languageLabel, *deckPathLabel, *replaysPathLabel, *picsPathLabel, *cardDatabasePathLabel, *tokenDatabasePathLabel;
|
||||
QStringList findQmFiles();
|
||||
QString languageName(const QString &qmFile);
|
||||
QLineEdit *deckPathEdit, *replaysPathEdit, *picsPathEdit, *cardDatabasePathEdit, *tokenDatabasePathEdit;
|
||||
QGroupBox *personalGroupBox, *pathsGroupBox;
|
||||
QComboBox *languageBox;
|
||||
QCheckBox *picDownloadCheckBox;
|
||||
QLabel *languageLabel, *deckPathLabel, *replaysPathLabel, *picsPathLabel, *cardDatabasePathLabel, *tokenDatabasePathLabel;
|
||||
};
|
||||
|
||||
class AppearanceSettingsPage : public AbstractSettingsPage {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void handBgClearButtonClicked();
|
||||
void handBgButtonClicked();
|
||||
void stackBgClearButtonClicked();
|
||||
void stackBgButtonClicked();
|
||||
void tableBgClearButtonClicked();
|
||||
void tableBgButtonClicked();
|
||||
void playerAreaBgClearButtonClicked();
|
||||
void playerAreaBgButtonClicked();
|
||||
void cardBackPicturePathClearButtonClicked();
|
||||
void cardBackPicturePathButtonClicked();
|
||||
void handBgClearButtonClicked();
|
||||
void handBgButtonClicked();
|
||||
void stackBgClearButtonClicked();
|
||||
void stackBgButtonClicked();
|
||||
void tableBgClearButtonClicked();
|
||||
void tableBgButtonClicked();
|
||||
void playerAreaBgClearButtonClicked();
|
||||
void playerAreaBgButtonClicked();
|
||||
void cardBackPicturePathClearButtonClicked();
|
||||
void cardBackPicturePathButtonClicked();
|
||||
signals:
|
||||
void handBgChanged(const QString &path);
|
||||
void stackBgChanged(const QString &path);
|
||||
void tableBgChanged(const QString &path);
|
||||
void playerAreaBgChanged(const QString &path);
|
||||
void cardBackPicturePathChanged(const QString &path);
|
||||
void handBgChanged(const QString &path);
|
||||
void stackBgChanged(const QString &path);
|
||||
void tableBgChanged(const QString &path);
|
||||
void playerAreaBgChanged(const QString &path);
|
||||
void cardBackPicturePathChanged(const QString &path);
|
||||
private:
|
||||
QLabel *handBgLabel, *stackBgLabel, *tableBgLabel, *playerAreaBgLabel, *cardBackPicturePathLabel, *minPlayersForMultiColumnLayoutLabel;
|
||||
QLineEdit *handBgEdit, *stackBgEdit, *tableBgEdit, *playerAreaBgEdit, *cardBackPicturePathEdit;
|
||||
QCheckBox *displayCardNamesCheckBox, *horizontalHandCheckBox, *invertVerticalCoordinateCheckBox, *zoneViewSortByNameCheckBox, *zoneViewSortByTypeCheckBox;
|
||||
QGroupBox *zoneBgGroupBox, *cardsGroupBox, *handGroupBox, *tableGroupBox, *zoneViewGroupBox;
|
||||
QSpinBox *minPlayersForMultiColumnLayoutEdit;
|
||||
QLabel *handBgLabel, *stackBgLabel, *tableBgLabel, *playerAreaBgLabel, *cardBackPicturePathLabel, *minPlayersForMultiColumnLayoutLabel;
|
||||
QLineEdit *handBgEdit, *stackBgEdit, *tableBgEdit, *playerAreaBgEdit, *cardBackPicturePathEdit;
|
||||
QCheckBox *displayCardNamesCheckBox, *horizontalHandCheckBox, *invertVerticalCoordinateCheckBox, *zoneViewSortByNameCheckBox, *zoneViewSortByTypeCheckBox;
|
||||
QGroupBox *zoneBgGroupBox, *cardsGroupBox, *handGroupBox, *tableGroupBox, *zoneViewGroupBox;
|
||||
QSpinBox *minPlayersForMultiColumnLayoutEdit;
|
||||
public:
|
||||
AppearanceSettingsPage();
|
||||
void retranslateUi();
|
||||
AppearanceSettingsPage();
|
||||
void retranslateUi();
|
||||
};
|
||||
|
||||
class UserInterfaceSettingsPage : public AbstractSettingsPage {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void soundPathClearButtonClicked();
|
||||
void soundPathButtonClicked();
|
||||
void soundPathClearButtonClicked();
|
||||
void soundPathButtonClicked();
|
||||
signals:
|
||||
void soundPathChanged();
|
||||
void soundPathChanged();
|
||||
private:
|
||||
QCheckBox *notificationsEnabledCheckBox;
|
||||
QCheckBox *doubleClickToPlayCheckBox;
|
||||
QCheckBox *playToStackCheckBox;
|
||||
QCheckBox *tapAnimationCheckBox;
|
||||
QCheckBox *soundEnabledCheckBox;
|
||||
QLabel *soundPathLabel;
|
||||
QLineEdit *soundPathEdit;
|
||||
QGroupBox *generalGroupBox, *animationGroupBox, *soundGroupBox;
|
||||
QCheckBox *notificationsEnabledCheckBox;
|
||||
QCheckBox *doubleClickToPlayCheckBox;
|
||||
QCheckBox *playToStackCheckBox;
|
||||
QCheckBox *tapAnimationCheckBox;
|
||||
QCheckBox *soundEnabledCheckBox;
|
||||
QLabel *soundPathLabel;
|
||||
QLineEdit *soundPathEdit;
|
||||
QGroupBox *generalGroupBox, *animationGroupBox, *soundGroupBox;
|
||||
public:
|
||||
UserInterfaceSettingsPage();
|
||||
void retranslateUi();
|
||||
UserInterfaceSettingsPage();
|
||||
void retranslateUi();
|
||||
};
|
||||
|
||||
class DeckEditorSettingsPage : public AbstractSettingsPage {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
DeckEditorSettingsPage();
|
||||
void retranslateUi();
|
||||
DeckEditorSettingsPage();
|
||||
void retranslateUi();
|
||||
private:
|
||||
QCheckBox *priceTagsCheckBox;
|
||||
QGroupBox *generalGroupBox;
|
||||
QCheckBox *priceTagsCheckBox;
|
||||
QGroupBox *generalGroupBox;
|
||||
};
|
||||
|
||||
class MessagesSettingsPage : public AbstractSettingsPage {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
MessagesSettingsPage();
|
||||
void retranslateUi();
|
||||
MessagesSettingsPage();
|
||||
void retranslateUi();
|
||||
private slots:
|
||||
void actAdd();
|
||||
void actRemove();
|
||||
void actAdd();
|
||||
void actRemove();
|
||||
private:
|
||||
QListWidget *messageList;
|
||||
QAction *aAdd, *aRemove;
|
||||
QListWidget *messageList;
|
||||
QAction *aAdd, *aRemove;
|
||||
|
||||
void storeSettings();
|
||||
void storeSettings();
|
||||
};
|
||||
|
||||
class DlgSettings : public QDialog {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
DlgSettings(QWidget *parent = 0);
|
||||
DlgSettings(QWidget *parent = 0);
|
||||
private slots:
|
||||
void changePage(QListWidgetItem *current, QListWidgetItem *previous);
|
||||
void updateLanguage();
|
||||
void changePage(QListWidgetItem *current, QListWidgetItem *previous);
|
||||
void updateLanguage();
|
||||
private:
|
||||
QListWidget *contentsWidget;
|
||||
QStackedWidget *pagesWidget;
|
||||
QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton;
|
||||
void createIcons();
|
||||
void retranslateUi();
|
||||
QListWidget *contentsWidget;
|
||||
QStackedWidget *pagesWidget;
|
||||
QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton;
|
||||
void createIcons();
|
||||
void retranslateUi();
|
||||
protected:
|
||||
void changeEvent(QEvent *event);
|
||||
void closeEvent(QCloseEvent *event);
|
||||
void changeEvent(QEvent *event);
|
||||
void closeEvent(QCloseEvent *event);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -13,103 +13,103 @@
|
|||
#include <QGraphicsView>
|
||||
|
||||
GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent)
|
||||
: QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize())
|
||||
: QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize())
|
||||
{
|
||||
animationTimer = new QBasicTimer;
|
||||
addItem(phasesToolbar);
|
||||
connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange()));
|
||||
animationTimer = new QBasicTimer;
|
||||
addItem(phasesToolbar);
|
||||
connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange()));
|
||||
|
||||
rearrange();
|
||||
rearrange();
|
||||
}
|
||||
|
||||
GameScene::~GameScene()
|
||||
{
|
||||
delete animationTimer;
|
||||
delete animationTimer;
|
||||
}
|
||||
|
||||
void GameScene::retranslateUi()
|
||||
{
|
||||
for (int i = 0; i < zoneViews.size(); ++i)
|
||||
zoneViews[i]->retranslateUi();
|
||||
for (int i = 0; i < zoneViews.size(); ++i)
|
||||
zoneViews[i]->retranslateUi();
|
||||
}
|
||||
|
||||
void GameScene::addPlayer(Player *player)
|
||||
{
|
||||
qDebug("GameScene::addPlayer");
|
||||
players << player;
|
||||
addItem(player);
|
||||
connect(player, SIGNAL(sizeChanged()), this, SLOT(rearrange()));
|
||||
connect(player, SIGNAL(gameConceded()), this, SLOT(rearrange()));
|
||||
qDebug("GameScene::addPlayer");
|
||||
players << player;
|
||||
addItem(player);
|
||||
connect(player, SIGNAL(sizeChanged()), this, SLOT(rearrange()));
|
||||
connect(player, SIGNAL(gameConceded()), this, SLOT(rearrange()));
|
||||
}
|
||||
|
||||
void GameScene::removePlayer(Player *player)
|
||||
{
|
||||
qDebug("GameScene::removePlayer");
|
||||
players.removeAt(players.indexOf(player));
|
||||
removeItem(player);
|
||||
rearrange();
|
||||
qDebug("GameScene::removePlayer");
|
||||
players.removeAt(players.indexOf(player));
|
||||
removeItem(player);
|
||||
rearrange();
|
||||
}
|
||||
|
||||
void GameScene::rearrange()
|
||||
{
|
||||
playersByColumn.clear();
|
||||
playersByColumn.clear();
|
||||
|
||||
QList<Player *> playersPlaying;
|
||||
int firstPlayer = -1;
|
||||
for (int i = 0; i < players.size(); ++i)
|
||||
if (!players[i]->getConceded()) {
|
||||
playersPlaying.append(players[i]);
|
||||
if ((firstPlayer == -1) && (players[i]->getLocal()))
|
||||
firstPlayer = playersPlaying.size() - 1;
|
||||
}
|
||||
if (firstPlayer == -1)
|
||||
firstPlayer = 0;
|
||||
const int playersCount = playersPlaying.size();
|
||||
const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2;
|
||||
const int rows = ceil((qreal) playersCount / columns);
|
||||
qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing;
|
||||
QList<int> columnWidth;
|
||||
int firstPlayerOfColumn = firstPlayer;
|
||||
for (int col = 0; col < columns; ++col) {
|
||||
playersByColumn.append(QList<Player *>());
|
||||
columnWidth.append(0);
|
||||
qreal thisColumnHeight = -playerAreaSpacing;
|
||||
const int rowsInColumn = rows - (playersCount % columns) * col; // only correct for max. 2 cols
|
||||
for (int j = 0; j < rowsInColumn; ++j) {
|
||||
Player *player = playersPlaying[(firstPlayerOfColumn + j) % playersCount];
|
||||
if (col == 0)
|
||||
playersByColumn[col].prepend(player);
|
||||
else
|
||||
playersByColumn[col].append(player);
|
||||
thisColumnHeight += player->boundingRect().height() + playerAreaSpacing;
|
||||
if (player->boundingRect().width() > columnWidth[col])
|
||||
columnWidth[col] = player->boundingRect().width();
|
||||
}
|
||||
if (thisColumnHeight > sceneHeight)
|
||||
sceneHeight = thisColumnHeight;
|
||||
sceneWidth += columnWidth[col] + playerAreaSpacing;
|
||||
QList<Player *> playersPlaying;
|
||||
int firstPlayer = -1;
|
||||
for (int i = 0; i < players.size(); ++i)
|
||||
if (!players[i]->getConceded()) {
|
||||
playersPlaying.append(players[i]);
|
||||
if ((firstPlayer == -1) && (players[i]->getLocal()))
|
||||
firstPlayer = playersPlaying.size() - 1;
|
||||
}
|
||||
if (firstPlayer == -1)
|
||||
firstPlayer = 0;
|
||||
const int playersCount = playersPlaying.size();
|
||||
const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2;
|
||||
const int rows = ceil((qreal) playersCount / columns);
|
||||
qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing;
|
||||
QList<int> columnWidth;
|
||||
int firstPlayerOfColumn = firstPlayer;
|
||||
for (int col = 0; col < columns; ++col) {
|
||||
playersByColumn.append(QList<Player *>());
|
||||
columnWidth.append(0);
|
||||
qreal thisColumnHeight = -playerAreaSpacing;
|
||||
const int rowsInColumn = rows - (playersCount % columns) * col; // only correct for max. 2 cols
|
||||
for (int j = 0; j < rowsInColumn; ++j) {
|
||||
Player *player = playersPlaying[(firstPlayerOfColumn + j) % playersCount];
|
||||
if (col == 0)
|
||||
playersByColumn[col].prepend(player);
|
||||
else
|
||||
playersByColumn[col].append(player);
|
||||
thisColumnHeight += player->boundingRect().height() + playerAreaSpacing;
|
||||
if (player->boundingRect().width() > columnWidth[col])
|
||||
columnWidth[col] = player->boundingRect().width();
|
||||
}
|
||||
if (thisColumnHeight > sceneHeight)
|
||||
sceneHeight = thisColumnHeight;
|
||||
sceneWidth += columnWidth[col] + playerAreaSpacing;
|
||||
|
||||
firstPlayerOfColumn += rowsInColumn;
|
||||
}
|
||||
firstPlayerOfColumn += rowsInColumn;
|
||||
}
|
||||
|
||||
phasesToolbar->setHeight(sceneHeight);
|
||||
qreal phasesWidth = phasesToolbar->getWidth();
|
||||
sceneWidth += phasesWidth;
|
||||
phasesToolbar->setHeight(sceneHeight);
|
||||
qreal phasesWidth = phasesToolbar->getWidth();
|
||||
sceneWidth += phasesWidth;
|
||||
|
||||
qreal x = phasesWidth;
|
||||
for (int col = 0; col < columns; ++col) {
|
||||
qreal y = 0;
|
||||
for (int row = 0; row < playersByColumn[col].size(); ++row) {
|
||||
Player *player = playersByColumn[col][row];
|
||||
player->setPos(x, y);
|
||||
player->setMirrored(row != rows - 1);
|
||||
y += player->boundingRect().height() + playerAreaSpacing;
|
||||
}
|
||||
x += columnWidth[col] + playerAreaSpacing;
|
||||
}
|
||||
qreal x = phasesWidth;
|
||||
for (int col = 0; col < columns; ++col) {
|
||||
qreal y = 0;
|
||||
for (int row = 0; row < playersByColumn[col].size(); ++row) {
|
||||
Player *player = playersByColumn[col][row];
|
||||
player->setPos(x, y);
|
||||
player->setMirrored(row != rows - 1);
|
||||
y += player->boundingRect().height() + playerAreaSpacing;
|
||||
}
|
||||
x += columnWidth[col] + playerAreaSpacing;
|
||||
}
|
||||
|
||||
setSceneRect(sceneRect().x(), sceneRect().y(), sceneWidth, sceneHeight);
|
||||
processViewSizeChange(viewSize);
|
||||
setSceneRect(sceneRect().x(), sceneRect().y(), sceneWidth, sceneHeight);
|
||||
processViewSizeChange(viewSize);
|
||||
}
|
||||
|
||||
void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numberCards)
|
||||
|
@ -123,166 +123,166 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb
|
|||
}
|
||||
}
|
||||
|
||||
ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false);
|
||||
ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false);
|
||||
zoneViews.append(item);
|
||||
connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *)));
|
||||
addItem(item);
|
||||
item->setPos(50, 50);
|
||||
addItem(item);
|
||||
item->setPos(50, 50);
|
||||
}
|
||||
|
||||
void GameScene::addRevealedZoneView(Player *player, CardZone *zone, const QList<const ServerInfo_Card *> &cardList, bool withWritePermission)
|
||||
{
|
||||
ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList);
|
||||
zoneViews.append(item);
|
||||
ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList);
|
||||
zoneViews.append(item);
|
||||
connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *)));
|
||||
addItem(item);
|
||||
item->setPos(50, 50);
|
||||
addItem(item);
|
||||
item->setPos(50, 50);
|
||||
}
|
||||
|
||||
void GameScene::removeZoneView(ZoneViewWidget *item)
|
||||
{
|
||||
zoneViews.removeAt(zoneViews.indexOf(item));
|
||||
removeItem(item);
|
||||
removeItem(item);
|
||||
}
|
||||
|
||||
void GameScene::clearViews()
|
||||
{
|
||||
while (!zoneViews.isEmpty())
|
||||
zoneViews.first()->close();
|
||||
while (!zoneViews.isEmpty())
|
||||
zoneViews.first()->close();
|
||||
}
|
||||
|
||||
void GameScene::closeMostRecentZoneView()
|
||||
{
|
||||
if (!zoneViews.isEmpty())
|
||||
zoneViews.last()->close();
|
||||
if (!zoneViews.isEmpty())
|
||||
zoneViews.last()->close();
|
||||
}
|
||||
|
||||
QTransform GameScene::getViewTransform() const
|
||||
{
|
||||
return views().at(0)->transform();
|
||||
return views().at(0)->transform();
|
||||
}
|
||||
|
||||
QTransform GameScene::getViewportTransform() const
|
||||
{
|
||||
return views().at(0)->viewportTransform();
|
||||
return views().at(0)->viewportTransform();
|
||||
}
|
||||
|
||||
void GameScene::processViewSizeChange(const QSize &newSize)
|
||||
{
|
||||
viewSize = newSize;
|
||||
viewSize = newSize;
|
||||
|
||||
qreal newRatio = ((qreal) newSize.width()) / newSize.height();
|
||||
qreal minWidth = 0;
|
||||
QList<qreal> minWidthByColumn;
|
||||
for (int col = 0; col < playersByColumn.size(); ++col) {
|
||||
minWidthByColumn.append(0);
|
||||
for (int row = 0; row < playersByColumn[col].size(); ++row) {
|
||||
qreal w = playersByColumn[col][row]->getMinimumWidth();
|
||||
if (w > minWidthByColumn[col])
|
||||
minWidthByColumn[col] = w;
|
||||
}
|
||||
minWidth += minWidthByColumn[col];
|
||||
}
|
||||
minWidth += phasesToolbar->getWidth();
|
||||
qreal newRatio = ((qreal) newSize.width()) / newSize.height();
|
||||
qreal minWidth = 0;
|
||||
QList<qreal> minWidthByColumn;
|
||||
for (int col = 0; col < playersByColumn.size(); ++col) {
|
||||
minWidthByColumn.append(0);
|
||||
for (int row = 0; row < playersByColumn[col].size(); ++row) {
|
||||
qreal w = playersByColumn[col][row]->getMinimumWidth();
|
||||
if (w > minWidthByColumn[col])
|
||||
minWidthByColumn[col] = w;
|
||||
}
|
||||
minWidth += minWidthByColumn[col];
|
||||
}
|
||||
minWidth += phasesToolbar->getWidth();
|
||||
|
||||
qreal minRatio = minWidth / sceneRect().height();
|
||||
qreal newWidth;
|
||||
if (minRatio > newRatio) {
|
||||
// Aspect ratio is dominated by table width.
|
||||
newWidth = minWidth;
|
||||
} else {
|
||||
// Aspect ratio is dominated by window dimensions.
|
||||
newWidth = newRatio * sceneRect().height();
|
||||
}
|
||||
setSceneRect(0, 0, newWidth, sceneRect().height());
|
||||
qreal minRatio = minWidth / sceneRect().height();
|
||||
qreal newWidth;
|
||||
if (minRatio > newRatio) {
|
||||
// Aspect ratio is dominated by table width.
|
||||
newWidth = minWidth;
|
||||
} else {
|
||||
// Aspect ratio is dominated by window dimensions.
|
||||
newWidth = newRatio * sceneRect().height();
|
||||
}
|
||||
setSceneRect(0, 0, newWidth, sceneRect().height());
|
||||
|
||||
qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size();
|
||||
for (int col = 0; col < playersByColumn.size(); ++col)
|
||||
for (int row = 0; row < playersByColumn[col].size(); ++row)
|
||||
playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn);
|
||||
qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size();
|
||||
for (int col = 0; col < playersByColumn.size(); ++col)
|
||||
for (int row = 0; row < playersByColumn[col].size(); ++row)
|
||||
playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn);
|
||||
}
|
||||
|
||||
void GameScene::updateHover(const QPointF &scenePos)
|
||||
{
|
||||
QList<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;
|
||||
for (int i = 0; i < itemList.size(); ++i)
|
||||
if ((zone = qgraphicsitem_cast<CardZone *>(itemList[i])))
|
||||
break;
|
||||
// Search for the topmost zone and ignore all cards not belonging to that zone.
|
||||
CardZone *zone = 0;
|
||||
for (int i = 0; i < itemList.size(); ++i)
|
||||
if ((zone = qgraphicsitem_cast<CardZone *>(itemList[i])))
|
||||
break;
|
||||
|
||||
CardItem *maxZCard = 0;
|
||||
if (zone) {
|
||||
qreal maxZ = -1;
|
||||
for (int i = 0; i < itemList.size(); ++i) {
|
||||
CardItem *card = qgraphicsitem_cast<CardItem *>(itemList[i]);
|
||||
if (!card)
|
||||
continue;
|
||||
if (card->getAttachedTo()) {
|
||||
if (card->getAttachedTo()->getZone() != zone)
|
||||
continue;
|
||||
} else if (card->getZone() != zone)
|
||||
continue;
|
||||
CardItem *maxZCard = 0;
|
||||
if (zone) {
|
||||
qreal maxZ = -1;
|
||||
for (int i = 0; i < itemList.size(); ++i) {
|
||||
CardItem *card = qgraphicsitem_cast<CardItem *>(itemList[i]);
|
||||
if (!card)
|
||||
continue;
|
||||
if (card->getAttachedTo()) {
|
||||
if (card->getAttachedTo()->getZone() != zone)
|
||||
continue;
|
||||
} else if (card->getZone() != zone)
|
||||
continue;
|
||||
|
||||
if (card->getRealZValue() > maxZ) {
|
||||
maxZ = card->getRealZValue();
|
||||
maxZCard = card;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hoveredCard && (maxZCard != hoveredCard))
|
||||
hoveredCard->setHovered(false);
|
||||
if (maxZCard && (maxZCard != hoveredCard))
|
||||
maxZCard->setHovered(true);
|
||||
hoveredCard = maxZCard;
|
||||
if (card->getRealZValue() > maxZ) {
|
||||
maxZ = card->getRealZValue();
|
||||
maxZCard = card;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hoveredCard && (maxZCard != hoveredCard))
|
||||
hoveredCard->setHovered(false);
|
||||
if (maxZCard && (maxZCard != hoveredCard))
|
||||
maxZCard->setHovered(true);
|
||||
hoveredCard = maxZCard;
|
||||
}
|
||||
|
||||
bool GameScene::event(QEvent *event)
|
||||
{
|
||||
if (event->type() == QEvent::GraphicsSceneMouseMove)
|
||||
updateHover(static_cast<QGraphicsSceneMouseEvent *>(event)->scenePos());
|
||||
if (event->type() == QEvent::GraphicsSceneMouseMove)
|
||||
updateHover(static_cast<QGraphicsSceneMouseEvent *>(event)->scenePos());
|
||||
|
||||
return QGraphicsScene::event(event);
|
||||
return QGraphicsScene::event(event);
|
||||
}
|
||||
|
||||
void GameScene::timerEvent(QTimerEvent * /*event*/)
|
||||
{
|
||||
QMutableSetIterator<CardItem *> i(cardsToAnimate);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
if (!i.value()->animationEvent())
|
||||
i.remove();
|
||||
}
|
||||
if (cardsToAnimate.isEmpty())
|
||||
animationTimer->stop();
|
||||
QMutableSetIterator<CardItem *> i(cardsToAnimate);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
if (!i.value()->animationEvent())
|
||||
i.remove();
|
||||
}
|
||||
if (cardsToAnimate.isEmpty())
|
||||
animationTimer->stop();
|
||||
}
|
||||
|
||||
void GameScene::registerAnimationItem(AbstractCardItem *card)
|
||||
{
|
||||
cardsToAnimate.insert(static_cast<CardItem *>(card));
|
||||
if (!animationTimer->isActive())
|
||||
animationTimer->start(50, this);
|
||||
cardsToAnimate.insert(static_cast<CardItem *>(card));
|
||||
if (!animationTimer->isActive())
|
||||
animationTimer->start(50, this);
|
||||
}
|
||||
|
||||
void GameScene::unregisterAnimationItem(AbstractCardItem *card)
|
||||
{
|
||||
cardsToAnimate.remove(static_cast<CardItem *>(card));
|
||||
if (cardsToAnimate.isEmpty())
|
||||
animationTimer->stop();
|
||||
cardsToAnimate.remove(static_cast<CardItem *>(card));
|
||||
if (cardsToAnimate.isEmpty())
|
||||
animationTimer->stop();
|
||||
}
|
||||
|
||||
void GameScene::startRubberBand(const QPointF &selectionOrigin)
|
||||
{
|
||||
emit sigStartRubberBand(selectionOrigin);
|
||||
emit sigStartRubberBand(selectionOrigin);
|
||||
}
|
||||
|
||||
void GameScene::resizeRubberBand(const QPointF &cursorPoint)
|
||||
{
|
||||
emit sigResizeRubberBand(cursorPoint);
|
||||
emit sigResizeRubberBand(cursorPoint);
|
||||
}
|
||||
|
||||
void GameScene::stopRubberBand()
|
||||
{
|
||||
emit sigStopRubberBand();
|
||||
emit sigStopRubberBand();
|
||||
}
|
||||
|
|
|
@ -16,49 +16,49 @@ class PhasesToolbar;
|
|||
class QBasicTimer;
|
||||
|
||||
class GameScene : public QGraphicsScene {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
static const int playerAreaSpacing = 5;
|
||||
static const int playerAreaSpacing = 5;
|
||||
|
||||
PhasesToolbar *phasesToolbar;
|
||||
QList<Player *> players;
|
||||
QList<QList<Player *> > playersByColumn;
|
||||
QList<ZoneViewWidget *> zoneViews;
|
||||
QSize viewSize;
|
||||
QPointer<CardItem> hoveredCard;
|
||||
QBasicTimer *animationTimer;
|
||||
QSet<CardItem *> cardsToAnimate;
|
||||
void updateHover(const QPointF &scenePos);
|
||||
PhasesToolbar *phasesToolbar;
|
||||
QList<Player *> players;
|
||||
QList<QList<Player *> > playersByColumn;
|
||||
QList<ZoneViewWidget *> zoneViews;
|
||||
QSize viewSize;
|
||||
QPointer<CardItem> hoveredCard;
|
||||
QBasicTimer *animationTimer;
|
||||
QSet<CardItem *> cardsToAnimate;
|
||||
void updateHover(const QPointF &scenePos);
|
||||
public:
|
||||
GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0);
|
||||
~GameScene();
|
||||
void retranslateUi();
|
||||
void processViewSizeChange(const QSize &newSize);
|
||||
QTransform getViewTransform() const;
|
||||
QTransform getViewportTransform() const;
|
||||
GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0);
|
||||
~GameScene();
|
||||
void retranslateUi();
|
||||
void processViewSizeChange(const QSize &newSize);
|
||||
QTransform getViewTransform() const;
|
||||
QTransform getViewportTransform() const;
|
||||
|
||||
void startRubberBand(const QPointF &selectionOrigin);
|
||||
void resizeRubberBand(const QPointF &cursorPoint);
|
||||
void stopRubberBand();
|
||||
void startRubberBand(const QPointF &selectionOrigin);
|
||||
void resizeRubberBand(const QPointF &cursorPoint);
|
||||
void stopRubberBand();
|
||||
|
||||
void registerAnimationItem(AbstractCardItem *item);
|
||||
void unregisterAnimationItem(AbstractCardItem *card);
|
||||
void registerAnimationItem(AbstractCardItem *item);
|
||||
void unregisterAnimationItem(AbstractCardItem *card);
|
||||
public slots:
|
||||
void toggleZoneView(Player *player, const QString &zoneName, int numberCards);
|
||||
void addRevealedZoneView(Player *player, CardZone *zone, const QList<const ServerInfo_Card *> &cardList, bool withWritePermission);
|
||||
void removeZoneView(ZoneViewWidget *item);
|
||||
void addPlayer(Player *player);
|
||||
void removePlayer(Player *player);
|
||||
void clearViews();
|
||||
void closeMostRecentZoneView();
|
||||
void rearrange();
|
||||
void toggleZoneView(Player *player, const QString &zoneName, int numberCards);
|
||||
void addRevealedZoneView(Player *player, CardZone *zone, const QList<const ServerInfo_Card *> &cardList, bool withWritePermission);
|
||||
void removeZoneView(ZoneViewWidget *item);
|
||||
void addPlayer(Player *player);
|
||||
void removePlayer(Player *player);
|
||||
void clearViews();
|
||||
void closeMostRecentZoneView();
|
||||
void rearrange();
|
||||
protected:
|
||||
bool event(QEvent *event);
|
||||
void timerEvent(QTimerEvent *event);
|
||||
bool event(QEvent *event);
|
||||
void timerEvent(QTimerEvent *event);
|
||||
signals:
|
||||
void sigStartRubberBand(const QPointF &selectionOrigin);
|
||||
void sigResizeRubberBand(const QPointF &cursorPoint);
|
||||
void sigStopRubberBand();
|
||||
void sigStartRubberBand(const QPointF &selectionOrigin);
|
||||
void sigResizeRubberBand(const QPointF &cursorPoint);
|
||||
void sigStopRubberBand();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -18,173 +18,173 @@
|
|||
#include "pb/response.pb.h"
|
||||
|
||||
GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, QWidget *parent)
|
||||
: QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room)
|
||||
: QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room)
|
||||
{
|
||||
gameListView = new QTreeView;
|
||||
gameListModel = new GamesModel(_rooms, _gameTypes, this);
|
||||
gameListProxyModel = new GamesProxyModel(this, tabSupervisor->getUserInfo());
|
||||
gameListProxyModel->setSourceModel(gameListModel);
|
||||
gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
gameListView->setModel(gameListProxyModel);
|
||||
gameListView->setSortingEnabled(true);
|
||||
gameListView->setAlternatingRowColors(true);
|
||||
gameListView->setRootIsDecorated(true);
|
||||
if (_room)
|
||||
gameListView->header()->hideSection(1);
|
||||
else
|
||||
gameListProxyModel->setUnavailableGamesVisible(true);
|
||||
gameListView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
|
||||
gameListView = new QTreeView;
|
||||
gameListModel = new GamesModel(_rooms, _gameTypes, this);
|
||||
gameListProxyModel = new GamesProxyModel(this, tabSupervisor->getUserInfo());
|
||||
gameListProxyModel->setSourceModel(gameListModel);
|
||||
gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
gameListView->setModel(gameListProxyModel);
|
||||
gameListView->setSortingEnabled(true);
|
||||
gameListView->setAlternatingRowColors(true);
|
||||
gameListView->setRootIsDecorated(true);
|
||||
if (_room)
|
||||
gameListView->header()->hideSection(1);
|
||||
else
|
||||
gameListProxyModel->setUnavailableGamesVisible(true);
|
||||
gameListView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
|
||||
|
||||
filterButton = new QPushButton;
|
||||
filterButton->setIcon(QIcon(":/resources/icon_search.svg"));
|
||||
connect(filterButton, SIGNAL(clicked()), this, SLOT(actSetFilter()));
|
||||
clearFilterButton = new QPushButton;
|
||||
clearFilterButton->setIcon(QIcon(":/resources/icon_clearsearch.svg"));
|
||||
clearFilterButton->setEnabled(false);
|
||||
connect(clearFilterButton, SIGNAL(clicked()), this, SLOT(actClearFilter()));
|
||||
filterButton = new QPushButton;
|
||||
filterButton->setIcon(QIcon(":/resources/icon_search.svg"));
|
||||
connect(filterButton, SIGNAL(clicked()), this, SLOT(actSetFilter()));
|
||||
clearFilterButton = new QPushButton;
|
||||
clearFilterButton->setIcon(QIcon(":/resources/icon_clearsearch.svg"));
|
||||
clearFilterButton->setEnabled(false);
|
||||
connect(clearFilterButton, SIGNAL(clicked()), this, SLOT(actClearFilter()));
|
||||
|
||||
if (room) {
|
||||
createButton = new QPushButton;
|
||||
connect(createButton, SIGNAL(clicked()), this, SLOT(actCreate()));
|
||||
} else
|
||||
createButton = 0;
|
||||
joinButton = new QPushButton;
|
||||
spectateButton = new QPushButton;
|
||||
if (room) {
|
||||
createButton = new QPushButton;
|
||||
connect(createButton, SIGNAL(clicked()), this, SLOT(actCreate()));
|
||||
} else
|
||||
createButton = 0;
|
||||
joinButton = new QPushButton;
|
||||
spectateButton = new QPushButton;
|
||||
|
||||
QHBoxLayout *buttonLayout = new QHBoxLayout;
|
||||
buttonLayout->addWidget(filterButton);
|
||||
buttonLayout->addWidget(clearFilterButton);
|
||||
buttonLayout->addStretch();
|
||||
if (room)
|
||||
buttonLayout->addWidget(createButton);
|
||||
buttonLayout->addWidget(joinButton);
|
||||
buttonLayout->addWidget(spectateButton);
|
||||
buttonLayout->setAlignment(Qt::AlignTop);
|
||||
QHBoxLayout *buttonLayout = new QHBoxLayout;
|
||||
buttonLayout->addWidget(filterButton);
|
||||
buttonLayout->addWidget(clearFilterButton);
|
||||
buttonLayout->addStretch();
|
||||
if (room)
|
||||
buttonLayout->addWidget(createButton);
|
||||
buttonLayout->addWidget(joinButton);
|
||||
buttonLayout->addWidget(spectateButton);
|
||||
buttonLayout->setAlignment(Qt::AlignTop);
|
||||
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addWidget(gameListView);
|
||||
mainLayout->addLayout(buttonLayout);
|
||||
QVBoxLayout *mainLayout = new QVBoxLayout;
|
||||
mainLayout->addWidget(gameListView);
|
||||
mainLayout->addLayout(buttonLayout);
|
||||
|
||||
retranslateUi();
|
||||
setLayout(mainLayout);
|
||||
retranslateUi();
|
||||
setLayout(mainLayout);
|
||||
|
||||
setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5);
|
||||
setMinimumHeight(200);
|
||||
setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5);
|
||||
setMinimumHeight(200);
|
||||
|
||||
connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin()));
|
||||
connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin()));
|
||||
connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin()));
|
||||
connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin()));
|
||||
}
|
||||
|
||||
void GameSelector::actSetFilter()
|
||||
{
|
||||
GameTypeMap gameTypeMap;
|
||||
if (room)
|
||||
gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId());
|
||||
DlgFilterGames dlg(gameTypeMap, this);
|
||||
dlg.setUnavailableGamesVisible(gameListProxyModel->getUnavailableGamesVisible());
|
||||
dlg.setPasswordProtectedGamesVisible(gameListProxyModel->getPasswordProtectedGamesVisible());
|
||||
dlg.setGameNameFilter(gameListProxyModel->getGameNameFilter());
|
||||
dlg.setCreatorNameFilter(gameListProxyModel->getCreatorNameFilter());
|
||||
dlg.setGameTypeFilter(gameListProxyModel->getGameTypeFilter());
|
||||
dlg.setMaxPlayersFilter(gameListProxyModel->getMaxPlayersFilterMin(), gameListProxyModel->getMaxPlayersFilterMax());
|
||||
GameTypeMap gameTypeMap;
|
||||
if (room)
|
||||
gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId());
|
||||
DlgFilterGames dlg(gameTypeMap, this);
|
||||
dlg.setUnavailableGamesVisible(gameListProxyModel->getUnavailableGamesVisible());
|
||||
dlg.setPasswordProtectedGamesVisible(gameListProxyModel->getPasswordProtectedGamesVisible());
|
||||
dlg.setGameNameFilter(gameListProxyModel->getGameNameFilter());
|
||||
dlg.setCreatorNameFilter(gameListProxyModel->getCreatorNameFilter());
|
||||
dlg.setGameTypeFilter(gameListProxyModel->getGameTypeFilter());
|
||||
dlg.setMaxPlayersFilter(gameListProxyModel->getMaxPlayersFilterMin(), gameListProxyModel->getMaxPlayersFilterMax());
|
||||
|
||||
if (!dlg.exec())
|
||||
return;
|
||||
if (!dlg.exec())
|
||||
return;
|
||||
|
||||
clearFilterButton->setEnabled(true);
|
||||
clearFilterButton->setEnabled(true);
|
||||
|
||||
gameListProxyModel->setUnavailableGamesVisible(dlg.getUnavailableGamesVisible());
|
||||
gameListProxyModel->setPasswordProtectedGamesVisible(dlg.getPasswordProtectedGamesVisible());
|
||||
gameListProxyModel->setGameNameFilter(dlg.getGameNameFilter());
|
||||
gameListProxyModel->setCreatorNameFilter(dlg.getCreatorNameFilter());
|
||||
gameListProxyModel->setGameTypeFilter(dlg.getGameTypeFilter());
|
||||
gameListProxyModel->setMaxPlayersFilter(dlg.getMaxPlayersFilterMin(), dlg.getMaxPlayersFilterMax());
|
||||
gameListProxyModel->setUnavailableGamesVisible(dlg.getUnavailableGamesVisible());
|
||||
gameListProxyModel->setPasswordProtectedGamesVisible(dlg.getPasswordProtectedGamesVisible());
|
||||
gameListProxyModel->setGameNameFilter(dlg.getGameNameFilter());
|
||||
gameListProxyModel->setCreatorNameFilter(dlg.getCreatorNameFilter());
|
||||
gameListProxyModel->setGameTypeFilter(dlg.getGameTypeFilter());
|
||||
gameListProxyModel->setMaxPlayersFilter(dlg.getMaxPlayersFilterMin(), dlg.getMaxPlayersFilterMax());
|
||||
}
|
||||
|
||||
void GameSelector::actClearFilter()
|
||||
{
|
||||
clearFilterButton->setEnabled(false);
|
||||
clearFilterButton->setEnabled(false);
|
||||
|
||||
gameListProxyModel->resetFilterParameters();
|
||||
gameListProxyModel->resetFilterParameters();
|
||||
}
|
||||
|
||||
void GameSelector::actCreate()
|
||||
{
|
||||
DlgCreateGame dlg(room, room->getGameTypes(), this);
|
||||
dlg.exec();
|
||||
DlgCreateGame dlg(room, room->getGameTypes(), this);
|
||||
dlg.exec();
|
||||
}
|
||||
|
||||
void GameSelector::checkResponse(const Response &response)
|
||||
{
|
||||
if (createButton)
|
||||
createButton->setEnabled(true);
|
||||
joinButton->setEnabled(true);
|
||||
spectateButton->setEnabled(true);
|
||||
if (createButton)
|
||||
createButton->setEnabled(true);
|
||||
joinButton->setEnabled(true);
|
||||
spectateButton->setEnabled(true);
|
||||
|
||||
switch (response.response_code()) {
|
||||
case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break;
|
||||
case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break;
|
||||
case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break;
|
||||
case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break;
|
||||
case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break;
|
||||
case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break;
|
||||
case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break;
|
||||
case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break;
|
||||
default: ;
|
||||
}
|
||||
switch (response.response_code()) {
|
||||
case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break;
|
||||
case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break;
|
||||
case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break;
|
||||
case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break;
|
||||
case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break;
|
||||
case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break;
|
||||
case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break;
|
||||
case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break;
|
||||
default: ;
|
||||
}
|
||||
}
|
||||
|
||||
void GameSelector::actJoin()
|
||||
{
|
||||
bool spectator = sender() == spectateButton;
|
||||
bool spectator = sender() == spectateButton;
|
||||
|
||||
QModelIndex ind = gameListView->currentIndex();
|
||||
if (!ind.isValid())
|
||||
return;
|
||||
const ServerInfo_Game &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt());
|
||||
bool overrideRestrictions = !tabSupervisor->getAdminLocked();
|
||||
QString password;
|
||||
if (game.with_password() && !(spectator && !game.spectators_need_password()) && !overrideRestrictions) {
|
||||
bool ok;
|
||||
password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok);
|
||||
if (!ok)
|
||||
return;
|
||||
}
|
||||
QModelIndex ind = gameListView->currentIndex();
|
||||
if (!ind.isValid())
|
||||
return;
|
||||
const ServerInfo_Game &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt());
|
||||
bool overrideRestrictions = !tabSupervisor->getAdminLocked();
|
||||
QString password;
|
||||
if (game.with_password() && !(spectator && !game.spectators_need_password()) && !overrideRestrictions) {
|
||||
bool ok;
|
||||
password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok);
|
||||
if (!ok)
|
||||
return;
|
||||
}
|
||||
|
||||
Command_JoinGame cmd;
|
||||
cmd.set_game_id(game.game_id());
|
||||
cmd.set_password(password.toStdString());
|
||||
cmd.set_spectator(spectator);
|
||||
cmd.set_override_restrictions(overrideRestrictions);
|
||||
Command_JoinGame cmd;
|
||||
cmd.set_game_id(game.game_id());
|
||||
cmd.set_password(password.toStdString());
|
||||
cmd.set_spectator(spectator);
|
||||
cmd.set_override_restrictions(overrideRestrictions);
|
||||
|
||||
TabRoom *r = tabSupervisor->getRoomTabs().value(game.room_id());
|
||||
if (!r) {
|
||||
QMessageBox::critical(this, tr("Error"), tr("Please join the respective room first."));
|
||||
return;
|
||||
}
|
||||
TabRoom *r = tabSupervisor->getRoomTabs().value(game.room_id());
|
||||
if (!r) {
|
||||
QMessageBox::critical(this, tr("Error"), tr("Please join the respective room first."));
|
||||
return;
|
||||
}
|
||||
|
||||
PendingCommand *pend = r->prepareRoomCommand(cmd);
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response)));
|
||||
r->sendRoomCommand(pend);
|
||||
PendingCommand *pend = r->prepareRoomCommand(cmd);
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response)));
|
||||
r->sendRoomCommand(pend);
|
||||
|
||||
if (createButton)
|
||||
createButton->setEnabled(false);
|
||||
joinButton->setEnabled(false);
|
||||
spectateButton->setEnabled(false);
|
||||
if (createButton)
|
||||
createButton->setEnabled(false);
|
||||
joinButton->setEnabled(false);
|
||||
spectateButton->setEnabled(false);
|
||||
}
|
||||
|
||||
void GameSelector::retranslateUi()
|
||||
{
|
||||
setTitle(tr("Games"));
|
||||
filterButton->setText(tr("&Filter games"));
|
||||
clearFilterButton->setText(tr("C&lear filter"));
|
||||
if (createButton)
|
||||
createButton->setText(tr("C&reate"));
|
||||
joinButton->setText(tr("&Join"));
|
||||
spectateButton->setText(tr("J&oin as spectator"));
|
||||
setTitle(tr("Games"));
|
||||
filterButton->setText(tr("&Filter games"));
|
||||
clearFilterButton->setText(tr("C&lear filter"));
|
||||
if (createButton)
|
||||
createButton->setText(tr("C&reate"));
|
||||
joinButton->setText(tr("&Join"));
|
||||
spectateButton->setText(tr("J&oin as spectator"));
|
||||
}
|
||||
|
||||
void GameSelector::processGameInfo(const ServerInfo_Game &info)
|
||||
{
|
||||
gameListModel->updateGameList(info);
|
||||
gameListModel->updateGameList(info);
|
||||
}
|
||||
|
|
|
@ -16,28 +16,28 @@ class ServerInfo_Game;
|
|||
class Response;
|
||||
|
||||
class GameSelector : public QGroupBox {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void actSetFilter();
|
||||
void actClearFilter();
|
||||
void actCreate();
|
||||
void actJoin();
|
||||
void checkResponse(const Response &response);
|
||||
void actSetFilter();
|
||||
void actClearFilter();
|
||||
void actCreate();
|
||||
void actJoin();
|
||||
void checkResponse(const Response &response);
|
||||
signals:
|
||||
void gameJoined(int gameId);
|
||||
void gameJoined(int gameId);
|
||||
private:
|
||||
AbstractClient *client;
|
||||
const TabSupervisor *tabSupervisor;
|
||||
TabRoom *room;
|
||||
AbstractClient *client;
|
||||
const TabSupervisor *tabSupervisor;
|
||||
TabRoom *room;
|
||||
|
||||
QTreeView *gameListView;
|
||||
GamesModel *gameListModel;
|
||||
GamesProxyModel *gameListProxyModel;
|
||||
QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton;
|
||||
QTreeView *gameListView;
|
||||
GamesModel *gameListModel;
|
||||
GamesProxyModel *gameListProxyModel;
|
||||
QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton;
|
||||
public:
|
||||
GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, QWidget *parent = 0);
|
||||
void retranslateUi();
|
||||
void processGameInfo(const ServerInfo_Game &info);
|
||||
GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, QWidget *parent = 0);
|
||||
void retranslateUi();
|
||||
void processGameInfo(const ServerInfo_Game &info);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -3,187 +3,187 @@
|
|||
#include <QStringList>
|
||||
|
||||
GamesModel::GamesModel(const QMap<int, QString> &_rooms, const QMap<int, GameTypeMap> &_gameTypes, QObject *parent)
|
||||
: QAbstractTableModel(parent), rooms(_rooms), gameTypes(_gameTypes)
|
||||
: QAbstractTableModel(parent), rooms(_rooms), gameTypes(_gameTypes)
|
||||
{
|
||||
}
|
||||
|
||||
QVariant GamesModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (role == Qt::UserRole)
|
||||
return index.row();
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
if ((index.row() >= gameList.size()) || (index.column() >= columnCount()))
|
||||
return QVariant();
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (role == Qt::UserRole)
|
||||
return index.row();
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
if ((index.row() >= gameList.size()) || (index.column() >= columnCount()))
|
||||
return QVariant();
|
||||
|
||||
const ServerInfo_Game &g = gameList[index.row()];
|
||||
switch (index.column()) {
|
||||
case 0: return QString::fromStdString(g.description());
|
||||
case 1: return rooms.value(g.room_id());
|
||||
case 2: return QString::fromStdString(g.creator_info().name());
|
||||
case 3: {
|
||||
QStringList result;
|
||||
GameTypeMap gameTypeMap = gameTypes.value(g.room_id());
|
||||
for (int i = g.game_types_size() - 1; i >= 0; --i)
|
||||
result.append(gameTypeMap.value(g.game_types(i)));
|
||||
return result.join(", ");
|
||||
}
|
||||
case 4: return g.with_password() ? ((g.spectators_need_password() || !g.spectators_allowed()) ? tr("yes") : tr("yes, free for spectators")) : tr("no");
|
||||
case 5: {
|
||||
QStringList result;
|
||||
if (g.only_buddies())
|
||||
result.append(tr("buddies only"));
|
||||
if (g.only_registered())
|
||||
result.append(tr("reg. users only"));
|
||||
return result.join(", ");
|
||||
}
|
||||
case 6: return QString("%1/%2").arg(g.player_count()).arg(g.max_players());
|
||||
case 7: return g.spectators_allowed() ? QVariant(g.spectators_count()) : QVariant(tr("not allowed"));
|
||||
default: return QVariant();
|
||||
}
|
||||
const ServerInfo_Game &g = gameList[index.row()];
|
||||
switch (index.column()) {
|
||||
case 0: return QString::fromStdString(g.description());
|
||||
case 1: return rooms.value(g.room_id());
|
||||
case 2: return QString::fromStdString(g.creator_info().name());
|
||||
case 3: {
|
||||
QStringList result;
|
||||
GameTypeMap gameTypeMap = gameTypes.value(g.room_id());
|
||||
for (int i = g.game_types_size() - 1; i >= 0; --i)
|
||||
result.append(gameTypeMap.value(g.game_types(i)));
|
||||
return result.join(", ");
|
||||
}
|
||||
case 4: return g.with_password() ? ((g.spectators_need_password() || !g.spectators_allowed()) ? tr("yes") : tr("yes, free for spectators")) : tr("no");
|
||||
case 5: {
|
||||
QStringList result;
|
||||
if (g.only_buddies())
|
||||
result.append(tr("buddies only"));
|
||||
if (g.only_registered())
|
||||
result.append(tr("reg. users only"));
|
||||
return result.join(", ");
|
||||
}
|
||||
case 6: return QString("%1/%2").arg(g.player_count()).arg(g.max_players());
|
||||
case 7: return g.spectators_allowed() ? QVariant(g.spectators_count()) : QVariant(tr("not allowed"));
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
QVariant GamesModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal))
|
||||
return QVariant();
|
||||
switch (section) {
|
||||
case 0: return tr("Description");
|
||||
case 1: return tr("Room");
|
||||
case 2: return tr("Creator");
|
||||
case 3: return tr("Game type");
|
||||
case 4: return tr("Password");
|
||||
case 5: return tr("Restrictions");
|
||||
case 6: return tr("Players");
|
||||
case 7: return tr("Spectators");
|
||||
default: return QVariant();
|
||||
}
|
||||
if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal))
|
||||
return QVariant();
|
||||
switch (section) {
|
||||
case 0: return tr("Description");
|
||||
case 1: return tr("Room");
|
||||
case 2: return tr("Creator");
|
||||
case 3: return tr("Game type");
|
||||
case 4: return tr("Password");
|
||||
case 5: return tr("Restrictions");
|
||||
case 6: return tr("Players");
|
||||
case 7: return tr("Spectators");
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
const ServerInfo_Game &GamesModel::getGame(int row)
|
||||
{
|
||||
Q_ASSERT(row < gameList.size());
|
||||
return gameList[row];
|
||||
Q_ASSERT(row < gameList.size());
|
||||
return gameList[row];
|
||||
}
|
||||
|
||||
void GamesModel::updateGameList(const ServerInfo_Game &game)
|
||||
{
|
||||
for (int i = 0; i < gameList.size(); i++)
|
||||
if (gameList[i].game_id() == game.game_id()) {
|
||||
if (game.closed()) {
|
||||
beginRemoveRows(QModelIndex(), i, i);
|
||||
gameList.removeAt(i);
|
||||
endRemoveRows();
|
||||
} else {
|
||||
gameList[i].MergeFrom(game);
|
||||
emit dataChanged(index(i, 0), index(i, 7));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (game.player_count() <= 0)
|
||||
return;
|
||||
beginInsertRows(QModelIndex(), gameList.size(), gameList.size());
|
||||
gameList.append(game);
|
||||
endInsertRows();
|
||||
for (int i = 0; i < gameList.size(); i++)
|
||||
if (gameList[i].game_id() == game.game_id()) {
|
||||
if (game.closed()) {
|
||||
beginRemoveRows(QModelIndex(), i, i);
|
||||
gameList.removeAt(i);
|
||||
endRemoveRows();
|
||||
} else {
|
||||
gameList[i].MergeFrom(game);
|
||||
emit dataChanged(index(i, 0), index(i, 7));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (game.player_count() <= 0)
|
||||
return;
|
||||
beginInsertRows(QModelIndex(), gameList.size(), gameList.size());
|
||||
gameList.append(game);
|
||||
endInsertRows();
|
||||
}
|
||||
|
||||
GamesProxyModel::GamesProxyModel(QObject *parent, ServerInfo_User *_ownUser)
|
||||
: QSortFilterProxyModel(parent),
|
||||
: QSortFilterProxyModel(parent),
|
||||
ownUser(_ownUser),
|
||||
unavailableGamesVisible(false),
|
||||
maxPlayersFilterMin(-1),
|
||||
maxPlayersFilterMax(-1)
|
||||
{
|
||||
setDynamicSortFilter(true);
|
||||
setDynamicSortFilter(true);
|
||||
}
|
||||
|
||||
void GamesProxyModel::setUnavailableGamesVisible(bool _unavailableGamesVisible)
|
||||
{
|
||||
unavailableGamesVisible = _unavailableGamesVisible;
|
||||
invalidateFilter();
|
||||
unavailableGamesVisible = _unavailableGamesVisible;
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
void GamesProxyModel::setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible)
|
||||
{
|
||||
passwordProtectedGamesVisible = _passwordProtectedGamesVisible;
|
||||
invalidateFilter();
|
||||
passwordProtectedGamesVisible = _passwordProtectedGamesVisible;
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
void GamesProxyModel::setGameNameFilter(const QString &_gameNameFilter)
|
||||
{
|
||||
gameNameFilter = _gameNameFilter;
|
||||
invalidateFilter();
|
||||
gameNameFilter = _gameNameFilter;
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
void GamesProxyModel::setCreatorNameFilter(const QString &_creatorNameFilter)
|
||||
{
|
||||
creatorNameFilter = _creatorNameFilter;
|
||||
invalidateFilter();
|
||||
creatorNameFilter = _creatorNameFilter;
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
void GamesProxyModel::setGameTypeFilter(const QSet<int> &_gameTypeFilter)
|
||||
{
|
||||
gameTypeFilter = _gameTypeFilter;
|
||||
invalidateFilter();
|
||||
gameTypeFilter = _gameTypeFilter;
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
void GamesProxyModel::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax)
|
||||
{
|
||||
maxPlayersFilterMin = _maxPlayersFilterMin;
|
||||
maxPlayersFilterMax = _maxPlayersFilterMax;
|
||||
invalidateFilter();
|
||||
maxPlayersFilterMin = _maxPlayersFilterMin;
|
||||
maxPlayersFilterMax = _maxPlayersFilterMax;
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
void GamesProxyModel::resetFilterParameters()
|
||||
{
|
||||
unavailableGamesVisible = false;
|
||||
passwordProtectedGamesVisible = false;
|
||||
gameNameFilter = QString();
|
||||
creatorNameFilter = QString();
|
||||
gameTypeFilter.clear();
|
||||
maxPlayersFilterMin = -1;
|
||||
maxPlayersFilterMax = -1;
|
||||
unavailableGamesVisible = false;
|
||||
passwordProtectedGamesVisible = false;
|
||||
gameNameFilter = QString();
|
||||
creatorNameFilter = QString();
|
||||
gameTypeFilter.clear();
|
||||
maxPlayersFilterMin = -1;
|
||||
maxPlayersFilterMax = -1;
|
||||
|
||||
invalidateFilter();
|
||||
invalidateFilter();
|
||||
}
|
||||
|
||||
bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourceParent*/) const
|
||||
{
|
||||
GamesModel *model = qobject_cast<GamesModel *>(sourceModel());
|
||||
if (!model)
|
||||
return false;
|
||||
GamesModel *model = qobject_cast<GamesModel *>(sourceModel());
|
||||
if (!model)
|
||||
return false;
|
||||
|
||||
const ServerInfo_Game &game = model->getGame(sourceRow);
|
||||
if (!unavailableGamesVisible) {
|
||||
if (game.player_count() == game.max_players())
|
||||
return false;
|
||||
if (game.started())
|
||||
return false;
|
||||
if (!(ownUser->user_level() & ServerInfo_User::IsRegistered))
|
||||
if (game.only_registered())
|
||||
return false;
|
||||
}
|
||||
if (!passwordProtectedGamesVisible && game.with_password())
|
||||
return false;
|
||||
if (!gameNameFilter.isEmpty())
|
||||
if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive))
|
||||
return false;
|
||||
if (!creatorNameFilter.isEmpty())
|
||||
if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive))
|
||||
return false;
|
||||
const ServerInfo_Game &game = model->getGame(sourceRow);
|
||||
if (!unavailableGamesVisible) {
|
||||
if (game.player_count() == game.max_players())
|
||||
return false;
|
||||
if (game.started())
|
||||
return false;
|
||||
if (!(ownUser->user_level() & ServerInfo_User::IsRegistered))
|
||||
if (game.only_registered())
|
||||
return false;
|
||||
}
|
||||
if (!passwordProtectedGamesVisible && game.with_password())
|
||||
return false;
|
||||
if (!gameNameFilter.isEmpty())
|
||||
if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive))
|
||||
return false;
|
||||
if (!creatorNameFilter.isEmpty())
|
||||
if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive))
|
||||
return false;
|
||||
|
||||
QSet<int> gameTypes;
|
||||
for (int i = 0; i < game.game_types_size(); ++i)
|
||||
gameTypes.insert(game.game_types(i));
|
||||
if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty())
|
||||
return false;
|
||||
QSet<int> gameTypes;
|
||||
for (int i = 0; i < game.game_types_size(); ++i)
|
||||
gameTypes.insert(game.game_types(i));
|
||||
if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty())
|
||||
return false;
|
||||
|
||||
if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin))
|
||||
return false;
|
||||
if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax))
|
||||
return false;
|
||||
if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin))
|
||||
return false;
|
||||
if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -11,51 +11,51 @@
|
|||
class ServerInfo_User;
|
||||
|
||||
class GamesModel : public QAbstractTableModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QList<ServerInfo_Game> gameList;
|
||||
QMap<int, QString> rooms;
|
||||
QMap<int, GameTypeMap> gameTypes;
|
||||
QList<ServerInfo_Game> gameList;
|
||||
QMap<int, QString> rooms;
|
||||
QMap<int, GameTypeMap> gameTypes;
|
||||
public:
|
||||
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 8; }
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
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 8; }
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
|
||||
const ServerInfo_Game &getGame(int row);
|
||||
void updateGameList(const ServerInfo_Game &game);
|
||||
const QMap<int, GameTypeMap> &getGameTypes() { return gameTypes; }
|
||||
const ServerInfo_Game &getGame(int row);
|
||||
void updateGameList(const ServerInfo_Game &game);
|
||||
const QMap<int, GameTypeMap> &getGameTypes() { return gameTypes; }
|
||||
};
|
||||
|
||||
class GamesProxyModel : public QSortFilterProxyModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
ServerInfo_User *ownUser;
|
||||
bool unavailableGamesVisible;
|
||||
bool passwordProtectedGamesVisible;
|
||||
QString gameNameFilter, creatorNameFilter;
|
||||
QSet<int> gameTypeFilter;
|
||||
int maxPlayersFilterMin, maxPlayersFilterMax;
|
||||
ServerInfo_User *ownUser;
|
||||
bool unavailableGamesVisible;
|
||||
bool passwordProtectedGamesVisible;
|
||||
QString gameNameFilter, creatorNameFilter;
|
||||
QSet<int> gameTypeFilter;
|
||||
int maxPlayersFilterMin, maxPlayersFilterMax;
|
||||
public:
|
||||
GamesProxyModel(QObject *parent = 0, ServerInfo_User *_ownUser = 0);
|
||||
GamesProxyModel(QObject *parent = 0, ServerInfo_User *_ownUser = 0);
|
||||
|
||||
bool getUnavailableGamesVisible() const { return unavailableGamesVisible; }
|
||||
void setUnavailableGamesVisible(bool _unavailableGamesVisible);
|
||||
bool getPasswordProtectedGamesVisible() const { return passwordProtectedGamesVisible; }
|
||||
void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible);
|
||||
QString getGameNameFilter() const { return gameNameFilter; }
|
||||
void setGameNameFilter(const QString &_gameNameFilter);
|
||||
QString getCreatorNameFilter() const { return creatorNameFilter; }
|
||||
void setCreatorNameFilter(const QString &_creatorNameFilter);
|
||||
QSet<int> getGameTypeFilter() const { return gameTypeFilter; }
|
||||
void setGameTypeFilter(const QSet<int> &_gameTypeFilter);
|
||||
int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; }
|
||||
int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; }
|
||||
void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax);
|
||||
void resetFilterParameters();
|
||||
bool getUnavailableGamesVisible() const { return unavailableGamesVisible; }
|
||||
void setUnavailableGamesVisible(bool _unavailableGamesVisible);
|
||||
bool getPasswordProtectedGamesVisible() const { return passwordProtectedGamesVisible; }
|
||||
void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible);
|
||||
QString getGameNameFilter() const { return gameNameFilter; }
|
||||
void setGameNameFilter(const QString &_gameNameFilter);
|
||||
QString getCreatorNameFilter() const { return creatorNameFilter; }
|
||||
void setCreatorNameFilter(const QString &_creatorNameFilter);
|
||||
QSet<int> getGameTypeFilter() const { return gameTypeFilter; }
|
||||
void setGameTypeFilter(const QSet<int> &_gameTypeFilter);
|
||||
int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; }
|
||||
int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; }
|
||||
void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax);
|
||||
void resetFilterParameters();
|
||||
protected:
|
||||
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
|
||||
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -5,57 +5,57 @@
|
|||
#include <QRubberBand>
|
||||
|
||||
GameView::GameView(QGraphicsScene *scene, QWidget *parent)
|
||||
: QGraphicsView(scene, parent), rubberBand(0)
|
||||
: QGraphicsView(scene, parent), rubberBand(0)
|
||||
{
|
||||
setBackgroundBrush(QBrush(QColor(0, 0, 0)));
|
||||
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing);
|
||||
setFocusPolicy(Qt::NoFocus);
|
||||
setViewportUpdateMode(BoundingRectViewportUpdate);
|
||||
setBackgroundBrush(QBrush(QColor(0, 0, 0)));
|
||||
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing);
|
||||
setFocusPolicy(Qt::NoFocus);
|
||||
setViewportUpdateMode(BoundingRectViewportUpdate);
|
||||
|
||||
connect(scene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &)));
|
||||
connect(scene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &)));
|
||||
|
||||
connect(scene, SIGNAL(sigStartRubberBand(const QPointF &)), this, SLOT(startRubberBand(const QPointF &)));
|
||||
connect(scene, SIGNAL(sigResizeRubberBand(const QPointF &)), this, SLOT(resizeRubberBand(const QPointF &)));
|
||||
connect(scene, SIGNAL(sigStopRubberBand()), this, SLOT(stopRubberBand()));
|
||||
connect(scene, SIGNAL(sigStartRubberBand(const QPointF &)), this, SLOT(startRubberBand(const QPointF &)));
|
||||
connect(scene, SIGNAL(sigResizeRubberBand(const QPointF &)), this, SLOT(resizeRubberBand(const QPointF &)));
|
||||
connect(scene, SIGNAL(sigStopRubberBand()), this, SLOT(stopRubberBand()));
|
||||
|
||||
aCloseMostRecentZoneView = new QAction(this);
|
||||
aCloseMostRecentZoneView->setShortcut(tr("Esc"));
|
||||
connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView()));
|
||||
addAction(aCloseMostRecentZoneView);
|
||||
aCloseMostRecentZoneView = new QAction(this);
|
||||
aCloseMostRecentZoneView->setShortcut(tr("Esc"));
|
||||
connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView()));
|
||||
addAction(aCloseMostRecentZoneView);
|
||||
|
||||
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
|
||||
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
|
||||
}
|
||||
|
||||
void GameView::resizeEvent(QResizeEvent *event)
|
||||
{
|
||||
QGraphicsView::resizeEvent(event);
|
||||
QGraphicsView::resizeEvent(event);
|
||||
|
||||
GameScene *s = dynamic_cast<GameScene *>(scene());
|
||||
if (s)
|
||||
s->processViewSizeChange(event->size());
|
||||
GameScene *s = dynamic_cast<GameScene *>(scene());
|
||||
if (s)
|
||||
s->processViewSizeChange(event->size());
|
||||
|
||||
updateSceneRect(scene()->sceneRect());
|
||||
updateSceneRect(scene()->sceneRect());
|
||||
}
|
||||
|
||||
void GameView::updateSceneRect(const QRectF &rect)
|
||||
{
|
||||
fitInView(rect, Qt::KeepAspectRatio);
|
||||
fitInView(rect, Qt::KeepAspectRatio);
|
||||
}
|
||||
|
||||
void GameView::startRubberBand(const QPointF &_selectionOrigin)
|
||||
{
|
||||
selectionOrigin = _selectionOrigin;
|
||||
rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0)));
|
||||
rubberBand->show();
|
||||
selectionOrigin = _selectionOrigin;
|
||||
rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0)));
|
||||
rubberBand->show();
|
||||
}
|
||||
|
||||
void GameView::resizeRubberBand(const QPointF &cursorPoint)
|
||||
{
|
||||
if (rubberBand)
|
||||
rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized());
|
||||
if (rubberBand)
|
||||
rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized());
|
||||
}
|
||||
|
||||
void GameView::stopRubberBand()
|
||||
{
|
||||
rubberBand->hide();
|
||||
rubberBand->hide();
|
||||
}
|
||||
|
|
|
@ -6,21 +6,21 @@
|
|||
class QRubberBand;
|
||||
|
||||
class GameView : public QGraphicsView {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QAction *aCloseMostRecentZoneView;
|
||||
QRubberBand *rubberBand;
|
||||
QPointF selectionOrigin;
|
||||
QAction *aCloseMostRecentZoneView;
|
||||
QRubberBand *rubberBand;
|
||||
QPointF selectionOrigin;
|
||||
protected:
|
||||
void resizeEvent(QResizeEvent *event);
|
||||
void resizeEvent(QResizeEvent *event);
|
||||
private slots:
|
||||
void startRubberBand(const QPointF &selectionOrigin);
|
||||
void resizeRubberBand(const QPointF &cursorPoint);
|
||||
void stopRubberBand();
|
||||
void startRubberBand(const QPointF &selectionOrigin);
|
||||
void resizeRubberBand(const QPointF &cursorPoint);
|
||||
void stopRubberBand();
|
||||
public slots:
|
||||
void updateSceneRect(const QRectF &rect);
|
||||
void updateSceneRect(const QRectF &rect);
|
||||
public:
|
||||
GameView(QGraphicsScene *scene, QWidget *parent = 0);
|
||||
GameView(QGraphicsScene *scene, QWidget *parent = 0);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -6,9 +6,9 @@
|
|||
#include "cardzone.h"
|
||||
|
||||
HandCounter::HandCounter(QGraphicsItem *parent)
|
||||
: AbstractGraphicsItem(parent), number(0)
|
||||
: AbstractGraphicsItem(parent), number(0)
|
||||
{
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
}
|
||||
|
||||
HandCounter::~HandCounter()
|
||||
|
@ -17,43 +17,43 @@ HandCounter::~HandCounter()
|
|||
|
||||
void HandCounter::updateNumber()
|
||||
{
|
||||
number = static_cast<CardZone *>(sender())->getCards().size();
|
||||
update();
|
||||
number = static_cast<CardZone *>(sender())->getCards().size();
|
||||
update();
|
||||
}
|
||||
|
||||
QRectF HandCounter::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, 72, 72);
|
||||
return QRectF(0, 0, 72, 72);
|
||||
}
|
||||
|
||||
void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
painter->save();
|
||||
QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize();
|
||||
QPixmap cachedPixmap;
|
||||
painter->save();
|
||||
QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize();
|
||||
QPixmap cachedPixmap;
|
||||
#if QT_VERSION >= 0x040600
|
||||
if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) {
|
||||
if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) {
|
||||
#else
|
||||
if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), cachedPixmap)) {
|
||||
if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), cachedPixmap)) {
|
||||
#endif
|
||||
QSvgRenderer svg(QString(":/resources/hand.svg"));
|
||||
cachedPixmap = QPixmap(translatedSize);
|
||||
cachedPixmap.fill(Qt::transparent);
|
||||
QPainter painter(&cachedPixmap);
|
||||
svg.render(&painter, QRectF(0, 0, translatedSize.width(), translatedSize.height()));
|
||||
QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap);
|
||||
}
|
||||
painter->resetTransform();
|
||||
painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect());
|
||||
painter->restore();
|
||||
QSvgRenderer svg(QString(":/resources/hand.svg"));
|
||||
cachedPixmap = QPixmap(translatedSize);
|
||||
cachedPixmap.fill(Qt::transparent);
|
||||
QPainter painter(&cachedPixmap);
|
||||
svg.render(&painter, QRectF(0, 0, translatedSize.width(), translatedSize.height()));
|
||||
QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap);
|
||||
}
|
||||
painter->resetTransform();
|
||||
painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect());
|
||||
painter->restore();
|
||||
|
||||
paintNumberEllipse(number, 24, Qt::white, -1, -1, painter);
|
||||
paintNumberEllipse(number, 24, Qt::white, -1, -1, painter);
|
||||
}
|
||||
|
||||
void HandCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::RightButton) {
|
||||
emit showContextMenu(event->screenPos());
|
||||
event->accept();
|
||||
}
|
||||
if (event->button() == Qt::RightButton) {
|
||||
emit showContextMenu(event->screenPos());
|
||||
event->accept();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,22 +8,22 @@ class QPainter;
|
|||
class QPixmap;
|
||||
|
||||
class HandCounter : public AbstractGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
int number;
|
||||
int number;
|
||||
protected:
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
public slots:
|
||||
void updateNumber();
|
||||
void updateNumber();
|
||||
signals:
|
||||
void showContextMenu(const QPoint &screenPos);
|
||||
void showContextMenu(const QPoint &screenPos);
|
||||
public:
|
||||
enum { Type = typeOther };
|
||||
int type() const { return Type; }
|
||||
HandCounter(QGraphicsItem *parent = 0);
|
||||
~HandCounter();
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
enum { Type = typeOther };
|
||||
int type() const { return Type; }
|
||||
HandCounter(QGraphicsItem *parent = 0);
|
||||
~HandCounter();
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -8,137 +8,137 @@
|
|||
#include "pb/command_move_card.pb.h"
|
||||
|
||||
HandZone::HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent)
|
||||
: SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight)
|
||||
: SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight)
|
||||
{
|
||||
connect(settingsCache, SIGNAL(handBgPathChanged()), this, SLOT(updateBgPixmap()));
|
||||
updateBgPixmap();
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
connect(settingsCache, SIGNAL(handBgPathChanged()), this, SLOT(updateBgPixmap()));
|
||||
updateBgPixmap();
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
}
|
||||
|
||||
void HandZone::updateBgPixmap()
|
||||
{
|
||||
QString bgPath = settingsCache->getHandBgPath();
|
||||
if (!bgPath.isEmpty())
|
||||
bgPixmap.load(bgPath);
|
||||
update();
|
||||
QString bgPath = settingsCache->getHandBgPath();
|
||||
if (!bgPath.isEmpty())
|
||||
bgPixmap.load(bgPath);
|
||||
update();
|
||||
}
|
||||
|
||||
void HandZone::addCardImpl(CardItem *card, int x, int /*y*/)
|
||||
{
|
||||
if (x == -1)
|
||||
x = cards.size();
|
||||
cards.insert(x, card);
|
||||
if (x == -1)
|
||||
x = cards.size();
|
||||
cards.insert(x, card);
|
||||
|
||||
if (!cards.getContentsKnown()) {
|
||||
card->setId(-1);
|
||||
card->setName();
|
||||
}
|
||||
card->setParentItem(this);
|
||||
card->resetState();
|
||||
card->setVisible(true);
|
||||
card->update();
|
||||
if (!cards.getContentsKnown()) {
|
||||
card->setId(-1);
|
||||
card->setName();
|
||||
}
|
||||
card->setParentItem(this);
|
||||
card->resetState();
|
||||
card->setVisible(true);
|
||||
card->update();
|
||||
}
|
||||
|
||||
void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint & dropPoint)
|
||||
{
|
||||
QPoint point = dropPoint + scenePos().toPoint();
|
||||
int x = -1;
|
||||
if (settingsCache->getHorizontalHand()) {
|
||||
for (x = 0; x < cards.size(); x++)
|
||||
if (point.x() < ((CardItem *) cards.at(x))->scenePos().x())
|
||||
break;
|
||||
} else {
|
||||
for (x = 0; x < cards.size(); x++)
|
||||
if (point.y() < ((CardItem *) cards.at(x))->scenePos().y())
|
||||
break;
|
||||
}
|
||||
QPoint point = dropPoint + scenePos().toPoint();
|
||||
int x = -1;
|
||||
if (settingsCache->getHorizontalHand()) {
|
||||
for (x = 0; x < cards.size(); x++)
|
||||
if (point.x() < ((CardItem *) cards.at(x))->scenePos().x())
|
||||
break;
|
||||
} else {
|
||||
for (x = 0; x < cards.size(); x++)
|
||||
if (point.y() < ((CardItem *) cards.at(x))->scenePos().y())
|
||||
break;
|
||||
}
|
||||
|
||||
Command_MoveCard cmd;
|
||||
cmd.set_start_player_id(startZone->getPlayer()->getId());
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_target_player_id(player->getId());
|
||||
cmd.set_target_zone(getName().toStdString());
|
||||
cmd.set_x(x);
|
||||
cmd.set_y(-1);
|
||||
Command_MoveCard cmd;
|
||||
cmd.set_start_player_id(startZone->getPlayer()->getId());
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_target_player_id(player->getId());
|
||||
cmd.set_target_zone(getName().toStdString());
|
||||
cmd.set_x(x);
|
||||
cmd.set_y(-1);
|
||||
|
||||
for (int i = 0; i < dragItems.size(); ++i)
|
||||
cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId());
|
||||
for (int i = 0; i < dragItems.size(); ++i)
|
||||
cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId());
|
||||
|
||||
player->sendGameCommand(cmd);
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
|
||||
QRectF HandZone::boundingRect() const
|
||||
{
|
||||
if (settingsCache->getHorizontalHand())
|
||||
return QRectF(0, 0, width, CARD_HEIGHT + 10);
|
||||
else
|
||||
return QRectF(0, 0, 100, zoneHeight);
|
||||
if (settingsCache->getHorizontalHand())
|
||||
return QRectF(0, 0, width, CARD_HEIGHT + 10);
|
||||
else
|
||||
return QRectF(0, 0, 100, zoneHeight);
|
||||
}
|
||||
|
||||
void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/)
|
||||
{
|
||||
if (bgPixmap.isNull())
|
||||
painter->fillRect(boundingRect(), Qt::darkGreen);
|
||||
else
|
||||
painter->fillRect(boundingRect(), QBrush(bgPixmap));
|
||||
if (bgPixmap.isNull())
|
||||
painter->fillRect(boundingRect(), Qt::darkGreen);
|
||||
else
|
||||
painter->fillRect(boundingRect(), QBrush(bgPixmap));
|
||||
}
|
||||
|
||||
void HandZone::reorganizeCards()
|
||||
{
|
||||
if (!cards.isEmpty()) {
|
||||
const int cardCount = cards.size();
|
||||
if (settingsCache->getHorizontalHand()) {
|
||||
const int xPadding = 5;
|
||||
qreal totalWidth = boundingRect().width() - 2 * xPadding;
|
||||
qreal cardWidth = cards.at(0)->boundingRect().width();
|
||||
if (!cards.isEmpty()) {
|
||||
const int cardCount = cards.size();
|
||||
if (settingsCache->getHorizontalHand()) {
|
||||
const int xPadding = 5;
|
||||
qreal totalWidth = boundingRect().width() - 2 * xPadding;
|
||||
qreal cardWidth = cards.at(0)->boundingRect().width();
|
||||
|
||||
for (int i = 0; i < cardCount; i++) {
|
||||
CardItem *c = cards.at(i);
|
||||
for (int i = 0; i < cardCount; i++) {
|
||||
CardItem *c = cards.at(i);
|
||||
|
||||
// If the total width of the cards is smaller than the available width,
|
||||
// the cards do not need to overlap and are displayed in the center of the area.
|
||||
if (cardWidth * cardCount > totalWidth)
|
||||
c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
|
||||
else
|
||||
c->setPos(xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2, 5);
|
||||
c->setRealZValue(i);
|
||||
}
|
||||
} else {
|
||||
qreal totalWidth = boundingRect().width();
|
||||
qreal totalHeight = boundingRect().height();
|
||||
qreal cardWidth = cards.at(0)->boundingRect().width();
|
||||
qreal cardHeight = cards.at(0)->boundingRect().height();
|
||||
qreal xspace = 5;
|
||||
qreal x1 = xspace;
|
||||
qreal x2 = totalWidth - xspace - cardWidth;
|
||||
// If the total width of the cards is smaller than the available width,
|
||||
// the cards do not need to overlap and are displayed in the center of the area.
|
||||
if (cardWidth * cardCount > totalWidth)
|
||||
c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
|
||||
else
|
||||
c->setPos(xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2, 5);
|
||||
c->setRealZValue(i);
|
||||
}
|
||||
} else {
|
||||
qreal totalWidth = boundingRect().width();
|
||||
qreal totalHeight = boundingRect().height();
|
||||
qreal cardWidth = cards.at(0)->boundingRect().width();
|
||||
qreal cardHeight = cards.at(0)->boundingRect().height();
|
||||
qreal xspace = 5;
|
||||
qreal x1 = xspace;
|
||||
qreal x2 = totalWidth - xspace - cardWidth;
|
||||
|
||||
for (int i = 0; i < cardCount; i++) {
|
||||
CardItem *c = cards.at(i);
|
||||
qreal x = i % 2 ? x2 : x1;
|
||||
// If the total height of the cards is smaller than the available height,
|
||||
// the cards do not need to overlap and are displayed in the center of the area.
|
||||
if (cardHeight * cardCount > totalHeight)
|
||||
c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1));
|
||||
else
|
||||
c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2);
|
||||
c->setRealZValue(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
update();
|
||||
for (int i = 0; i < cardCount; i++) {
|
||||
CardItem *c = cards.at(i);
|
||||
qreal x = i % 2 ? x2 : x1;
|
||||
// If the total height of the cards is smaller than the available height,
|
||||
// the cards do not need to overlap and are displayed in the center of the area.
|
||||
if (cardHeight * cardCount > totalHeight)
|
||||
c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1));
|
||||
else
|
||||
c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2);
|
||||
c->setRealZValue(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void HandZone::setWidth(qreal _width)
|
||||
{
|
||||
if (settingsCache->getHorizontalHand()) {
|
||||
prepareGeometryChange();
|
||||
width = _width;
|
||||
reorganizeCards();
|
||||
}
|
||||
if (settingsCache->getHorizontalHand()) {
|
||||
prepareGeometryChange();
|
||||
width = _width;
|
||||
reorganizeCards();
|
||||
}
|
||||
}
|
||||
|
||||
void HandZone::updateOrientation()
|
||||
{
|
||||
prepareGeometryChange();
|
||||
reorganizeCards();
|
||||
prepareGeometryChange();
|
||||
reorganizeCards();
|
||||
}
|
||||
|
|
|
@ -4,23 +4,23 @@
|
|||
#include "selectzone.h"
|
||||
|
||||
class HandZone : public SelectZone {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
qreal width, zoneHeight;
|
||||
QPixmap bgPixmap;
|
||||
qreal width, zoneHeight;
|
||||
QPixmap bgPixmap;
|
||||
private slots:
|
||||
void updateBgPixmap();
|
||||
void updateBgPixmap();
|
||||
public slots:
|
||||
void updateOrientation();
|
||||
void updateOrientation();
|
||||
public:
|
||||
HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0);
|
||||
void handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint &dropPoint);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void reorganizeCards();
|
||||
void setWidth(qreal _width);
|
||||
HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0);
|
||||
void handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint &dropPoint);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void reorganizeCards();
|
||||
void setWidth(qreal _width);
|
||||
protected:
|
||||
void addCardImpl(CardItem *card, int x, int y);
|
||||
void addCardImpl(CardItem *card, int x, int y);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -4,17 +4,17 @@
|
|||
#include "pb/session_commands.pb.h"
|
||||
|
||||
LocalClient::LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent)
|
||||
: AbstractClient(parent), lsi(_lsi)
|
||||
: AbstractClient(parent), lsi(_lsi)
|
||||
{
|
||||
connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &)));
|
||||
connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &)));
|
||||
|
||||
Command_Login loginCmd;
|
||||
loginCmd.set_user_name(_playerName.toStdString());
|
||||
sendCommand(prepareSessionCommand(loginCmd));
|
||||
Command_Login loginCmd;
|
||||
loginCmd.set_user_name(_playerName.toStdString());
|
||||
sendCommand(prepareSessionCommand(loginCmd));
|
||||
|
||||
Command_JoinRoom joinCmd;
|
||||
joinCmd.set_room_id(0);
|
||||
sendCommand(prepareSessionCommand(joinCmd));
|
||||
Command_JoinRoom joinCmd;
|
||||
joinCmd.set_room_id(0);
|
||||
sendCommand(prepareSessionCommand(joinCmd));
|
||||
}
|
||||
|
||||
LocalClient::~LocalClient()
|
||||
|
@ -23,10 +23,10 @@ LocalClient::~LocalClient()
|
|||
|
||||
void LocalClient::sendCommandContainer(const CommandContainer &cont)
|
||||
{
|
||||
lsi->itemFromClient(cont);
|
||||
lsi->itemFromClient(cont);
|
||||
}
|
||||
|
||||
void LocalClient::itemFromServer(const ServerMessage &item)
|
||||
{
|
||||
processProtocolItem(item);
|
||||
processProtocolItem(item);
|
||||
}
|
||||
|
|
|
@ -6,16 +6,16 @@
|
|||
class LocalServerInterface;
|
||||
|
||||
class LocalClient : public AbstractClient {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
LocalServerInterface *lsi;
|
||||
LocalServerInterface *lsi;
|
||||
public:
|
||||
LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent = 0);
|
||||
~LocalClient();
|
||||
LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent = 0);
|
||||
~LocalClient();
|
||||
|
||||
void sendCommandContainer(const CommandContainer &cont);
|
||||
void sendCommandContainer(const CommandContainer &cont);
|
||||
private slots:
|
||||
void itemFromServer(const ServerMessage &item);
|
||||
void itemFromServer(const ServerMessage &item);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -3,37 +3,37 @@
|
|||
#include "server_room.h"
|
||||
|
||||
LocalServer::LocalServer(QObject *parent)
|
||||
: Server(false, parent)
|
||||
: Server(false, parent)
|
||||
{
|
||||
setDatabaseInterface(new LocalServer_DatabaseInterface(this));
|
||||
addRoom(new Server_Room(0, QString(), QString(), false, QString(), QStringList(), this));
|
||||
setDatabaseInterface(new LocalServer_DatabaseInterface(this));
|
||||
addRoom(new Server_Room(0, QString(), QString(), false, QString(), QStringList(), this));
|
||||
}
|
||||
|
||||
LocalServer::~LocalServer()
|
||||
{
|
||||
prepareDestroy();
|
||||
prepareDestroy();
|
||||
}
|
||||
|
||||
LocalServerInterface *LocalServer::newConnection()
|
||||
{
|
||||
LocalServerInterface *lsi = new LocalServerInterface(this, getDatabaseInterface());
|
||||
addClient(lsi);
|
||||
return lsi;
|
||||
LocalServerInterface *lsi = new LocalServerInterface(this, getDatabaseInterface());
|
||||
addClient(lsi);
|
||||
return lsi;
|
||||
}
|
||||
|
||||
LocalServer_DatabaseInterface::LocalServer_DatabaseInterface(LocalServer *_localServer)
|
||||
: Server_DatabaseInterface(_localServer), localServer(_localServer)
|
||||
: Server_DatabaseInterface(_localServer), localServer(_localServer)
|
||||
{
|
||||
}
|
||||
|
||||
ServerInfo_User LocalServer_DatabaseInterface::getUserData(const QString &name, bool /*withId*/)
|
||||
{
|
||||
ServerInfo_User result;
|
||||
result.set_name(name.toStdString());
|
||||
return result;
|
||||
ServerInfo_User result;
|
||||
result.set_name(name.toStdString());
|
||||
return result;
|
||||
}
|
||||
|
||||
AuthenticationResult LocalServer_DatabaseInterface::checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft)
|
||||
{
|
||||
return UnknownUser;
|
||||
return UnknownUser;
|
||||
}
|
||||
|
|
|
@ -8,25 +8,25 @@ class LocalServerInterface;
|
|||
|
||||
class LocalServer : public Server
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
LocalServer(QObject *parent = 0);
|
||||
~LocalServer();
|
||||
LocalServer(QObject *parent = 0);
|
||||
~LocalServer();
|
||||
|
||||
LocalServerInterface *newConnection();
|
||||
LocalServerInterface *newConnection();
|
||||
};
|
||||
|
||||
class LocalServer_DatabaseInterface : public Server_DatabaseInterface {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
LocalServer *localServer;
|
||||
LocalServer *localServer;
|
||||
protected:
|
||||
ServerInfo_User getUserData(const QString &name, bool withId = false);
|
||||
ServerInfo_User getUserData(const QString &name, bool withId = false);
|
||||
public:
|
||||
LocalServer_DatabaseInterface(LocalServer *_localServer);
|
||||
AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft);
|
||||
int getNextGameId() { return localServer->getNextLocalGameId(); }
|
||||
int getNextReplayId() { return -1; }
|
||||
LocalServer_DatabaseInterface(LocalServer *_localServer);
|
||||
AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft);
|
||||
int getNextGameId() { return localServer->getNextLocalGameId(); }
|
||||
int getNextReplayId() { return -1; }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
#include <QDebug>
|
||||
|
||||
LocalServerInterface::LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface)
|
||||
: Server_ProtocolHandler(_server, _databaseInterface, _server)
|
||||
: Server_ProtocolHandler(_server, _databaseInterface, _server)
|
||||
{
|
||||
}
|
||||
|
||||
|
@ -13,10 +13,10 @@ LocalServerInterface::~LocalServerInterface()
|
|||
|
||||
void LocalServerInterface::transmitProtocolItem(const ServerMessage &item)
|
||||
{
|
||||
emit itemToClient(item);
|
||||
emit itemToClient(item);
|
||||
}
|
||||
|
||||
void LocalServerInterface::itemFromClient(const CommandContainer &item)
|
||||
{
|
||||
processCommandContainer(item);
|
||||
processCommandContainer(item);
|
||||
}
|
||||
|
|
|
@ -7,17 +7,17 @@ class LocalServer;
|
|||
|
||||
class LocalServerInterface : public Server_ProtocolHandler
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface);
|
||||
~LocalServerInterface();
|
||||
LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface);
|
||||
~LocalServerInterface();
|
||||
|
||||
QString getAddress() const { return QString(); }
|
||||
void transmitProtocolItem(const ServerMessage &item);
|
||||
QString getAddress() const { return QString(); }
|
||||
void transmitProtocolItem(const ServerMessage &item);
|
||||
signals:
|
||||
void itemToClient(const ServerMessage &item);
|
||||
void itemToClient(const ServerMessage &item);
|
||||
public slots:
|
||||
void itemFromClient(const CommandContainer &item);
|
||||
void itemFromClient(const CommandContainer &item);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -56,118 +56,118 @@ QString translationPath = QString();
|
|||
|
||||
void myMessageOutput(QtMsgType /*type*/, const char *msg)
|
||||
{
|
||||
static FILE *f = NULL;
|
||||
if (!f)
|
||||
f = fopen("qdebug.txt", "w");
|
||||
fprintf(f, "%s\n", msg);
|
||||
fflush(f);
|
||||
static FILE *f = NULL;
|
||||
if (!f)
|
||||
f = fopen("qdebug.txt", "w");
|
||||
fprintf(f, "%s\n", msg);
|
||||
fflush(f);
|
||||
}
|
||||
|
||||
void installNewTranslator()
|
||||
{
|
||||
QString lang = settingsCache->getLang();
|
||||
QString lang = settingsCache->getLang();
|
||||
|
||||
qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
|
||||
qApp->installTranslator(qtTranslator);
|
||||
translator->load(translationPrefix + "_" + lang, translationPath);
|
||||
qApp->installTranslator(translator);
|
||||
qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
|
||||
qApp->installTranslator(qtTranslator);
|
||||
translator->load(translationPrefix + "_" + lang, translationPath);
|
||||
qApp->installTranslator(translator);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QApplication app(argc, argv);
|
||||
QApplication app(argc, argv);
|
||||
|
||||
if (app.arguments().contains("--debug-output"))
|
||||
qInstallMsgHandler(myMessageOutput);
|
||||
if (app.arguments().contains("--debug-output"))
|
||||
qInstallMsgHandler(myMessageOutput);
|
||||
#ifdef Q_OS_MAC
|
||||
QDir baseDir(app.applicationDirPath());
|
||||
baseDir.cdUp();
|
||||
baseDir.cdUp();
|
||||
baseDir.cdUp();
|
||||
QDir pluginsDir = baseDir;
|
||||
pluginsDir.cd("PlugIns");
|
||||
app.addLibraryPath(pluginsDir.absolutePath());
|
||||
QDir baseDir(app.applicationDirPath());
|
||||
baseDir.cdUp();
|
||||
baseDir.cdUp();
|
||||
baseDir.cdUp();
|
||||
QDir pluginsDir = baseDir;
|
||||
pluginsDir.cd("PlugIns");
|
||||
app.addLibraryPath(pluginsDir.absolutePath());
|
||||
#endif
|
||||
#ifdef Q_OS_WIN
|
||||
app.addLibraryPath(app.applicationDirPath() + "/plugins");
|
||||
app.addLibraryPath(app.applicationDirPath() + "/plugins");
|
||||
#endif
|
||||
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
|
||||
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
|
||||
|
||||
QCoreApplication::setOrganizationName("Cockatrice");
|
||||
QCoreApplication::setOrganizationDomain("cockatrice.de");
|
||||
QCoreApplication::setApplicationName("Cockatrice");
|
||||
QCoreApplication::setOrganizationName("Cockatrice");
|
||||
QCoreApplication::setOrganizationDomain("cockatrice.de");
|
||||
QCoreApplication::setApplicationName("Cockatrice");
|
||||
|
||||
if (translationPath.isEmpty()) {
|
||||
if (translationPath.isEmpty()) {
|
||||
#ifdef Q_OS_MAC
|
||||
QDir translationsDir = baseDir;
|
||||
translationsDir.cd("translations");
|
||||
translationPath = translationsDir.absolutePath();
|
||||
QDir translationsDir = baseDir;
|
||||
translationsDir.cd("translations");
|
||||
translationPath = translationsDir.absolutePath();
|
||||
#endif
|
||||
#ifdef Q_OS_WIN
|
||||
translationPath = app.applicationDirPath() + "/translations";
|
||||
translationPath = app.applicationDirPath() + "/translations";
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
rng = new RNG_SFMT;
|
||||
settingsCache = new SettingsCache;
|
||||
db = new CardDatabase;
|
||||
rng = new RNG_SFMT;
|
||||
settingsCache = new SettingsCache;
|
||||
db = new CardDatabase;
|
||||
|
||||
qtTranslator = new QTranslator;
|
||||
translator = new QTranslator;
|
||||
installNewTranslator();
|
||||
qtTranslator = new QTranslator;
|
||||
translator = new QTranslator;
|
||||
installNewTranslator();
|
||||
|
||||
qsrand(QDateTime::currentDateTime().toTime_t());
|
||||
qsrand(QDateTime::currentDateTime().toTime_t());
|
||||
|
||||
bool startMainProgram = true;
|
||||
const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
|
||||
if (!db->getLoadSuccess())
|
||||
if (db->loadCardDatabase(dataDir + "/cards.xml"))
|
||||
settingsCache->setCardDatabasePath(dataDir + "/cards.xml");
|
||||
if (settingsCache->getTokenDatabasePath().isEmpty())
|
||||
settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml");
|
||||
if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) {
|
||||
QDir().mkpath(dataDir + "/decks");
|
||||
settingsCache->setDeckPath(dataDir + "/decks");
|
||||
}
|
||||
if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) {
|
||||
QDir().mkpath(dataDir + "/replays");
|
||||
settingsCache->setReplaysPath(dataDir + "/replays");
|
||||
}
|
||||
if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) {
|
||||
QDir().mkpath(dataDir + "/pics");
|
||||
settingsCache->setPicsPath(dataDir + "/pics");
|
||||
}
|
||||
if (!db->getLoadSuccess() || !QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty() || settingsCache->getPicsPath().isEmpty() || !QDir(settingsCache->getPicsPath()).exists()) {
|
||||
DlgSettings dlgSettings;
|
||||
dlgSettings.show();
|
||||
app.exec();
|
||||
startMainProgram = (db->getLoadSuccess() && QDir(settingsCache->getDeckPath()).exists() && !settingsCache->getDeckPath().isEmpty() && QDir(settingsCache->getPicsPath()).exists() && !settingsCache->getPicsPath().isEmpty());
|
||||
}
|
||||
bool startMainProgram = true;
|
||||
const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
|
||||
if (!db->getLoadSuccess())
|
||||
if (db->loadCardDatabase(dataDir + "/cards.xml"))
|
||||
settingsCache->setCardDatabasePath(dataDir + "/cards.xml");
|
||||
if (settingsCache->getTokenDatabasePath().isEmpty())
|
||||
settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml");
|
||||
if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) {
|
||||
QDir().mkpath(dataDir + "/decks");
|
||||
settingsCache->setDeckPath(dataDir + "/decks");
|
||||
}
|
||||
if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) {
|
||||
QDir().mkpath(dataDir + "/replays");
|
||||
settingsCache->setReplaysPath(dataDir + "/replays");
|
||||
}
|
||||
if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) {
|
||||
QDir().mkpath(dataDir + "/pics");
|
||||
settingsCache->setPicsPath(dataDir + "/pics");
|
||||
}
|
||||
if (!db->getLoadSuccess() || !QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty() || settingsCache->getPicsPath().isEmpty() || !QDir(settingsCache->getPicsPath()).exists()) {
|
||||
DlgSettings dlgSettings;
|
||||
dlgSettings.show();
|
||||
app.exec();
|
||||
startMainProgram = (db->getLoadSuccess() && QDir(settingsCache->getDeckPath()).exists() && !settingsCache->getDeckPath().isEmpty() && QDir(settingsCache->getPicsPath()).exists() && !settingsCache->getPicsPath().isEmpty());
|
||||
}
|
||||
|
||||
if (startMainProgram) {
|
||||
qDebug("main(): starting main program");
|
||||
soundEngine = new SoundEngine;
|
||||
qDebug("main(): SoundEngine constructor finished");
|
||||
if (startMainProgram) {
|
||||
qDebug("main(): starting main program");
|
||||
soundEngine = new SoundEngine;
|
||||
qDebug("main(): SoundEngine constructor finished");
|
||||
|
||||
MainWindow ui;
|
||||
qDebug("main(): MainWindow constructor finished");
|
||||
MainWindow ui;
|
||||
qDebug("main(): MainWindow constructor finished");
|
||||
|
||||
QIcon icon(":/resources/appicon.svg");
|
||||
ui.setWindowIcon(icon);
|
||||
QIcon icon(":/resources/appicon.svg");
|
||||
ui.setWindowIcon(icon);
|
||||
|
||||
ui.show();
|
||||
qDebug("main(): ui.show() finished");
|
||||
ui.show();
|
||||
qDebug("main(): ui.show() finished");
|
||||
|
||||
app.exec();
|
||||
}
|
||||
app.exec();
|
||||
}
|
||||
|
||||
qDebug("Event loop finished, terminating...");
|
||||
delete db;
|
||||
delete settingsCache;
|
||||
delete rng;
|
||||
PingPixmapGenerator::clear();
|
||||
CountryPixmapGenerator::clear();
|
||||
UserLevelPixmapGenerator::clear();
|
||||
qDebug("Event loop finished, terminating...");
|
||||
delete db;
|
||||
delete settingsCache;
|
||||
delete rng;
|
||||
PingPixmapGenerator::clear();
|
||||
CountryPixmapGenerator::clear();
|
||||
UserLevelPixmapGenerator::clear();
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -12,81 +12,81 @@ class GameEventContext;
|
|||
class CardItem;
|
||||
|
||||
struct LogMoveCard {
|
||||
Player *player;
|
||||
CardItem *card;
|
||||
QString cardName;
|
||||
CardZone *startZone;
|
||||
int oldX;
|
||||
CardZone *targetZone;
|
||||
int newX;
|
||||
Player *player;
|
||||
CardItem *card;
|
||||
QString cardName;
|
||||
CardZone *startZone;
|
||||
int oldX;
|
||||
CardZone *targetZone;
|
||||
int newX;
|
||||
};
|
||||
|
||||
class MessageLogWidget : public ChatView {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
enum MessageContext { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan };
|
||||
enum MessageContext { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan };
|
||||
|
||||
QString sanitizeHtml(QString dirty) const;
|
||||
QString cardLink(const QString &cardName) const;
|
||||
bool isFemale(Player *player) const;
|
||||
bool userIsFemale() const;
|
||||
QPair<QString, QString> getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const;
|
||||
MessageContext currentContext;
|
||||
QString sanitizeHtml(QString dirty) const;
|
||||
QString cardLink(const QString &cardName) const;
|
||||
bool isFemale(Player *player) const;
|
||||
bool userIsFemale() const;
|
||||
QPair<QString, QString> getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const;
|
||||
MessageContext currentContext;
|
||||
|
||||
QList<LogMoveCard> moveCardQueue;
|
||||
QMap<CardItem *, QString> moveCardPT;
|
||||
QMap<CardItem *, bool> moveCardTapped;
|
||||
QList<LogMoveCard> moveCardQueue;
|
||||
QMap<CardItem *, QString> moveCardPT;
|
||||
QMap<CardItem *, bool> moveCardTapped;
|
||||
|
||||
Player *mulliganPlayer;
|
||||
int mulliganNumber;
|
||||
Player *mulliganPlayer;
|
||||
int mulliganNumber;
|
||||
public slots:
|
||||
void logGameJoined(int gameId);
|
||||
void logReplayStarted(int gameId);
|
||||
void logJoin(Player *player);
|
||||
void logLeave(Player *player);
|
||||
void logGameClosed();
|
||||
void logKicked();
|
||||
void logJoinSpectator(QString name);
|
||||
void logLeaveSpectator(QString name);
|
||||
void logDeckSelect(Player *player, QString deckHash);
|
||||
void logReadyStart(Player *player);
|
||||
void logNotReadyStart(Player *player);
|
||||
void logSetSideboardLock(Player *player, bool locked);
|
||||
void logConcede(Player *player);
|
||||
void logGameStart();
|
||||
void logConnectionStateChanged(Player *player, bool connectionState);
|
||||
void logSay(Player *player, QString message);
|
||||
void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message);
|
||||
void logShuffle(Player *player, CardZone *zone);
|
||||
void logRollDie(Player *player, int sides, int roll);
|
||||
void logDrawCards(Player *player, int number);
|
||||
void logUndoDraw(Player *player, QString cardName);
|
||||
void doMoveCard(LogMoveCard &attributes);
|
||||
void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX);
|
||||
void logMulligan(Player *player, int number);
|
||||
void logFlipCard(Player *player, QString cardName, bool faceDown);
|
||||
void logDestroyCard(Player *player, QString cardName);
|
||||
void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName);
|
||||
void logUnattachCard(Player *player, QString cardName);
|
||||
void logCreateToken(Player *player, QString cardName, QString pt);
|
||||
void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget);
|
||||
void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue);
|
||||
void logSetTapped(Player *player, CardItem *card, bool tapped);
|
||||
void logSetCounter(Player *player, QString counterName, int value, int oldValue);
|
||||
void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap);
|
||||
void logSetPT(Player *player, CardItem *card, QString newPT);
|
||||
void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation);
|
||||
void logDumpZone(Player *player, CardZone *zone, int numberCards);
|
||||
void logStopDumpZone(Player *player, CardZone *zone);
|
||||
void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown);
|
||||
void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal);
|
||||
void logSetActivePlayer(Player *player);
|
||||
void logSetActivePhase(int phase);
|
||||
void containerProcessingStarted(const GameEventContext &context);
|
||||
void containerProcessingDone();
|
||||
void logGameJoined(int gameId);
|
||||
void logReplayStarted(int gameId);
|
||||
void logJoin(Player *player);
|
||||
void logLeave(Player *player);
|
||||
void logGameClosed();
|
||||
void logKicked();
|
||||
void logJoinSpectator(QString name);
|
||||
void logLeaveSpectator(QString name);
|
||||
void logDeckSelect(Player *player, QString deckHash);
|
||||
void logReadyStart(Player *player);
|
||||
void logNotReadyStart(Player *player);
|
||||
void logSetSideboardLock(Player *player, bool locked);
|
||||
void logConcede(Player *player);
|
||||
void logGameStart();
|
||||
void logConnectionStateChanged(Player *player, bool connectionState);
|
||||
void logSay(Player *player, QString message);
|
||||
void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message);
|
||||
void logShuffle(Player *player, CardZone *zone);
|
||||
void logRollDie(Player *player, int sides, int roll);
|
||||
void logDrawCards(Player *player, int number);
|
||||
void logUndoDraw(Player *player, QString cardName);
|
||||
void doMoveCard(LogMoveCard &attributes);
|
||||
void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX);
|
||||
void logMulligan(Player *player, int number);
|
||||
void logFlipCard(Player *player, QString cardName, bool faceDown);
|
||||
void logDestroyCard(Player *player, QString cardName);
|
||||
void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName);
|
||||
void logUnattachCard(Player *player, QString cardName);
|
||||
void logCreateToken(Player *player, QString cardName, QString pt);
|
||||
void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget);
|
||||
void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue);
|
||||
void logSetTapped(Player *player, CardItem *card, bool tapped);
|
||||
void logSetCounter(Player *player, QString counterName, int value, int oldValue);
|
||||
void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap);
|
||||
void logSetPT(Player *player, CardItem *card, QString newPT);
|
||||
void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation);
|
||||
void logDumpZone(Player *player, CardZone *zone, int numberCards);
|
||||
void logStopDumpZone(Player *player, CardZone *zone);
|
||||
void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown);
|
||||
void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal);
|
||||
void logSetActivePlayer(Player *player);
|
||||
void logSetActivePhase(int phase);
|
||||
void containerProcessingStarted(const GameEventContext &context);
|
||||
void containerProcessingDone();
|
||||
public:
|
||||
void connectToPlayer(Player *player);
|
||||
MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent = 0);
|
||||
void connectToPlayer(Player *player);
|
||||
MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent = 0);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -6,26 +6,26 @@
|
|||
#include <QVariant>
|
||||
|
||||
class PendingCommand : public QObject {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData);
|
||||
void finished(Response::ResponseCode respCode);
|
||||
void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData);
|
||||
void finished(Response::ResponseCode respCode);
|
||||
private:
|
||||
CommandContainer commandContainer;
|
||||
QVariant extraData;
|
||||
int ticks;
|
||||
CommandContainer commandContainer;
|
||||
QVariant extraData;
|
||||
int ticks;
|
||||
public:
|
||||
PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant())
|
||||
: commandContainer(_commandContainer), extraData(_extraData), ticks(0) { }
|
||||
CommandContainer &getCommandContainer() { return commandContainer; }
|
||||
void setExtraData(const QVariant &_extraData) { extraData = _extraData; }
|
||||
QVariant getExtraData() const { return extraData; }
|
||||
void processResponse(const Response &response)
|
||||
{
|
||||
emit finished(response, commandContainer, extraData);
|
||||
emit finished(response.response_code());
|
||||
}
|
||||
int tick() { return ++ticks; }
|
||||
PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant())
|
||||
: commandContainer(_commandContainer), extraData(_extraData), ticks(0) { }
|
||||
CommandContainer &getCommandContainer() { return commandContainer; }
|
||||
void setExtraData(const QVariant &_extraData) { extraData = _extraData; }
|
||||
QVariant getExtraData() const { return extraData; }
|
||||
void processResponse(const Response &response)
|
||||
{
|
||||
emit finished(response, commandContainer, extraData);
|
||||
emit finished(response.response_code());
|
||||
}
|
||||
int tick() { return ++ticks; }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -13,239 +13,239 @@
|
|||
#include "pb/command_draw_cards.pb.h"
|
||||
|
||||
PhaseButton::PhaseButton(const QString &_name, QGraphicsItem *parent, QAction *_doubleClickAction, bool _highlightable)
|
||||
: QObject(), QGraphicsItem(parent), name(_name), active(false), highlightable(_highlightable), activeAnimationCounter(0), doubleClickAction(_doubleClickAction), width(50)
|
||||
: QObject(), QGraphicsItem(parent), name(_name), active(false), highlightable(_highlightable), activeAnimationCounter(0), doubleClickAction(_doubleClickAction), width(50)
|
||||
{
|
||||
if (highlightable) {
|
||||
activeAnimationTimer = new QTimer(this);
|
||||
connect(activeAnimationTimer, SIGNAL(timeout()), this, SLOT(updateAnimation()));
|
||||
activeAnimationTimer->setSingleShot(false);
|
||||
} else
|
||||
activeAnimationCounter = 9.0;
|
||||
if (highlightable) {
|
||||
activeAnimationTimer = new QTimer(this);
|
||||
connect(activeAnimationTimer, SIGNAL(timeout()), this, SLOT(updateAnimation()));
|
||||
activeAnimationTimer->setSingleShot(false);
|
||||
} else
|
||||
activeAnimationCounter = 9.0;
|
||||
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
}
|
||||
|
||||
QRectF PhaseButton::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, width, width);
|
||||
return QRectF(0, 0, width, width);
|
||||
}
|
||||
|
||||
void PhaseButton::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
QRectF iconRect = boundingRect().adjusted(3, 3, -3, -3);
|
||||
QRectF translatedIconRect = painter->combinedTransform().mapRect(iconRect);
|
||||
qreal scaleFactor = translatedIconRect.width() / iconRect.width();
|
||||
QPixmap iconPixmap = PhasePixmapGenerator::generatePixmap(round(translatedIconRect.height()), name);
|
||||
QRectF iconRect = boundingRect().adjusted(3, 3, -3, -3);
|
||||
QRectF translatedIconRect = painter->combinedTransform().mapRect(iconRect);
|
||||
qreal scaleFactor = translatedIconRect.width() / iconRect.width();
|
||||
QPixmap iconPixmap = PhasePixmapGenerator::generatePixmap(round(translatedIconRect.height()), name);
|
||||
|
||||
painter->setBrush(QColor(220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0)));
|
||||
painter->setPen(Qt::gray);
|
||||
painter->drawRect(0, 0, width - 1, width - 1);
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->drawPixmap(iconPixmap.rect().translated(round(3 * scaleFactor), round(3 * scaleFactor)), iconPixmap, iconPixmap.rect());
|
||||
painter->restore();
|
||||
painter->setBrush(QColor(220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0)));
|
||||
painter->setPen(Qt::gray);
|
||||
painter->drawRect(0, 0, width - 1, width - 1);
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->drawPixmap(iconPixmap.rect().translated(round(3 * scaleFactor), round(3 * scaleFactor)), iconPixmap, iconPixmap.rect());
|
||||
painter->restore();
|
||||
|
||||
painter->setBrush(QColor(0, 0, 0, 255 * ((10 - activeAnimationCounter) / 15.0)));
|
||||
painter->setPen(Qt::gray);
|
||||
painter->drawRect(0, 0, width - 1, width - 1);
|
||||
painter->setBrush(QColor(0, 0, 0, 255 * ((10 - activeAnimationCounter) / 15.0)));
|
||||
painter->setPen(Qt::gray);
|
||||
painter->drawRect(0, 0, width - 1, width - 1);
|
||||
}
|
||||
|
||||
void PhaseButton::setWidth(double _width)
|
||||
{
|
||||
prepareGeometryChange();
|
||||
width = _width;
|
||||
prepareGeometryChange();
|
||||
width = _width;
|
||||
}
|
||||
|
||||
void PhaseButton::setActive(bool _active)
|
||||
{
|
||||
if ((active == _active) || !highlightable)
|
||||
return;
|
||||
if ((active == _active) || !highlightable)
|
||||
return;
|
||||
|
||||
active = _active;
|
||||
activeAnimationTimer->start(50);
|
||||
active = _active;
|
||||
activeAnimationTimer->start(50);
|
||||
}
|
||||
|
||||
void PhaseButton::updateAnimation()
|
||||
{
|
||||
if (!highlightable)
|
||||
return;
|
||||
if (!highlightable)
|
||||
return;
|
||||
|
||||
if (active) {
|
||||
if (++activeAnimationCounter >= 10)
|
||||
activeAnimationTimer->stop();
|
||||
} else {
|
||||
if (--activeAnimationCounter <= 0)
|
||||
activeAnimationTimer->stop();
|
||||
}
|
||||
update();
|
||||
if (active) {
|
||||
if (++activeAnimationCounter >= 10)
|
||||
activeAnimationTimer->stop();
|
||||
} else {
|
||||
if (--activeAnimationCounter <= 0)
|
||||
activeAnimationTimer->stop();
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void PhaseButton::mousePressEvent(QGraphicsSceneMouseEvent * /*event*/)
|
||||
{
|
||||
emit clicked();
|
||||
emit clicked();
|
||||
}
|
||||
|
||||
void PhaseButton::mouseDoubleClickEvent(QGraphicsSceneMouseEvent */*event*/)
|
||||
{
|
||||
triggerDoubleClickAction();
|
||||
triggerDoubleClickAction();
|
||||
}
|
||||
|
||||
void PhaseButton::triggerDoubleClickAction()
|
||||
{
|
||||
if (doubleClickAction)
|
||||
doubleClickAction->trigger();
|
||||
if (doubleClickAction)
|
||||
doubleClickAction->trigger();
|
||||
}
|
||||
|
||||
PhasesToolbar::PhasesToolbar(QGraphicsItem *parent)
|
||||
: QGraphicsItem(parent), width(100), height(100)
|
||||
: QGraphicsItem(parent), width(100), height(100)
|
||||
{
|
||||
QAction *aUntapAll = new QAction(this);
|
||||
connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll()));
|
||||
QAction *aDrawCard = new QAction(this);
|
||||
connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard()));
|
||||
QAction *aUntapAll = new QAction(this);
|
||||
connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll()));
|
||||
QAction *aDrawCard = new QAction(this);
|
||||
connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard()));
|
||||
|
||||
PhaseButton *untapButton = new PhaseButton("untap", this, aUntapAll);
|
||||
PhaseButton *upkeepButton = new PhaseButton("upkeep", this);
|
||||
PhaseButton *drawButton = new PhaseButton("draw", this, aDrawCard);
|
||||
PhaseButton *main1Button = new PhaseButton("main1", this);
|
||||
PhaseButton *combatStartButton = new PhaseButton("combat_start", this);
|
||||
PhaseButton *combatAttackersButton = new PhaseButton("combat_attackers", this);
|
||||
PhaseButton *combatBlockersButton = new PhaseButton("combat_blockers", this);
|
||||
PhaseButton *combatDamageButton = new PhaseButton("combat_damage", this);
|
||||
PhaseButton *combatEndButton = new PhaseButton("combat_end", this);
|
||||
PhaseButton *main2Button = new PhaseButton("main2", this);
|
||||
PhaseButton *cleanupButton = new PhaseButton("cleanup", this);
|
||||
PhaseButton *untapButton = new PhaseButton("untap", this, aUntapAll);
|
||||
PhaseButton *upkeepButton = new PhaseButton("upkeep", this);
|
||||
PhaseButton *drawButton = new PhaseButton("draw", this, aDrawCard);
|
||||
PhaseButton *main1Button = new PhaseButton("main1", this);
|
||||
PhaseButton *combatStartButton = new PhaseButton("combat_start", this);
|
||||
PhaseButton *combatAttackersButton = new PhaseButton("combat_attackers", this);
|
||||
PhaseButton *combatBlockersButton = new PhaseButton("combat_blockers", this);
|
||||
PhaseButton *combatDamageButton = new PhaseButton("combat_damage", this);
|
||||
PhaseButton *combatEndButton = new PhaseButton("combat_end", this);
|
||||
PhaseButton *main2Button = new PhaseButton("main2", this);
|
||||
PhaseButton *cleanupButton = new PhaseButton("cleanup", this);
|
||||
|
||||
buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton
|
||||
<< combatAttackersButton << combatBlockersButton << combatDamageButton << combatEndButton
|
||||
<< main2Button << cleanupButton;
|
||||
buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton
|
||||
<< combatAttackersButton << combatBlockersButton << combatDamageButton << combatEndButton
|
||||
<< main2Button << cleanupButton;
|
||||
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
connect(buttonList[i], SIGNAL(clicked()), this, SLOT(phaseButtonClicked()));
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
connect(buttonList[i], SIGNAL(clicked()), this, SLOT(phaseButtonClicked()));
|
||||
|
||||
nextTurnButton = new PhaseButton("nextturn", this, 0, false);
|
||||
connect(nextTurnButton, SIGNAL(clicked()), this, SLOT(actNextTurn()));
|
||||
nextTurnButton = new PhaseButton("nextturn", this, 0, false);
|
||||
connect(nextTurnButton, SIGNAL(clicked()), this, SLOT(actNextTurn()));
|
||||
|
||||
rearrangeButtons();
|
||||
rearrangeButtons();
|
||||
|
||||
retranslateUi();
|
||||
retranslateUi();
|
||||
}
|
||||
|
||||
QRectF PhasesToolbar::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, width, height);
|
||||
return QRectF(0, 0, width, height);
|
||||
}
|
||||
|
||||
void PhasesToolbar::retranslateUi()
|
||||
{
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
buttonList[i]->setToolTip(getLongPhaseName(i));
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
buttonList[i]->setToolTip(getLongPhaseName(i));
|
||||
}
|
||||
|
||||
QString PhasesToolbar::getLongPhaseName(int phase) const
|
||||
{
|
||||
switch (phase) {
|
||||
case 0: return tr("Untap step");
|
||||
case 1: return tr("Upkeep step");
|
||||
case 2: return tr("Draw step");
|
||||
case 3: return tr("First main phase");
|
||||
case 4: return tr("Beginning of combat step");
|
||||
case 5: return tr("Declare attackers step");
|
||||
case 6: return tr("Declare blockers step");
|
||||
case 7: return tr("Combat damage step");
|
||||
case 8: return tr("End of combat step");
|
||||
case 9: return tr("Second main phase");
|
||||
case 10: return tr("End of turn step");
|
||||
default: return QString();
|
||||
}
|
||||
switch (phase) {
|
||||
case 0: return tr("Untap step");
|
||||
case 1: return tr("Upkeep step");
|
||||
case 2: return tr("Draw step");
|
||||
case 3: return tr("First main phase");
|
||||
case 4: return tr("Beginning of combat step");
|
||||
case 5: return tr("Declare attackers step");
|
||||
case 6: return tr("Declare blockers step");
|
||||
case 7: return tr("Combat damage step");
|
||||
case 8: return tr("End of combat step");
|
||||
case 9: return tr("Second main phase");
|
||||
case 10: return tr("End of turn step");
|
||||
default: return QString();
|
||||
}
|
||||
}
|
||||
|
||||
void PhasesToolbar::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
painter->fillRect(boundingRect(), QColor(50, 50, 50));
|
||||
painter->fillRect(boundingRect(), QColor(50, 50, 50));
|
||||
}
|
||||
|
||||
const double PhasesToolbar::marginSize = 3;
|
||||
|
||||
void PhasesToolbar::rearrangeButtons()
|
||||
{
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
buttonList[i]->setWidth(symbolSize);
|
||||
nextTurnButton->setWidth(symbolSize);
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
buttonList[i]->setWidth(symbolSize);
|
||||
nextTurnButton->setWidth(symbolSize);
|
||||
|
||||
double y = marginSize;
|
||||
buttonList[0]->setPos(marginSize, y);
|
||||
buttonList[1]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[2]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[3]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[4]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[5]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[6]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[7]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[8]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[9]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[10]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
y += ySpacing;
|
||||
nextTurnButton->setPos(marginSize, y += symbolSize);
|
||||
double y = marginSize;
|
||||
buttonList[0]->setPos(marginSize, y);
|
||||
buttonList[1]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[2]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[3]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[4]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[5]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[6]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[7]->setPos(marginSize, y += symbolSize);
|
||||
buttonList[8]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[9]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
buttonList[10]->setPos(marginSize, y += symbolSize);
|
||||
y += ySpacing;
|
||||
y += ySpacing;
|
||||
nextTurnButton->setPos(marginSize, y += symbolSize);
|
||||
}
|
||||
|
||||
void PhasesToolbar::setHeight(double _height)
|
||||
{
|
||||
prepareGeometryChange();
|
||||
prepareGeometryChange();
|
||||
|
||||
height = _height;
|
||||
ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount);
|
||||
symbolSize = ySpacing * 5;
|
||||
width = symbolSize + 2 * marginSize;
|
||||
height = _height;
|
||||
ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount);
|
||||
symbolSize = ySpacing * 5;
|
||||
width = symbolSize + 2 * marginSize;
|
||||
|
||||
rearrangeButtons();
|
||||
rearrangeButtons();
|
||||
}
|
||||
|
||||
void PhasesToolbar::setActivePhase(int phase)
|
||||
{
|
||||
if (phase >= buttonList.size())
|
||||
return;
|
||||
if (phase >= buttonList.size())
|
||||
return;
|
||||
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
buttonList[i]->setActive(i == phase);
|
||||
for (int i = 0; i < buttonList.size(); ++i)
|
||||
buttonList[i]->setActive(i == phase);
|
||||
}
|
||||
|
||||
void PhasesToolbar::phaseButtonClicked()
|
||||
{
|
||||
PhaseButton *button = qobject_cast<PhaseButton *>(sender());
|
||||
if (button->getActive())
|
||||
button->triggerDoubleClickAction();
|
||||
PhaseButton *button = qobject_cast<PhaseButton *>(sender());
|
||||
if (button->getActive())
|
||||
button->triggerDoubleClickAction();
|
||||
|
||||
Command_SetActivePhase cmd;
|
||||
cmd.set_phase(buttonList.indexOf(button));
|
||||
Command_SetActivePhase cmd;
|
||||
cmd.set_phase(buttonList.indexOf(button));
|
||||
|
||||
emit sendGameCommand(cmd, -1);
|
||||
emit sendGameCommand(cmd, -1);
|
||||
}
|
||||
|
||||
void PhasesToolbar::actNextTurn()
|
||||
{
|
||||
emit sendGameCommand(Command_NextTurn(), -1);
|
||||
emit sendGameCommand(Command_NextTurn(), -1);
|
||||
}
|
||||
|
||||
void PhasesToolbar::actUntapAll()
|
||||
{
|
||||
Command_SetCardAttr cmd;
|
||||
cmd.set_zone("table");
|
||||
cmd.set_attribute(AttrTapped);
|
||||
cmd.set_attr_value("0");
|
||||
Command_SetCardAttr cmd;
|
||||
cmd.set_zone("table");
|
||||
cmd.set_attribute(AttrTapped);
|
||||
cmd.set_attr_value("0");
|
||||
|
||||
emit sendGameCommand(cmd, -1);
|
||||
emit sendGameCommand(cmd, -1);
|
||||
}
|
||||
|
||||
void PhasesToolbar::actDrawCard()
|
||||
{
|
||||
Command_DrawCards cmd;
|
||||
cmd.set_number(1);
|
||||
Command_DrawCards cmd;
|
||||
cmd.set_number(1);
|
||||
|
||||
emit sendGameCommand(cmd, -1);
|
||||
emit sendGameCommand(cmd, -1);
|
||||
}
|
||||
|
|
|
@ -10,62 +10,62 @@ class Player;
|
|||
class GameCommand;
|
||||
|
||||
class PhaseButton : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QString name;
|
||||
bool active, highlightable;
|
||||
int activeAnimationCounter;
|
||||
QTimer *activeAnimationTimer;
|
||||
QAction *doubleClickAction;
|
||||
double width;
|
||||
QString name;
|
||||
bool active, highlightable;
|
||||
int activeAnimationCounter;
|
||||
QTimer *activeAnimationTimer;
|
||||
QAction *doubleClickAction;
|
||||
double width;
|
||||
|
||||
void updatePixmap(QPixmap &pixmap);
|
||||
void updatePixmap(QPixmap &pixmap);
|
||||
private slots:
|
||||
void updateAnimation();
|
||||
void updateAnimation();
|
||||
public:
|
||||
PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true);
|
||||
QRectF boundingRect() const;
|
||||
void setWidth(double _width);
|
||||
void setActive(bool _active);
|
||||
bool getActive() const { return active; }
|
||||
void triggerDoubleClickAction();
|
||||
PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true);
|
||||
QRectF boundingRect() const;
|
||||
void setWidth(double _width);
|
||||
void setActive(bool _active);
|
||||
bool getActive() const { return active; }
|
||||
void triggerDoubleClickAction();
|
||||
signals:
|
||||
void clicked();
|
||||
void clicked();
|
||||
protected:
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
|
||||
};
|
||||
|
||||
class PhasesToolbar : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QList<PhaseButton *> buttonList;
|
||||
PhaseButton *nextTurnButton;
|
||||
double width, height, ySpacing, symbolSize;
|
||||
static const int buttonCount = 12;
|
||||
static const int spaceCount = 6;
|
||||
static const double marginSize;
|
||||
void rearrangeButtons();
|
||||
QList<PhaseButton *> buttonList;
|
||||
PhaseButton *nextTurnButton;
|
||||
double width, height, ySpacing, symbolSize;
|
||||
static const int buttonCount = 12;
|
||||
static const int spaceCount = 6;
|
||||
static const double marginSize;
|
||||
void rearrangeButtons();
|
||||
public:
|
||||
PhasesToolbar(QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void retranslateUi();
|
||||
void setHeight(double _height);
|
||||
double getWidth() const { return width; }
|
||||
int phaseCount() const { return buttonList.size(); }
|
||||
QString getLongPhaseName(int phase) const;
|
||||
PhasesToolbar(QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void retranslateUi();
|
||||
void setHeight(double _height);
|
||||
double getWidth() const { return width; }
|
||||
int phaseCount() const { return buttonList.size(); }
|
||||
QString getLongPhaseName(int phase) const;
|
||||
public slots:
|
||||
void setActivePhase(int phase);
|
||||
void setActivePhase(int phase);
|
||||
private slots:
|
||||
void phaseButtonClicked();
|
||||
void actNextTurn();
|
||||
void actUntapAll();
|
||||
void actDrawCard();
|
||||
void phaseButtonClicked();
|
||||
void actNextTurn();
|
||||
void actUntapAll();
|
||||
void actDrawCard();
|
||||
signals:
|
||||
void sendGameCommand(const ::google::protobuf::Message &command, int playerId);
|
||||
void sendGameCommand(const ::google::protobuf::Message &command, int playerId);
|
||||
protected:
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/);
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -10,109 +10,109 @@
|
|||
#include "pb/command_move_card.pb.h"
|
||||
|
||||
PileZone::PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent)
|
||||
: CardZone(_p, _name, false, _isShufflable, _contentsKnown, parent)
|
||||
: CardZone(_p, _name, false, _isShufflable, _contentsKnown, parent)
|
||||
{
|
||||
setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor!
|
||||
setAcceptsHoverEvents(true);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor!
|
||||
setAcceptsHoverEvents(true);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
|
||||
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
|
||||
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
|
||||
}
|
||||
|
||||
QRectF PileZone::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT);
|
||||
return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT);
|
||||
}
|
||||
|
||||
void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
if (!cards.isEmpty())
|
||||
cards.at(0)->paintPicture(painter, cards.at(0)->getTranslatedSize(painter), 90);
|
||||
if (!cards.isEmpty())
|
||||
cards.at(0)->paintPicture(painter, cards.at(0)->getTranslatedSize(painter), 90);
|
||||
|
||||
painter->drawRect(QRectF(0.5, 0.5, CARD_WIDTH - 1, CARD_HEIGHT - 1));
|
||||
painter->drawRect(QRectF(0.5, 0.5, CARD_WIDTH - 1, CARD_HEIGHT - 1));
|
||||
|
||||
painter->translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2);
|
||||
painter->rotate(-90);
|
||||
painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2);
|
||||
paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter);
|
||||
painter->translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2);
|
||||
painter->rotate(-90);
|
||||
painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2);
|
||||
paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter);
|
||||
}
|
||||
|
||||
void PileZone::addCardImpl(CardItem *card, int x, int /*y*/)
|
||||
{
|
||||
connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate()));
|
||||
cards.insert(x, card);
|
||||
card->setPos(0, 0);
|
||||
if (!contentsKnown()) {
|
||||
card->setName(QString());
|
||||
card->setId(-1);
|
||||
// If we obscure a previously revealed card, its name has to be forgotten
|
||||
if (cards.size() > x + 1)
|
||||
cards.at(x + 1)->setName(QString());
|
||||
}
|
||||
card->setVisible(false);
|
||||
card->resetState();
|
||||
card->setParentItem(this);
|
||||
connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate()));
|
||||
cards.insert(x, card);
|
||||
card->setPos(0, 0);
|
||||
if (!contentsKnown()) {
|
||||
card->setName(QString());
|
||||
card->setId(-1);
|
||||
// If we obscure a previously revealed card, its name has to be forgotten
|
||||
if (cards.size() > x + 1)
|
||||
cards.at(x + 1)->setName(QString());
|
||||
}
|
||||
card->setVisible(false);
|
||||
card->resetState();
|
||||
card->setParentItem(this);
|
||||
}
|
||||
|
||||
void PileZone::handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/)
|
||||
{
|
||||
Command_MoveCard cmd;
|
||||
cmd.set_start_player_id(startZone->getPlayer()->getId());
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_target_player_id(player->getId());
|
||||
cmd.set_target_zone(getName().toStdString());
|
||||
cmd.set_x(0);
|
||||
cmd.set_y(0);
|
||||
Command_MoveCard cmd;
|
||||
cmd.set_start_player_id(startZone->getPlayer()->getId());
|
||||
cmd.set_start_zone(startZone->getName().toStdString());
|
||||
cmd.set_target_player_id(player->getId());
|
||||
cmd.set_target_zone(getName().toStdString());
|
||||
cmd.set_x(0);
|
||||
cmd.set_y(0);
|
||||
|
||||
for (int i = 0; i < dragItems.size(); ++i)
|
||||
cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId());
|
||||
for (int i = 0; i < dragItems.size(); ++i)
|
||||
cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId());
|
||||
|
||||
player->sendGameCommand(cmd);
|
||||
player->sendGameCommand(cmd);
|
||||
}
|
||||
|
||||
void PileZone::reorganizeCards()
|
||||
{
|
||||
update();
|
||||
update();
|
||||
}
|
||||
|
||||
void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
CardZone::mousePressEvent(event);
|
||||
if (event->isAccepted())
|
||||
return;
|
||||
CardZone::mousePressEvent(event);
|
||||
if (event->isAccepted())
|
||||
return;
|
||||
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
event->accept();
|
||||
} else
|
||||
event->ignore();
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
event->accept();
|
||||
} else
|
||||
event->ignore();
|
||||
}
|
||||
|
||||
void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance())
|
||||
return;
|
||||
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance())
|
||||
return;
|
||||
|
||||
if (cards.isEmpty())
|
||||
return;
|
||||
if (cards.isEmpty())
|
||||
return;
|
||||
|
||||
bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier);
|
||||
bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier);
|
||||
CardItem *card = bottomCard ? cards.last() : cards.first();
|
||||
const int cardid = contentsKnown() ? card->getId() : (bottomCard ? cards.size() - 1 : 0);
|
||||
CardDragItem *drag = card->createDragItem(cardid, event->pos(), event->scenePos(), faceDown);
|
||||
drag->grabMouse();
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier);
|
||||
bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier);
|
||||
CardItem *card = bottomCard ? cards.last() : cards.first();
|
||||
const int cardid = contentsKnown() ? card->getId() : (bottomCard ? cards.size() - 1 : 0);
|
||||
CardDragItem *drag = card->createDragItem(cardid, event->pos(), event->scenePos(), faceDown);
|
||||
drag->grabMouse();
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
}
|
||||
|
||||
void PileZone::mouseReleaseEvent(QGraphicsSceneMouseEvent */*event*/)
|
||||
{
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
}
|
||||
|
||||
void PileZone::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
|
||||
{
|
||||
if (!cards.isEmpty())
|
||||
cards[0]->processHoverEvent();
|
||||
QGraphicsItem::hoverEnterEvent(event);
|
||||
if (!cards.isEmpty())
|
||||
cards[0]->processHoverEvent();
|
||||
QGraphicsItem::hoverEnterEvent(event);
|
||||
}
|
||||
|
|
|
@ -4,21 +4,21 @@
|
|||
#include "cardzone.h"
|
||||
|
||||
class PileZone : public CardZone {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void callUpdate() { update(); }
|
||||
void callUpdate() { update(); }
|
||||
public:
|
||||
PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void reorganizeCards();
|
||||
void handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint &dropPoint);
|
||||
PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
void reorganizeCards();
|
||||
void handleDropEvent(const QList<CardDragItem *> &dragItems, CardZone *startZone, const QPoint &dropPoint);
|
||||
protected:
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
|
||||
void addCardImpl(CardItem *card, int x, int y);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
|
||||
void addCardImpl(CardItem *card, int x, int y);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -9,152 +9,152 @@ QMap<QString, QPixmap> PhasePixmapGenerator::pmCache;
|
|||
|
||||
QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name)
|
||||
{
|
||||
QString key = name + QString::number(height);
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
QString key = name + QString::number(height);
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
|
||||
QSvgRenderer svg(QString(":/resources/phases/icon_phase_" + name + ".svg"));
|
||||
QSvgRenderer svg(QString(":/resources/phases/icon_phase_" + name + ".svg"));
|
||||
|
||||
QPixmap pixmap(height, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, height, height));
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
QPixmap pixmap(height, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, height, height));
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
QMap<QString, QPixmap> CounterPixmapGenerator::pmCache;
|
||||
|
||||
QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool highlight)
|
||||
{
|
||||
if (highlight)
|
||||
name.append("_highlight");
|
||||
QString key = name + QString::number(height);
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
if (highlight)
|
||||
name.append("_highlight");
|
||||
QString key = name + QString::number(height);
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
|
||||
QSvgRenderer svg(QString(":/resources/counters/" + name + ".svg"));
|
||||
QSvgRenderer svg(QString(":/resources/counters/" + name + ".svg"));
|
||||
|
||||
if (!svg.isValid()) {
|
||||
name = "general";
|
||||
if (highlight)
|
||||
name.append("_highlight");
|
||||
svg.load(QString(":/resources/counters/" + name + ".svg"));
|
||||
}
|
||||
if (!svg.isValid()) {
|
||||
name = "general";
|
||||
if (highlight)
|
||||
name.append("_highlight");
|
||||
svg.load(QString(":/resources/counters/" + name + ".svg"));
|
||||
}
|
||||
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max)
|
||||
{
|
||||
int key = size * 1000000 + max * 1000 + value;
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
int key = size * 1000000 + max * 1000 + value;
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
|
||||
QPixmap pixmap(size, size);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
QColor color;
|
||||
if ((max == -1) || (value == -1))
|
||||
color = Qt::black;
|
||||
else
|
||||
color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255);
|
||||
QPixmap pixmap(size, size);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
QColor color;
|
||||
if ((max == -1) || (value == -1))
|
||||
color = Qt::black;
|
||||
else
|
||||
color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255);
|
||||
|
||||
QRadialGradient g(QPointF((double) pixmap.width() / 2, (double) pixmap.height() / 2), qMin(pixmap.width(), pixmap.height()) / 2.0);
|
||||
g.setColorAt(0, color);
|
||||
g.setColorAt(1, Qt::transparent);
|
||||
painter.fillRect(0, 0, pixmap.width(), pixmap.height(), QBrush(g));
|
||||
QRadialGradient g(QPointF((double) pixmap.width() / 2, (double) pixmap.height() / 2), qMin(pixmap.width(), pixmap.height()) / 2.0);
|
||||
g.setColorAt(0, color);
|
||||
g.setColorAt(1, Qt::transparent);
|
||||
painter.fillRect(0, 0, pixmap.width(), pixmap.height(), QBrush(g));
|
||||
|
||||
pmCache.insert(key, pixmap);
|
||||
pmCache.insert(key, pixmap);
|
||||
|
||||
return pixmap;
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
QMap<int, QPixmap> PingPixmapGenerator::pmCache;
|
||||
|
||||
QPixmap GenderPixmapGenerator::generatePixmap(int height, int _gender)
|
||||
{
|
||||
ServerInfo_User::Gender gender = static_cast<ServerInfo_User::Gender>(_gender);
|
||||
if ((gender != ServerInfo_User::Male) && (gender != ServerInfo_User::Female))
|
||||
gender = ServerInfo_User::GenderUnknown;
|
||||
ServerInfo_User::Gender gender = static_cast<ServerInfo_User::Gender>(_gender);
|
||||
if ((gender != ServerInfo_User::Male) && (gender != ServerInfo_User::Female))
|
||||
gender = ServerInfo_User::GenderUnknown;
|
||||
|
||||
int key = gender * 100000 + height;
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
int key = gender * 100000 + height;
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
|
||||
QString genderStr;
|
||||
switch (gender) {
|
||||
case ServerInfo_User::Male: genderStr = "male"; break;
|
||||
case ServerInfo_User::Female: genderStr = "female"; break;
|
||||
default: genderStr = "unknown";
|
||||
};
|
||||
QString genderStr;
|
||||
switch (gender) {
|
||||
case ServerInfo_User::Male: genderStr = "male"; break;
|
||||
case ServerInfo_User::Female: genderStr = "female"; break;
|
||||
default: genderStr = "unknown";
|
||||
};
|
||||
|
||||
QSvgRenderer svg(QString(":/resources/genders/" + genderStr + ".svg"));
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
QSvgRenderer svg(QString(":/resources/genders/" + genderStr + ".svg"));
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
QMap<int, QPixmap> GenderPixmapGenerator::pmCache;
|
||||
|
||||
QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode)
|
||||
{
|
||||
if (countryCode.size() != 2)
|
||||
return QPixmap();
|
||||
QString key = countryCode + QString::number(height);
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
if (countryCode.size() != 2)
|
||||
return QPixmap();
|
||||
QString key = countryCode + QString::number(height);
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
|
||||
QSvgRenderer svg(QString(":/resources/countries/" + countryCode + ".svg"));
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
painter.setPen(Qt::black);
|
||||
painter.drawRect(0, 0, width - 1, height - 1);
|
||||
QSvgRenderer svg(QString(":/resources/countries/" + countryCode + ".svg"));
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
painter.setPen(Qt::black);
|
||||
painter.drawRect(0, 0, width - 1, height - 1);
|
||||
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
QMap<QString, QPixmap> CountryPixmapGenerator::pmCache;
|
||||
|
||||
QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel)
|
||||
{
|
||||
int key = height * 10000 + (int) userLevel;
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
int key = height * 10000 + (int) userLevel;
|
||||
if (pmCache.contains(key))
|
||||
return pmCache.value(key);
|
||||
|
||||
QString levelString;
|
||||
if (userLevel.testFlag(ServerInfo_User::IsAdmin))
|
||||
levelString = "admin";
|
||||
else if (userLevel.testFlag(ServerInfo_User::IsModerator))
|
||||
levelString = "moderator";
|
||||
else if (userLevel.testFlag(ServerInfo_User::IsRegistered))
|
||||
levelString = "registered";
|
||||
else
|
||||
levelString = "normal";
|
||||
QSvgRenderer svg(QString(":/resources/userlevels/" + levelString + ".svg"));
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
QString levelString;
|
||||
if (userLevel.testFlag(ServerInfo_User::IsAdmin))
|
||||
levelString = "admin";
|
||||
else if (userLevel.testFlag(ServerInfo_User::IsModerator))
|
||||
levelString = "moderator";
|
||||
else if (userLevel.testFlag(ServerInfo_User::IsRegistered))
|
||||
levelString = "registered";
|
||||
else
|
||||
levelString = "normal";
|
||||
QSvgRenderer svg(QString(":/resources/userlevels/" + levelString + ".svg"));
|
||||
int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height());
|
||||
QPixmap pixmap(width, height);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
svg.render(&painter, QRectF(0, 0, width, height));
|
||||
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
pmCache.insert(key, pixmap);
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
QMap<int, QPixmap> UserLevelPixmapGenerator::pmCache;
|
||||
|
|
|
@ -8,50 +8,50 @@
|
|||
|
||||
class PhasePixmapGenerator {
|
||||
private:
|
||||
static QMap<QString, QPixmap> pmCache;
|
||||
static QMap<QString, QPixmap> pmCache;
|
||||
public:
|
||||
static QPixmap generatePixmap(int size, QString name);
|
||||
static void clear() { pmCache.clear(); }
|
||||
static QPixmap generatePixmap(int size, QString name);
|
||||
static void clear() { pmCache.clear(); }
|
||||
};
|
||||
|
||||
class CounterPixmapGenerator {
|
||||
private:
|
||||
static QMap<QString, QPixmap> pmCache;
|
||||
static QMap<QString, QPixmap> pmCache;
|
||||
public:
|
||||
static QPixmap generatePixmap(int size, QString name, bool highlight);
|
||||
static void clear() { pmCache.clear(); }
|
||||
static QPixmap generatePixmap(int size, QString name, bool highlight);
|
||||
static void clear() { pmCache.clear(); }
|
||||
};
|
||||
|
||||
class PingPixmapGenerator {
|
||||
private:
|
||||
static QMap<int, QPixmap> pmCache;
|
||||
static QMap<int, QPixmap> pmCache;
|
||||
public:
|
||||
static QPixmap generatePixmap(int size, int value, int max);
|
||||
static void clear() { pmCache.clear(); }
|
||||
static QPixmap generatePixmap(int size, int value, int max);
|
||||
static void clear() { pmCache.clear(); }
|
||||
};
|
||||
|
||||
class GenderPixmapGenerator {
|
||||
private:
|
||||
static QMap<int, QPixmap> pmCache;
|
||||
static QMap<int, QPixmap> pmCache;
|
||||
public:
|
||||
static QPixmap generatePixmap(int height, int gender);
|
||||
static void clear() { pmCache.clear(); }
|
||||
static QPixmap generatePixmap(int height, int gender);
|
||||
static void clear() { pmCache.clear(); }
|
||||
};
|
||||
|
||||
class CountryPixmapGenerator {
|
||||
private:
|
||||
static QMap<QString, QPixmap> pmCache;
|
||||
static QMap<QString, QPixmap> pmCache;
|
||||
public:
|
||||
static QPixmap generatePixmap(int height, const QString &countryCode);
|
||||
static void clear() { pmCache.clear(); }
|
||||
static QPixmap generatePixmap(int height, const QString &countryCode);
|
||||
static void clear() { pmCache.clear(); }
|
||||
};
|
||||
|
||||
class UserLevelPixmapGenerator {
|
||||
private:
|
||||
static QMap<int, QPixmap> pmCache;
|
||||
static QMap<int, QPixmap> pmCache;
|
||||
public:
|
||||
static QPixmap generatePixmap(int height, UserLevelFlags userLevel);
|
||||
static void clear() { pmCache.clear(); }
|
||||
static QPixmap generatePixmap(int height, UserLevelFlags userLevel);
|
||||
static void clear() { pmCache.clear(); }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -57,246 +57,246 @@ class Event_ChangeZoneProperties;
|
|||
class PendingCommand;
|
||||
|
||||
class PlayerArea : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QBrush bgPixmapBrush;
|
||||
QRectF bRect;
|
||||
QBrush bgPixmapBrush;
|
||||
QRectF bRect;
|
||||
private slots:
|
||||
void updateBgPixmap();
|
||||
void updateBgPixmap();
|
||||
public:
|
||||
enum { Type = typeOther };
|
||||
int type() const { return Type; }
|
||||
enum { Type = typeOther };
|
||||
int type() const { return Type; }
|
||||
|
||||
PlayerArea(QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const { return bRect; }
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
PlayerArea(QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const { return bRect; }
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
|
||||
void setSize(qreal width, qreal height);
|
||||
void setSize(qreal width, qreal height);
|
||||
};
|
||||
|
||||
class Player : public QObject, public QGraphicsItem {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void openDeckEditor(const DeckLoader *deck);
|
||||
void newCardAdded(AbstractCardItem *card);
|
||||
// Log events
|
||||
void logSay(Player *player, QString message);
|
||||
void logShuffle(Player *player, CardZone *zone);
|
||||
void logRollDie(Player *player, int sides, int roll);
|
||||
void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool _playerTarget);
|
||||
void logCreateToken(Player *player, QString cardName, QString pt);
|
||||
void logDrawCards(Player *player, int number);
|
||||
void logUndoDraw(Player *player, QString cardName);
|
||||
void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX);
|
||||
void logFlipCard(Player *player, QString cardName, bool faceDown);
|
||||
void logDestroyCard(Player *player, QString cardName);
|
||||
void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName);
|
||||
void logUnattachCard(Player *player, QString cardName);
|
||||
void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue);
|
||||
void logSetTapped(Player *player, CardItem *card, bool tapped);
|
||||
void logSetCounter(Player *player, QString counterName, int value, int oldValue);
|
||||
void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap);
|
||||
void logSetPT(Player *player, CardItem *card, QString newPT);
|
||||
void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation);
|
||||
void logDumpZone(Player *player, CardZone *zone, int numberCards);
|
||||
void logStopDumpZone(Player *player, CardZone *zone);
|
||||
void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown);
|
||||
void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal);
|
||||
void openDeckEditor(const DeckLoader *deck);
|
||||
void newCardAdded(AbstractCardItem *card);
|
||||
// Log events
|
||||
void logSay(Player *player, QString message);
|
||||
void logShuffle(Player *player, CardZone *zone);
|
||||
void logRollDie(Player *player, int sides, int roll);
|
||||
void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool _playerTarget);
|
||||
void logCreateToken(Player *player, QString cardName, QString pt);
|
||||
void logDrawCards(Player *player, int number);
|
||||
void logUndoDraw(Player *player, QString cardName);
|
||||
void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX);
|
||||
void logFlipCard(Player *player, QString cardName, bool faceDown);
|
||||
void logDestroyCard(Player *player, QString cardName);
|
||||
void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName);
|
||||
void logUnattachCard(Player *player, QString cardName);
|
||||
void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue);
|
||||
void logSetTapped(Player *player, CardItem *card, bool tapped);
|
||||
void logSetCounter(Player *player, QString counterName, int value, int oldValue);
|
||||
void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap);
|
||||
void logSetPT(Player *player, CardItem *card, QString newPT);
|
||||
void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation);
|
||||
void logDumpZone(Player *player, CardZone *zone, int numberCards);
|
||||
void logStopDumpZone(Player *player, CardZone *zone);
|
||||
void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown);
|
||||
void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal);
|
||||
|
||||
void sizeChanged();
|
||||
void gameConceded();
|
||||
void sizeChanged();
|
||||
void gameConceded();
|
||||
public slots:
|
||||
void actUntapAll();
|
||||
void actRollDie();
|
||||
void actCreateToken();
|
||||
void actCreateAnotherToken();
|
||||
void actShuffle();
|
||||
void actDrawCard();
|
||||
void actDrawCards();
|
||||
void actUndoDraw();
|
||||
void actUntapAll();
|
||||
void actRollDie();
|
||||
void actCreateToken();
|
||||
void actCreateAnotherToken();
|
||||
void actShuffle();
|
||||
void actDrawCard();
|
||||
void actDrawCards();
|
||||
void actUndoDraw();
|
||||
void actMulligan();
|
||||
void actMoveTopCardsToGrave();
|
||||
void actMoveTopCardsToExile();
|
||||
void actMoveTopCardToBottom();
|
||||
void actMoveTopCardsToGrave();
|
||||
void actMoveTopCardsToExile();
|
||||
void actMoveTopCardToBottom();
|
||||
|
||||
void actViewLibrary();
|
||||
void actViewTopCards();
|
||||
void actAlwaysRevealTopCard();
|
||||
void actViewGraveyard();
|
||||
void actViewRfg();
|
||||
void actViewSideboard();
|
||||
void actViewLibrary();
|
||||
void actViewTopCards();
|
||||
void actAlwaysRevealTopCard();
|
||||
void actViewGraveyard();
|
||||
void actViewRfg();
|
||||
void actViewSideboard();
|
||||
|
||||
void actSayMessage();
|
||||
void actSayMessage();
|
||||
private slots:
|
||||
void addPlayer(Player *player);
|
||||
void removePlayer(Player *player);
|
||||
void playerListActionTriggered();
|
||||
void addPlayer(Player *player);
|
||||
void removePlayer(Player *player);
|
||||
void playerListActionTriggered();
|
||||
|
||||
void updateBoundingRect();
|
||||
void rearrangeZones();
|
||||
void updateBoundingRect();
|
||||
void rearrangeZones();
|
||||
|
||||
void actOpenDeckInDeckEditor();
|
||||
void actCreatePredefinedToken();
|
||||
void cardMenuAction();
|
||||
void actCardCounterTrigger();
|
||||
void actAttach();
|
||||
void actUnattach();
|
||||
void actDrawArrow();
|
||||
void actIncPT(int deltaP, int deltaT);
|
||||
void actSetPT();
|
||||
void actIncP();
|
||||
void actDecP();
|
||||
void actIncT();
|
||||
void actDecT();
|
||||
void actIncPT();
|
||||
void actDecPT();
|
||||
void actSetAnnotation();
|
||||
void actPlay();
|
||||
void actHide();
|
||||
void actOpenDeckInDeckEditor();
|
||||
void actCreatePredefinedToken();
|
||||
void cardMenuAction();
|
||||
void actCardCounterTrigger();
|
||||
void actAttach();
|
||||
void actUnattach();
|
||||
void actDrawArrow();
|
||||
void actIncPT(int deltaP, int deltaT);
|
||||
void actSetPT();
|
||||
void actIncP();
|
||||
void actDecP();
|
||||
void actIncT();
|
||||
void actDecT();
|
||||
void actIncPT();
|
||||
void actDecPT();
|
||||
void actSetAnnotation();
|
||||
void actPlay();
|
||||
void actHide();
|
||||
|
||||
private:
|
||||
TabGame *game;
|
||||
QMenu *playerMenu, *handMenu, *graveMenu, *rfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu,
|
||||
*mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard;
|
||||
QList<QMenu *> playerLists;
|
||||
QList<QAction *> allPlayersActions;
|
||||
QAction *aMoveHandToTopLibrary, *aMoveHandToBottomLibrary, *aMoveHandToGrave, *aMoveHandToRfg,
|
||||
*aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg,
|
||||
*aMoveRfgToTopLibrary, *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave,
|
||||
*aViewLibrary, *aViewTopCards, *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, *aMoveTopCardToBottom,
|
||||
*aViewGraveyard, *aViewRfg, *aViewSideboard,
|
||||
TabGame *game;
|
||||
QMenu *playerMenu, *handMenu, *graveMenu, *rfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu,
|
||||
*mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard;
|
||||
QList<QMenu *> playerLists;
|
||||
QList<QAction *> allPlayersActions;
|
||||
QAction *aMoveHandToTopLibrary, *aMoveHandToBottomLibrary, *aMoveHandToGrave, *aMoveHandToRfg,
|
||||
*aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg,
|
||||
*aMoveRfgToTopLibrary, *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave,
|
||||
*aViewLibrary, *aViewTopCards, *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, *aMoveTopCardToBottom,
|
||||
*aViewGraveyard, *aViewRfg, *aViewSideboard,
|
||||
*aDrawCard, *aDrawCards, *aUndoDraw, *aMulligan, *aShuffle,
|
||||
*aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken,
|
||||
*aCardMenu;
|
||||
*aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken,
|
||||
*aCardMenu;
|
||||
|
||||
QList<QAction *> aAddCounter, aSetCounter, aRemoveCounter;
|
||||
QAction *aPlay,
|
||||
*aHide,
|
||||
*aTap, *aUntap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone,
|
||||
*aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToGraveyard, *aMoveToExile;
|
||||
QList<QAction *> aAddCounter, aSetCounter, aRemoveCounter;
|
||||
QAction *aPlay,
|
||||
*aHide,
|
||||
*aTap, *aUntap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone,
|
||||
*aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToGraveyard, *aMoveToExile;
|
||||
|
||||
bool shortcutsActive;
|
||||
int defaultNumberTopCards;
|
||||
QString lastTokenName, lastTokenColor, lastTokenPT, lastTokenAnnotation;
|
||||
bool lastTokenDestroy;
|
||||
ServerInfo_User *userInfo;
|
||||
int id;
|
||||
bool active;
|
||||
bool local;
|
||||
bool mirrored;
|
||||
bool handVisible;
|
||||
bool conceded;
|
||||
bool shortcutsActive;
|
||||
int defaultNumberTopCards;
|
||||
QString lastTokenName, lastTokenColor, lastTokenPT, lastTokenAnnotation;
|
||||
bool lastTokenDestroy;
|
||||
ServerInfo_User *userInfo;
|
||||
int id;
|
||||
bool active;
|
||||
bool local;
|
||||
bool mirrored;
|
||||
bool handVisible;
|
||||
bool conceded;
|
||||
|
||||
bool dialogSemaphore;
|
||||
bool clearCardsToDelete();
|
||||
QList<CardItem *> cardsToDelete;
|
||||
bool dialogSemaphore;
|
||||
bool clearCardsToDelete();
|
||||
QList<CardItem *> cardsToDelete;
|
||||
|
||||
DeckLoader *deck;
|
||||
QStringList predefinedTokens;
|
||||
DeckLoader *deck;
|
||||
QStringList predefinedTokens;
|
||||
|
||||
PlayerArea *playerArea;
|
||||
QMap<QString, CardZone *> zones;
|
||||
StackZone *stack;
|
||||
TableZone *table;
|
||||
HandZone *hand;
|
||||
PlayerTarget *playerTarget;
|
||||
PlayerArea *playerArea;
|
||||
QMap<QString, CardZone *> zones;
|
||||
StackZone *stack;
|
||||
TableZone *table;
|
||||
HandZone *hand;
|
||||
PlayerTarget *playerTarget;
|
||||
|
||||
void setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards);
|
||||
void setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards);
|
||||
|
||||
QRectF bRect;
|
||||
QRectF bRect;
|
||||
|
||||
QMap<int, AbstractCounter *> counters;
|
||||
QMap<int, ArrowItem *> arrows;
|
||||
void rearrangeCounters();
|
||||
QMap<int, AbstractCounter *> counters;
|
||||
QMap<int, ArrowItem *> arrows;
|
||||
void rearrangeCounters();
|
||||
|
||||
void initSayMenu();
|
||||
void initSayMenu();
|
||||
|
||||
void eventConnectionStateChanged(const Event_ConnectionStateChanged &event);
|
||||
void eventGameSay(const Event_GameSay &event);
|
||||
void eventShuffle(const Event_Shuffle &event);
|
||||
void eventRollDie(const Event_RollDie &event);
|
||||
void eventCreateArrow(const Event_CreateArrow &event);
|
||||
void eventDeleteArrow(const Event_DeleteArrow &event);
|
||||
void eventCreateToken(const Event_CreateToken &event);
|
||||
void eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context);
|
||||
void eventSetCardCounter(const Event_SetCardCounter &event);
|
||||
void eventCreateCounter(const Event_CreateCounter &event);
|
||||
void eventSetCounter(const Event_SetCounter &event);
|
||||
void eventDelCounter(const Event_DelCounter &event);
|
||||
void eventDumpZone(const Event_DumpZone &event);
|
||||
void eventStopDumpZone(const Event_StopDumpZone &event);
|
||||
void eventMoveCard(const Event_MoveCard &event, const GameEventContext &context);
|
||||
void eventFlipCard(const Event_FlipCard &event);
|
||||
void eventDestroyCard(const Event_DestroyCard &event);
|
||||
void eventAttachCard(const Event_AttachCard &event);
|
||||
void eventDrawCards(const Event_DrawCards &event);
|
||||
void eventRevealCards(const Event_RevealCards &event);
|
||||
void eventChangeZoneProperties(const Event_ChangeZoneProperties &event);
|
||||
void eventConnectionStateChanged(const Event_ConnectionStateChanged &event);
|
||||
void eventGameSay(const Event_GameSay &event);
|
||||
void eventShuffle(const Event_Shuffle &event);
|
||||
void eventRollDie(const Event_RollDie &event);
|
||||
void eventCreateArrow(const Event_CreateArrow &event);
|
||||
void eventDeleteArrow(const Event_DeleteArrow &event);
|
||||
void eventCreateToken(const Event_CreateToken &event);
|
||||
void eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context);
|
||||
void eventSetCardCounter(const Event_SetCardCounter &event);
|
||||
void eventCreateCounter(const Event_CreateCounter &event);
|
||||
void eventSetCounter(const Event_SetCounter &event);
|
||||
void eventDelCounter(const Event_DelCounter &event);
|
||||
void eventDumpZone(const Event_DumpZone &event);
|
||||
void eventStopDumpZone(const Event_StopDumpZone &event);
|
||||
void eventMoveCard(const Event_MoveCard &event, const GameEventContext &context);
|
||||
void eventFlipCard(const Event_FlipCard &event);
|
||||
void eventDestroyCard(const Event_DestroyCard &event);
|
||||
void eventAttachCard(const Event_AttachCard &event);
|
||||
void eventDrawCards(const Event_DrawCards &event);
|
||||
void eventRevealCards(const Event_RevealCards &event);
|
||||
void eventChangeZoneProperties(const Event_ChangeZoneProperties &event);
|
||||
public:
|
||||
static const int counterAreaWidth = 55;
|
||||
enum CardMenuActionType { cmTap, cmUntap, cmDoesntUntap, cmFlip, cmPeek, cmClone, cmMoveToTopLibrary, cmMoveToBottomLibrary, cmMoveToGraveyard, cmMoveToExile };
|
||||
static const int counterAreaWidth = 55;
|
||||
enum CardMenuActionType { cmTap, cmUntap, cmDoesntUntap, cmFlip, cmPeek, cmClone, cmMoveToTopLibrary, cmMoveToBottomLibrary, cmMoveToGraveyard, cmMoveToExile };
|
||||
|
||||
enum { Type = typeOther };
|
||||
int type() const { return Type; }
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
enum { Type = typeOther };
|
||||
int type() const { return Type; }
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
|
||||
void playCard(CardItem *c, bool faceDown, bool tapped);
|
||||
void addCard(CardItem *c);
|
||||
void deleteCard(CardItem *c);
|
||||
void addZone(CardZone *z);
|
||||
void playCard(CardItem *c, bool faceDown, bool tapped);
|
||||
void addCard(CardItem *c);
|
||||
void deleteCard(CardItem *c);
|
||||
void addZone(CardZone *z);
|
||||
|
||||
AbstractCounter *addCounter(const ServerInfo_Counter &counter);
|
||||
AbstractCounter *addCounter(int counterId, const QString &name, QColor color, int radius, int value);
|
||||
void delCounter(int counterId);
|
||||
void clearCounters();
|
||||
AbstractCounter *addCounter(const ServerInfo_Counter &counter);
|
||||
AbstractCounter *addCounter(int counterId, const QString &name, QColor color, int radius, int value);
|
||||
void delCounter(int counterId);
|
||||
void clearCounters();
|
||||
|
||||
ArrowItem *addArrow(const ServerInfo_Arrow &arrow);
|
||||
ArrowItem *addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color);
|
||||
void delArrow(int arrowId);
|
||||
void removeArrow(ArrowItem *arrow);
|
||||
void clearArrows();
|
||||
PlayerTarget *getPlayerTarget() const { return playerTarget; }
|
||||
ArrowItem *addArrow(const ServerInfo_Arrow &arrow);
|
||||
ArrowItem *addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color);
|
||||
void delArrow(int arrowId);
|
||||
void removeArrow(ArrowItem *arrow);
|
||||
void clearArrows();
|
||||
PlayerTarget *getPlayerTarget() const { return playerTarget; }
|
||||
|
||||
Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent);
|
||||
~Player();
|
||||
void retranslateUi();
|
||||
void clear();
|
||||
TabGame *getGame() const { return game; }
|
||||
void setDeck(const DeckLoader &_deck);
|
||||
QMenu *getPlayerMenu() const { return playerMenu; }
|
||||
int getId() const { return id; }
|
||||
QString getName() const;
|
||||
ServerInfo_User *getUserInfo() const { return userInfo; }
|
||||
bool getLocal() const { return local; }
|
||||
bool getMirrored() const { return mirrored; }
|
||||
const QMap<QString, CardZone *> &getZones() const { return zones; }
|
||||
const QMap<int, ArrowItem *> &getArrows() const { return arrows; }
|
||||
void setCardMenu(QMenu *menu);
|
||||
QMenu *getCardMenu() const;
|
||||
void updateCardMenu(CardItem *card);
|
||||
bool getActive() const { return active; }
|
||||
void setActive(bool _active);
|
||||
void setShortcutsActive();
|
||||
void setShortcutsInactive();
|
||||
void updateZones();
|
||||
Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent);
|
||||
~Player();
|
||||
void retranslateUi();
|
||||
void clear();
|
||||
TabGame *getGame() const { return game; }
|
||||
void setDeck(const DeckLoader &_deck);
|
||||
QMenu *getPlayerMenu() const { return playerMenu; }
|
||||
int getId() const { return id; }
|
||||
QString getName() const;
|
||||
ServerInfo_User *getUserInfo() const { return userInfo; }
|
||||
bool getLocal() const { return local; }
|
||||
bool getMirrored() const { return mirrored; }
|
||||
const QMap<QString, CardZone *> &getZones() const { return zones; }
|
||||
const QMap<int, ArrowItem *> &getArrows() const { return arrows; }
|
||||
void setCardMenu(QMenu *menu);
|
||||
QMenu *getCardMenu() const;
|
||||
void updateCardMenu(CardItem *card);
|
||||
bool getActive() const { return active; }
|
||||
void setActive(bool _active);
|
||||
void setShortcutsActive();
|
||||
void setShortcutsInactive();
|
||||
void updateZones();
|
||||
|
||||
void setConceded(bool _conceded);
|
||||
bool getConceded() const { return conceded; }
|
||||
void setConceded(bool _conceded);
|
||||
bool getConceded() const { return conceded; }
|
||||
|
||||
qreal getMinimumWidth() const;
|
||||
void setMirrored(bool _mirrored);
|
||||
void processSceneSizeChange(int newPlayerWidth);
|
||||
qreal getMinimumWidth() const;
|
||||
void setMirrored(bool _mirrored);
|
||||
void processSceneSizeChange(int newPlayerWidth);
|
||||
|
||||
void processPlayerInfo(const ServerInfo_Player &info);
|
||||
void processCardAttachment(const ServerInfo_Player &info);
|
||||
void processPlayerInfo(const ServerInfo_Player &info);
|
||||
void processCardAttachment(const ServerInfo_Player &info);
|
||||
|
||||
void processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context);
|
||||
void processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context);
|
||||
|
||||
PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd);
|
||||
PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList);
|
||||
void sendGameCommand(PendingCommand *pend);
|
||||
void sendGameCommand(const google::protobuf::Message &command);
|
||||
PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd);
|
||||
PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList);
|
||||
void sendGameCommand(PendingCommand *pend);
|
||||
void sendGameCommand(const google::protobuf::Message &command);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -17,63 +17,63 @@
|
|||
#include "pb/serverinfo_playerproperties.pb.h"
|
||||
|
||||
PlayerListItemDelegate::PlayerListItemDelegate(QObject *const parent)
|
||||
: QStyledItemDelegate(parent)
|
||||
: QStyledItemDelegate(parent)
|
||||
{
|
||||
}
|
||||
|
||||
bool PlayerListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
|
||||
{
|
||||
if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) {
|
||||
QMouseEvent *const mouseEvent = static_cast<QMouseEvent *>(event);
|
||||
if (mouseEvent->button() == Qt::RightButton) {
|
||||
static_cast<PlayerListWidget *>(parent())->showContextMenu(mouseEvent->globalPos(), index);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return QStyledItemDelegate::editorEvent(event, model, option, index);
|
||||
if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) {
|
||||
QMouseEvent *const mouseEvent = static_cast<QMouseEvent *>(event);
|
||||
if (mouseEvent->button() == Qt::RightButton) {
|
||||
static_cast<PlayerListWidget *>(parent())->showContextMenu(mouseEvent->globalPos(), index);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return QStyledItemDelegate::editorEvent(event, model, option, index);
|
||||
}
|
||||
|
||||
PlayerListTWI::PlayerListTWI()
|
||||
: QTreeWidgetItem(Type)
|
||||
: QTreeWidgetItem(Type)
|
||||
{
|
||||
}
|
||||
|
||||
bool PlayerListTWI::operator<(const QTreeWidgetItem &other) const
|
||||
{
|
||||
// Sort by spectator/player
|
||||
if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole))
|
||||
return data(1, Qt::UserRole).toBool();
|
||||
// Sort by spectator/player
|
||||
if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole))
|
||||
return data(1, Qt::UserRole).toBool();
|
||||
|
||||
// Sort by player ID
|
||||
return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt();
|
||||
// Sort by player ID
|
||||
return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt();
|
||||
}
|
||||
|
||||
PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent)
|
||||
: QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false)
|
||||
: QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false)
|
||||
{
|
||||
readyIcon = QIcon(":/resources/icon_ready_start.svg");
|
||||
notReadyIcon = QIcon(":/resources/icon_not_ready_start.svg");
|
||||
concededIcon = QIcon(":/resources/icon_conceded.svg");
|
||||
playerIcon = QIcon(":/resources/icon_player.svg");
|
||||
spectatorIcon = QIcon(":/resources/icon_spectator.svg");
|
||||
lockIcon = QIcon(":/resources/lock.svg");
|
||||
readyIcon = QIcon(":/resources/icon_ready_start.svg");
|
||||
notReadyIcon = QIcon(":/resources/icon_not_ready_start.svg");
|
||||
concededIcon = QIcon(":/resources/icon_conceded.svg");
|
||||
playerIcon = QIcon(":/resources/icon_player.svg");
|
||||
spectatorIcon = QIcon(":/resources/icon_spectator.svg");
|
||||
lockIcon = QIcon(":/resources/lock.svg");
|
||||
|
||||
if (tabSupervisor) {
|
||||
itemDelegate = new PlayerListItemDelegate(this);
|
||||
setItemDelegate(itemDelegate);
|
||||
if (tabSupervisor) {
|
||||
itemDelegate = new PlayerListItemDelegate(this);
|
||||
setItemDelegate(itemDelegate);
|
||||
|
||||
userContextMenu = new UserContextMenu(tabSupervisor, this, game);
|
||||
connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
|
||||
} else
|
||||
userContextMenu = 0;
|
||||
userContextMenu = new UserContextMenu(tabSupervisor, this, game);
|
||||
connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
|
||||
} else
|
||||
userContextMenu = 0;
|
||||
|
||||
setMinimumHeight(60);
|
||||
setIconSize(QSize(20, 15));
|
||||
setColumnCount(6);
|
||||
setHeaderHidden(true);
|
||||
setRootIsDecorated(false);
|
||||
header()->setResizeMode(QHeaderView::ResizeToContents);
|
||||
retranslateUi();
|
||||
setMinimumHeight(60);
|
||||
setIconSize(QSize(20, 15));
|
||||
setColumnCount(6);
|
||||
setHeaderHidden(true);
|
||||
setRootIsDecorated(false);
|
||||
header()->setResizeMode(QHeaderView::ResizeToContents);
|
||||
retranslateUi();
|
||||
}
|
||||
|
||||
void PlayerListWidget::retranslateUi()
|
||||
|
@ -82,97 +82,97 @@ void PlayerListWidget::retranslateUi()
|
|||
|
||||
void PlayerListWidget::addPlayer(const ServerInfo_PlayerProperties &player)
|
||||
{
|
||||
QTreeWidgetItem *newPlayer = new PlayerListTWI;
|
||||
players.insert(player.player_id(), newPlayer);
|
||||
updatePlayerProperties(player);
|
||||
addTopLevelItem(newPlayer);
|
||||
sortItems(1, Qt::AscendingOrder);
|
||||
QTreeWidgetItem *newPlayer = new PlayerListTWI;
|
||||
players.insert(player.player_id(), newPlayer);
|
||||
updatePlayerProperties(player);
|
||||
addTopLevelItem(newPlayer);
|
||||
sortItems(1, Qt::AscendingOrder);
|
||||
}
|
||||
|
||||
void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId)
|
||||
{
|
||||
if (playerId == -1)
|
||||
playerId = prop.player_id();
|
||||
if (playerId == -1)
|
||||
playerId = prop.player_id();
|
||||
|
||||
QTreeWidgetItem *player = players.value(playerId, 0);
|
||||
if (!player)
|
||||
return;
|
||||
QTreeWidgetItem *player = players.value(playerId, 0);
|
||||
if (!player)
|
||||
return;
|
||||
|
||||
if (prop.has_spectator()) {
|
||||
player->setIcon(1, prop.spectator() ? spectatorIcon : playerIcon);
|
||||
player->setData(1, Qt::UserRole, !prop.spectator());
|
||||
}
|
||||
if (prop.has_conceded())
|
||||
player->setData(2, Qt::UserRole, prop.conceded());
|
||||
if (prop.has_ready_start())
|
||||
player->setData(2, Qt::UserRole + 1, prop.ready_start());
|
||||
if (prop.has_conceded() || prop.has_ready_start())
|
||||
player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon()) : (prop.ready_start() ? readyIcon : notReadyIcon));
|
||||
if (prop.has_user_info()) {
|
||||
player->setData(3, Qt::UserRole, prop.user_info().user_level());
|
||||
player->setIcon(3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level()))));
|
||||
player->setText(4, QString::fromStdString(prop.user_info().name()));
|
||||
const QString country = QString::fromStdString(prop.user_info().country());
|
||||
if (!country.isEmpty())
|
||||
player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country)));
|
||||
player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name()));
|
||||
}
|
||||
if (prop.has_player_id())
|
||||
player->setData(4, Qt::UserRole + 1, prop.player_id());
|
||||
if (prop.has_deck_hash())
|
||||
player->setText(5, QString::fromStdString(prop.deck_hash()));
|
||||
if (prop.has_sideboard_locked())
|
||||
player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon());
|
||||
if (prop.has_ping_seconds())
|
||||
player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10)));
|
||||
if (prop.has_spectator()) {
|
||||
player->setIcon(1, prop.spectator() ? spectatorIcon : playerIcon);
|
||||
player->setData(1, Qt::UserRole, !prop.spectator());
|
||||
}
|
||||
if (prop.has_conceded())
|
||||
player->setData(2, Qt::UserRole, prop.conceded());
|
||||
if (prop.has_ready_start())
|
||||
player->setData(2, Qt::UserRole + 1, prop.ready_start());
|
||||
if (prop.has_conceded() || prop.has_ready_start())
|
||||
player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon()) : (prop.ready_start() ? readyIcon : notReadyIcon));
|
||||
if (prop.has_user_info()) {
|
||||
player->setData(3, Qt::UserRole, prop.user_info().user_level());
|
||||
player->setIcon(3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level()))));
|
||||
player->setText(4, QString::fromStdString(prop.user_info().name()));
|
||||
const QString country = QString::fromStdString(prop.user_info().country());
|
||||
if (!country.isEmpty())
|
||||
player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country)));
|
||||
player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name()));
|
||||
}
|
||||
if (prop.has_player_id())
|
||||
player->setData(4, Qt::UserRole + 1, prop.player_id());
|
||||
if (prop.has_deck_hash())
|
||||
player->setText(5, QString::fromStdString(prop.deck_hash()));
|
||||
if (prop.has_sideboard_locked())
|
||||
player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon());
|
||||
if (prop.has_ping_seconds())
|
||||
player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10)));
|
||||
}
|
||||
|
||||
void PlayerListWidget::removePlayer(int playerId)
|
||||
{
|
||||
QTreeWidgetItem *player = players.value(playerId, 0);
|
||||
if (!player)
|
||||
return;
|
||||
players.remove(playerId);
|
||||
delete takeTopLevelItem(indexOfTopLevelItem(player));
|
||||
QTreeWidgetItem *player = players.value(playerId, 0);
|
||||
if (!player)
|
||||
return;
|
||||
players.remove(playerId);
|
||||
delete takeTopLevelItem(indexOfTopLevelItem(player));
|
||||
}
|
||||
|
||||
void PlayerListWidget::setActivePlayer(int playerId)
|
||||
{
|
||||
QMapIterator<int, QTreeWidgetItem *> i(players);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
QTreeWidgetItem *twi = i.value();
|
||||
QColor c = i.key() == playerId ? QColor(150, 255, 150) : Qt::white;
|
||||
twi->setBackground(4, c);
|
||||
}
|
||||
QMapIterator<int, QTreeWidgetItem *> i(players);
|
||||
while (i.hasNext()) {
|
||||
i.next();
|
||||
QTreeWidgetItem *twi = i.value();
|
||||
QColor c = i.key() == playerId ? QColor(150, 255, 150) : Qt::white;
|
||||
twi->setBackground(4, c);
|
||||
}
|
||||
}
|
||||
|
||||
void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming)
|
||||
{
|
||||
gameStarted = _gameStarted;
|
||||
QMapIterator<int, QTreeWidgetItem *> i(players);
|
||||
while (i.hasNext()) {
|
||||
QTreeWidgetItem *twi = i.next().value();
|
||||
if (gameStarted) {
|
||||
if (resuming)
|
||||
twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon());
|
||||
else {
|
||||
twi->setData(2, Qt::UserRole, false);
|
||||
twi->setIcon(2, QIcon());
|
||||
}
|
||||
} else
|
||||
twi->setIcon(2, notReadyIcon);
|
||||
}
|
||||
gameStarted = _gameStarted;
|
||||
QMapIterator<int, QTreeWidgetItem *> i(players);
|
||||
while (i.hasNext()) {
|
||||
QTreeWidgetItem *twi = i.next().value();
|
||||
if (gameStarted) {
|
||||
if (resuming)
|
||||
twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon());
|
||||
else {
|
||||
twi->setData(2, Qt::UserRole, false);
|
||||
twi->setIcon(2, QIcon());
|
||||
}
|
||||
} else
|
||||
twi->setIcon(2, notReadyIcon);
|
||||
}
|
||||
}
|
||||
|
||||
void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index)
|
||||
{
|
||||
if (!userContextMenu)
|
||||
return;
|
||||
if (!userContextMenu)
|
||||
return;
|
||||
|
||||
const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString();
|
||||
int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt();
|
||||
UserLevelFlags userLevel(index.sibling(index.row(), 3).data(Qt::UserRole).toInt());
|
||||
const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString();
|
||||
int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt();
|
||||
UserLevelFlags userLevel(index.sibling(index.row(), 3).data(Qt::UserRole).toInt());
|
||||
|
||||
userContextMenu->showContextMenu(pos, userName, userLevel, playerId);
|
||||
userContextMenu->showContextMenu(pos, userName, userLevel, playerId);
|
||||
}
|
||||
|
|
|
@ -14,38 +14,38 @@ class UserContextMenu;
|
|||
|
||||
class PlayerListItemDelegate : public QStyledItemDelegate {
|
||||
public:
|
||||
PlayerListItemDelegate(QObject *const parent);
|
||||
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
|
||||
PlayerListItemDelegate(QObject *const parent);
|
||||
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
|
||||
};
|
||||
|
||||
class PlayerListTWI : public QTreeWidgetItem {
|
||||
public:
|
||||
PlayerListTWI();
|
||||
bool operator<(const QTreeWidgetItem &other) const;
|
||||
PlayerListTWI();
|
||||
bool operator<(const QTreeWidgetItem &other) const;
|
||||
};
|
||||
|
||||
class PlayerListWidget : public QTreeWidget {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
PlayerListItemDelegate *itemDelegate;
|
||||
QMap<int, QTreeWidgetItem *> players;
|
||||
TabSupervisor *tabSupervisor;
|
||||
AbstractClient *client;
|
||||
TabGame *game;
|
||||
UserContextMenu *userContextMenu;
|
||||
QIcon readyIcon, notReadyIcon, concededIcon, playerIcon, spectatorIcon, lockIcon;
|
||||
bool gameStarted;
|
||||
PlayerListItemDelegate *itemDelegate;
|
||||
QMap<int, QTreeWidgetItem *> players;
|
||||
TabSupervisor *tabSupervisor;
|
||||
AbstractClient *client;
|
||||
TabGame *game;
|
||||
UserContextMenu *userContextMenu;
|
||||
QIcon readyIcon, notReadyIcon, concededIcon, playerIcon, spectatorIcon, lockIcon;
|
||||
bool gameStarted;
|
||||
signals:
|
||||
void openMessageDialog(const QString &userName, bool focus);
|
||||
void openMessageDialog(const QString &userName, bool focus);
|
||||
public:
|
||||
PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0);
|
||||
void retranslateUi();
|
||||
void addPlayer(const ServerInfo_PlayerProperties &player);
|
||||
void removePlayer(int playerId);
|
||||
void setActivePlayer(int playerId);
|
||||
void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1);
|
||||
void setGameStarted(bool _gameStarted, bool resuming);
|
||||
void showContextMenu(const QPoint &pos, const QModelIndex &index);
|
||||
PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0);
|
||||
void retranslateUi();
|
||||
void addPlayer(const ServerInfo_PlayerProperties &player);
|
||||
void removePlayer(int playerId);
|
||||
void setActivePlayer(int playerId);
|
||||
void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1);
|
||||
void setGameStarted(bool _gameStarted, bool resuming);
|
||||
void showContextMenu(const QPoint &pos, const QModelIndex &index);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -8,149 +8,149 @@
|
|||
#include <math.h>
|
||||
|
||||
PlayerCounter::PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent)
|
||||
: AbstractCounter(_player, _id, _name, false, _value, parent)
|
||||
: AbstractCounter(_player, _id, _name, false, _value, parent)
|
||||
{
|
||||
}
|
||||
|
||||
QRectF PlayerCounter::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, 50, 30);
|
||||
return QRectF(0, 0, 50, 30);
|
||||
}
|
||||
|
||||
void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
const int radius = 8;
|
||||
const qreal border = 1;
|
||||
QPainterPath path(QPointF(50 - border / 2, border / 2));
|
||||
path.lineTo(radius, border / 2);
|
||||
path.arcTo(border / 2, border / 2, 2 * radius, 2 * radius, 90, 90);
|
||||
path.lineTo(border / 2, 30 - border / 2);
|
||||
path.lineTo(50 - border / 2, 30 - border / 2);
|
||||
path.closeSubpath();
|
||||
const int radius = 8;
|
||||
const qreal border = 1;
|
||||
QPainterPath path(QPointF(50 - border / 2, border / 2));
|
||||
path.lineTo(radius, border / 2);
|
||||
path.arcTo(border / 2, border / 2, 2 * radius, 2 * radius, 90, 90);
|
||||
path.lineTo(border / 2, 30 - border / 2);
|
||||
path.lineTo(50 - border / 2, 30 - border / 2);
|
||||
path.closeSubpath();
|
||||
|
||||
QPen pen(QColor(100, 100, 100));
|
||||
pen.setWidth(border);
|
||||
painter->setPen(pen);
|
||||
painter->setBrush(hovered ? QColor(50, 50, 50, 160) : QColor(0, 0, 0, 160));
|
||||
QPen pen(QColor(100, 100, 100));
|
||||
pen.setWidth(border);
|
||||
painter->setPen(pen);
|
||||
painter->setBrush(hovered ? QColor(50, 50, 50, 160) : QColor(0, 0, 0, 160));
|
||||
|
||||
painter->drawPath(path);
|
||||
painter->drawPath(path);
|
||||
|
||||
QRectF translatedRect = painter->combinedTransform().mapRect(boundingRect());
|
||||
QSize translatedSize = translatedRect.size().toSize();
|
||||
painter->resetTransform();
|
||||
QFont font("Serif");
|
||||
font.setWeight(QFont::Bold);
|
||||
font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9));
|
||||
painter->setFont(font);
|
||||
painter->setPen(Qt::white);
|
||||
painter->drawText(translatedRect, Qt::AlignCenter, QString::number(value));
|
||||
QRectF translatedRect = painter->combinedTransform().mapRect(boundingRect());
|
||||
QSize translatedSize = translatedRect.size().toSize();
|
||||
painter->resetTransform();
|
||||
QFont font("Serif");
|
||||
font.setWeight(QFont::Bold);
|
||||
font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9));
|
||||
painter->setFont(font);
|
||||
painter->setPen(Qt::white);
|
||||
painter->drawText(translatedRect, Qt::AlignCenter, QString::number(value));
|
||||
}
|
||||
|
||||
PlayerTarget::PlayerTarget(Player *_owner, QGraphicsItem *parentItem)
|
||||
: ArrowTarget(_owner, parentItem), playerCounter(0)
|
||||
: ArrowTarget(_owner, parentItem), playerCounter(0)
|
||||
{
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
setCacheMode(DeviceCoordinateCache);
|
||||
|
||||
const std::string &bmp = _owner->getUserInfo()->avatar_bmp();
|
||||
if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size()))
|
||||
fullPixmap = QPixmap();
|
||||
const std::string &bmp = _owner->getUserInfo()->avatar_bmp();
|
||||
if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size()))
|
||||
fullPixmap = QPixmap();
|
||||
}
|
||||
|
||||
PlayerTarget::~PlayerTarget()
|
||||
{
|
||||
// Explicit deletion is necessary in spite of parent/child relationship
|
||||
// as we need this object to be alive to receive the destroyed() signal.
|
||||
delete playerCounter;
|
||||
// Explicit deletion is necessary in spite of parent/child relationship
|
||||
// as we need this object to be alive to receive the destroyed() signal.
|
||||
delete playerCounter;
|
||||
}
|
||||
|
||||
QRectF PlayerTarget::boundingRect() const
|
||||
{
|
||||
return QRectF(0, 0, 160, 64);
|
||||
return QRectF(0, 0, 160, 64);
|
||||
}
|
||||
|
||||
void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
|
||||
{
|
||||
const ServerInfo_User *const info = owner->getUserInfo();
|
||||
const ServerInfo_User *const info = owner->getUserInfo();
|
||||
|
||||
const qreal border = 2;
|
||||
const qreal border = 2;
|
||||
|
||||
QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border);
|
||||
QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect);
|
||||
QSize translatedSize = translatedRect.size().toSize();
|
||||
QPixmap cachedPixmap;
|
||||
const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey());
|
||||
QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border);
|
||||
QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect);
|
||||
QSize translatedSize = translatedRect.size().toSize();
|
||||
QPixmap cachedPixmap;
|
||||
const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey());
|
||||
#if QT_VERSION >= 0x040600
|
||||
if (!QPixmapCache::find(cacheKey, &cachedPixmap)) {
|
||||
if (!QPixmapCache::find(cacheKey, &cachedPixmap)) {
|
||||
#else
|
||||
if (!QPixmapCache::find(cacheKey, cachedPixmap)) {
|
||||
if (!QPixmapCache::find(cacheKey, cachedPixmap)) {
|
||||
#endif
|
||||
cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height());
|
||||
cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height());
|
||||
|
||||
QPainter tempPainter(&cachedPixmap);
|
||||
QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2);
|
||||
grad.setColorAt(1, Qt::black);
|
||||
grad.setColorAt(0, QColor(180, 180, 180));
|
||||
tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad);
|
||||
QPainter tempPainter(&cachedPixmap);
|
||||
QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2);
|
||||
grad.setColorAt(1, Qt::black);
|
||||
grad.setColorAt(0, QColor(180, 180, 180));
|
||||
tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad);
|
||||
|
||||
QPixmap tempPixmap;
|
||||
if (fullPixmap.isNull())
|
||||
tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level()));
|
||||
else
|
||||
tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||
QPixmap tempPixmap;
|
||||
if (fullPixmap.isNull())
|
||||
tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level()));
|
||||
else
|
||||
tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||
|
||||
tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap);
|
||||
QPixmapCache::insert(cacheKey, cachedPixmap);
|
||||
}
|
||||
tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap);
|
||||
QPixmapCache::insert(cacheKey, cachedPixmap);
|
||||
}
|
||||
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0);
|
||||
painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect());
|
||||
painter->restore();
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0);
|
||||
painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect());
|
||||
painter->restore();
|
||||
|
||||
QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20);
|
||||
painter->fillRect(nameRect, QColor(0, 0, 0, 160));
|
||||
QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect);
|
||||
QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20);
|
||||
painter->fillRect(nameRect, QColor(0, 0, 0, 160));
|
||||
QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect);
|
||||
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
painter->save();
|
||||
painter->resetTransform();
|
||||
|
||||
QString name = QString::fromStdString(info->name());
|
||||
if (name.size() > 13)
|
||||
name = name.mid(0, 10) + "...";
|
||||
QString name = QString::fromStdString(info->name());
|
||||
if (name.size() > 13)
|
||||
name = name.mid(0, 10) + "...";
|
||||
|
||||
QFont font;
|
||||
font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9));
|
||||
painter->setFont(font);
|
||||
painter->setPen(Qt::white);
|
||||
painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name);
|
||||
painter->restore();
|
||||
QFont font;
|
||||
font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9));
|
||||
painter->setFont(font);
|
||||
painter->setPen(Qt::white);
|
||||
painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name);
|
||||
painter->restore();
|
||||
|
||||
QPen pen(QColor(100, 100, 100));
|
||||
pen.setWidth(border);
|
||||
pen.setJoinStyle(Qt::RoundJoin);
|
||||
painter->setPen(pen);
|
||||
painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2));
|
||||
QPen pen(QColor(100, 100, 100));
|
||||
pen.setWidth(border);
|
||||
pen.setJoinStyle(Qt::RoundJoin);
|
||||
painter->setPen(pen);
|
||||
painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2));
|
||||
|
||||
if (getBeingPointedAt())
|
||||
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
|
||||
if (getBeingPointedAt())
|
||||
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
|
||||
}
|
||||
|
||||
AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value)
|
||||
{
|
||||
if (playerCounter) {
|
||||
disconnect(playerCounter, 0, this, 0);
|
||||
playerCounter->delCounter();
|
||||
}
|
||||
if (playerCounter) {
|
||||
disconnect(playerCounter, 0, this, 0);
|
||||
playerCounter->delCounter();
|
||||
}
|
||||
|
||||
playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this);
|
||||
playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height());
|
||||
connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted()));
|
||||
playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this);
|
||||
playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height());
|
||||
connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted()));
|
||||
|
||||
return playerCounter;
|
||||
return playerCounter;
|
||||
}
|
||||
|
||||
void PlayerTarget::counterDeleted()
|
||||
{
|
||||
playerCounter = 0;
|
||||
playerCounter = 0;
|
||||
}
|
||||
|
|
|
@ -9,30 +9,30 @@
|
|||
class Player;
|
||||
|
||||
class PlayerCounter : public AbstractCounter {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0);
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
};
|
||||
|
||||
class PlayerTarget : public ArrowTarget {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QPixmap fullPixmap;
|
||||
PlayerCounter *playerCounter;
|
||||
QPixmap fullPixmap;
|
||||
PlayerCounter *playerCounter;
|
||||
public slots:
|
||||
void counterDeleted();
|
||||
void counterDeleted();
|
||||
public:
|
||||
enum { Type = typePlayerTarget };
|
||||
int type() const { return Type; }
|
||||
enum { Type = typePlayerTarget };
|
||||
int type() const { return Type; }
|
||||
|
||||
PlayerTarget(Player *_player = 0, QGraphicsItem *parentItem = 0);
|
||||
~PlayerTarget();
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
PlayerTarget(Player *_player = 0, QGraphicsItem *parentItem = 0);
|
||||
~PlayerTarget();
|
||||
QRectF boundingRect() const;
|
||||
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
|
||||
|
||||
AbstractCounter *addCounter(int _counterId, const QString &_name, int _value);
|
||||
AbstractCounter *addCounter(int _counterId, const QString &_name, int _value);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -131,30 +131,30 @@ QByteArray Json::serialize(const QVariant &data, bool &success)
|
|||
|
||||
str = "[ " + join( values, ", " ) + " ]";
|
||||
}
|
||||
else if(data.type() == QVariant::Hash) // variant is a hash?
|
||||
{
|
||||
const QVariantHash vhash = data.toHash();
|
||||
QHashIterator<QString, QVariant> it( vhash );
|
||||
str = "{ ";
|
||||
QList<QByteArray> pairs;
|
||||
else if(data.type() == QVariant::Hash) // variant is a hash?
|
||||
{
|
||||
const QVariantHash vhash = data.toHash();
|
||||
QHashIterator<QString, QVariant> it( vhash );
|
||||
str = "{ ";
|
||||
QList<QByteArray> pairs;
|
||||
|
||||
while(it.hasNext())
|
||||
{
|
||||
it.next();
|
||||
QByteArray serializedValue = serialize(it.value());
|
||||
while(it.hasNext())
|
||||
{
|
||||
it.next();
|
||||
QByteArray serializedValue = serialize(it.value());
|
||||
|
||||
if(serializedValue.isNull())
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
if(serializedValue.isNull())
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
|
||||
pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue;
|
||||
}
|
||||
pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue;
|
||||
}
|
||||
|
||||
str += join(pairs, ", ");
|
||||
str += " }";
|
||||
}
|
||||
str += join(pairs, ", ");
|
||||
str += " }";
|
||||
}
|
||||
else if(data.type() == QVariant::Map) // variant is a map?
|
||||
{
|
||||
const QVariantMap vmap = data.toMap();
|
||||
|
|
|
@ -12,220 +12,220 @@
|
|||
static const unsigned int protocolVersion = 14;
|
||||
|
||||
RemoteClient::RemoteClient(QObject *parent)
|
||||
: AbstractClient(parent), timeRunning(0), lastDataReceived(0), messageInProgress(false), handshakeStarted(false), messageLength(0)
|
||||
: AbstractClient(parent), timeRunning(0), lastDataReceived(0), messageInProgress(false), handshakeStarted(false), messageLength(0)
|
||||
{
|
||||
timer = new QTimer(this);
|
||||
timer->setInterval(1000);
|
||||
connect(timer, SIGNAL(timeout()), this, SLOT(ping()));
|
||||
timer = new QTimer(this);
|
||||
timer->setInterval(1000);
|
||||
connect(timer, SIGNAL(timeout()), this, SLOT(ping()));
|
||||
|
||||
socket = new QTcpSocket(this);
|
||||
socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
|
||||
connect(socket, SIGNAL(connected()), this, SLOT(slotConnected()));
|
||||
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
|
||||
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketError(QAbstractSocket::SocketError)));
|
||||
socket = new QTcpSocket(this);
|
||||
socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
|
||||
connect(socket, SIGNAL(connected()), this, SLOT(slotConnected()));
|
||||
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
|
||||
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketError(QAbstractSocket::SocketError)));
|
||||
|
||||
connect(this, SIGNAL(serverIdentificationEventReceived(const Event_ServerIdentification &)), this, SLOT(processServerIdentificationEvent(const Event_ServerIdentification &)));
|
||||
connect(this, SIGNAL(connectionClosedEventReceived(Event_ConnectionClosed)), this, SLOT(processConnectionClosedEvent(Event_ConnectionClosed)));
|
||||
connect(this, SIGNAL(sigConnectToServer(QString, unsigned int, QString, QString)), this, SLOT(doConnectToServer(QString, unsigned int, QString, QString)));
|
||||
connect(this, SIGNAL(sigDisconnectFromServer()), this, SLOT(doDisconnectFromServer()));
|
||||
connect(this, SIGNAL(serverIdentificationEventReceived(const Event_ServerIdentification &)), this, SLOT(processServerIdentificationEvent(const Event_ServerIdentification &)));
|
||||
connect(this, SIGNAL(connectionClosedEventReceived(Event_ConnectionClosed)), this, SLOT(processConnectionClosedEvent(Event_ConnectionClosed)));
|
||||
connect(this, SIGNAL(sigConnectToServer(QString, unsigned int, QString, QString)), this, SLOT(doConnectToServer(QString, unsigned int, QString, QString)));
|
||||
connect(this, SIGNAL(sigDisconnectFromServer()), this, SLOT(doDisconnectFromServer()));
|
||||
}
|
||||
|
||||
RemoteClient::~RemoteClient()
|
||||
{
|
||||
doDisconnectFromServer();
|
||||
thread()->quit();
|
||||
doDisconnectFromServer();
|
||||
thread()->quit();
|
||||
}
|
||||
|
||||
void RemoteClient::slotSocketError(QAbstractSocket::SocketError /*error*/)
|
||||
{
|
||||
QString errorString = socket->errorString();
|
||||
doDisconnectFromServer();
|
||||
emit socketError(errorString);
|
||||
QString errorString = socket->errorString();
|
||||
doDisconnectFromServer();
|
||||
emit socketError(errorString);
|
||||
}
|
||||
|
||||
void RemoteClient::slotConnected()
|
||||
{
|
||||
timeRunning = lastDataReceived = 0;
|
||||
timer->start();
|
||||
timeRunning = lastDataReceived = 0;
|
||||
timer->start();
|
||||
|
||||
// dirty hack to be compatible with v14 server
|
||||
sendCommandContainer(CommandContainer());
|
||||
getNewCmdId();
|
||||
// end of hack
|
||||
// dirty hack to be compatible with v14 server
|
||||
sendCommandContainer(CommandContainer());
|
||||
getNewCmdId();
|
||||
// end of hack
|
||||
|
||||
setStatus(StatusAwaitingWelcome);
|
||||
setStatus(StatusAwaitingWelcome);
|
||||
}
|
||||
|
||||
void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentification &event)
|
||||
{
|
||||
if (event.protocol_version() != protocolVersion) {
|
||||
emit protocolVersionMismatch(protocolVersion, event.protocol_version());
|
||||
setStatus(StatusDisconnecting);
|
||||
return;
|
||||
}
|
||||
setStatus(StatusLoggingIn);
|
||||
if (event.protocol_version() != protocolVersion) {
|
||||
emit protocolVersionMismatch(protocolVersion, event.protocol_version());
|
||||
setStatus(StatusDisconnecting);
|
||||
return;
|
||||
}
|
||||
setStatus(StatusLoggingIn);
|
||||
|
||||
Command_Login cmdLogin;
|
||||
cmdLogin.set_user_name(userName.toStdString());
|
||||
cmdLogin.set_password(password.toStdString());
|
||||
Command_Login cmdLogin;
|
||||
cmdLogin.set_user_name(userName.toStdString());
|
||||
cmdLogin.set_password(password.toStdString());
|
||||
|
||||
PendingCommand *pend = prepareSessionCommand(cmdLogin);
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(loginResponse(Response)));
|
||||
sendCommand(pend);
|
||||
PendingCommand *pend = prepareSessionCommand(cmdLogin);
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(loginResponse(Response)));
|
||||
sendCommand(pend);
|
||||
}
|
||||
|
||||
void RemoteClient::processConnectionClosedEvent(const Event_ConnectionClosed & /*event*/)
|
||||
{
|
||||
doDisconnectFromServer();
|
||||
doDisconnectFromServer();
|
||||
}
|
||||
|
||||
void RemoteClient::loginResponse(const Response &response)
|
||||
{
|
||||
const Response_Login &resp = response.GetExtension(Response_Login::ext);
|
||||
if (response.response_code() == Response::RespOk) {
|
||||
setStatus(StatusLoggedIn);
|
||||
emit userInfoChanged(resp.user_info());
|
||||
const Response_Login &resp = response.GetExtension(Response_Login::ext);
|
||||
if (response.response_code() == Response::RespOk) {
|
||||
setStatus(StatusLoggedIn);
|
||||
emit userInfoChanged(resp.user_info());
|
||||
|
||||
QList<ServerInfo_User> buddyList;
|
||||
for (int i = resp.buddy_list_size() - 1; i >= 0; --i)
|
||||
buddyList.append(resp.buddy_list(i));
|
||||
emit buddyListReceived(buddyList);
|
||||
QList<ServerInfo_User> buddyList;
|
||||
for (int i = resp.buddy_list_size() - 1; i >= 0; --i)
|
||||
buddyList.append(resp.buddy_list(i));
|
||||
emit buddyListReceived(buddyList);
|
||||
|
||||
QList<ServerInfo_User> ignoreList;
|
||||
for (int i = resp.ignore_list_size() - 1; i >= 0; --i)
|
||||
ignoreList.append(resp.ignore_list(i));
|
||||
emit ignoreListReceived(ignoreList);
|
||||
} else {
|
||||
emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time());
|
||||
setStatus(StatusDisconnecting);
|
||||
}
|
||||
QList<ServerInfo_User> ignoreList;
|
||||
for (int i = resp.ignore_list_size() - 1; i >= 0; --i)
|
||||
ignoreList.append(resp.ignore_list(i));
|
||||
emit ignoreListReceived(ignoreList);
|
||||
} else {
|
||||
emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time());
|
||||
setStatus(StatusDisconnecting);
|
||||
}
|
||||
}
|
||||
|
||||
void RemoteClient::readData()
|
||||
{
|
||||
lastDataReceived = timeRunning;
|
||||
QByteArray data = socket->readAll();
|
||||
lastDataReceived = timeRunning;
|
||||
QByteArray data = socket->readAll();
|
||||
|
||||
inputBuffer.append(data);
|
||||
inputBuffer.append(data);
|
||||
|
||||
do {
|
||||
if (!messageInProgress) {
|
||||
if (inputBuffer.size() >= 4) {
|
||||
// dirty hack to be compatible with v14 server that sends 60 bytes of garbage at the beginning
|
||||
if (!handshakeStarted) {
|
||||
handshakeStarted = true;
|
||||
if (inputBuffer.startsWith("<?xm")) {
|
||||
messageInProgress = true;
|
||||
messageLength = 60;
|
||||
}
|
||||
} else {
|
||||
// end of hack
|
||||
messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24)
|
||||
+ (((quint32) (unsigned char) inputBuffer[1]) << 16)
|
||||
+ (((quint32) (unsigned char) inputBuffer[2]) << 8)
|
||||
+ ((quint32) (unsigned char) inputBuffer[3]);
|
||||
inputBuffer.remove(0, 4);
|
||||
messageInProgress = true;
|
||||
}
|
||||
} else
|
||||
return;
|
||||
}
|
||||
if (inputBuffer.size() < messageLength)
|
||||
return;
|
||||
do {
|
||||
if (!messageInProgress) {
|
||||
if (inputBuffer.size() >= 4) {
|
||||
// dirty hack to be compatible with v14 server that sends 60 bytes of garbage at the beginning
|
||||
if (!handshakeStarted) {
|
||||
handshakeStarted = true;
|
||||
if (inputBuffer.startsWith("<?xm")) {
|
||||
messageInProgress = true;
|
||||
messageLength = 60;
|
||||
}
|
||||
} else {
|
||||
// end of hack
|
||||
messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24)
|
||||
+ (((quint32) (unsigned char) inputBuffer[1]) << 16)
|
||||
+ (((quint32) (unsigned char) inputBuffer[2]) << 8)
|
||||
+ ((quint32) (unsigned char) inputBuffer[3]);
|
||||
inputBuffer.remove(0, 4);
|
||||
messageInProgress = true;
|
||||
}
|
||||
} else
|
||||
return;
|
||||
}
|
||||
if (inputBuffer.size() < messageLength)
|
||||
return;
|
||||
|
||||
ServerMessage newServerMessage;
|
||||
newServerMessage.ParseFromArray(inputBuffer.data(), messageLength);
|
||||
ServerMessage newServerMessage;
|
||||
newServerMessage.ParseFromArray(inputBuffer.data(), messageLength);
|
||||
#ifdef QT_DEBUG
|
||||
qDebug() << "IN" << messageLength << QString::fromStdString(newServerMessage.ShortDebugString());
|
||||
qDebug() << "IN" << messageLength << QString::fromStdString(newServerMessage.ShortDebugString());
|
||||
#endif
|
||||
inputBuffer.remove(0, messageLength);
|
||||
messageInProgress = false;
|
||||
inputBuffer.remove(0, messageLength);
|
||||
messageInProgress = false;
|
||||
|
||||
processProtocolItem(newServerMessage);
|
||||
processProtocolItem(newServerMessage);
|
||||
|
||||
if (getStatus() == StatusDisconnecting) // use thread-safe getter
|
||||
doDisconnectFromServer();
|
||||
} while (!inputBuffer.isEmpty());
|
||||
if (getStatus() == StatusDisconnecting) // use thread-safe getter
|
||||
doDisconnectFromServer();
|
||||
} while (!inputBuffer.isEmpty());
|
||||
}
|
||||
|
||||
void RemoteClient::sendCommandContainer(const CommandContainer &cont)
|
||||
{
|
||||
QByteArray buf;
|
||||
unsigned int size = cont.ByteSize();
|
||||
QByteArray buf;
|
||||
unsigned int size = cont.ByteSize();
|
||||
#ifdef QT_DEBUG
|
||||
qDebug() << "OUT" << size << QString::fromStdString(cont.ShortDebugString());
|
||||
qDebug() << "OUT" << size << QString::fromStdString(cont.ShortDebugString());
|
||||
#endif
|
||||
buf.resize(size + 4);
|
||||
cont.SerializeToArray(buf.data() + 4, size);
|
||||
buf.data()[3] = (unsigned char) size;
|
||||
buf.data()[2] = (unsigned char) (size >> 8);
|
||||
buf.data()[1] = (unsigned char) (size >> 16);
|
||||
buf.data()[0] = (unsigned char) (size >> 24);
|
||||
buf.resize(size + 4);
|
||||
cont.SerializeToArray(buf.data() + 4, size);
|
||||
buf.data()[3] = (unsigned char) size;
|
||||
buf.data()[2] = (unsigned char) (size >> 8);
|
||||
buf.data()[1] = (unsigned char) (size >> 16);
|
||||
buf.data()[0] = (unsigned char) (size >> 24);
|
||||
|
||||
socket->write(buf);
|
||||
socket->write(buf);
|
||||
}
|
||||
|
||||
void RemoteClient::doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password)
|
||||
{
|
||||
doDisconnectFromServer();
|
||||
doDisconnectFromServer();
|
||||
|
||||
userName = _userName;
|
||||
password = _password;
|
||||
socket->connectToHost(hostname, port);
|
||||
setStatus(StatusConnecting);
|
||||
userName = _userName;
|
||||
password = _password;
|
||||
socket->connectToHost(hostname, port);
|
||||
setStatus(StatusConnecting);
|
||||
}
|
||||
|
||||
void RemoteClient::doDisconnectFromServer()
|
||||
{
|
||||
timer->stop();
|
||||
timer->stop();
|
||||
|
||||
messageInProgress = false;
|
||||
handshakeStarted = false;
|
||||
messageLength = 0;
|
||||
messageInProgress = false;
|
||||
handshakeStarted = false;
|
||||
messageLength = 0;
|
||||
|
||||
QList<PendingCommand *> pc = pendingCommands.values();
|
||||
for (int i = 0; i < pc.size(); i++) {
|
||||
Response response;
|
||||
response.set_response_code(Response::RespNotConnected);
|
||||
response.set_cmd_id(pc[i]->getCommandContainer().cmd_id());
|
||||
pc[i]->processResponse(response);
|
||||
QList<PendingCommand *> pc = pendingCommands.values();
|
||||
for (int i = 0; i < pc.size(); i++) {
|
||||
Response response;
|
||||
response.set_response_code(Response::RespNotConnected);
|
||||
response.set_cmd_id(pc[i]->getCommandContainer().cmd_id());
|
||||
pc[i]->processResponse(response);
|
||||
|
||||
delete pc[i];
|
||||
}
|
||||
pendingCommands.clear();
|
||||
delete pc[i];
|
||||
}
|
||||
pendingCommands.clear();
|
||||
|
||||
setStatus(StatusDisconnected);
|
||||
socket->close();
|
||||
setStatus(StatusDisconnected);
|
||||
socket->close();
|
||||
}
|
||||
|
||||
void RemoteClient::ping()
|
||||
{
|
||||
QMutableMapIterator<int, PendingCommand *> i(pendingCommands);
|
||||
while (i.hasNext()) {
|
||||
PendingCommand *pend = i.next().value();
|
||||
if (pend->tick() > maxTimeout) {
|
||||
i.remove();
|
||||
pend->deleteLater();
|
||||
}
|
||||
}
|
||||
QMutableMapIterator<int, PendingCommand *> i(pendingCommands);
|
||||
while (i.hasNext()) {
|
||||
PendingCommand *pend = i.next().value();
|
||||
if (pend->tick() > maxTimeout) {
|
||||
i.remove();
|
||||
pend->deleteLater();
|
||||
}
|
||||
}
|
||||
|
||||
int maxTime = timeRunning - lastDataReceived;
|
||||
emit maxPingTime(maxTime, maxTimeout);
|
||||
if (maxTime >= maxTimeout) {
|
||||
disconnectFromServer();
|
||||
emit serverTimeout();
|
||||
} else {
|
||||
sendCommand(prepareSessionCommand(Command_Ping()));
|
||||
++timeRunning;
|
||||
}
|
||||
int maxTime = timeRunning - lastDataReceived;
|
||||
emit maxPingTime(maxTime, maxTimeout);
|
||||
if (maxTime >= maxTimeout) {
|
||||
disconnectFromServer();
|
||||
emit serverTimeout();
|
||||
} else {
|
||||
sendCommand(prepareSessionCommand(Command_Ping()));
|
||||
++timeRunning;
|
||||
}
|
||||
}
|
||||
|
||||
void RemoteClient::connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password)
|
||||
{
|
||||
emit sigConnectToServer(hostname, port, _userName, _password);
|
||||
emit sigConnectToServer(hostname, port, _userName, _password);
|
||||
}
|
||||
|
||||
void RemoteClient::disconnectFromServer()
|
||||
{
|
||||
emit sigDisconnectFromServer();
|
||||
emit sigDisconnectFromServer();
|
||||
}
|
||||
|
|
|
@ -7,45 +7,45 @@
|
|||
class QTimer;
|
||||
|
||||
class RemoteClient : public AbstractClient {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void maxPingTime(int seconds, int maxSeconds);
|
||||
void serverTimeout();
|
||||
void loginError(Response::ResponseCode resp, QString reasonStr, quint32 endTime);
|
||||
void socketError(const QString &errorString);
|
||||
void protocolVersionMismatch(int clientVersion, int serverVersion);
|
||||
void protocolError();
|
||||
void sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password);
|
||||
void sigDisconnectFromServer();
|
||||
void maxPingTime(int seconds, int maxSeconds);
|
||||
void serverTimeout();
|
||||
void loginError(Response::ResponseCode resp, QString reasonStr, quint32 endTime);
|
||||
void socketError(const QString &errorString);
|
||||
void protocolVersionMismatch(int clientVersion, int serverVersion);
|
||||
void protocolError();
|
||||
void sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password);
|
||||
void sigDisconnectFromServer();
|
||||
private slots:
|
||||
void slotConnected();
|
||||
void readData();
|
||||
void slotSocketError(QAbstractSocket::SocketError error);
|
||||
void ping();
|
||||
void processServerIdentificationEvent(const Event_ServerIdentification &event);
|
||||
void processConnectionClosedEvent(const Event_ConnectionClosed &event);
|
||||
void loginResponse(const Response &response);
|
||||
void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password);
|
||||
void doDisconnectFromServer();
|
||||
void slotConnected();
|
||||
void readData();
|
||||
void slotSocketError(QAbstractSocket::SocketError error);
|
||||
void ping();
|
||||
void processServerIdentificationEvent(const Event_ServerIdentification &event);
|
||||
void processConnectionClosedEvent(const Event_ConnectionClosed &event);
|
||||
void loginResponse(const Response &response);
|
||||
void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password);
|
||||
void doDisconnectFromServer();
|
||||
private:
|
||||
static const int maxTimeout = 10;
|
||||
int timeRunning, lastDataReceived;
|
||||
static const int maxTimeout = 10;
|
||||
int timeRunning, lastDataReceived;
|
||||
|
||||
QByteArray inputBuffer;
|
||||
bool messageInProgress;
|
||||
bool handshakeStarted;
|
||||
int messageLength;
|
||||
QByteArray inputBuffer;
|
||||
bool messageInProgress;
|
||||
bool handshakeStarted;
|
||||
int messageLength;
|
||||
|
||||
QTimer *timer;
|
||||
QTcpSocket *socket;
|
||||
QTimer *timer;
|
||||
QTcpSocket *socket;
|
||||
protected slots:
|
||||
void sendCommandContainer(const CommandContainer &cont);
|
||||
void sendCommandContainer(const CommandContainer &cont);
|
||||
public:
|
||||
RemoteClient(QObject *parent = 0);
|
||||
~RemoteClient();
|
||||
QString peerName() const { return socket->peerName(); }
|
||||
void connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password);
|
||||
void disconnectFromServer();
|
||||
RemoteClient(QObject *parent = 0);
|
||||
~RemoteClient();
|
||||
QString peerName() const { return socket->peerName(); }
|
||||
void connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password);
|
||||
void disconnectFromServer();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -10,324 +10,324 @@
|
|||
#include "pb/serverinfo_deckstorage.pb.h"
|
||||
|
||||
RemoteDeckList_TreeModel::DirectoryNode::DirectoryNode(const QString &_name, RemoteDeckList_TreeModel::DirectoryNode *_parent)
|
||||
: RemoteDeckList_TreeModel::Node(_name, _parent)
|
||||
: RemoteDeckList_TreeModel::Node(_name, _parent)
|
||||
{
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::DirectoryNode::~DirectoryNode()
|
||||
{
|
||||
clearTree();
|
||||
clearTree();
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeModel::DirectoryNode::clearTree()
|
||||
{
|
||||
for (int i = 0; i < size(); ++i)
|
||||
delete at(i);
|
||||
clear();
|
||||
for (int i = 0; i < size(); ++i)
|
||||
delete at(i);
|
||||
clear();
|
||||
}
|
||||
|
||||
QString RemoteDeckList_TreeModel::DirectoryNode::getPath() const
|
||||
{
|
||||
if (parent) {
|
||||
QString parentPath = parent->getPath();
|
||||
if (parentPath.isEmpty())
|
||||
return name;
|
||||
else
|
||||
return parentPath + "/" + name;
|
||||
} else
|
||||
return name;
|
||||
if (parent) {
|
||||
QString parentPath = parent->getPath();
|
||||
if (parentPath.isEmpty())
|
||||
return name;
|
||||
else
|
||||
return parentPath + "/" + name;
|
||||
} else
|
||||
return name;
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeByPath(QStringList path)
|
||||
{
|
||||
QString pathItem;
|
||||
if (parent) {
|
||||
if (path.isEmpty())
|
||||
return this;
|
||||
pathItem = path.takeFirst();
|
||||
if (pathItem.isEmpty() && name.isEmpty())
|
||||
return this;
|
||||
}
|
||||
QString pathItem;
|
||||
if (parent) {
|
||||
if (path.isEmpty())
|
||||
return this;
|
||||
pathItem = path.takeFirst();
|
||||
if (pathItem.isEmpty() && name.isEmpty())
|
||||
return this;
|
||||
}
|
||||
|
||||
for (int i = 0; i < size(); ++i) {
|
||||
DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i));
|
||||
if (!node)
|
||||
continue;
|
||||
if (node->getName() == pathItem)
|
||||
return node->getNodeByPath(path);
|
||||
}
|
||||
return 0;
|
||||
for (int i = 0; i < size(); ++i) {
|
||||
DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i));
|
||||
if (!node)
|
||||
continue;
|
||||
if (node->getName() == pathItem)
|
||||
return node->getNodeByPath(path);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeById(int id) const
|
||||
{
|
||||
for (int i = 0; i < size(); ++i) {
|
||||
DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i));
|
||||
if (node) {
|
||||
FileNode *result = node->getNodeById(id);
|
||||
if (result)
|
||||
return result;
|
||||
} else {
|
||||
FileNode *file = dynamic_cast<FileNode *>(at(i));
|
||||
if (file->getId() == id)
|
||||
return file;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
for (int i = 0; i < size(); ++i) {
|
||||
DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i));
|
||||
if (node) {
|
||||
FileNode *result = node->getNodeById(id);
|
||||
if (result)
|
||||
return result;
|
||||
} else {
|
||||
FileNode *file = dynamic_cast<FileNode *>(at(i));
|
||||
if (file->getId() == id)
|
||||
return file;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent)
|
||||
: QAbstractItemModel(parent), client(_client)
|
||||
: QAbstractItemModel(parent), client(_client)
|
||||
{
|
||||
QFileIconProvider fip;
|
||||
dirIcon = fip.icon(QFileIconProvider::Folder);
|
||||
fileIcon = fip.icon(QFileIconProvider::File);
|
||||
QFileIconProvider fip;
|
||||
dirIcon = fip.icon(QFileIconProvider::Folder);
|
||||
fileIcon = fip.icon(QFileIconProvider::File);
|
||||
|
||||
root = new DirectoryNode;
|
||||
refreshTree();
|
||||
root = new DirectoryNode;
|
||||
refreshTree();
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::~RemoteDeckList_TreeModel()
|
||||
{
|
||||
delete root;
|
||||
delete root;
|
||||
}
|
||||
|
||||
int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
DirectoryNode *node = getNode<DirectoryNode *>(parent);
|
||||
if (node)
|
||||
return node->size();
|
||||
else
|
||||
return 0;
|
||||
DirectoryNode *node = getNode<DirectoryNode *>(parent);
|
||||
if (node)
|
||||
return node->size();
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
int RemoteDeckList_TreeModel::columnCount(const QModelIndex &/*parent*/) const
|
||||
{
|
||||
return 3;
|
||||
return 3;
|
||||
}
|
||||
|
||||
QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (index.column() >= 3)
|
||||
return QVariant();
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (index.column() >= 3)
|
||||
return QVariant();
|
||||
|
||||
Node *temp = static_cast<Node *>(index.internalPointer());
|
||||
FileNode *file = dynamic_cast<FileNode *>(temp);
|
||||
if (!file) {
|
||||
DirectoryNode *node = dynamic_cast<DirectoryNode *>(temp);
|
||||
switch (role) {
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return node->getName();
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
return index.column() == 0 ? dirIcon : QVariant();
|
||||
default: return QVariant();
|
||||
}
|
||||
} else {
|
||||
switch (role) {
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return file->getName();
|
||||
case 1: return file->getId();
|
||||
case 2: return file->getUploadTime();
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
return index.column() == 0 ? fileIcon : QVariant();
|
||||
case Qt::TextAlignmentRole:
|
||||
return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft;
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
Node *temp = static_cast<Node *>(index.internalPointer());
|
||||
FileNode *file = dynamic_cast<FileNode *>(temp);
|
||||
if (!file) {
|
||||
DirectoryNode *node = dynamic_cast<DirectoryNode *>(temp);
|
||||
switch (role) {
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return node->getName();
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
return index.column() == 0 ? dirIcon : QVariant();
|
||||
default: return QVariant();
|
||||
}
|
||||
} else {
|
||||
switch (role) {
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return file->getName();
|
||||
case 1: return file->getId();
|
||||
case 2: return file->getUploadTime();
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
return index.column() == 0 ? fileIcon : QVariant();
|
||||
case Qt::TextAlignmentRole:
|
||||
return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft;
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
if (orientation != Qt::Horizontal)
|
||||
return QVariant();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
return section == 1 ? Qt::AlignRight : Qt::AlignLeft;
|
||||
case Qt::DisplayRole: {
|
||||
switch (section) {
|
||||
case 0: return tr("Name");
|
||||
case 1: return tr("ID");
|
||||
case 2: return tr("Upload time");
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
if (orientation != Qt::Horizontal)
|
||||
return QVariant();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
return section == 1 ? Qt::AlignRight : Qt::AlignLeft;
|
||||
case Qt::DisplayRole: {
|
||||
switch (section) {
|
||||
case 0: return tr("Name");
|
||||
case 1: return tr("ID");
|
||||
case 2: return tr("Upload time");
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex RemoteDeckList_TreeModel::index(int row, int column, const QModelIndex &parent) const
|
||||
{
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
|
||||
DirectoryNode *parentNode = getNode<DirectoryNode *>(parent);
|
||||
if (row >= parentNode->size())
|
||||
return QModelIndex();
|
||||
DirectoryNode *parentNode = getNode<DirectoryNode *>(parent);
|
||||
if (row >= parentNode->size())
|
||||
return QModelIndex();
|
||||
|
||||
return createIndex(row, column, parentNode->at(row));
|
||||
return createIndex(row, column, parentNode->at(row));
|
||||
}
|
||||
|
||||
QModelIndex RemoteDeckList_TreeModel::parent(const QModelIndex &ind) const
|
||||
{
|
||||
if (!ind.isValid())
|
||||
return QModelIndex();
|
||||
if (!ind.isValid())
|
||||
return QModelIndex();
|
||||
|
||||
return nodeToIndex(static_cast<Node *>(ind.internalPointer())->getParent());
|
||||
return nodeToIndex(static_cast<Node *>(ind.internalPointer())->getParent());
|
||||
}
|
||||
|
||||
Qt::ItemFlags RemoteDeckList_TreeModel::flags(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
|
||||
}
|
||||
|
||||
QModelIndex RemoteDeckList_TreeModel::nodeToIndex(Node *node) const
|
||||
{
|
||||
if (node == root)
|
||||
return QModelIndex();
|
||||
return createIndex(node->getParent()->indexOf(node), 0, node);
|
||||
if (node == root)
|
||||
return QModelIndex();
|
||||
return createIndex(node->getParent()->indexOf(node), 0, node);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeModel::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent)
|
||||
{
|
||||
const ServerInfo_DeckStorage_File &fileInfo = file.file();
|
||||
QDateTime time;
|
||||
time.setTime_t(fileInfo.creation_time());
|
||||
const ServerInfo_DeckStorage_File &fileInfo = file.file();
|
||||
QDateTime time;
|
||||
time.setTime_t(fileInfo.creation_time());
|
||||
|
||||
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
|
||||
parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent));
|
||||
endInsertRows();
|
||||
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
|
||||
parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent));
|
||||
endInsertRows();
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeModel::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent)
|
||||
{
|
||||
DirectoryNode *newItem = addNamedFolderToTree(QString::fromStdString(folder.name()), parent);
|
||||
const ServerInfo_DeckStorage_Folder &folderInfo = folder.folder();
|
||||
const int folderItemsSize = folderInfo.items_size();
|
||||
for (int i = 0; i < folderItemsSize; ++i) {
|
||||
const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i);
|
||||
if (subItem.has_folder())
|
||||
addFolderToTree(subItem, newItem);
|
||||
else
|
||||
addFileToTree(subItem, newItem);
|
||||
}
|
||||
DirectoryNode *newItem = addNamedFolderToTree(QString::fromStdString(folder.name()), parent);
|
||||
const ServerInfo_DeckStorage_Folder &folderInfo = folder.folder();
|
||||
const int folderItemsSize = folderInfo.items_size();
|
||||
for (int i = 0; i < folderItemsSize; ++i) {
|
||||
const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i);
|
||||
if (subItem.has_folder())
|
||||
addFolderToTree(subItem, newItem);
|
||||
else
|
||||
addFileToTree(subItem, newItem);
|
||||
}
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::addNamedFolderToTree(const QString &name, DirectoryNode *parent)
|
||||
{
|
||||
DirectoryNode *newItem = new DirectoryNode(name, parent);
|
||||
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
|
||||
parent->append(newItem);
|
||||
endInsertRows();
|
||||
return newItem;
|
||||
DirectoryNode *newItem = new DirectoryNode(name, parent);
|
||||
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
|
||||
parent->append(newItem);
|
||||
endInsertRows();
|
||||
return newItem;
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeModel::removeNode(RemoteDeckList_TreeModel::Node *node)
|
||||
{
|
||||
int ind = node->getParent()->indexOf(node);
|
||||
beginRemoveRows(nodeToIndex(node->getParent()), ind, ind);
|
||||
node->getParent()->removeAt(ind);
|
||||
endRemoveRows();
|
||||
delete node;
|
||||
int ind = node->getParent()->indexOf(node);
|
||||
beginRemoveRows(nodeToIndex(node->getParent()), ind, ind);
|
||||
node->getParent()->removeAt(ind);
|
||||
endRemoveRows();
|
||||
delete node;
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeModel::refreshTree()
|
||||
{
|
||||
PendingCommand *pend = client->prepareSessionCommand(Command_DeckList());
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &)));
|
||||
PendingCommand *pend = client->prepareSessionCommand(Command_DeckList());
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &)));
|
||||
|
||||
client->sendCommand(pend);
|
||||
client->sendCommand(pend);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeModel::deckListFinished(const Response &r)
|
||||
{
|
||||
const Response_DeckList &resp = r.GetExtension(Response_DeckList::ext);
|
||||
const Response_DeckList &resp = r.GetExtension(Response_DeckList::ext);
|
||||
|
||||
root->clearTree();
|
||||
reset();
|
||||
root->clearTree();
|
||||
reset();
|
||||
|
||||
ServerInfo_DeckStorage_TreeItem tempRoot;
|
||||
tempRoot.set_id(0);
|
||||
tempRoot.mutable_folder()->CopyFrom(resp.root());
|
||||
addFolderToTree(tempRoot, root);
|
||||
ServerInfo_DeckStorage_TreeItem tempRoot;
|
||||
tempRoot.set_id(0);
|
||||
tempRoot.mutable_folder()->CopyFrom(resp.root());
|
||||
addFolderToTree(tempRoot, root);
|
||||
|
||||
emit treeRefreshed();
|
||||
emit treeRefreshed();
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeWidget::RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent)
|
||||
: QTreeView(parent)
|
||||
: QTreeView(parent)
|
||||
{
|
||||
treeModel = new RemoteDeckList_TreeModel(_client, this);
|
||||
proxyModel = new QSortFilterProxyModel(this);
|
||||
proxyModel->setSourceModel(treeModel);
|
||||
proxyModel->setDynamicSortFilter(true);
|
||||
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
setModel(proxyModel);
|
||||
connect(treeModel, SIGNAL(treeRefreshed()), this, SLOT(expandAll()));
|
||||
treeModel = new RemoteDeckList_TreeModel(_client, this);
|
||||
proxyModel = new QSortFilterProxyModel(this);
|
||||
proxyModel->setSourceModel(treeModel);
|
||||
proxyModel->setDynamicSortFilter(true);
|
||||
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
setModel(proxyModel);
|
||||
connect(treeModel, SIGNAL(treeRefreshed()), this, SLOT(expandAll()));
|
||||
|
||||
header()->setResizeMode(QHeaderView::ResizeToContents);
|
||||
setUniformRowHeights(true);
|
||||
setSortingEnabled(true);
|
||||
proxyModel->sort(0, Qt::AscendingOrder);
|
||||
header()->setSortIndicator(0, Qt::AscendingOrder);
|
||||
header()->setResizeMode(QHeaderView::ResizeToContents);
|
||||
setUniformRowHeights(true);
|
||||
setSortingEnabled(true);
|
||||
proxyModel->sort(0, Qt::AscendingOrder);
|
||||
header()->setSortIndicator(0, Qt::AscendingOrder);
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::Node *RemoteDeckList_TreeWidget::getNode(const QModelIndex &ind) const
|
||||
{
|
||||
return treeModel->getNode<RemoteDeckList_TreeModel::Node *>(proxyModel->mapToSource(ind));
|
||||
return treeModel->getNode<RemoteDeckList_TreeModel::Node *>(proxyModel->mapToSource(ind));
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::Node *RemoteDeckList_TreeWidget::getCurrentItem() const
|
||||
{
|
||||
return getNode(selectionModel()->currentIndex());
|
||||
return getNode(selectionModel()->currentIndex());
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeWidget::getNodeByPath(const QString &path) const
|
||||
{
|
||||
return treeModel->getRoot()->getNodeByPath(path.split("/"));
|
||||
return treeModel->getRoot()->getNodeByPath(path.split("/"));
|
||||
}
|
||||
|
||||
RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeWidget::getNodeById(int id) const
|
||||
{
|
||||
return treeModel->getRoot()->getNodeById(id);
|
||||
return treeModel->getRoot()->getNodeById(id);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeWidget::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent)
|
||||
{
|
||||
treeModel->addFileToTree(file, parent);
|
||||
treeModel->addFileToTree(file, parent);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeWidget::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent)
|
||||
{
|
||||
treeModel->addFolderToTree(folder, parent);
|
||||
treeModel->addFolderToTree(folder, parent);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeWidget::addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent)
|
||||
{
|
||||
treeModel->addNamedFolderToTree(name, parent);
|
||||
treeModel->addNamedFolderToTree(name, parent);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeWidget::removeNode(RemoteDeckList_TreeModel::Node *node)
|
||||
{
|
||||
treeModel->removeNode(node);
|
||||
treeModel->removeNode(node);
|
||||
}
|
||||
|
||||
void RemoteDeckList_TreeWidget::refreshTree()
|
||||
{
|
||||
treeModel->refreshTree();
|
||||
treeModel->refreshTree();
|
||||
}
|
||||
|
|
|
@ -11,92 +11,92 @@ class QSortFilterProxyModel;
|
|||
class ServerInfo_DeckStorage_TreeItem;
|
||||
|
||||
class RemoteDeckList_TreeModel : public QAbstractItemModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
public:
|
||||
class DirectoryNode;
|
||||
class FileNode;
|
||||
class Node {
|
||||
protected:
|
||||
DirectoryNode *parent;
|
||||
QString name;
|
||||
public:
|
||||
Node(const QString &_name, DirectoryNode *_parent = 0)
|
||||
: parent(_parent), name(_name) { }
|
||||
virtual ~Node() { };
|
||||
DirectoryNode *getParent() const { return parent; }
|
||||
QString getName() const { return name; }
|
||||
};
|
||||
class DirectoryNode : public Node, public QList<Node *> {
|
||||
public:
|
||||
DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0);
|
||||
~DirectoryNode();
|
||||
void clearTree();
|
||||
QString getPath() const;
|
||||
DirectoryNode *getNodeByPath(QStringList path);
|
||||
FileNode *getNodeById(int id) const;
|
||||
};
|
||||
class FileNode : public Node {
|
||||
private:
|
||||
int id;
|
||||
QDateTime uploadTime;
|
||||
public:
|
||||
FileNode(const QString &_name, int _id, const QDateTime &_uploadTime, DirectoryNode *_parent = 0)
|
||||
: Node(_name, _parent), id(_id), uploadTime(_uploadTime) { }
|
||||
int getId() const { return id; }
|
||||
QDateTime getUploadTime() const { return uploadTime; }
|
||||
};
|
||||
class DirectoryNode;
|
||||
class FileNode;
|
||||
class Node {
|
||||
protected:
|
||||
DirectoryNode *parent;
|
||||
QString name;
|
||||
public:
|
||||
Node(const QString &_name, DirectoryNode *_parent = 0)
|
||||
: parent(_parent), name(_name) { }
|
||||
virtual ~Node() { };
|
||||
DirectoryNode *getParent() const { return parent; }
|
||||
QString getName() const { return name; }
|
||||
};
|
||||
class DirectoryNode : public Node, public QList<Node *> {
|
||||
public:
|
||||
DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0);
|
||||
~DirectoryNode();
|
||||
void clearTree();
|
||||
QString getPath() const;
|
||||
DirectoryNode *getNodeByPath(QStringList path);
|
||||
FileNode *getNodeById(int id) const;
|
||||
};
|
||||
class FileNode : public Node {
|
||||
private:
|
||||
int id;
|
||||
QDateTime uploadTime;
|
||||
public:
|
||||
FileNode(const QString &_name, int _id, const QDateTime &_uploadTime, DirectoryNode *_parent = 0)
|
||||
: Node(_name, _parent), id(_id), uploadTime(_uploadTime) { }
|
||||
int getId() const { return id; }
|
||||
QDateTime getUploadTime() const { return uploadTime; }
|
||||
};
|
||||
|
||||
template<typename T> T getNode(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return dynamic_cast<T>(root);
|
||||
return dynamic_cast<T>(static_cast<Node *>(index.internalPointer()));
|
||||
}
|
||||
template<typename T> T getNode(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return dynamic_cast<T>(root);
|
||||
return dynamic_cast<T>(static_cast<Node *>(index.internalPointer()));
|
||||
}
|
||||
private:
|
||||
AbstractClient *client;
|
||||
DirectoryNode *root;
|
||||
AbstractClient *client;
|
||||
DirectoryNode *root;
|
||||
|
||||
QIcon fileIcon, dirIcon;
|
||||
QIcon fileIcon, dirIcon;
|
||||
|
||||
QModelIndex nodeToIndex(Node *node) const;
|
||||
QModelIndex nodeToIndex(Node *node) const;
|
||||
signals:
|
||||
void treeRefreshed();
|
||||
void treeRefreshed();
|
||||
private slots:
|
||||
void deckListFinished(const Response &r);
|
||||
void deckListFinished(const Response &r);
|
||||
public:
|
||||
RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent = 0);
|
||||
~RemoteDeckList_TreeModel();
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const;
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent = 0);
|
||||
~RemoteDeckList_TreeModel();
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const;
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
|
||||
DirectoryNode *getRoot() const { return root; }
|
||||
void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent);
|
||||
void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent);
|
||||
DirectoryNode *addNamedFolderToTree(const QString &name, DirectoryNode *parent);
|
||||
void removeNode(Node *node);
|
||||
void refreshTree();
|
||||
DirectoryNode *getRoot() const { return root; }
|
||||
void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent);
|
||||
void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent);
|
||||
DirectoryNode *addNamedFolderToTree(const QString &name, DirectoryNode *parent);
|
||||
void removeNode(Node *node);
|
||||
void refreshTree();
|
||||
};
|
||||
|
||||
class RemoteDeckList_TreeWidget : public QTreeView {
|
||||
private:
|
||||
RemoteDeckList_TreeModel *treeModel;
|
||||
QSortFilterProxyModel *proxyModel;
|
||||
RemoteDeckList_TreeModel *treeModel;
|
||||
QSortFilterProxyModel *proxyModel;
|
||||
public:
|
||||
RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0);
|
||||
RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const;
|
||||
RemoteDeckList_TreeModel::Node *getCurrentItem() const;
|
||||
RemoteDeckList_TreeModel::DirectoryNode *getNodeByPath(const QString &path) const;
|
||||
RemoteDeckList_TreeModel::FileNode *getNodeById(int id) const;
|
||||
void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent);
|
||||
void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent);
|
||||
void addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent);
|
||||
void removeNode(RemoteDeckList_TreeModel::Node *node);
|
||||
void refreshTree();
|
||||
RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0);
|
||||
RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const;
|
||||
RemoteDeckList_TreeModel::Node *getCurrentItem() const;
|
||||
RemoteDeckList_TreeModel::DirectoryNode *getNodeByPath(const QString &path) const;
|
||||
RemoteDeckList_TreeModel::FileNode *getNodeById(int id) const;
|
||||
void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent);
|
||||
void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent);
|
||||
void addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent);
|
||||
void removeNode(RemoteDeckList_TreeModel::Node *node);
|
||||
void refreshTree();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -12,286 +12,286 @@
|
|||
const int RemoteReplayList_TreeModel::numberOfColumns = 6;
|
||||
|
||||
RemoteReplayList_TreeModel::MatchNode::MatchNode(const ServerInfo_ReplayMatch &_matchInfo)
|
||||
: RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo)
|
||||
: RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo)
|
||||
{
|
||||
for (int i = 0; i < matchInfo.replay_list_size(); ++i)
|
||||
append(new ReplayNode(matchInfo.replay_list(i), this));
|
||||
for (int i = 0; i < matchInfo.replay_list_size(); ++i)
|
||||
append(new ReplayNode(matchInfo.replay_list(i), this));
|
||||
}
|
||||
|
||||
RemoteReplayList_TreeModel::MatchNode::~MatchNode()
|
||||
{
|
||||
for (int i = 0; i < size(); ++i)
|
||||
delete at(i);
|
||||
for (int i = 0; i < size(); ++i)
|
||||
delete at(i);
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo)
|
||||
{
|
||||
matchInfo.MergeFrom(_matchInfo);
|
||||
matchInfo.MergeFrom(_matchInfo);
|
||||
}
|
||||
|
||||
RemoteReplayList_TreeModel::RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent)
|
||||
: QAbstractItemModel(parent), client(_client)
|
||||
: QAbstractItemModel(parent), client(_client)
|
||||
{
|
||||
QFileIconProvider fip;
|
||||
dirIcon = fip.icon(QFileIconProvider::Folder);
|
||||
fileIcon = fip.icon(QFileIconProvider::File);
|
||||
lockIcon = QIcon(":/resources/lock.svg");
|
||||
QFileIconProvider fip;
|
||||
dirIcon = fip.icon(QFileIconProvider::Folder);
|
||||
fileIcon = fip.icon(QFileIconProvider::File);
|
||||
lockIcon = QIcon(":/resources/lock.svg");
|
||||
|
||||
refreshTree();
|
||||
refreshTree();
|
||||
}
|
||||
|
||||
RemoteReplayList_TreeModel::~RemoteReplayList_TreeModel()
|
||||
{
|
||||
clearTree();
|
||||
clearTree();
|
||||
}
|
||||
|
||||
int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (!parent.isValid())
|
||||
return replayMatches.size();
|
||||
if (!parent.isValid())
|
||||
return replayMatches.size();
|
||||
|
||||
MatchNode *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
|
||||
if (matchNode)
|
||||
return matchNode->size();
|
||||
else
|
||||
return 0;
|
||||
MatchNode *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
|
||||
if (matchNode)
|
||||
return matchNode->size();
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (index.column() >= numberOfColumns)
|
||||
return QVariant();
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
if (index.column() >= numberOfColumns)
|
||||
return QVariant();
|
||||
|
||||
ReplayNode *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (replayNode) {
|
||||
const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
return index.column() == 0 ? Qt::AlignRight : Qt::AlignLeft;
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return replayInfo.replay_id();
|
||||
case 1: return QString::fromStdString(replayInfo.replay_name());
|
||||
case 5: return replayInfo.duration();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
return index.column() == 0 ? fileIcon : QVariant();
|
||||
}
|
||||
} else {
|
||||
MatchNode *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
const ServerInfo_ReplayMatch &matchInfo = matchNode->getMatchInfo();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
switch (index.column()) {
|
||||
case 0:
|
||||
case 5:
|
||||
return Qt::AlignRight;
|
||||
default:
|
||||
return Qt::AlignLeft;
|
||||
}
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return matchInfo.game_id();
|
||||
case 1: return QString::fromStdString(matchInfo.game_name());
|
||||
case 2: {
|
||||
QStringList playerList;
|
||||
for (int i = 0; i < matchInfo.player_names_size(); ++i)
|
||||
playerList.append(QString::fromStdString(matchInfo.player_names(i)));
|
||||
return playerList.join(", ");
|
||||
}
|
||||
case 4: return QDateTime::fromTime_t(matchInfo.time_started());
|
||||
case 5: return matchInfo.length();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
switch (index.column()) {
|
||||
case 0: return dirIcon;
|
||||
case 3: return matchInfo.do_not_hide() ? lockIcon : QVariant();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
}
|
||||
return QVariant();
|
||||
ReplayNode *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (replayNode) {
|
||||
const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
return index.column() == 0 ? Qt::AlignRight : Qt::AlignLeft;
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return replayInfo.replay_id();
|
||||
case 1: return QString::fromStdString(replayInfo.replay_name());
|
||||
case 5: return replayInfo.duration();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
return index.column() == 0 ? fileIcon : QVariant();
|
||||
}
|
||||
} else {
|
||||
MatchNode *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
const ServerInfo_ReplayMatch &matchInfo = matchNode->getMatchInfo();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
switch (index.column()) {
|
||||
case 0:
|
||||
case 5:
|
||||
return Qt::AlignRight;
|
||||
default:
|
||||
return Qt::AlignLeft;
|
||||
}
|
||||
case Qt::DisplayRole: {
|
||||
switch (index.column()) {
|
||||
case 0: return matchInfo.game_id();
|
||||
case 1: return QString::fromStdString(matchInfo.game_name());
|
||||
case 2: {
|
||||
QStringList playerList;
|
||||
for (int i = 0; i < matchInfo.player_names_size(); ++i)
|
||||
playerList.append(QString::fromStdString(matchInfo.player_names(i)));
|
||||
return playerList.join(", ");
|
||||
}
|
||||
case 4: return QDateTime::fromTime_t(matchInfo.time_started());
|
||||
case 5: return matchInfo.length();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
case Qt::DecorationRole:
|
||||
switch (index.column()) {
|
||||
case 0: return dirIcon;
|
||||
case 3: return matchInfo.do_not_hide() ? lockIcon : QVariant();
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
}
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
if (orientation != Qt::Horizontal)
|
||||
return QVariant();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
switch (section) {
|
||||
case 0:
|
||||
case 5:
|
||||
return Qt::AlignRight;
|
||||
default:
|
||||
return Qt::AlignLeft;
|
||||
}
|
||||
case Qt::DisplayRole: {
|
||||
switch (section) {
|
||||
case 0: return tr("ID");
|
||||
case 1: return tr("Name");
|
||||
case 2: return tr("Players");
|
||||
case 3: return tr("Keep");
|
||||
case 4: return tr("Time started");
|
||||
case 5: return tr("Duration (sec)");
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
if (orientation != Qt::Horizontal)
|
||||
return QVariant();
|
||||
switch (role) {
|
||||
case Qt::TextAlignmentRole:
|
||||
switch (section) {
|
||||
case 0:
|
||||
case 5:
|
||||
return Qt::AlignRight;
|
||||
default:
|
||||
return Qt::AlignLeft;
|
||||
}
|
||||
case Qt::DisplayRole: {
|
||||
switch (section) {
|
||||
case 0: return tr("ID");
|
||||
case 1: return tr("Name");
|
||||
case 2: return tr("Players");
|
||||
case 3: return tr("Keep");
|
||||
case 4: return tr("Time started");
|
||||
case 5: return tr("Duration (sec)");
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
default: return QVariant();
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelIndex &parent) const
|
||||
{
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
|
||||
MatchNode *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
|
||||
if (matchNode) {
|
||||
if (row >= matchNode->size())
|
||||
return QModelIndex();
|
||||
return createIndex(row, column, (void *) matchNode->at(row));
|
||||
} else {
|
||||
if (row >= replayMatches.size())
|
||||
return QModelIndex();
|
||||
return createIndex(row, column, (void *) replayMatches[row]);
|
||||
}
|
||||
MatchNode *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
|
||||
if (matchNode) {
|
||||
if (row >= matchNode->size())
|
||||
return QModelIndex();
|
||||
return createIndex(row, column, (void *) matchNode->at(row));
|
||||
} else {
|
||||
if (row >= replayMatches.size())
|
||||
return QModelIndex();
|
||||
return createIndex(row, column, (void *) replayMatches[row]);
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const
|
||||
{
|
||||
MatchNode const *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(ind.internalPointer()));
|
||||
if (matchNode)
|
||||
return QModelIndex();
|
||||
else {
|
||||
ReplayNode *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(ind.internalPointer()));
|
||||
return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode);
|
||||
}
|
||||
MatchNode const *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(ind.internalPointer()));
|
||||
if (matchNode)
|
||||
return QModelIndex();
|
||||
else {
|
||||
ReplayNode *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(ind.internalPointer()));
|
||||
return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode);
|
||||
}
|
||||
}
|
||||
|
||||
Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
|
||||
}
|
||||
|
||||
ServerInfo_Replay const* RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
ReplayNode *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (!node)
|
||||
return 0;
|
||||
return &node->getReplayInfo();
|
||||
ReplayNode *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (!node)
|
||||
return 0;
|
||||
return &node->getReplayInfo();
|
||||
}
|
||||
|
||||
ServerInfo_ReplayMatch const* RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
MatchNode *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (!node) {
|
||||
ReplayNode *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (!node)
|
||||
return 0;
|
||||
return &node->getParent()->getMatchInfo();
|
||||
} else
|
||||
return &node->getMatchInfo();
|
||||
MatchNode *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (!node) {
|
||||
ReplayNode *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
|
||||
if (!node)
|
||||
return 0;
|
||||
return &node->getParent()->getMatchInfo();
|
||||
} else
|
||||
return &node->getMatchInfo();
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::clearTree()
|
||||
{
|
||||
for (int i = 0; i < replayMatches.size(); ++i)
|
||||
delete replayMatches[i];
|
||||
replayMatches.clear();
|
||||
for (int i = 0; i < replayMatches.size(); ++i)
|
||||
delete replayMatches[i];
|
||||
replayMatches.clear();
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::refreshTree()
|
||||
{
|
||||
PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList());
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &)));
|
||||
PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList());
|
||||
connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &)));
|
||||
|
||||
client->sendCommand(pend);
|
||||
client->sendCommand(pend);
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matchInfo)
|
||||
{
|
||||
beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size());
|
||||
replayMatches.append(new MatchNode(matchInfo));
|
||||
endInsertRows();
|
||||
beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size());
|
||||
replayMatches.append(new MatchNode(matchInfo));
|
||||
endInsertRows();
|
||||
|
||||
emit treeRefreshed();
|
||||
emit treeRefreshed();
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo)
|
||||
{
|
||||
for (int i = 0; i < replayMatches.size(); ++i)
|
||||
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
|
||||
replayMatches[i]->updateMatchInfo(matchInfo);
|
||||
emit dataChanged(createIndex(i, 0, (void *) replayMatches[i]), createIndex(i, numberOfColumns - 1, (void *) replayMatches[i]));
|
||||
break;
|
||||
}
|
||||
for (int i = 0; i < replayMatches.size(); ++i)
|
||||
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
|
||||
replayMatches[i]->updateMatchInfo(matchInfo);
|
||||
emit dataChanged(createIndex(i, 0, (void *) replayMatches[i]), createIndex(i, numberOfColumns - 1, (void *) replayMatches[i]));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::removeMatchInfo(int gameId)
|
||||
{
|
||||
for (int i = 0; i < replayMatches.size(); ++i)
|
||||
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
|
||||
beginRemoveRows(QModelIndex(), i, i);
|
||||
replayMatches.removeAt(i);
|
||||
endRemoveRows();
|
||||
break;
|
||||
}
|
||||
for (int i = 0; i < replayMatches.size(); ++i)
|
||||
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
|
||||
beginRemoveRows(QModelIndex(), i, i);
|
||||
replayMatches.removeAt(i);
|
||||
endRemoveRows();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
|
||||
{
|
||||
const Response_ReplayList &resp = r.GetExtension(Response_ReplayList::ext);
|
||||
const Response_ReplayList &resp = r.GetExtension(Response_ReplayList::ext);
|
||||
|
||||
beginResetModel();
|
||||
clearTree();
|
||||
beginResetModel();
|
||||
clearTree();
|
||||
|
||||
for (int i = 0; i < resp.match_list_size(); ++i)
|
||||
replayMatches.append(new MatchNode(resp.match_list(i)));
|
||||
for (int i = 0; i < resp.match_list_size(); ++i)
|
||||
replayMatches.append(new MatchNode(resp.match_list(i)));
|
||||
|
||||
endResetModel();
|
||||
emit treeRefreshed();
|
||||
endResetModel();
|
||||
emit treeRefreshed();
|
||||
}
|
||||
|
||||
RemoteReplayList_TreeWidget::RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent)
|
||||
: QTreeView(parent)
|
||||
: QTreeView(parent)
|
||||
{
|
||||
treeModel = new RemoteReplayList_TreeModel(_client, this);
|
||||
proxyModel = new QSortFilterProxyModel(this);
|
||||
proxyModel->setSourceModel(treeModel);
|
||||
proxyModel->setDynamicSortFilter(true);
|
||||
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
setModel(proxyModel);
|
||||
treeModel = new RemoteReplayList_TreeModel(_client, this);
|
||||
proxyModel = new QSortFilterProxyModel(this);
|
||||
proxyModel->setSourceModel(treeModel);
|
||||
proxyModel->setDynamicSortFilter(true);
|
||||
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
setModel(proxyModel);
|
||||
|
||||
header()->setResizeMode(QHeaderView::ResizeToContents);
|
||||
header()->setStretchLastSection(false);
|
||||
setUniformRowHeights(true);
|
||||
setSortingEnabled(true);
|
||||
proxyModel->sort(0, Qt::AscendingOrder);
|
||||
header()->setSortIndicator(0, Qt::AscendingOrder);
|
||||
header()->setResizeMode(QHeaderView::ResizeToContents);
|
||||
header()->setStretchLastSection(false);
|
||||
setUniformRowHeights(true);
|
||||
setSortingEnabled(true);
|
||||
proxyModel->sort(0, Qt::AscendingOrder);
|
||||
header()->setSortIndicator(0, Qt::AscendingOrder);
|
||||
}
|
||||
|
||||
ServerInfo_Replay const *RemoteReplayList_TreeWidget::getCurrentReplay() const
|
||||
{
|
||||
return treeModel->getReplay(proxyModel->mapToSource(selectionModel()->currentIndex()));
|
||||
return treeModel->getReplay(proxyModel->mapToSource(selectionModel()->currentIndex()));
|
||||
}
|
||||
|
||||
ServerInfo_ReplayMatch const *RemoteReplayList_TreeWidget::getCurrentReplayMatch() const
|
||||
{
|
||||
return treeModel->getReplayMatch(proxyModel->mapToSource(selectionModel()->currentIndex()));
|
||||
return treeModel->getReplayMatch(proxyModel->mapToSource(selectionModel()->currentIndex()));
|
||||
}
|
||||
|
|
|
@ -12,82 +12,82 @@ class AbstractClient;
|
|||
class QSortFilterProxyModel;
|
||||
|
||||
class RemoteReplayList_TreeModel : public QAbstractItemModel {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
class MatchNode;
|
||||
class ReplayNode;
|
||||
class Node {
|
||||
protected:
|
||||
QString name;
|
||||
public:
|
||||
Node(const QString &_name)
|
||||
: name(_name) { }
|
||||
virtual ~Node() { };
|
||||
QString getName() const { return name; }
|
||||
};
|
||||
class MatchNode : public Node, public QList<ReplayNode *> {
|
||||
private:
|
||||
ServerInfo_ReplayMatch matchInfo;
|
||||
public:
|
||||
MatchNode(const ServerInfo_ReplayMatch &_matchInfo);
|
||||
~MatchNode();
|
||||
void clearTree();
|
||||
const ServerInfo_ReplayMatch &getMatchInfo() { return matchInfo; }
|
||||
void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo);
|
||||
};
|
||||
class ReplayNode : public Node {
|
||||
private:
|
||||
MatchNode *parent;
|
||||
ServerInfo_Replay replayInfo;
|
||||
public:
|
||||
ReplayNode(const ServerInfo_Replay &_replayInfo, MatchNode *_parent)
|
||||
: Node(QString::fromStdString(_replayInfo.replay_name())), parent(_parent), replayInfo(_replayInfo) { }
|
||||
MatchNode *getParent() const { return parent; }
|
||||
const ServerInfo_Replay &getReplayInfo() { return replayInfo; }
|
||||
};
|
||||
class MatchNode;
|
||||
class ReplayNode;
|
||||
class Node {
|
||||
protected:
|
||||
QString name;
|
||||
public:
|
||||
Node(const QString &_name)
|
||||
: name(_name) { }
|
||||
virtual ~Node() { };
|
||||
QString getName() const { return name; }
|
||||
};
|
||||
class MatchNode : public Node, public QList<ReplayNode *> {
|
||||
private:
|
||||
ServerInfo_ReplayMatch matchInfo;
|
||||
public:
|
||||
MatchNode(const ServerInfo_ReplayMatch &_matchInfo);
|
||||
~MatchNode();
|
||||
void clearTree();
|
||||
const ServerInfo_ReplayMatch &getMatchInfo() { return matchInfo; }
|
||||
void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo);
|
||||
};
|
||||
class ReplayNode : public Node {
|
||||
private:
|
||||
MatchNode *parent;
|
||||
ServerInfo_Replay replayInfo;
|
||||
public:
|
||||
ReplayNode(const ServerInfo_Replay &_replayInfo, MatchNode *_parent)
|
||||
: Node(QString::fromStdString(_replayInfo.replay_name())), parent(_parent), replayInfo(_replayInfo) { }
|
||||
MatchNode *getParent() const { return parent; }
|
||||
const ServerInfo_Replay &getReplayInfo() { return replayInfo; }
|
||||
};
|
||||
|
||||
AbstractClient *client;
|
||||
QList<MatchNode *> replayMatches;
|
||||
AbstractClient *client;
|
||||
QList<MatchNode *> replayMatches;
|
||||
|
||||
QIcon dirIcon, fileIcon, lockIcon;
|
||||
void clearTree();
|
||||
QIcon dirIcon, fileIcon, lockIcon;
|
||||
void clearTree();
|
||||
|
||||
static const int numberOfColumns;
|
||||
static const int numberOfColumns;
|
||||
signals:
|
||||
void treeRefreshed();
|
||||
void treeRefreshed();
|
||||
private slots:
|
||||
void replayListFinished(const Response &r);
|
||||
void replayListFinished(const Response &r);
|
||||
public:
|
||||
RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent = 0);
|
||||
~RemoteReplayList_TreeModel();
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return numberOfColumns; }
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
void refreshTree();
|
||||
ServerInfo_Replay const* getReplay(const QModelIndex &index) const;
|
||||
ServerInfo_ReplayMatch const* getReplayMatch(const QModelIndex &index) const;
|
||||
void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo);
|
||||
void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo);
|
||||
void removeMatchInfo(int gameId);
|
||||
RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent = 0);
|
||||
~RemoteReplayList_TreeModel();
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return numberOfColumns; }
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
void refreshTree();
|
||||
ServerInfo_Replay const* getReplay(const QModelIndex &index) const;
|
||||
ServerInfo_ReplayMatch const* getReplayMatch(const QModelIndex &index) const;
|
||||
void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo);
|
||||
void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo);
|
||||
void removeMatchInfo(int gameId);
|
||||
};
|
||||
|
||||
class RemoteReplayList_TreeWidget : public QTreeView {
|
||||
private:
|
||||
RemoteReplayList_TreeModel *treeModel;
|
||||
QSortFilterProxyModel *proxyModel;
|
||||
ServerInfo_Replay const *getNode(const QModelIndex &ind) const;
|
||||
RemoteReplayList_TreeModel *treeModel;
|
||||
QSortFilterProxyModel *proxyModel;
|
||||
ServerInfo_Replay const *getNode(const QModelIndex &ind) const;
|
||||
public:
|
||||
RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent = 0);
|
||||
ServerInfo_Replay const *getCurrentReplay() const;
|
||||
ServerInfo_ReplayMatch const *getCurrentReplayMatch() const;
|
||||
void refreshTree();
|
||||
void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { treeModel->addMatchInfo(matchInfo); }
|
||||
void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { treeModel->updateMatchInfo(gameId, matchInfo); }
|
||||
void removeMatchInfo(int gameId) { treeModel->removeMatchInfo(gameId); }
|
||||
RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent = 0);
|
||||
ServerInfo_Replay const *getCurrentReplay() const;
|
||||
ServerInfo_ReplayMatch const *getCurrentReplayMatch() const;
|
||||
void refreshTree();
|
||||
void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { treeModel->addMatchInfo(matchInfo); }
|
||||
void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { treeModel->updateMatchInfo(gameId, matchInfo); }
|
||||
void removeMatchInfo(int gameId) { treeModel->removeMatchInfo(gameId); }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -5,97 +5,97 @@
|
|||
#include <math.h>
|
||||
|
||||
ReplayTimelineWidget::ReplayTimelineWidget(QWidget *parent)
|
||||
: QWidget(parent), maxBinValue(1), maxTime(1), timeScaleFactor(1.0), currentTime(0), currentEvent(0)
|
||||
: QWidget(parent), maxBinValue(1), maxTime(1), timeScaleFactor(1.0), currentTime(0), currentEvent(0)
|
||||
{
|
||||
replayTimer = new QTimer(this);
|
||||
connect(replayTimer, SIGNAL(timeout()), this, SLOT(replayTimerTimeout()));
|
||||
replayTimer = new QTimer(this);
|
||||
connect(replayTimer, SIGNAL(timeout()), this, SLOT(replayTimerTimeout()));
|
||||
}
|
||||
|
||||
const int ReplayTimelineWidget::binLength = 5000;
|
||||
|
||||
void ReplayTimelineWidget::setTimeline(const QList<int> &_replayTimeline)
|
||||
{
|
||||
replayTimeline = _replayTimeline;
|
||||
histogram.clear();
|
||||
int binEndTime = binLength - 1;
|
||||
int binValue = 0;
|
||||
for (int i = 0; i < replayTimeline.size(); ++i) {
|
||||
if (replayTimeline[i] > binEndTime) {
|
||||
histogram.append(binValue);
|
||||
if (binValue > maxBinValue)
|
||||
maxBinValue = binValue;
|
||||
while (replayTimeline[i] > binEndTime + binLength) {
|
||||
histogram.append(0);
|
||||
binEndTime += binLength;
|
||||
}
|
||||
binValue = 1;
|
||||
binEndTime += binLength;
|
||||
} else
|
||||
++binValue;
|
||||
}
|
||||
histogram.append(binValue);
|
||||
if (!replayTimeline.isEmpty())
|
||||
maxTime = replayTimeline.last();
|
||||
replayTimeline = _replayTimeline;
|
||||
histogram.clear();
|
||||
int binEndTime = binLength - 1;
|
||||
int binValue = 0;
|
||||
for (int i = 0; i < replayTimeline.size(); ++i) {
|
||||
if (replayTimeline[i] > binEndTime) {
|
||||
histogram.append(binValue);
|
||||
if (binValue > maxBinValue)
|
||||
maxBinValue = binValue;
|
||||
while (replayTimeline[i] > binEndTime + binLength) {
|
||||
histogram.append(0);
|
||||
binEndTime += binLength;
|
||||
}
|
||||
binValue = 1;
|
||||
binEndTime += binLength;
|
||||
} else
|
||||
++binValue;
|
||||
}
|
||||
histogram.append(binValue);
|
||||
if (!replayTimeline.isEmpty())
|
||||
maxTime = replayTimeline.last();
|
||||
|
||||
update();
|
||||
update();
|
||||
}
|
||||
|
||||
void ReplayTimelineWidget::paintEvent(QPaintEvent *event)
|
||||
{
|
||||
QPainter painter(this);
|
||||
painter.drawRect(0, 0, width() - 1, height() - 1);
|
||||
QPainter painter(this);
|
||||
painter.drawRect(0, 0, width() - 1, height() - 1);
|
||||
|
||||
qreal binWidth = (qreal) width() / histogram.size();
|
||||
QPainterPath path;
|
||||
path.moveTo(0, height() - 1);
|
||||
for (int i = 0; i < histogram.size(); ++i)
|
||||
path.lineTo(round(i * binWidth), (height() - 1) * (1.0 - (qreal) histogram[i] / maxBinValue));
|
||||
path.lineTo(width() - 1, height() - 1);
|
||||
path.lineTo(0, height() - 1);
|
||||
painter.fillPath(path, Qt::black);
|
||||
qreal binWidth = (qreal) width() / histogram.size();
|
||||
QPainterPath path;
|
||||
path.moveTo(0, height() - 1);
|
||||
for (int i = 0; i < histogram.size(); ++i)
|
||||
path.lineTo(round(i * binWidth), (height() - 1) * (1.0 - (qreal) histogram[i] / maxBinValue));
|
||||
path.lineTo(width() - 1, height() - 1);
|
||||
path.lineTo(0, height() - 1);
|
||||
painter.fillPath(path, Qt::black);
|
||||
|
||||
const QColor barColor = QColor::fromHsv(120, 255, 255, 100);
|
||||
painter.fillRect(0, 0, (width() - 1) * currentTime / maxTime, height() - 1, barColor);
|
||||
const QColor barColor = QColor::fromHsv(120, 255, 255, 100);
|
||||
painter.fillRect(0, 0, (width() - 1) * currentTime / maxTime, height() - 1, barColor);
|
||||
}
|
||||
|
||||
QSize ReplayTimelineWidget::sizeHint() const
|
||||
{
|
||||
return QSize(-1, 50);
|
||||
return QSize(-1, 50);
|
||||
}
|
||||
|
||||
QSize ReplayTimelineWidget::minimumSizeHint() const
|
||||
{
|
||||
return QSize(400, 50);
|
||||
return QSize(400, 50);
|
||||
}
|
||||
|
||||
void ReplayTimelineWidget::replayTimerTimeout()
|
||||
{
|
||||
currentTime += 200;
|
||||
while ((currentEvent < replayTimeline.size()) && (replayTimeline[currentEvent] < currentTime)) {
|
||||
emit processNextEvent();
|
||||
++currentEvent;
|
||||
}
|
||||
if (currentEvent == replayTimeline.size()) {
|
||||
emit replayFinished();
|
||||
replayTimer->stop();
|
||||
}
|
||||
currentTime += 200;
|
||||
while ((currentEvent < replayTimeline.size()) && (replayTimeline[currentEvent] < currentTime)) {
|
||||
emit processNextEvent();
|
||||
++currentEvent;
|
||||
}
|
||||
if (currentEvent == replayTimeline.size()) {
|
||||
emit replayFinished();
|
||||
replayTimer->stop();
|
||||
}
|
||||
|
||||
if (!(currentTime % 1000))
|
||||
update();
|
||||
if (!(currentTime % 1000))
|
||||
update();
|
||||
}
|
||||
|
||||
void ReplayTimelineWidget::setTimeScaleFactor(qreal _timeScaleFactor)
|
||||
{
|
||||
timeScaleFactor = _timeScaleFactor;
|
||||
replayTimer->setInterval(200 / timeScaleFactor);
|
||||
timeScaleFactor = _timeScaleFactor;
|
||||
replayTimer->setInterval(200 / timeScaleFactor);
|
||||
}
|
||||
|
||||
void ReplayTimelineWidget::startReplay()
|
||||
{
|
||||
replayTimer->start(200 / timeScaleFactor);
|
||||
replayTimer->start(200 / timeScaleFactor);
|
||||
}
|
||||
|
||||
void ReplayTimelineWidget::stopReplay()
|
||||
{
|
||||
replayTimer->stop();
|
||||
replayTimer->stop();
|
||||
}
|
||||
|
|
|
@ -8,33 +8,33 @@ class QPaintEvent;
|
|||
class QTimer;
|
||||
|
||||
class ReplayTimelineWidget : public QWidget {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void processNextEvent();
|
||||
void replayFinished();
|
||||
void processNextEvent();
|
||||
void replayFinished();
|
||||
private:
|
||||
QTimer *replayTimer;
|
||||
QList<int> replayTimeline;
|
||||
QList<int> histogram;
|
||||
static const int binLength;
|
||||
int maxBinValue, maxTime;
|
||||
qreal timeScaleFactor;
|
||||
int currentTime;
|
||||
int currentEvent;
|
||||
QTimer *replayTimer;
|
||||
QList<int> replayTimeline;
|
||||
QList<int> histogram;
|
||||
static const int binLength;
|
||||
int maxBinValue, maxTime;
|
||||
qreal timeScaleFactor;
|
||||
int currentTime;
|
||||
int currentEvent;
|
||||
private slots:
|
||||
void replayTimerTimeout();
|
||||
void replayTimerTimeout();
|
||||
public:
|
||||
ReplayTimelineWidget(QWidget *parent = 0);
|
||||
void setTimeline(const QList<int> &_replayTimeline);
|
||||
QSize sizeHint() const;
|
||||
QSize minimumSizeHint() const;
|
||||
void setTimeScaleFactor(qreal _timeScaleFactor);
|
||||
int getCurrentEvent() const { return currentEvent; }
|
||||
ReplayTimelineWidget(QWidget *parent = 0);
|
||||
void setTimeline(const QList<int> &_replayTimeline);
|
||||
QSize sizeHint() const;
|
||||
QSize minimumSizeHint() const;
|
||||
void setTimeScaleFactor(qreal _timeScaleFactor);
|
||||
int getCurrentEvent() const { return currentEvent; }
|
||||
public slots:
|
||||
void startReplay();
|
||||
void stopReplay();
|
||||
void startReplay();
|
||||
void stopReplay();
|
||||
protected:
|
||||
void paintEvent(QPaintEvent *event);
|
||||
void paintEvent(QPaintEvent *event);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
@ -5,52 +5,52 @@
|
|||
#include <QDebug>
|
||||
|
||||
SelectZone::SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool isView)
|
||||
: CardZone(_player, _name, _hasCardAttr, _isShufflable, _contentsKnown, parent, isView)
|
||||
: CardZone(_player, _name, _hasCardAttr, _isShufflable, _contentsKnown, parent, isView)
|
||||
{
|
||||
}
|
||||
|
||||
void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->buttons().testFlag(Qt::LeftButton)) {
|
||||
QPointF pos = event->pos();
|
||||
if (pos.x() < 0)
|
||||
pos.setX(0);
|
||||
QRectF br = boundingRect();
|
||||
if (pos.x() > br.width())
|
||||
pos.setX(br.width());
|
||||
if (pos.y() < 0)
|
||||
pos.setY(0);
|
||||
if (pos.y() > br.height())
|
||||
pos.setY(br.height());
|
||||
if (event->buttons().testFlag(Qt::LeftButton)) {
|
||||
QPointF pos = event->pos();
|
||||
if (pos.x() < 0)
|
||||
pos.setX(0);
|
||||
QRectF br = boundingRect();
|
||||
if (pos.x() > br.width())
|
||||
pos.setX(br.width());
|
||||
if (pos.y() < 0)
|
||||
pos.setY(0);
|
||||
if (pos.y() > br.height())
|
||||
pos.setY(br.height());
|
||||
|
||||
QRectF selectionRect = QRectF(selectionOrigin, pos).normalized();
|
||||
for (int i = 0; i < cards.size(); ++i) {
|
||||
if (cards[i]->getAttachedTo())
|
||||
if (cards[i]->getAttachedTo()->getZone() != this)
|
||||
continue;
|
||||
cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect())));
|
||||
}
|
||||
static_cast<GameScene *>(scene())->resizeRubberBand(deviceTransform(static_cast<GameScene *>(scene())->getViewportTransform()).map(pos));
|
||||
event->accept();
|
||||
}
|
||||
QRectF selectionRect = QRectF(selectionOrigin, pos).normalized();
|
||||
for (int i = 0; i < cards.size(); ++i) {
|
||||
if (cards[i]->getAttachedTo())
|
||||
if (cards[i]->getAttachedTo()->getZone() != this)
|
||||
continue;
|
||||
cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect())));
|
||||
}
|
||||
static_cast<GameScene *>(scene())->resizeRubberBand(deviceTransform(static_cast<GameScene *>(scene())->getViewportTransform()).map(pos));
|
||||
event->accept();
|
||||
}
|
||||
}
|
||||
|
||||
void SelectZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
scene()->clearSelection();
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
scene()->clearSelection();
|
||||
|
||||
selectionOrigin = event->pos();
|
||||
static_cast<GameScene *>(scene())->startRubberBand(event->scenePos());
|
||||
event->accept();
|
||||
} else
|
||||
CardZone::mousePressEvent(event);
|
||||
selectionOrigin = event->pos();
|
||||
static_cast<GameScene *>(scene())->startRubberBand(event->scenePos());
|
||||
event->accept();
|
||||
} else
|
||||
CardZone::mousePressEvent(event);
|
||||
}
|
||||
|
||||
void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
|
||||
{
|
||||
selectionOrigin = QPoint();
|
||||
static_cast<GameScene *>(scene())->stopRubberBand();
|
||||
event->accept();
|
||||
selectionOrigin = QPoint();
|
||||
static_cast<GameScene *>(scene())->stopRubberBand();
|
||||
event->accept();
|
||||
}
|
||||
|
||||
|
|
|
@ -4,15 +4,15 @@
|
|||
#include "cardzone.h"
|
||||
|
||||
class SelectZone : public CardZone {
|
||||
Q_OBJECT
|
||||
Q_OBJECT
|
||||
private:
|
||||
QPointF selectionOrigin;
|
||||
QPointF selectionOrigin;
|
||||
protected:
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event);
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
|
||||
public:
|
||||
SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool isView = false);
|
||||
SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool isView = false);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue