diff --git a/cockatrice/cockatrice.pro b/cockatrice/cockatrice.pro index c21a733b..3b917dd0 100644 --- a/cockatrice/cockatrice.pro +++ b/cockatrice/cockatrice.pro @@ -50,6 +50,7 @@ HEADERS += src/counter.h \ src/remotedecklist_treewidget.h \ src/deckview.h \ src/playerlistwidget.h \ + ../common/serializable_item.h \ ../common/decklist.h \ ../common/protocol.h \ ../common/protocol_items.h \ @@ -98,6 +99,7 @@ SOURCES += src/counter.cpp \ src/remotedecklist_treewidget.cpp \ src/deckview.cpp \ src/playerlistwidget.cpp \ + ../common/serializable_item.cpp \ ../common/decklist.cpp \ ../common/protocol.cpp \ ../common/protocol_items.cpp \ diff --git a/cockatrice/src/client.cpp b/cockatrice/src/client.cpp index 587114fd..7cf23bf9 100644 --- a/cockatrice/src/client.cpp +++ b/cockatrice/src/client.cpp @@ -6,7 +6,7 @@ #include "protocol_items.h" Client::Client(QObject *parent) - : QObject(parent), currentItem(0), status(StatusDisconnected) + : QObject(parent), topLevelItem(0), status(StatusDisconnected) { ProtocolItem::initializeHash(); @@ -58,44 +58,31 @@ void Client::readData() qDebug() << data; xmlReader->addData(data); - if (currentItem) { - if (!currentItem->read(xmlReader)) - return; - currentItem = 0; - } - while (!xmlReader->atEnd()) { - xmlReader->readNext(); - if (xmlReader->isStartElement()) { - QString itemType = xmlReader->name().toString(); - if (itemType == "cockatrice_server_stream") { + if (topLevelItem) + topLevelItem->read(xmlReader); + else { + while (!xmlReader->atEnd()) { + xmlReader->readNext(); + if (xmlReader->isStartElement() && (xmlReader->name().toString() == "cockatrice_server_stream")) { int serverVersion = xmlReader->attributes().value("version").toString().toInt(); if (serverVersion != ProtocolItem::protocolVersion) { emit protocolVersionMismatch(ProtocolItem::protocolVersion, serverVersion); disconnectFromServer(); return; - } else { - xmlWriter->writeStartDocument(); - xmlWriter->writeStartElement("cockatrice_client_stream"); - xmlWriter->writeAttribute("version", QString::number(ProtocolItem::protocolVersion)); - - setStatus(StatusLoggingIn); - Command_Login *cmdLogin = new Command_Login(userName, password); - connect(cmdLogin, SIGNAL(finished(ResponseCode)), this, SLOT(loginResponse(ResponseCode))); - sendCommand(cmdLogin); - - continue; } - } - QString itemName = xmlReader->attributes().value("name").toString(); - qDebug() << "parseXml: startElement: " << "type =" << itemType << ", name =" << itemName; - currentItem = ProtocolItem::getNewItem(itemType + itemName); - if (!currentItem) - continue; - if (!currentItem->read(xmlReader)) - return; - else { - processProtocolItem(currentItem); - currentItem = 0; + xmlWriter->writeStartDocument(); + xmlWriter->writeStartElement("cockatrice_client_stream"); + xmlWriter->writeAttribute("version", QString::number(ProtocolItem::protocolVersion)); + + topLevelItem = new TopLevelProtocolItem; + connect(topLevelItem, SIGNAL(protocolItemReceived(ProtocolItem *)), this, SLOT(processProtocolItem(ProtocolItem *))); + + setStatus(StatusLoggingIn); + Command_Login *cmdLogin = new Command_Login(userName, password); + connect(cmdLogin, SIGNAL(finished(ResponseCode)), this, SLOT(loginResponse(ResponseCode))); + sendCommand(cmdLogin); + + topLevelItem->read(xmlReader); } } } @@ -171,7 +158,9 @@ void Client::connectToServer(const QString &hostname, unsigned int port, const Q void Client::disconnectFromServer() { - currentItem = 0; + delete topLevelItem; + topLevelItem = 0; + xmlReader->clear(); timer->stop(); diff --git a/cockatrice/src/client.h b/cockatrice/src/client.h index 9bdff6f9..ceca4bd9 100644 --- a/cockatrice/src/client.h +++ b/cockatrice/src/client.h @@ -14,6 +14,7 @@ class QXmlStreamWriter; class ProtocolItem; class ProtocolResponse; +class TopLevelProtocolItem; class ChatEvent; class GameEvent; class Event_ListGames; @@ -56,6 +57,7 @@ private slots: void slotSocketError(QAbstractSocket::SocketError error); void ping(); void loginResponse(ResponseCode response); + void processProtocolItem(ProtocolItem *item); private: static const int maxTimeout = 10; @@ -64,11 +66,10 @@ private: QTcpSocket *socket; QXmlStreamReader *xmlReader; QXmlStreamWriter *xmlWriter; - ProtocolItem *currentItem; + TopLevelProtocolItem *topLevelItem; ClientStatus status; QString userName, password; void setStatus(ClientStatus _status); - void processProtocolItem(ProtocolItem *item); public: Client(QObject *parent = 0); ~Client(); diff --git a/cockatrice/src/decklistmodel.cpp b/cockatrice/src/decklistmodel.cpp index 7accd69e..16fe1610 100644 --- a/cockatrice/src/decklistmodel.cpp +++ b/cockatrice/src/decklistmodel.cpp @@ -14,7 +14,7 @@ DeckListModel::DeckListModel(QObject *parent) : QAbstractItemModel(parent) { - deckList = new DeckList(this); + deckList = new DeckList; connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); root = new InnerDecklistNode; } @@ -22,6 +22,7 @@ DeckListModel::DeckListModel(QObject *parent) DeckListModel::~DeckListModel() { delete root; + delete deckList; } diff --git a/cockatrice/src/gamesmodel.cpp b/cockatrice/src/gamesmodel.cpp index 5182263f..365d461f 100644 --- a/cockatrice/src/gamesmodel.cpp +++ b/cockatrice/src/gamesmodel.cpp @@ -1,9 +1,12 @@ #include "gamesmodel.h" +#include "protocol_datastructures.h" GamesModel::~GamesModel() { if (!gameList.isEmpty()) { beginRemoveRows(QModelIndex(), 0, gameList.size() - 1); + for (int i = 0; i < gameList.size(); ++i) + delete gameList[i]; gameList.clear(); endRemoveRows(); } @@ -20,13 +23,13 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) return QVariant(); - const ServerGameInfo &g = gameList[index.row()]; + ServerInfo_Game *g = gameList[index.row()]; switch (index.column()) { - case 0: return g.getDescription(); - case 1: return g.getCreatorName(); - case 2: return g.getHasPassword() ? tr("yes") : tr("no"); - case 3: return QString("%1/%2").arg(g.getPlayerCount()).arg(g.getMaxPlayers()); - case 4: return g.getSpectatorsAllowed() ? QVariant(g.getSpectatorCount()) : QVariant(tr("not allowed")); + case 0: return g->getDescription(); + case 1: return g->getCreatorName(); + case 2: return g->getHasPassword() ? tr("yes") : tr("no"); + case 3: return QString("%1/%2").arg(g->getPlayerCount()).arg(g->getMaxPlayers()); + case 4: return g->getSpectatorsAllowed() ? QVariant(g->getSpectatorCount()) : QVariant(tr("not allowed")); default: return QVariant(); } } @@ -45,30 +48,32 @@ QVariant GamesModel::headerData(int section, Qt::Orientation orientation, int ro } } -const ServerGameInfo &GamesModel::getGame(int row) +ServerInfo_Game *GamesModel::getGame(int row) { Q_ASSERT(row < gameList.size()); return gameList[row]; } -void GamesModel::updateGameList(const ServerGameInfo &game) +void GamesModel::updateGameList(ServerInfo_Game *_game) { + ServerInfo_Game *game = new ServerInfo_Game(_game->getGameId(), _game->getDescription(), _game->getHasPassword(), _game->getPlayerCount(), _game->getMaxPlayers(), _game->getCreatorName(), _game->getSpectatorsAllowed(), _game->getSpectatorCount()); for (int i = 0; i < gameList.size(); i++) - if (gameList[i].getGameId() == game.getGameId()) { - if (game.getPlayerCount() == 0) { + if (gameList[i]->getGameId() == game->getGameId()) { + if (game->getPlayerCount() == 0) { beginRemoveRows(QModelIndex(), i, i); - gameList.removeAt(i); + delete gameList.takeAt(i); endRemoveRows(); } else { + delete gameList[i]; gameList[i] = game; emit dataChanged(index(i, 0), index(i, 4)); } return; } - if (game.getPlayerCount() == 0) + if (game->getPlayerCount() == 0) return; beginInsertRows(QModelIndex(), gameList.size(), gameList.size()); - gameList << game; + gameList.append(game); endInsertRows(); } @@ -93,8 +98,8 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourc if (!model) return false; - const ServerGameInfo &game = model->getGame(sourceRow); - if (game.getPlayerCount() == game.getMaxPlayers()) + ServerInfo_Game *game = model->getGame(sourceRow); + if (game->getPlayerCount() == game->getMaxPlayers()) return false; return true; diff --git a/cockatrice/src/gamesmodel.h b/cockatrice/src/gamesmodel.h index 6f5b2a6b..b9558db2 100644 --- a/cockatrice/src/gamesmodel.h +++ b/cockatrice/src/gamesmodel.h @@ -4,7 +4,8 @@ #include #include #include -#include "protocol_datastructures.h" + +class ServerInfo_Game; class GamesModel : public QAbstractTableModel { Q_OBJECT @@ -16,10 +17,10 @@ public: QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - const ServerGameInfo &getGame(int row); - void updateGameList(const ServerGameInfo &game); + ServerInfo_Game *getGame(int row); + void updateGameList(ServerInfo_Game *game); private: - QList gameList; + QList gameList; }; class GamesProxyModel : public QSortFilterProxyModel { diff --git a/cockatrice/src/player.cpp b/cockatrice/src/player.cpp index 8f9074ce..4cc446a7 100644 --- a/cockatrice/src/player.cpp +++ b/cockatrice/src/player.cpp @@ -373,7 +373,7 @@ void Player::actDrawCards() void Player::actUntapAll() { -// client->setCardAttr("table", -1, "tapped", "false"); + sendGameCommand(new Command_SetCardAttr(-1, "table", -1, "tapped", "0")); } void Player::actRollDie() @@ -448,12 +448,15 @@ void Player::eventRollDie(Event_RollDie *event) emit logRollDie(this, event->getSides(), event->getValue()); } -void Player::eventCreateArrow(Event_CreateArrow *event) +void Player::eventCreateArrows(Event_CreateArrows *event) { - ArrowItem *arrow = addArrow(event->getArrow()); - if (!arrow) - return; - emit logCreateArrow(this, arrow->getStartItem()->getOwner(), arrow->getStartItem()->getName(), arrow->getTargetItem()->getOwner(), arrow->getTargetItem()->getName()); + const QList eventArrowList = event->getArrowList(); + for (int i = 0; i < eventArrowList.size(); ++i) { + ArrowItem *arrow = addArrow(eventArrowList[i]); + if (!arrow) + return; + emit logCreateArrow(this, arrow->getStartItem()->getOwner(), arrow->getStartItem()->getName(), arrow->getTargetItem()->getOwner(), arrow->getTargetItem()->getName()); + } } void Player::eventDeleteArrow(Event_DeleteArrow *event) @@ -492,9 +495,11 @@ void Player::eventSetCardAttr(Event_SetCardAttr *event) } } -void Player::eventCreateCounter(Event_CreateCounter *event) +void Player::eventCreateCounters(Event_CreateCounters *event) { - addCounter(event->getCounter()); + const QList &eventCounterList = event->getCounterList(); + for (int i = 0; i < eventCounterList.size(); ++i) + addCounter(eventCounterList[i]); } void Player::eventSetCounter(Event_SetCounter *event) @@ -612,11 +617,11 @@ void Player::processGameEvent(GameEvent *event) case ItemId_Event_ReadyStart: eventReadyStart(qobject_cast(event)); break; case ItemId_Event_Shuffle: eventShuffle(qobject_cast(event)); break; case ItemId_Event_RollDie: eventRollDie(qobject_cast(event)); break; - case ItemId_Event_CreateArrow: eventCreateArrow(qobject_cast(event)); break; + case ItemId_Event_CreateArrows: eventCreateArrows(qobject_cast(event)); break; case ItemId_Event_DeleteArrow: eventDeleteArrow(qobject_cast(event)); break; case ItemId_Event_CreateToken: eventCreateToken(qobject_cast(event)); break; case ItemId_Event_SetCardAttr: eventSetCardAttr(qobject_cast(event)); break; - case ItemId_Event_CreateCounter: eventCreateCounter(qobject_cast(event)); break; + case ItemId_Event_CreateCounters: eventCreateCounters(qobject_cast(event)); break; case ItemId_Event_SetCounter: eventSetCounter(qobject_cast(event)); break; case ItemId_Event_DelCounter: eventDelCounter(qobject_cast(event)); break; case ItemId_Event_DumpZone: eventDumpZone(qobject_cast(event)); break; diff --git a/cockatrice/src/player.h b/cockatrice/src/player.h index 2b9836ad..48412b08 100644 --- a/cockatrice/src/player.h +++ b/cockatrice/src/player.h @@ -27,11 +27,11 @@ class Event_Say; class Event_ReadyStart; class Event_Shuffle; class Event_RollDie; -class Event_CreateArrow; +class Event_CreateArrows; class Event_DeleteArrow; class Event_CreateToken; class Event_SetCardAttr; -class Event_CreateCounter; +class Event_CreateCounters; class Event_SetCounter; class Event_DelCounter; class Event_DumpZone; @@ -118,11 +118,11 @@ private: void eventReadyStart(Event_ReadyStart *event); void eventShuffle(Event_Shuffle *event); void eventRollDie(Event_RollDie *event); - void eventCreateArrow(Event_CreateArrow *event); + void eventCreateArrows(Event_CreateArrows *event); void eventDeleteArrow(Event_DeleteArrow *event); void eventCreateToken(Event_CreateToken *event); void eventSetCardAttr(Event_SetCardAttr *event); - void eventCreateCounter(Event_CreateCounter *event); + void eventCreateCounters(Event_CreateCounters *event); void eventSetCounter(Event_SetCounter *event); void eventDelCounter(Event_DelCounter *event); void eventDumpZone(Event_DumpZone *event); diff --git a/cockatrice/src/remotedecklist_treewidget.cpp b/cockatrice/src/remotedecklist_treewidget.cpp index 159fe5a8..58f2188b 100644 --- a/cockatrice/src/remotedecklist_treewidget.cpp +++ b/cockatrice/src/remotedecklist_treewidget.cpp @@ -54,12 +54,13 @@ void RemoteDeckList_TreeWidget::addFolderToTree(DeckList_Directory *folder, QTre newItem->setData(0, Qt::UserRole, QString()); } - for (int i = 0; i < folder->size(); ++i) { - DeckList_Directory *subFolder = dynamic_cast(folder->at(i)); + const QList &folderItems = folder->getTreeItems(); + for (int i = 0; i < folderItems.size(); ++i) { + DeckList_Directory *subFolder = dynamic_cast(folderItems[i]); if (subFolder) addFolderToTree(subFolder, newItem); else - addFileToTree(dynamic_cast(folder->at(i)), newItem); + addFileToTree(dynamic_cast(folderItems[i]), newItem); } } diff --git a/cockatrice/src/tab_chatchannel.cpp b/cockatrice/src/tab_chatchannel.cpp index 786b295f..a998c806 100644 --- a/cockatrice/src/tab_chatchannel.cpp +++ b/cockatrice/src/tab_chatchannel.cpp @@ -51,9 +51,9 @@ void TabChatChannel::processChatEvent(ChatEvent *event) void TabChatChannel::processListPlayersEvent(Event_ChatListPlayers *event) { - const QList &players = event->getPlayerList(); + const QList &players = event->getPlayerList(); for (int i = 0; i < players.size(); ++i) - playerList->addItem(players[i].getName()); + playerList->addItem(players[i]->getName()); } void TabChatChannel::processJoinChannelEvent(Event_ChatJoinChannel *event) diff --git a/cockatrice/src/tab_deck_storage.cpp b/cockatrice/src/tab_deck_storage.cpp index e8d3c803..4c6d4a23 100644 --- a/cockatrice/src/tab_deck_storage.cpp +++ b/cockatrice/src/tab_deck_storage.cpp @@ -121,7 +121,6 @@ void TabDeckStorage::uploadFinished(ProtocolResponse *r) if (!resp) return; Command_DeckUpload *cmd = static_cast(sender()); - delete cmd->getDeck(); QTreeWidgetItemIterator it(serverDirView); while (*it) { diff --git a/cockatrice/src/tab_game.cpp b/cockatrice/src/tab_game.cpp index 96171dc1..22c1008c 100644 --- a/cockatrice/src/tab_game.cpp +++ b/cockatrice/src/tab_game.cpp @@ -324,11 +324,9 @@ void TabGame::deckSelectFinished(ProtocolResponse *r) Response_DeckDownload *resp = qobject_cast(r); if (!resp) return; - Command_DeckSelect *cmd = static_cast(sender()); - delete cmd->getDeck(); Deck_PictureCacher::cachePictures(resp->getDeck(), this); - deckView->setDeck(resp->getDeck()); + deckView->setDeck(new DeckList(resp->getDeck())); } void TabGame::readyStart() diff --git a/cockatrice/src/tab_server.cpp b/cockatrice/src/tab_server.cpp index 1da2f25b..4934e06e 100644 --- a/cockatrice/src/tab_server.cpp +++ b/cockatrice/src/tab_server.cpp @@ -78,16 +78,16 @@ void GameSelector::actJoin() QModelIndex ind = gameListView->currentIndex(); if (!ind.isValid()) return; - const ServerGameInfo &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt()); + ServerInfo_Game *game = gameListModel->getGame(ind.data(Qt::UserRole).toInt()); QString password; - if (game.getHasPassword()) { + if (game->getHasPassword()) { bool ok; password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok); if (!ok) return; } - Command_JoinGame *commandJoinGame = new Command_JoinGame(game.getGameId(), password, spectator); + Command_JoinGame *commandJoinGame = new Command_JoinGame(game->getGameId(), password, spectator); connect(commandJoinGame, SIGNAL(finished(ResponseCode)), this, SLOT(checkResponse(ResponseCode))); client->sendCommand(commandJoinGame); @@ -107,7 +107,7 @@ void GameSelector::retranslateUi() void GameSelector::processListGamesEvent(Event_ListGames *event) { - const QList &gamesToUpdate = event->getGameList(); + const QList &gamesToUpdate = event->getGameList(); for (int i = 0; i < gamesToUpdate.size(); ++i) gameListModel->updateGameList(gamesToUpdate[i]); } @@ -148,26 +148,26 @@ void ChatChannelSelector::retranslateUi() void ChatChannelSelector::processListChatChannelsEvent(Event_ListChatChannels *event) { - const QList &channelsToUpdate = event->getChannelList(); + const QList &channelsToUpdate = event->getChannelList(); for (int i = 0; i < channelsToUpdate.size(); ++i) { - const ServerChatChannelInfo &channel = channelsToUpdate[i]; + ServerInfo_ChatChannel *channel = channelsToUpdate[i]; for (int j = 0; j < channelList->topLevelItemCount(); ++j) { QTreeWidgetItem *twi = channelList->topLevelItem(j); - if (twi->text(0) == channel.getName()) { - twi->setText(1, channel.getDescription()); - twi->setText(2, QString::number(channel.getPlayerCount())); + if (twi->text(0) == channel->getName()) { + twi->setText(1, channel->getDescription()); + twi->setText(2, QString::number(channel->getPlayerCount())); return; } } - QTreeWidgetItem *twi = new QTreeWidgetItem(QStringList() << channel.getName() << channel.getDescription() << QString::number(channel.getPlayerCount())); + QTreeWidgetItem *twi = new QTreeWidgetItem(QStringList() << channel->getName() << channel->getDescription() << QString::number(channel->getPlayerCount())); twi->setTextAlignment(2, Qt::AlignRight); channelList->addTopLevelItem(twi); channelList->resizeColumnToContents(0); channelList->resizeColumnToContents(1); channelList->resizeColumnToContents(2); - if (channel.getAutoJoin()) - joinChannel(channel.getName()); + if (channel->getAutoJoin()) + joinChannel(channel->getName()); } } diff --git a/cockatrice/src/zoneviewzone.cpp b/cockatrice/src/zoneviewzone.cpp index b756aa75..699765ee 100644 --- a/cockatrice/src/zoneviewzone.cpp +++ b/cockatrice/src/zoneviewzone.cpp @@ -42,7 +42,7 @@ void ZoneViewZone::initializeCards() } } -void ZoneViewZone::zoneDumpReceived(QList cards) +/*void ZoneViewZone::zoneDumpReceived(QList cards) { for (int i = 0; i < cards.size(); i++) { CardItem *card = new CardItem(player, cards[i].getName(), i, this); @@ -52,7 +52,7 @@ void ZoneViewZone::zoneDumpReceived(QList cards) emit contentsChanged(); reorganizeCards(); } - +*/ // Because of boundingRect(), this function must not be called before the zone was added to a scene. void ZoneViewZone::reorganizeCards() { diff --git a/cockatrice/src/zoneviewzone.h b/cockatrice/src/zoneviewzone.h index 105c18b5..ea92e261 100644 --- a/cockatrice/src/zoneviewzone.h +++ b/cockatrice/src/zoneviewzone.h @@ -29,7 +29,7 @@ public: public slots: void setSortingEnabled(int _sortingEnabled); private slots: - void zoneDumpReceived(QList cards); +// void zoneDumpReceived(QList cards); protected: void addCardImpl(CardItem *card, int x, int y); QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; diff --git a/common/decklist.cpp b/common/decklist.cpp index 8bb9621d..4588084b 100644 --- a/common/decklist.cpp +++ b/common/decklist.cpp @@ -21,6 +21,18 @@ int AbstractDecklistNode::depth() const return 0; } +InnerDecklistNode::InnerDecklistNode(InnerDecklistNode *other, InnerDecklistNode *_parent) + : AbstractDecklistNode(_parent), name(other->getName()) +{ + for (int i = 0; i < other->size(); ++i) { + InnerDecklistNode *inner = dynamic_cast(other->at(i)); + if (inner) + new InnerDecklistNode(inner, this); + else + new DecklistCardNode(dynamic_cast(other->at(i)), this); + } +} + InnerDecklistNode::~InnerDecklistNode() { clearTree(); @@ -48,6 +60,11 @@ void InnerDecklistNode::clearTree() clear(); } +DecklistCardNode::DecklistCardNode(DecklistCardNode *other, InnerDecklistNode *_parent) + : AbstractDecklistCardNode(_parent), name(other->getName()), number(other->getNumber()) +{ +} + AbstractDecklistNode *InnerDecklistNode::findChild(const QString &name) { for (int i = 0; i < size(); i++) @@ -178,76 +195,71 @@ const QStringList DeckList::fileNameFilters = QStringList() << QObject::tr("Plain text decks (*.dec *.mwDeck)") << QObject::tr("All files (*.*)"); -DeckList::DeckList(QObject *parent) - : QObject(parent), currentZone(0) +DeckList::DeckList() + : SerializableItem("cockatrice_deck"), currentZone(0) { root = new InnerDecklistNode; } +DeckList::DeckList(DeckList *other) + : SerializableItem("cockatrice_deck"), currentZone(0) +{ + root = new InnerDecklistNode(other->getRoot()); +} + DeckList::~DeckList() { delete root; } -bool DeckList::readElement(QXmlStreamReader *xml) +void DeckList::readElement(QXmlStreamReader *xml) { if (currentZone) { if (currentZone->readElement(xml)) currentZone = 0; - return false; - } - - if (xml->isEndElement()) { + } else if (xml->isEndElement()) { if (xml->name() == "deckname") name = currentElementText; else if (xml->name() == "comments") comments = currentElementText; - else if (xml->name() == "cockatrice_deck") - return true; currentElementText.clear(); } else if (xml->isStartElement() && (xml->name() == "zone")) currentZone = new InnerDecklistNode(xml->attributes().value("name").toString(), root); else if (xml->isCharacters() && !xml->isWhitespace()) currentElementText = xml->text().toString(); - - return false; } void DeckList::writeElement(QXmlStreamWriter *xml) { - xml->writeStartElement("cockatrice_deck"); xml->writeAttribute("version", "1"); xml->writeTextElement("deckname", name); xml->writeTextElement("comments", comments); for (int i = 0; i < root->size(); i++) root->at(i)->writeElement(xml); - - xml->writeEndElement(); // cockatrice_deck } -bool DeckList::loadFromXml(QXmlStreamReader *xml) +void DeckList::loadFromXml(QXmlStreamReader *xml) { while (!xml->atEnd()) { xml->readNext(); if (xml->isStartElement()) { if (xml->name() != "cockatrice_deck") - return false; + return; while (!xml->atEnd()) { xml->readNext(); - if (readElement(xml)) - return true; + readElement(xml); } } } - return false; } bool DeckList::loadFromFile_Native(QIODevice *device) { QXmlStreamReader xml(device); - return loadFromXml(&xml); + loadFromXml(&xml); + return true; } bool DeckList::saveToFile_Native(QIODevice *device) @@ -256,7 +268,7 @@ bool DeckList::saveToFile_Native(QIODevice *device) xml.setAutoFormatting(true); xml.writeStartDocument(); - writeElement(&xml); + write(&xml); xml.writeEndDocument(); return true; diff --git a/common/decklist.h b/common/decklist.h index fad96094..cd235241 100644 --- a/common/decklist.h +++ b/common/decklist.h @@ -5,6 +5,7 @@ #include #include #include +#include "serializable_item.h" class CardDatabase; class QIODevice; @@ -36,6 +37,7 @@ private: class compareFunctor; public: InnerDecklistNode(const QString &_name = QString(), InnerDecklistNode *_parent = 0) : AbstractDecklistNode(_parent), name(_name) { } + InnerDecklistNode(InnerDecklistNode *other, InnerDecklistNode *_parent = 0); virtual ~InnerDecklistNode(); QString getName() const { return name; } void setName(const QString &_name) { name = _name; } @@ -72,13 +74,14 @@ private: int number; public: DecklistCardNode(const QString &_name = QString(), int _number = 1, InnerDecklistNode *_parent = 0) : AbstractDecklistCardNode(_parent), name(_name), number(_number) { } + DecklistCardNode(DecklistCardNode *other, InnerDecklistNode *_parent); int getNumber() const { return number; } void setNumber(int _number) { number = _number; } QString getName() const { return name; } void setName(const QString &_name) { name = _name; } }; -class DeckList : public QObject { +class DeckList : public SerializableItem { Q_OBJECT public: enum FileFormat { PlainTextFormat, CockatriceFormat }; @@ -96,16 +99,17 @@ public slots: void setComments(const QString &_comments = QString()) { comments = _comments; } public: static const QStringList fileNameFilters; - DeckList(QObject *parent = 0); + DeckList(); + DeckList(DeckList *other); ~DeckList(); QString getName() const { return name; } QString getComments() const { return comments; } QString getLastFileName() const { return lastFileName; } FileFormat getLastFileFormat() const { return lastFileFormat; } - bool readElement(QXmlStreamReader *xml); + void readElement(QXmlStreamReader *xml); void writeElement(QXmlStreamWriter *xml); - bool loadFromXml(QXmlStreamReader *xml); + void loadFromXml(QXmlStreamReader *xml); bool loadFromFile_Native(QIODevice *device); bool saveToFile_Native(QIODevice *device); diff --git a/common/protocol.cpp b/common/protocol.cpp index 28f150fb..23465570 100644 --- a/common/protocol.cpp +++ b/common/protocol.cpp @@ -5,100 +5,87 @@ #include "protocol_items.h" #include "decklist.h" -QHash ProtocolItem::itemNameHash; - -ProtocolItem::ProtocolItem(const QString &_itemName) - : itemName(_itemName) +ProtocolItem::ProtocolItem(const QString &_itemType, const QString &_itemSubType) + : SerializableItem_Map(_itemType, _itemSubType) { } -bool ProtocolItem::read(QXmlStreamReader *xml) -{ - while (!xml->atEnd()) { - xml->readNext(); - if (readElement(xml)) - continue; - if (xml->isEndElement()) { - if (xml->name() == getItemType()) { - extractParameters(); - return true; - } else { - QString tagName = xml->name().toString(); - if (parameters.contains(tagName)) - parameters[tagName] = currentElementText; - currentElementText.clear(); - } - } else if (xml->isCharacters() && !xml->isWhitespace()) - currentElementText = xml->text().toString(); - } - return false; -} - -void ProtocolItem::write(QXmlStreamWriter *xml) -{ - xml->writeStartElement(getItemType()); - if (!itemName.isEmpty()) - xml->writeAttribute("name", itemName); - - QMapIterator i(parameters); - while (i.hasNext()) { - i.next(); - xml->writeTextElement(i.key(), i.value()); - } - - writeElement(xml); - - xml->writeEndElement(); -} - -ProtocolItem *ProtocolItem::getNewItem(const QString &name) -{ - if (!itemNameHash.contains(name)) - return 0; - return itemNameHash.value(name)(); -} - void ProtocolItem::initializeHash() { - if (!itemNameHash.isEmpty()) - return; - initializeHashAuto(); - itemNameHash.insert("cmddeck_upload", Command_DeckUpload::newItem); - itemNameHash.insert("cmddeck_select", Command_DeckSelect::newItem); + registerSerializableItem("chat_channel", ServerInfo_ChatChannel::newItem); + registerSerializableItem("chat_user", ServerInfo_ChatUser::newItem); + registerSerializableItem("game", ServerInfo_Game::newItem); + registerSerializableItem("card", ServerInfo_Card::newItem); + registerSerializableItem("zone", ServerInfo_Zone::newItem); + registerSerializableItem("counter", ServerInfo_Counter::newItem); + registerSerializableItem("arrow", ServerInfo_Arrow::newItem); + registerSerializableItem("player", ServerInfo_Player::newItem); + registerSerializableItem("file", DeckList_File::newItem); + registerSerializableItem("directory", DeckList_Directory::newItem); - itemNameHash.insert("resp", ProtocolResponse::newItem); + registerSerializableItem("cmddeck_upload", Command_DeckUpload::newItem); + registerSerializableItem("cmddeck_select", Command_DeckSelect::newItem); + + registerSerializableItem("resp", ProtocolResponse::newItem); ProtocolResponse::initializeHash(); - itemNameHash.insert("respdeck_list", Response_DeckList::newItem); - itemNameHash.insert("respdeck_download", Response_DeckDownload::newItem); - itemNameHash.insert("respdeck_upload", Response_DeckUpload::newItem); + registerSerializableItem("respdeck_list", Response_DeckList::newItem); + registerSerializableItem("respdeck_download", Response_DeckDownload::newItem); + registerSerializableItem("respdeck_upload", Response_DeckUpload::newItem); - itemNameHash.insert("generic_eventlist_games", Event_ListGames::newItem); - itemNameHash.insert("generic_eventlist_chat_channels", Event_ListChatChannels::newItem); - itemNameHash.insert("game_eventgame_state_changed", Event_GameStateChanged::newItem); - itemNameHash.insert("game_eventcreate_arrow", Event_CreateArrow::newItem); - itemNameHash.insert("game_eventcreate_counter", Event_CreateCounter::newItem); - itemNameHash.insert("game_eventdraw_cards", Event_DrawCards::newItem); - itemNameHash.insert("chat_eventchat_list_players", Event_ChatListPlayers::newItem); + registerSerializableItem("generic_eventlist_games", Event_ListGames::newItem); + registerSerializableItem("generic_eventlist_chat_channels", Event_ListChatChannels::newItem); + registerSerializableItem("game_eventgame_state_changed", Event_GameStateChanged::newItem); + registerSerializableItem("game_eventcreate_arrows", Event_CreateArrows::newItem); + registerSerializableItem("game_eventcreate_counters", Event_CreateCounters::newItem); + registerSerializableItem("game_eventdraw_cards", Event_DrawCards::newItem); + registerSerializableItem("chat_eventchat_list_players", Event_ChatListPlayers::newItem); +} + +TopLevelProtocolItem::TopLevelProtocolItem() + : SerializableItem(QString()), currentItem(0) +{ +} + +bool TopLevelProtocolItem::readCurrentItem(QXmlStreamReader *xml) +{ + if (currentItem) { + if (currentItem->read(xml)) { + emit protocolItemReceived(currentItem); + currentItem = 0; + } + return true; + } else + return false; +} + +void TopLevelProtocolItem::readElement(QXmlStreamReader *xml) +{ + if (!readCurrentItem(xml) && (xml->isStartElement())) { + QString childName = xml->name().toString(); + QString childSubType = xml->attributes().value("type").toString(); + + currentItem = dynamic_cast(getNewItem(childName + childSubType)); + if (!currentItem) + currentItem = new ProtocolItem_Invalid; + + readCurrentItem(xml); + } +} + +void TopLevelProtocolItem::writeElement(QXmlStreamWriter * /*xml*/) +{ } int Command::lastCmdId = 0; Command::Command(const QString &_itemName, int _cmdId) - : ProtocolItem(_itemName), cmdId(_cmdId), ticks(0) + : ProtocolItem("cmd", _itemName), ticks(0) { - if (cmdId == -1) - cmdId = lastCmdId++; - setParameter("cmd_id", cmdId); -} - -void Command::extractParameters() -{ - bool ok; - cmdId = parameters["cmd_id"].toInt(&ok); - if (!ok) - cmdId = -1; + if (_cmdId == -1) + _cmdId = lastCmdId++; + insertItem(new SerializableItem_Int("cmd_id", _cmdId)); } void Command::processResponse(ProtocolResponse *response) @@ -108,99 +95,40 @@ void Command::processResponse(ProtocolResponse *response) } Command_DeckUpload::Command_DeckUpload(DeckList *_deck, const QString &_path) - : Command("deck_upload"), deck(_deck), path(_path), readFinished(false) + : Command("deck_upload") { - setParameter("path", path); + insertItem(new SerializableItem_String("path", _path)); + if (!_deck) + _deck = new DeckList; + insertItem(_deck); } -void Command_DeckUpload::extractParameters() +DeckList *Command_DeckUpload::getDeck() const { - Command::extractParameters(); - - path = parameters["path"]; -} - -bool Command_DeckUpload::readElement(QXmlStreamReader *xml) -{ - if (readFinished) - return false; - - if (!deck) { - if (xml->isStartElement() && (xml->name() == "cockatrice_deck")) { - deck = new DeckList; - return true; - } - return false; - } - - if (deck->readElement(xml)) - readFinished = true; - return true; -} - -void Command_DeckUpload::writeElement(QXmlStreamWriter *xml) -{ - if (deck) - deck->writeElement(xml); + return static_cast(itemMap.value("cockatrice_deck")); } Command_DeckSelect::Command_DeckSelect(int _gameId, DeckList *_deck, int _deckId) - : GameCommand("deck_select", _gameId), deck(_deck), deckId(_deckId), readFinished(false) + : GameCommand("deck_select", _gameId) { - setParameter("deck_id", _deckId); + insertItem(new SerializableItem_Int("deck_id", _deckId)); + if (!_deck) + _deck = new DeckList; + insertItem(_deck); } -void Command_DeckSelect::extractParameters() +DeckList *Command_DeckSelect::getDeck() const { - GameCommand::extractParameters(); - - bool ok; - deckId = parameters["deck_id"].toInt(&ok); - if (!ok) - deckId = -1; -} - -bool Command_DeckSelect::readElement(QXmlStreamReader *xml) -{ - if (readFinished) - return false; - - if (!deck) { - if (xml->isStartElement() && (xml->name() == "cockatrice_deck")) { - deck = new DeckList; - return true; - } - return false; - } - - if (deck->readElement(xml)) - readFinished = true; - return true; -} - -void Command_DeckSelect::writeElement(QXmlStreamWriter *xml) -{ - if (deck) - deck->writeElement(xml); + return static_cast(itemMap.value("cockatrice_deck")); } QHash ProtocolResponse::responseHash; ProtocolResponse::ProtocolResponse(int _cmdId, ResponseCode _responseCode, const QString &_itemName) - : ProtocolItem(_itemName), cmdId(_cmdId), responseCode(_responseCode) + : ProtocolItem("resp", _itemName) { - setParameter("cmd_id", cmdId); - setParameter("response_code", responseHash.key(responseCode)); -} - -void ProtocolResponse::extractParameters() -{ - bool ok; - cmdId = parameters["cmd_id"].toInt(&ok); - if (!ok) - cmdId = -1; - - responseCode = responseHash.value(parameters["response_code"], RespOk); + insertItem(new SerializableItem_Int("cmd_id", _cmdId)); + insertItem(new SerializableItem_String("response_code", responseHash.key(_responseCode))); } void ProtocolResponse::initializeHash() @@ -215,359 +143,93 @@ void ProtocolResponse::initializeHash() } Response_DeckList::Response_DeckList(int _cmdId, ResponseCode _responseCode, DeckList_Directory *_root) - : ProtocolResponse(_cmdId, _responseCode, "deck_list"), root(_root), readFinished(false) + : ProtocolResponse(_cmdId, _responseCode, "deck_list") { -} - -Response_DeckList::~Response_DeckList() -{ - delete root; -} - -bool Response_DeckList::readElement(QXmlStreamReader *xml) -{ - if (readFinished) - return false; - - if (!root) { - if (xml->isStartElement() && (xml->name() == "directory")) { - root = new DeckList_Directory; - return true; - } - return false; - } - - if (root->readElement(xml)) - readFinished = true; - return true; -} - -void Response_DeckList::writeElement(QXmlStreamWriter *xml) -{ - root->writeElement(xml); + if (!_root) + _root = new DeckList_Directory; + insertItem(_root); } Response_DeckDownload::Response_DeckDownload(int _cmdId, ResponseCode _responseCode, DeckList *_deck) - : ProtocolResponse(_cmdId, _responseCode, "deck_download"), deck(_deck), readFinished(false) + : ProtocolResponse(_cmdId, _responseCode, "deck_download") { + if (!_deck) + _deck = new DeckList; + insertItem(_deck); } -bool Response_DeckDownload::readElement(QXmlStreamReader *xml) +DeckList *Response_DeckDownload::getDeck() const { - if (readFinished) - return false; - - if (!deck) { - if (xml->isStartElement() && (xml->name() == "cockatrice_deck")) { - deck = new DeckList; - return true; - } - return false; - } - - if (deck->readElement(xml)) - readFinished = true; - return true; -} - -void Response_DeckDownload::writeElement(QXmlStreamWriter *xml) -{ - if (deck) - deck->writeElement(xml); + return static_cast(itemMap.value("cockatrice_deck")); } Response_DeckUpload::Response_DeckUpload(int _cmdId, ResponseCode _responseCode, DeckList_File *_file) - : ProtocolResponse(_cmdId, _responseCode, "deck_upload"), file(_file), readFinished(false) + : ProtocolResponse(_cmdId, _responseCode, "deck_upload") { -} - -Response_DeckUpload::~Response_DeckUpload() -{ - delete file; -} - -bool Response_DeckUpload::readElement(QXmlStreamReader *xml) -{ - if (readFinished) - return false; - - if (!file) { - if (xml->isStartElement() && (xml->name() == "file")) { - file = new DeckList_File(xml->attributes().value("name").toString(), xml->attributes().value("id").toString().toInt(), QDateTime::fromTime_t(xml->attributes().value("upload_time").toString().toUInt())); - return true; - } - return false; - } - - if (file->readElement(xml)) - readFinished = true; - return true; -} - -void Response_DeckUpload::writeElement(QXmlStreamWriter *xml) -{ - if (file) - file->writeElement(xml); -} - -GenericEvent::GenericEvent(const QString &_eventName) - : ProtocolItem(_eventName) -{ -} - -void GameEvent::extractParameters() -{ - bool ok; - gameId = parameters["game_id"].toInt(&ok); - if (!ok) - gameId = -1; - playerId = parameters["player_id"].toInt(&ok); - if (!ok) - playerId = -1; + if (!_file) + _file = new DeckList_File; + insertItem(_file); } GameEvent::GameEvent(const QString &_eventName, int _gameId, int _playerId) - : ProtocolItem(_eventName), gameId(_gameId), playerId(_playerId) + : ProtocolItem("game_event", _eventName) { - setParameter("game_id", gameId); - setParameter("player_id", playerId); -} - -void ChatEvent::extractParameters() -{ - channel = parameters["channel"]; + insertItem(new SerializableItem_Int("game_id", _gameId)); + insertItem(new SerializableItem_Int("player_id", _playerId)); } ChatEvent::ChatEvent(const QString &_eventName, const QString &_channel) - : ProtocolItem(_eventName), channel(_channel) + : ProtocolItem("chat_event", _eventName) { - setParameter("channel", channel); + insertItem(new SerializableItem_String("channel", _channel)); } -bool Event_ListChatChannels::readElement(QXmlStreamReader *xml) +Event_ListChatChannels::Event_ListChatChannels(const QList &_channelList) + : GenericEvent("list_chat_channels") { - if (xml->isStartElement() && (xml->name() == "channel")) { - channelList.append(ServerChatChannelInfo( - xml->attributes().value("name").toString(), - xml->attributes().value("description").toString(), - xml->attributes().value("player_count").toString().toInt(), - xml->attributes().value("auto_join").toString().toInt() - )); - return true; - } - return false; + for (int i = 0; i < _channelList.size(); ++i) + itemList.append(_channelList[i]); } -void Event_ListChatChannels::writeElement(QXmlStreamWriter *xml) +Event_ChatListPlayers::Event_ChatListPlayers(const QString &_channel, const QList &_playerList) + : ChatEvent("chat_list_players", _channel) { - for (int i = 0; i < channelList.size(); ++i) { - xml->writeStartElement("channel"); - xml->writeAttribute("name", channelList[i].getName()); - xml->writeAttribute("description", channelList[i].getDescription()); - xml->writeAttribute("player_count", QString::number(channelList[i].getPlayerCount())); - xml->writeAttribute("auto_join", channelList[i].getAutoJoin() ? "1" : "0"); - xml->writeEndElement(); - } + for (int i = 0; i < _playerList.size(); ++i) + itemList.append(_playerList[i]); } -bool Event_ChatListPlayers::readElement(QXmlStreamReader *xml) +Event_ListGames::Event_ListGames(const QList &_gameList) + : GenericEvent("list_games") { - if (xml->isStartElement() && ((xml->name() == "player"))) { - playerList.append(ServerChatUserInfo( - xml->attributes().value("name").toString() - )); - return true; - } - return false; -} - -void Event_ChatListPlayers::writeElement(QXmlStreamWriter *xml) -{ - for (int i = 0; i < playerList.size(); ++i) { - xml->writeStartElement("player"); - xml->writeAttribute("name", playerList[i].getName()); - xml->writeEndElement(); - } -} - -bool Event_ListGames::readElement(QXmlStreamReader *xml) -{ - if (xml->isStartElement() && (xml->name() == "game")) { - gameList.append(ServerGameInfo( - xml->attributes().value("id").toString().toInt(), - xml->attributes().value("description").toString(), - xml->attributes().value("has_password").toString().toInt(), - xml->attributes().value("player_count").toString().toInt(), - xml->attributes().value("max_players").toString().toInt(), - xml->attributes().value("creator").toString(), - xml->attributes().value("spectators_allowed").toString().toInt(), - xml->attributes().value("spectator_count").toString().toInt() - )); - return true; - } - return false; -} - -void Event_ListGames::writeElement(QXmlStreamWriter *xml) -{ - for (int i = 0; i < gameList.size(); ++i) { - xml->writeStartElement("game"); - xml->writeAttribute("id", QString::number(gameList[i].getGameId())); - xml->writeAttribute("description", gameList[i].getDescription()); - xml->writeAttribute("has_password", gameList[i].getHasPassword() ? "1" : "0"); - xml->writeAttribute("player_count", QString::number(gameList[i].getPlayerCount())); - xml->writeAttribute("max_players", QString::number(gameList[i].getMaxPlayers())); - xml->writeAttribute("creator", gameList[i].getCreatorName()); - xml->writeAttribute("spectators_allowed", gameList[i].getSpectatorsAllowed() ? "1" : "0"); - xml->writeAttribute("spectator_count", QString::number(gameList[i].getSpectatorCount())); - xml->writeEndElement(); - } + for (int i = 0; i < _gameList.size(); ++i) + itemList.append(_gameList[i]); } Event_GameStateChanged::Event_GameStateChanged(int _gameId, const QList &_playerList) - : GameEvent("game_state_changed", _gameId, -1), currentItem(0), playerList(_playerList) + : GameEvent("game_state_changed", _gameId, -1) { + for (int i = 0; i < _playerList.size(); ++i) + itemList.append(_playerList[i]); } -Event_GameStateChanged::~Event_GameStateChanged() +Event_CreateArrows::Event_CreateArrows(int _gameId, int _playerId, const QList &_arrowList) + : GameEvent("create_arrows", _gameId, _playerId) { - for (int i = 0; i < playerList.size(); ++i) - delete playerList[i]; + for (int i = 0; i < _arrowList.size(); ++i) + itemList.append(_arrowList[i]); } -bool Event_GameStateChanged::readElement(QXmlStreamReader *xml) +Event_CreateCounters::Event_CreateCounters(int _gameId, int _playerId, const QList &_counterList) + : GameEvent("create_counters", _gameId, _playerId) { - if (currentItem) { - if (currentItem->readElement(xml)) - currentItem = 0; - return true; - } - if (xml->isStartElement() && (xml->name() == "player")) { - ServerInfo_Player *player = new ServerInfo_Player; - playerList.append(player); - currentItem = player; - } else - return false; - if (currentItem) - if (currentItem->readElement(xml)) - currentItem = 0; - return true; -} - -void Event_GameStateChanged::writeElement(QXmlStreamWriter *xml) -{ - for (int i = 0; i < playerList.size(); ++i) - playerList[i]->writeElement(xml); -} - -Event_CreateArrow::Event_CreateArrow(int _gameId, int _playerId, ServerInfo_Arrow *_arrow) - : GameEvent("create_arrow", _gameId, _playerId), arrow(_arrow), readFinished(false) -{ -} - -Event_CreateArrow::~Event_CreateArrow() -{ - delete arrow; -} - -bool Event_CreateArrow::readElement(QXmlStreamReader *xml) -{ - if (readFinished) - return false; - - if (!arrow) { - if (xml->isStartElement() && (xml->name() == "arrow")) - arrow = new ServerInfo_Arrow; - else - return false; - } - - if (arrow->readElement(xml)) - readFinished = true; - return true; -} - -void Event_CreateArrow::writeElement(QXmlStreamWriter *xml) -{ - if (arrow) - arrow->writeElement(xml); -} - -Event_CreateCounter::Event_CreateCounter(int _gameId, int _playerId, ServerInfo_Counter *_counter) - : GameEvent("create_counter", _gameId, _playerId), counter(_counter), readFinished(false) -{ -} - -Event_CreateCounter::~Event_CreateCounter() -{ - delete counter; -} - -bool Event_CreateCounter::readElement(QXmlStreamReader *xml) -{ - if (readFinished) - return false; - - if (!counter) { - if (xml->isStartElement() && (xml->name() == "counter")) - counter = new ServerInfo_Counter; - else - return false; - } - - if (counter->readElement(xml)) - readFinished = true; - return true; -} - -void Event_CreateCounter::writeElement(QXmlStreamWriter *xml) -{ - if (counter) - counter->writeElement(xml); + for (int i = 0; i < _counterList.size(); ++i) + itemList.append(_counterList[i]); } Event_DrawCards::Event_DrawCards(int _gameId, int _playerId, int _numberCards, const QList &_cardList) - : GameEvent("draw_cards", _gameId, _playerId), currentItem(0), numberCards(_numberCards), cardList(_cardList) + : GameEvent("draw_cards", _gameId, _playerId) { - setParameter("number_cards", numberCards); -} - -Event_DrawCards::~Event_DrawCards() -{ - for (int i = 0; i < cardList.size(); ++i) - delete cardList[i]; -} - -void Event_DrawCards::extractParameters() -{ - GameEvent::extractParameters(); - bool ok; - numberCards = parameters["number_cards"].toInt(&ok); - if (!ok) - numberCards = -1; -} - -bool Event_DrawCards::readElement(QXmlStreamReader *xml) -{ - if (currentItem) { - if (currentItem->readElement(xml)) - currentItem = 0; - return true; - } - if (xml->isStartElement() && (xml->name() == "card")) { - ServerInfo_Card *card = new ServerInfo_Card; - cardList.append(card); - currentItem = card; - } else - return false; - if (currentItem) - if (currentItem->readElement(xml)) - currentItem = 0; - return true; -} - -void Event_DrawCards::writeElement(QXmlStreamWriter *xml) -{ - for (int i = 0; i < cardList.size(); ++i) - cardList[i]->writeElement(xml); + insertItem(new SerializableItem_Int("number_cards", _numberCards)); + for (int i = 0; i < _cardList.size(); ++i) + itemList.append(_cardList[i]); } diff --git a/common/protocol.h b/common/protocol.h index 5825c56c..7cee3fce 100644 --- a/common/protocol.h +++ b/common/protocol.h @@ -23,43 +23,44 @@ enum ItemId { ItemId_Event_ChatListPlayers = ItemId_Other + 201, ItemId_Event_ListGames = ItemId_Other + 202, ItemId_Event_GameStateChanged = ItemId_Other + 203, - ItemId_Event_CreateArrow = ItemId_Other + 204, - ItemId_Event_CreateCounter = ItemId_Other + 205, + ItemId_Event_CreateArrows = ItemId_Other + 204, + ItemId_Event_CreateCounters = ItemId_Other + 205, ItemId_Event_DrawCards = ItemId_Other + 206, ItemId_Response_DeckList = ItemId_Other + 300, ItemId_Response_DeckDownload = ItemId_Other + 301, - ItemId_Response_DeckUpload = ItemId_Other + 302 + ItemId_Response_DeckUpload = ItemId_Other + 302, + ItemId_Invalid = ItemId_Other + 1000 }; -class ProtocolItem : public QObject { +class ProtocolItem : public SerializableItem_Map { Q_OBJECT -private: - QString currentElementText; -protected: - typedef ProtocolItem *(*NewItemFunction)(); - static QHash itemNameHash; - - QString itemName; - QMap parameters; - void setParameter(const QString &name, const QString &value) { parameters[name] = value; } - void setParameter(const QString &name, bool value) { parameters[name] = (value ? "1" : "0"); } - void setParameter(const QString &name, int value) { parameters[name] = QString::number(value); } - void setParameter(const QString &name, const QColor &value) { parameters[name] = QString::number(ColorConverter::colorToInt(value)); } - virtual void extractParameters() { } - virtual QString getItemType() const = 0; - - virtual bool readElement(QXmlStreamReader * /*xml*/) { return false; } - virtual void writeElement(QXmlStreamWriter * /*xml*/) { } private: static void initializeHashAuto(); public: - static const int protocolVersion = 4; - virtual int getItemId() const = 0; - ProtocolItem(const QString &_itemName); + static const int protocolVersion = 5; static void initializeHash(); - static ProtocolItem *getNewItem(const QString &name); - bool read(QXmlStreamReader *xml); - void write(QXmlStreamWriter *xml); + virtual int getItemId() const = 0; + ProtocolItem(const QString &_itemType, const QString &_itemSubType); +}; + +class ProtocolItem_Invalid : public ProtocolItem { +public: + ProtocolItem_Invalid() : ProtocolItem(QString(), QString()) { } + int getItemId() const { return ItemId_Invalid; } +}; + +class TopLevelProtocolItem : public SerializableItem { + Q_OBJECT +signals: + void protocolItemReceived(ProtocolItem *item); +private: + ProtocolItem *currentItem; + bool readCurrentItem(QXmlStreamReader *xml); +protected: + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); +public: + TopLevelProtocolItem(); }; // ---------------- @@ -72,106 +73,59 @@ signals: void finished(ProtocolResponse *response); void finished(ResponseCode response); private: - int cmdId; int ticks; static int lastCmdId; QVariant extraData; -protected: - QString getItemType() const { return "cmd"; } - void extractParameters(); public: Command(const QString &_itemName = QString(), int _cmdId = -1); - int getCmdId() const { return cmdId; } + int getCmdId() const { return static_cast(itemMap.value("cmd_id"))->getData(); } int tick() { return ++ticks; } void processResponse(ProtocolResponse *response); void setExtraData(const QVariant &_extraData) { extraData = _extraData; } QVariant getExtraData() const { return extraData; } }; -class InvalidCommand : public Command { - Q_OBJECT -public: - InvalidCommand() : Command() { } - int getItemId() const { return ItemId_Other; } -}; - class ChatCommand : public Command { Q_OBJECT -private: - QString channel; -protected: - void extractParameters() - { - Command::extractParameters(); - channel = parameters["channel"]; - } public: ChatCommand(const QString &_cmdName, const QString &_channel) - : Command(_cmdName), channel(_channel) + : Command(_cmdName) { - setParameter("channel", channel); + insertItem(new SerializableItem_String("channel", _channel)); } - QString getChannel() const { return channel; } + QString getChannel() const { return static_cast(itemMap.value("channel"))->getData(); } }; class GameCommand : public Command { Q_OBJECT -private: - int gameId; -protected: - void extractParameters() - { - Command::extractParameters(); - gameId = parameters["game_id"].toInt(); - } public: GameCommand(const QString &_cmdName, int _gameId) - : Command(_cmdName), gameId(_gameId) + : Command(_cmdName) { - setParameter("game_id", gameId); - } - int getGameId() const { return gameId; } - void setGameId(int _gameId) - { - gameId = _gameId; - setParameter("game_id", gameId); + insertItem(new SerializableItem_Int("game_id", _gameId)); } + int getGameId() const { return static_cast(itemMap.value("game_id"))->getData(); } + void setGameId(int _gameId) { static_cast(itemMap.value("game_id"))->setData(_gameId); } }; class Command_DeckUpload : public Command { Q_OBJECT -private: - DeckList *deck; - QString path; - bool readFinished; -protected: - void extractParameters(); - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: Command_DeckUpload(DeckList *_deck = 0, const QString &_path = QString()); - static ProtocolItem *newItem() { return new Command_DeckUpload; } + static SerializableItem *newItem() { return new Command_DeckUpload; } int getItemId() const { return ItemId_Command_DeckUpload; } - DeckList *getDeck() const { return deck; } - QString getPath() const { return path; } + DeckList *getDeck() const; + QString getPath() const { return static_cast(itemMap.value("path"))->getData(); } }; class Command_DeckSelect : public GameCommand { Q_OBJECT -private: - DeckList *deck; - int deckId; - bool readFinished; -protected: - void extractParameters(); - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: Command_DeckSelect(int _gameId = -1, DeckList *_deck = 0, int _deckId = -1); - static ProtocolItem *newItem() { return new Command_DeckSelect; } + static SerializableItem *newItem() { return new Command_DeckSelect; } int getItemId() const { return ItemId_Command_DeckSelect; } - DeckList *getDeck() const { return deck; } - int getDeckId() const { return deckId; } + DeckList *getDeck() const; + int getDeckId() const { return static_cast(itemMap.value("deck_id"))->getData(); } }; // ----------------- @@ -181,66 +135,41 @@ public: class ProtocolResponse : public ProtocolItem { Q_OBJECT private: - int cmdId; - ResponseCode responseCode; static QHash responseHash; -protected: - QString getItemType() const { return "resp"; } - void extractParameters(); public: ProtocolResponse(int _cmdId = -1, ResponseCode _responseCode = RespOk, const QString &_itemName = QString()); int getItemId() const { return ItemId_Other; } static void initializeHash(); - static ProtocolItem *newItem() { return new ProtocolResponse; } - int getCmdId() const { return cmdId; } - ResponseCode getResponseCode() const { return responseCode; } + static SerializableItem *newItem() { return new ProtocolResponse; } + int getCmdId() const { return static_cast(itemMap.value("cmd_id"))->getData(); } + ResponseCode getResponseCode() const { return responseHash.value(static_cast(itemMap.value("response_code"))->getData(), RespOk); } }; class Response_DeckList : public ProtocolResponse { Q_OBJECT -private: - DeckList_Directory *root; - bool readFinished; -protected: - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: Response_DeckList(int _cmdId = -1, ResponseCode _responseCode = RespOk, DeckList_Directory *_root = 0); - ~Response_DeckList(); int getItemId() const { return ItemId_Response_DeckList; } - static ProtocolItem *newItem() { return new Response_DeckList; } - DeckList_Directory *getRoot() const { return root; } + static SerializableItem *newItem() { return new Response_DeckList; } + DeckList_Directory *getRoot() const { return static_cast(itemMap.value("directory")); } }; class Response_DeckDownload : public ProtocolResponse { Q_OBJECT -private: - DeckList *deck; - bool readFinished; -protected: - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: Response_DeckDownload(int _cmdId = -1, ResponseCode _responseCode = RespOk, DeckList *_deck = 0); int getItemId() const { return ItemId_Response_DeckDownload; } - static ProtocolItem *newItem() { return new Response_DeckDownload; } - DeckList *getDeck() const { return deck; } + static SerializableItem *newItem() { return new Response_DeckDownload; } + DeckList *getDeck() const; }; class Response_DeckUpload : public ProtocolResponse { Q_OBJECT -private: - DeckList_File *file; - bool readFinished; -protected: - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: Response_DeckUpload(int _cmdId = -1, ResponseCode _responseCode = RespOk, DeckList_File *_file = 0); - ~Response_DeckUpload(); int getItemId() const { return ItemId_Response_DeckUpload; } - static ProtocolItem *newItem() { return new Response_DeckUpload; } - DeckList_File *getFile() const { return file; } + static SerializableItem *newItem() { return new Response_DeckUpload; } + DeckList_File *getFile() const { return static_cast(itemMap.value("file")); } }; // -------------- @@ -249,162 +178,89 @@ public: class GenericEvent : public ProtocolItem { Q_OBJECT -protected: - QString getItemType() const { return "generic_event"; } public: - GenericEvent(const QString &_eventName); + GenericEvent(const QString &_eventName) + : ProtocolItem("generic_event", _eventName) { } }; class GameEvent : public ProtocolItem { Q_OBJECT -private: - int gameId; - int playerId; -protected: - QString getItemType() const { return "game_event"; } - void extractParameters(); public: GameEvent(const QString &_eventName, int _gameId, int _playerId); - int getGameId() const { return gameId; } - int getPlayerId() const { return playerId; } - void setGameId(int _gameId) - { - gameId = _gameId; - setParameter("game_id", gameId); - } + int getGameId() const { return static_cast(itemMap.value("game_id"))->getData(); } + int getPlayerId() const { return static_cast(itemMap.value("player_id"))->getData(); } + void setGameId(int _gameId) { static_cast(itemMap.value("game_id"))->setData(_gameId); } }; class ChatEvent : public ProtocolItem { Q_OBJECT -private: - QString channel; -protected: - QString getItemType() const { return "chat_event"; } - void extractParameters(); public: ChatEvent(const QString &_eventName, const QString &_channel); - QString getChannel() const { return channel; } + QString getChannel() const { return static_cast(itemMap.value("channel"))->getData(); } }; class Event_ListChatChannels : public GenericEvent { Q_OBJECT -private: - QList channelList; public: - Event_ListChatChannels() : GenericEvent("list_chat_channels") { } + Event_ListChatChannels(const QList &_channelList = QList()); int getItemId() const { return ItemId_Event_ListChatChannels; } - static ProtocolItem *newItem() { return new Event_ListChatChannels; } - void addChannel(const QString &_name, const QString &_description, int _playerCount, bool _autoJoin) - { - channelList.append(ServerChatChannelInfo(_name, _description, _playerCount, _autoJoin)); - } - const QList &getChannelList() const { return channelList; } - - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); + static SerializableItem *newItem() { return new Event_ListChatChannels; } + QList getChannelList() const { return typecastItemList(); } }; class Event_ChatListPlayers : public ChatEvent { Q_OBJECT -private: - QList playerList; public: - Event_ChatListPlayers(const QString &_channel = QString()) : ChatEvent("chat_list_players", _channel) { } + Event_ChatListPlayers(const QString &_channel = QString(), const QList &_playerList = QList()); int getItemId() const { return ItemId_Event_ChatListPlayers; } - static ProtocolItem *newItem() { return new Event_ChatListPlayers; } - void addPlayer(const QString &_name) - { - playerList.append(ServerChatUserInfo(_name)); - } - const QList &getPlayerList() const { return playerList; } - - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); + static SerializableItem *newItem() { return new Event_ChatListPlayers; } + QList getPlayerList() const { return typecastItemList(); } }; class Event_ListGames : public GenericEvent { Q_OBJECT -private: - QList gameList; public: - Event_ListGames() : GenericEvent("list_games") { } + Event_ListGames(const QList &_gameList = QList()); int getItemId() const { return ItemId_Event_ListGames; } - static ProtocolItem *newItem() { return new Event_ListGames; } - void addGame(int _gameId, const QString &_description, bool _hasPassword, int _playerCount, int _maxPlayers, const QString &_creatorName, bool _spectatorsAllowed, int _spectatorCount) - { - gameList.append(ServerGameInfo(_gameId, _description, _hasPassword, _playerCount, _maxPlayers, _creatorName, _spectatorsAllowed, _spectatorCount)); - } - const QList &getGameList() const { return gameList; } - - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); + static SerializableItem *newItem() { return new Event_ListGames; } + QList getGameList() const { return typecastItemList(); } }; class Event_GameStateChanged : public GameEvent { Q_OBJECT -private: - SerializableItem *currentItem; - QList playerList; public: Event_GameStateChanged(int _gameId = -1, const QList &_playerList = QList()); - ~Event_GameStateChanged(); - const QList &getPlayerList() const { return playerList; } - static ProtocolItem *newItem() { return new Event_GameStateChanged; } + static SerializableItem *newItem() { return new Event_GameStateChanged; } int getItemId() const { return ItemId_Event_GameStateChanged; } - - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); + QList getPlayerList() const { return typecastItemList(); } }; -class Event_CreateArrow : public GameEvent { +class Event_CreateArrows : public GameEvent { Q_OBJECT -private: - ServerInfo_Arrow *arrow; - bool readFinished; -protected: - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: - Event_CreateArrow(int _gameId = -1, int _playerId = -1, ServerInfo_Arrow *_arrow = 0); - ~Event_CreateArrow(); - int getItemId() const { return ItemId_Event_CreateArrow; } - static ProtocolItem *newItem() { return new Event_CreateArrow; } - ServerInfo_Arrow *getArrow() const { return arrow; } + Event_CreateArrows(int _gameId = -1, int _playerId = -1, const QList &_arrowList = QList()); + int getItemId() const { return ItemId_Event_CreateArrows; } + static SerializableItem *newItem() { return new Event_CreateArrows; } + QList getArrowList() const { return typecastItemList(); } }; -class Event_CreateCounter : public GameEvent { +class Event_CreateCounters : public GameEvent { Q_OBJECT -private: - ServerInfo_Counter *counter; - bool readFinished; -protected: - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: - Event_CreateCounter(int _gameId = -1, int _playerId = -1, ServerInfo_Counter *_counter = 0); - ~Event_CreateCounter(); - int getItemId() const { return ItemId_Event_CreateCounter; } - static ProtocolItem *newItem() { return new Event_CreateCounter; } - ServerInfo_Counter *getCounter() const { return counter; } + Event_CreateCounters(int _gameId = -1, int _playerId = -1, const QList &_counterList = QList()); + int getItemId() const { return ItemId_Event_CreateCounters; } + static SerializableItem *newItem() { return new Event_CreateCounters; } + QList getCounterList() const { return typecastItemList(); } }; class Event_DrawCards : public GameEvent { Q_OBJECT -private: - SerializableItem *currentItem; - int numberCards; - QList cardList; -protected: - void extractParameters(); - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); public: Event_DrawCards(int _gameId = -1, int _playerId = -1, int numberCards = -1, const QList &_cardList = QList()); - ~Event_DrawCards(); int getItemId() const { return ItemId_Event_DrawCards; } - static ProtocolItem *newItem() { return new Event_DrawCards; } - int getNumberCards() const { return numberCards; } - const QList &getCardList() const { return cardList; } + static SerializableItem *newItem() { return new Event_DrawCards; } + int getNumberCards() const { return static_cast(itemMap.value("number_cards"))->getData(); } + QList getCardList() const { return typecastItemList(); } }; #endif diff --git a/common/protocol_datastructures.cpp b/common/protocol_datastructures.cpp index cf7451fa..3df331c1 100644 --- a/common/protocol_datastructures.cpp +++ b/common/protocol_datastructures.cpp @@ -2,244 +2,154 @@ #include #include -ServerInfo_Player::~ServerInfo_Player() +ServerInfo_ChatChannel::ServerInfo_ChatChannel(const QString &_name, const QString &_description, int _playerCount, bool _autoJoin) + : SerializableItem_Map("chat_channel") { - for (int i = 0; i < zoneList.size(); ++i) - delete zoneList[i]; - for (int i = 0; i < arrowList.size(); ++i) - delete arrowList[i]; - for (int i = 0; i < counterList.size(); ++i) - delete counterList[i]; + insertItem(new SerializableItem_String("name", _name)); + insertItem(new SerializableItem_String("description", _description)); + insertItem(new SerializableItem_Int("player_count", _playerCount)); + insertItem(new SerializableItem_Bool("auto_join", _autoJoin)); } -ServerInfo_Zone::~ServerInfo_Zone() +ServerInfo_ChatUser::ServerInfo_ChatUser(const QString &_name) + : SerializableItem_Map("chat_user") { - for (int i = 0; i < cardList.size(); ++i) - delete cardList[i]; + insertItem(new SerializableItem_String("name", _name)); } -bool ServerInfo_Arrow::readElement(QXmlStreamReader *xml) +ServerInfo_Game::ServerInfo_Game(int _gameId, const QString &_description, bool _hasPassword, int _playerCount, int _maxPlayers, const QString &_creatorName, bool _spectatorsAllowed, int _spectatorCount) + : SerializableItem_Map("game") { - if (xml->isStartElement() && (xml->name() == "arrow")) { - id = xml->attributes().value("id").toString().toInt(); - startPlayerId = xml->attributes().value("start_player_id").toString().toInt(); - startZone = xml->attributes().value("start_zone").toString(); - startCardId = xml->attributes().value("start_card_id").toString().toInt(); - targetPlayerId = xml->attributes().value("target_player_id").toString().toInt(); - targetZone = xml->attributes().value("target_zone").toString(); - targetCardId = xml->attributes().value("target_card_id").toString().toInt(); - color = ColorConverter::colorFromInt(xml->attributes().value("color").toString().toInt()); - } else if (xml->isEndElement() && (xml->name() == "arrow")) - return true; - return false; + insertItem(new SerializableItem_Int("game_id", _gameId)); + insertItem(new SerializableItem_String("description", _description)); + insertItem(new SerializableItem_Bool("has_password", _hasPassword)); + insertItem(new SerializableItem_Int("player_count", _playerCount)); + insertItem(new SerializableItem_Int("max_players", _maxPlayers)); + insertItem(new SerializableItem_String("creator_name", _creatorName)); + insertItem(new SerializableItem_Bool("spectators_allowed", _spectatorsAllowed)); + insertItem(new SerializableItem_Int("spectator_count", _spectatorCount)); } -void ServerInfo_Arrow::writeElement(QXmlStreamWriter *xml) +ServerInfo_Card::ServerInfo_Card(int _id, const QString &_name, int _x, int _y, int _counters, bool _tapped, bool _attacking, const QString &_annotation) + : SerializableItem_Map("card") { - xml->writeStartElement("arrow"); - xml->writeAttribute("id", QString::number(id)); - xml->writeAttribute("start_player_id", QString::number(startPlayerId)); - xml->writeAttribute("start_zone", startZone); - xml->writeAttribute("start_card_id", QString::number(startCardId)); - xml->writeAttribute("target_player_id", QString::number(targetPlayerId)); - xml->writeAttribute("target_zone", targetZone); - xml->writeAttribute("target_card_id", QString::number(targetCardId)); - xml->writeAttribute("color", QString::number(ColorConverter::colorToInt(color))); - xml->writeEndElement(); + insertItem(new SerializableItem_Int("id", _id)); + insertItem(new SerializableItem_String("name", _name)); + insertItem(new SerializableItem_Int("x", _x)); + insertItem(new SerializableItem_Int("y", _y)); + insertItem(new SerializableItem_Int("counters", _counters)); + insertItem(new SerializableItem_Bool("tapped", _tapped)); + insertItem(new SerializableItem_Bool("attacking", _attacking)); + insertItem(new SerializableItem_String("annotation", _annotation)); } -bool ServerInfo_Counter::readElement(QXmlStreamReader *xml) +ServerInfo_Zone::ServerInfo_Zone(const QString &_name, ZoneType _type, bool _hasCoords, int _cardCount, const QList &_cardList) + : SerializableItem_Map("zone") { - if (xml->isStartElement() && (xml->name() == "counter")) { - id = xml->attributes().value("id").toString().toInt(); - name = xml->attributes().value("name").toString(); - color = ColorConverter::colorFromInt(xml->attributes().value("color").toString().toInt()); - radius = xml->attributes().value("radius").toString().toInt(); - count = xml->attributes().value("count").toString().toInt(); - } else if (xml->isEndElement() && (xml->name() == "counter")) - return true; - return false; + insertItem(new SerializableItem_String("name", _name)); + insertItem(new SerializableItem_String("zone_type", typeToString(_type))); + insertItem(new SerializableItem_Bool("has_coords", _hasCoords)); + insertItem(new SerializableItem_Int("card_count", _cardCount)); + + for (int i = 0; i < _cardList.size(); ++i) + itemList.append(_cardList[i]); } -void ServerInfo_Counter::writeElement(QXmlStreamWriter *xml) +ZoneType ServerInfo_Zone::typeFromString(const QString &type) const { - xml->writeStartElement("counter"); - xml->writeAttribute("id", QString::number(id)); - xml->writeAttribute("name", name); - xml->writeAttribute("color", QString::number(ColorConverter::colorToInt(color))); - xml->writeAttribute("radius", QString::number(radius)); - xml->writeAttribute("count", QString::number(count)); - xml->writeEndElement(); + if (type == "private") + return PrivateZone; + else if (type == "hidden") + return HiddenZone; + return PublicZone; } -bool ServerInfo_Card::readElement(QXmlStreamReader *xml) +QString ServerInfo_Zone::typeToString(ZoneType type) const { - if (xml->isStartElement() && (xml->name() == "card")) { - id = xml->attributes().value("id").toString().toInt(); - name = xml->attributes().value("name").toString(); - x = xml->attributes().value("x").toString().toInt(); - y = xml->attributes().value("y").toString().toInt(); - counters = xml->attributes().value("counters").toString().toInt(); - tapped = xml->attributes().value("tapped").toString().toInt(); - attacking = xml->attributes().value("attacking").toString().toInt(); - annotation = xml->attributes().value("annotation").toString(); - } else if (xml->isEndElement() && (xml->name() == "card")) - return true; - return false; -} - -void ServerInfo_Card::writeElement(QXmlStreamWriter *xml) -{ - xml->writeStartElement("card"); - xml->writeAttribute("id", QString::number(id)); - xml->writeAttribute("name", name); - xml->writeAttribute("x", QString::number(x)); - xml->writeAttribute("y", QString::number(y)); - xml->writeAttribute("counters", QString::number(counters)); - xml->writeAttribute("tapped", tapped ? "1" : "0"); - xml->writeAttribute("attacking", attacking ? "1" : "0"); - xml->writeAttribute("annotation", annotation); - xml->writeEndElement(); -} - -bool ServerInfo_Zone::readElement(QXmlStreamReader *xml) -{ - if (currentItem) { - if (currentItem->readElement(xml)) - currentItem = 0; - return false; - } - if (xml->isStartElement() && (xml->name() == "zone")) { - name = xml->attributes().value("name").toString(); - type = (ZoneType) xml->attributes().value("type").toString().toInt(); - hasCoords = xml->attributes().value("has_coords").toString().toInt(); - cardCount = xml->attributes().value("card_count").toString().toInt(); - } else if (xml->isStartElement() && (xml->name() == "card")) { - ServerInfo_Card *card = new ServerInfo_Card; - cardList.append(card); - currentItem = card; - } else if (xml->isEndElement() && (xml->name() == "zone")) - return true; - - if (currentItem) - if (currentItem->readElement(xml)) - currentItem = 0; - return false; - -} - -void ServerInfo_Zone::writeElement(QXmlStreamWriter *xml) -{ - xml->writeStartElement("zone"); - xml->writeAttribute("name", name); - QString typeStr; switch (type) { - case PrivateZone: typeStr = "private"; break; - case HiddenZone: typeStr = "hidden"; break; - case PublicZone: typeStr = "public"; break; + case PrivateZone: return "private"; + case HiddenZone: return "hidden"; + default: return "public"; } - xml->writeAttribute("type", typeStr); - xml->writeAttribute("has_coords", hasCoords ? "1" : "0"); - xml->writeAttribute("card_count", QString::number(cardCount)); - for (int i = 0; i < cardList.size(); ++i) - cardList[i]->writeElement(xml); - xml->writeEndElement(); } -bool ServerInfo_Player::readElement(QXmlStreamReader *xml) +QList ServerInfo_Zone::getCardList() const { - if (currentItem) { - if (currentItem->readElement(xml)) - currentItem = 0; - return false; + QList result; + for (int i = 0; i < itemList.size(); ++i) { + ServerInfo_Card *card = dynamic_cast(itemList[i]); + if (card) + result.append(card); } - if (xml->isStartElement() && (xml->name() == "player")) { - playerId = xml->attributes().value("player_id").toString().toInt(); - name = xml->attributes().value("name").toString(); - } else if (xml->isStartElement() && (xml->name() == "zone")) { - ServerInfo_Zone *zone = new ServerInfo_Zone; - zoneList.append(zone); - currentItem = zone; - } else if (xml->isStartElement() && (xml->name() == "counter")) { - ServerInfo_Counter *counter = new ServerInfo_Counter; - counterList.append(counter); - currentItem = counter; - } else if (xml->isStartElement() && (xml->name() == "arrow")) { - ServerInfo_Arrow *arrow = new ServerInfo_Arrow; - arrowList.append(arrow); - currentItem = arrow; - } else if (xml->isEndElement() && (xml->name() == "player")) - return true; - - if (currentItem) - if (currentItem->readElement(xml)) - currentItem = 0; - return false; + return result; } -void ServerInfo_Player::writeElement(QXmlStreamWriter *xml) +ServerInfo_Counter::ServerInfo_Counter(int _id, const QString &_name, const QColor &_color, int _radius, int _count) + : SerializableItem_Map("counter") { - xml->writeStartElement("player"); - xml->writeAttribute("player_id", QString::number(playerId)); - xml->writeAttribute("name", name); - for (int i = 0; i < zoneList.size(); ++i) - zoneList[i]->writeElement(xml); - for (int i = 0; i < counterList.size(); ++i) - counterList[i]->writeElement(xml); - for (int i = 0; i < arrowList.size(); ++i) - arrowList[i]->writeElement(xml); - xml->writeEndElement(); + insertItem(new SerializableItem_Int("id", _id)); + insertItem(new SerializableItem_String("name", _name)); + insertItem(new SerializableItem_Color("color", _color)); + insertItem(new SerializableItem_Int("radius", _radius)); + insertItem(new SerializableItem_Int("count", _count)); } -bool DeckList_File::readElement(QXmlStreamReader *xml) +ServerInfo_Arrow::ServerInfo_Arrow(int _id, int _startPlayerId, const QString &_startZone, int _startCardId, int _targetPlayerId, const QString &_targetZone, int _targetCardId, const QColor &_color) + : SerializableItem_Map("arrow") { - if (xml->isEndElement()) - return true; - else - return false; + insertItem(new SerializableItem_Int("id", _id)); + insertItem(new SerializableItem_Int("start_player_id", _startPlayerId)); + insertItem(new SerializableItem_String("start_zone", _startZone)); + insertItem(new SerializableItem_Int("start_card_id", _startCardId)); + insertItem(new SerializableItem_Int("target_player_id", _targetPlayerId)); + insertItem(new SerializableItem_String("target_zone", _targetZone)); + insertItem(new SerializableItem_Int("target_card_id", _targetCardId)); + insertItem(new SerializableItem_Color("color", _color)); } -void DeckList_File::writeElement(QXmlStreamWriter *xml) +ServerInfo_Player::ServerInfo_Player(int _playerId, const QString &_name, const QList &_zoneList, const QList &_counterList, const QList &_arrowList) + : SerializableItem_Map("player"), zoneList(_zoneList), counterList(_counterList), arrowList(_arrowList) { - xml->writeStartElement("file"); - xml->writeAttribute("name", name); - xml->writeAttribute("id", QString::number(id)); - xml->writeAttribute("upload_time", QString::number(uploadTime.toTime_t())); - xml->writeEndElement(); + insertItem(new SerializableItem_Int("player_id", _playerId)); + insertItem(new SerializableItem_String("name", _name)); + + for (int i = 0; i < _zoneList.size(); ++i) + itemList.append(_zoneList[i]); + for (int i = 0; i < _counterList.size(); ++i) + itemList.append(_counterList[i]); + for (int i = 0; i < _arrowList.size(); ++i) + itemList.append(_arrowList[i]); } -DeckList_Directory::~DeckList_Directory() +void ServerInfo_Player::extractData() { - for (int i = 0; i < size(); ++i) - delete at(i); -} - -bool DeckList_Directory::readElement(QXmlStreamReader *xml) -{ - if (currentItem) { - if (currentItem->readElement(xml)) - currentItem = 0; - return false; + for (int i = 0; i < itemList.size(); ++i) { + ServerInfo_Zone *zone = dynamic_cast(itemList[i]); + ServerInfo_Counter *counter = dynamic_cast(itemList[i]); + ServerInfo_Arrow *arrow = dynamic_cast(itemList[i]); + if (zone) + zoneList.append(zone); + else if (counter) + counterList.append(counter); + else if (arrow) + arrowList.append(arrow); } - if (xml->isStartElement() && (xml->name() == "directory")) { - DeckList_Directory *newItem = new DeckList_Directory(xml->attributes().value("name").toString()); - append(newItem); - currentItem = newItem; - } else if (xml->isStartElement() && (xml->name() == "file")) { - DeckList_File *newItem = new DeckList_File(xml->attributes().value("name").toString(), xml->attributes().value("id").toString().toInt(), QDateTime::fromTime_t(xml->attributes().value("upload_time").toString().toUInt())); - append(newItem); - currentItem = newItem; - } else if (xml->isEndElement() && (xml->name() == "directory")) - return true; - - return false; } -void DeckList_Directory::writeElement(QXmlStreamWriter *xml) +DeckList_TreeItem::DeckList_TreeItem(const QString &_itemType, const QString &_name, int _id) + : SerializableItem_Map(_itemType) +{ + insertItem(new SerializableItem_String("name", _name)); + insertItem(new SerializableItem_Int("id", _id)); +} + +DeckList_File::DeckList_File(const QString &_name, int _id, QDateTime _uploadTime) + : DeckList_TreeItem("file", _name, _id) +{ + insertItem(new SerializableItem_DateTime("upload_time", _uploadTime)); +} + +DeckList_Directory::DeckList_Directory(const QString &_name, int _id) + : DeckList_TreeItem("directory", _name, _id) { - xml->writeStartElement("directory"); - xml->writeAttribute("name", name); - for (int i = 0; i < size(); ++i) - at(i)->writeElement(xml); - xml->writeEndElement(); } diff --git a/common/protocol_datastructures.h b/common/protocol_datastructures.h index 32fda8b4..bf9d234a 100644 --- a/common/protocol_datastructures.h +++ b/common/protocol_datastructures.h @@ -4,9 +4,7 @@ #include #include #include - -class QXmlStreamReader; -class QXmlStreamWriter; +#include "serializable_item.h" enum ResponseCode { RespNothing, RespOk, RespInvalidCommand, RespInvalidData, RespNameNotFound, RespLoginNeeded, RespContextError, RespWrongPassword, RespSpectatorsNotAllowed }; @@ -20,210 +18,124 @@ enum ResponseCode { RespNothing, RespOk, RespInvalidCommand, RespInvalidData, Re // list index, whereas cards in any other zone are referenced by their ids. enum ZoneType { PrivateZone, PublicZone, HiddenZone }; -class ColorConverter { +class ServerInfo_ChatChannel : public SerializableItem_Map { public: - static int colorToInt(const QColor &color) - { - return color.red() * 65536 + color.green() * 256 + color.blue(); - } - static QColor colorFromInt(int colorValue) - { - return QColor(colorValue / 65536, (colorValue % 65536) / 256, colorValue % 256); - } + ServerInfo_ChatChannel(const QString &_name = QString(), const QString &_description = QString(), int _playerCount = -1, bool _autoJoin = false); + static SerializableItem *newItem() { return new ServerInfo_ChatChannel; } + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } + QString getDescription() const { return static_cast(itemMap.value("description"))->getData(); } + int getPlayerCount() const { return static_cast(itemMap.value("player_count"))->getData(); } + bool getAutoJoin() const { return static_cast(itemMap.value("auto_join"))->getData(); } }; -class SerializableItem { -protected: - SerializableItem *currentItem; +class ServerInfo_ChatUser : public SerializableItem_Map { public: - SerializableItem() : currentItem(0) { } - virtual bool readElement(QXmlStreamReader *xml) = 0; - virtual void writeElement(QXmlStreamWriter *xml) = 0; + ServerInfo_ChatUser(const QString &_name = QString()); + static SerializableItem *newItem() { return new ServerInfo_ChatUser; } + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } }; -class ServerChatChannelInfo { +class ServerInfo_Game : public SerializableItem_Map { +public: + ServerInfo_Game(int _gameId = -1, const QString &_description = QString(), bool _hasPassword = false, int _playerCount = -1, int _maxPlayers = -1, const QString &_creatorName = QString(), bool _spectatorsAllowed = false, int _spectatorCount = -1); + static SerializableItem *newItem() { return new ServerInfo_Game; } + int getGameId() const { return static_cast(itemMap.value("game_id"))->getData(); } + QString getDescription() const { return static_cast(itemMap.value("description"))->getData(); } + bool getHasPassword() const { return static_cast(itemMap.value("has_password"))->getData(); } + int getPlayerCount() const { return static_cast(itemMap.value("player_count"))->getData(); } + int getMaxPlayers() const { return static_cast(itemMap.value("max_players"))->getData(); } + QString getCreatorName() const { return static_cast(itemMap.value("creator_name"))->getData(); } + bool getSpectatorsAllowed() const { return static_cast(itemMap.value("spectators_allowed"))->getData(); } + int getSpectatorCount() const { return static_cast(itemMap.value("spectator_count"))->getData(); } +}; + +class ServerInfo_Card : public SerializableItem_Map { +public: + ServerInfo_Card(int _id = -1, const QString &_name = QString(), int _x = -1, int _y = -1, int _counters = -1, bool _tapped = false, bool _attacking = false, const QString &_annotation = QString()); + static SerializableItem *newItem() { return new ServerInfo_Card; } + int getId() const { return static_cast(itemMap.value("id"))->getData(); } + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } + int getX() const { return static_cast(itemMap.value("x"))->getData(); } + int getY() const { return static_cast(itemMap.value("y"))->getData(); } + int getCounters() const { return static_cast(itemMap.value("counters"))->getData(); } + bool getTapped() const { return static_cast(itemMap.value("tapped"))->getData(); } + bool getAttacking() const { return static_cast(itemMap.value("attacking"))->getData(); } + QString getAnnotation() const { return static_cast(itemMap.value("annotation"))->getData(); } +}; + +class ServerInfo_Zone : public SerializableItem_Map { private: - QString name; - QString description; - int playerCount; - bool autoJoin; + ZoneType typeFromString(const QString &type) const; + QString typeToString(ZoneType type) const; public: - ServerChatChannelInfo(const QString &_name, const QString &_description, int _playerCount, bool _autoJoin) - : name(_name), description(_description), playerCount(_playerCount), autoJoin(_autoJoin) { } - QString getName() const { return name; } - QString getDescription() const { return description; } - int getPlayerCount() const { return playerCount; } - bool getAutoJoin() const { return autoJoin; } + ServerInfo_Zone(const QString &_name = QString(), ZoneType _type = PrivateZone, bool _hasCoords = false, int _cardCount = -1, const QList &_cardList = QList()); + static SerializableItem *newItem() { return new ServerInfo_Zone; } + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } + ZoneType getType() const { return typeFromString(static_cast(itemMap.value("type"))->getData()); } + bool getHasCoords() const { return static_cast(itemMap.value("has_coords"))->getData(); } + int getCardCount() const { return static_cast(itemMap.value("card_count"))->getData(); } + QList getCardList() const; }; -class ServerChatUserInfo { -private: - QString name; +class ServerInfo_Counter : public SerializableItem_Map { public: - ServerChatUserInfo(const QString &_name) - : name(_name) { } - QString getName() const { return name; } + ServerInfo_Counter(int _id = -1, const QString &_name = QString(), const QColor &_color = QColor(), int _radius = -1, int _count = -1); + static SerializableItem *newItem() { return new ServerInfo_Counter; } + int getId() const { return static_cast(itemMap.value("id"))->getData(); } + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } + QColor getColor() const { return static_cast(itemMap.value("color"))->getData(); } + int getRadius() const { return static_cast(itemMap.value("radius"))->getData(); } + int getCount() const { return static_cast(itemMap.value("count"))->getData(); } }; -class ServerGameInfo { -private: - int gameId; - QString description; - bool hasPassword; - int playerCount; - int maxPlayers; - QString creatorName; - bool spectatorsAllowed; - int spectatorCount; +class ServerInfo_Arrow : public SerializableItem_Map { public: - ServerGameInfo(int _gameId, const QString &_description, bool _hasPassword, int _playerCount, int _maxPlayers, const QString &_creatorName, bool _spectatorsAllowed, int _spectatorCount) - : gameId(_gameId), description(_description), hasPassword(_hasPassword), playerCount(_playerCount), maxPlayers(_maxPlayers), creatorName(_creatorName), spectatorsAllowed(_spectatorsAllowed), spectatorCount(_spectatorCount) { } - int getGameId() const { return gameId; } - QString getDescription() const { return description; } - bool getHasPassword() const { return hasPassword; } - int getPlayerCount() const { return playerCount; } - int getMaxPlayers() const { return maxPlayers; } - QString getCreatorName() const { return creatorName; } - bool getSpectatorsAllowed() const { return spectatorsAllowed; } - int getSpectatorCount() const { return spectatorCount; } + ServerInfo_Arrow(int _id = -1, int _startPlayerId = -1, const QString &_startZone = QString(), int _startCardId = -1, int _targetPlayerId = -1, const QString &_targetZone = QString(), int _targetCardId = -1, const QColor &_color = QColor()); + static SerializableItem *newItem() { return new ServerInfo_Arrow; } + int getId() const { return static_cast(itemMap.value("id"))->getData(); } + int getStartPlayerId() const { return static_cast(itemMap.value("start_player_id"))->getData(); } + QString getStartZone() const { return static_cast(itemMap.value("start_zone"))->getData(); } + int getStartCardId() const { return static_cast(itemMap.value("start_card_id"))->getData(); } + int getTargetPlayerId() const { return static_cast(itemMap.value("target_player_id"))->getData(); } + QString getTargetZone() const { return static_cast(itemMap.value("target_zone"))->getData(); } + int getTargetCardId() const { return static_cast(itemMap.value("target_card_id"))->getData(); } + QColor getColor() const { return static_cast(itemMap.value("color"))->getData(); } }; -class ServerInfo_Card : public SerializableItem { +class ServerInfo_Player : public SerializableItem_Map { private: - int id; - QString name; - int x, y; - int counters; - bool tapped; - bool attacking; - QString annotation; -public: - ServerInfo_Card(int _id = -1, const QString &_name = QString(), int _x = -1, int _y = -1, int _counters = -1, bool _tapped = false, bool _attacking = false, const QString &_annotation = QString()) - : id(_id), name(_name), x(_x), y(_y), counters(_counters), tapped(_tapped), attacking(_attacking), annotation(_annotation) { } - int getId() const { return id; } - QString getName() const { return name; } - int getX() const { return x; } - int getY() const { return y; } - int getCounters() const { return counters; } - bool getTapped() const { return tapped; } - bool getAttacking() const { return attacking; } - QString getAnnotation() const { return annotation; } - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); -}; - -class ServerInfo_Zone : public SerializableItem { -private: - QString name; - ZoneType type; - bool hasCoords; - int cardCount; - QList cardList; -public: - ServerInfo_Zone(const QString &_name = QString(), ZoneType _type = PrivateZone, bool _hasCoords = false, int _cardCount = -1, const QList &_cardList = QList()) - : name(_name), type(_type), hasCoords(_hasCoords), cardCount(_cardCount), cardList(_cardList) { } - ~ServerInfo_Zone(); - QString getName() const { return name; } - ZoneType getType() const { return type; } - bool getHasCoords() const { return hasCoords; } - int getCardCount() const { return cardCount; } - const QList &getCardList() const { return cardList; } - void addCard(ServerInfo_Card *card) { cardList.append(card); ++cardCount; } - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); -}; - -class ServerInfo_Counter : public SerializableItem { -private: - int id; - QString name; - QColor color; - int radius; - int count; -public: - ServerInfo_Counter(int _id = -1, const QString &_name = QString(), const QColor &_color = QColor(), int _radius = -1, int _count = -1) - : id(_id), name(_name), color(_color), radius(_radius), count(_count) { } - int getId() const { return id; } - QString getName() const { return name; } - QColor getColor() const { return color; } - int getRadius() const { return radius; } - int getCount() const { return count; } - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); -}; - -class ServerInfo_Arrow : public SerializableItem { -private: - int id; - int startPlayerId; - QString startZone; - int startCardId; - int targetPlayerId; - QString targetZone; - int targetCardId; - QColor color; -public: - ServerInfo_Arrow(int _id = -1, int _startPlayerId = -1, const QString &_startZone = QString(), int _startCardId = -1, int _targetPlayerId = -1, const QString &_targetZone = QString(), int _targetCardId = -1, const QColor &_color = QColor()) - : id(_id), startPlayerId(_startPlayerId), startZone(_startZone), startCardId(_startCardId), targetPlayerId(_targetPlayerId), targetZone(_targetZone), targetCardId(_targetCardId), color(_color) { } - int getId() const { return id; } - int getStartPlayerId() const { return startPlayerId; } - QString getStartZone() const { return startZone; } - int getStartCardId() const { return startCardId; } - int getTargetPlayerId() const { return targetPlayerId; } - QString getTargetZone() const { return targetZone; } - int getTargetCardId() const { return targetCardId; } - QColor getColor() const { return color; } - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); -}; - -class ServerInfo_Player : public SerializableItem { -private: - int playerId; - QString name; QList zoneList; QList counterList; QList arrowList; +protected: + void extractData(); public: - ServerInfo_Player(int _playerId = -1, const QString &_name = QString(), const QList &_zoneList = QList(), const QList &_counterList = QList(), const QList &_arrowList = QList()) - : playerId(_playerId), name(_name), zoneList(_zoneList), counterList(_counterList), arrowList(_arrowList) { } - ~ServerInfo_Player(); - int getPlayerId() const { return playerId; } - QString getName() const { return name; } + ServerInfo_Player(int _playerId = -1, const QString &_name = QString(), const QList &_zoneList = QList(), const QList &_counterList = QList(), const QList &_arrowList = QList()); + static SerializableItem *newItem() { return new ServerInfo_Player; } + int getPlayerId() const { return static_cast(itemMap.value("player_id"))->getData(); } + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } const QList &getZoneList() const { return zoneList; } const QList &getCounterList() const { return counterList; } const QList &getArrowList() const { return arrowList; } - void addZone(ServerInfo_Zone *zone) { zoneList.append(zone); } - void addCounter(ServerInfo_Counter *counter) { counterList.append(counter); } - void addArrow(ServerInfo_Arrow *arrow) { arrowList.append(arrow); } - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); }; -class DeckList_TreeItem : public SerializableItem { -protected: - QString name; - int id; +class DeckList_TreeItem : public SerializableItem_Map { public: - DeckList_TreeItem(const QString &_name, int _id) : name(_name), id(_id) { } - QString getName() const { return name; } - int getId() const { return id; } + DeckList_TreeItem(const QString &_itemType, const QString &_name, int _id); + QString getName() const { return static_cast(itemMap.value("name"))->getData(); } + int getId() const { return static_cast(itemMap.value("id"))->getData(); } }; class DeckList_File : public DeckList_TreeItem { -private: - QDateTime uploadTime; public: - DeckList_File(const QString &_name, int _id, QDateTime _uploadTime) : DeckList_TreeItem(_name, _id), uploadTime(_uploadTime) { } - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); - QDateTime getUploadTime() const { return uploadTime; } + DeckList_File(const QString &_name = QString(), int _id = -1, QDateTime _uploadTime = QDateTime()); + static SerializableItem *newItem() { return new DeckList_File; } + QDateTime getUploadTime() const { return static_cast(itemMap.value("upload_time"))->getData(); } }; -class DeckList_Directory : public DeckList_TreeItem, public QList { +class DeckList_Directory : public DeckList_TreeItem { public: - DeckList_Directory(const QString &_name = QString(), int _id = 0) : DeckList_TreeItem(_name, _id) { } - ~DeckList_Directory(); - bool readElement(QXmlStreamReader *xml); - void writeElement(QXmlStreamWriter *xml); + DeckList_Directory(const QString &_name = QString(), int _id = 0); + static SerializableItem *newItem() { return new DeckList_Directory; } + QList getTreeItems() const { return typecastItemList(); } }; #endif diff --git a/common/protocol_items.cpp b/common/protocol_items.cpp index 48e73244..f09b87a5 100644 --- a/common/protocol_items.cpp +++ b/common/protocol_items.cpp @@ -6,378 +6,209 @@ Command_Ping::Command_Ping() { } Command_Login::Command_Login(const QString &_username, const QString &_password) - : Command("login"), username(_username), password(_password) + : Command("login") { - setParameter("username", username); - setParameter("password", password); -} -void Command_Login::extractParameters() -{ - Command::extractParameters(); - username = parameters["username"]; - password = parameters["password"]; + insertItem(new SerializableItem_String("username", _username)); + insertItem(new SerializableItem_String("password", _password)); } Command_DeckList::Command_DeckList() : Command("deck_list") { } Command_DeckNewDir::Command_DeckNewDir(const QString &_path, const QString &_dirName) - : Command("deck_new_dir"), path(_path), dirName(_dirName) + : Command("deck_new_dir") { - setParameter("path", path); - setParameter("dir_name", dirName); -} -void Command_DeckNewDir::extractParameters() -{ - Command::extractParameters(); - path = parameters["path"]; - dirName = parameters["dir_name"]; + insertItem(new SerializableItem_String("path", _path)); + insertItem(new SerializableItem_String("dir_name", _dirName)); } Command_DeckDelDir::Command_DeckDelDir(const QString &_path) - : Command("deck_del_dir"), path(_path) + : Command("deck_del_dir") { - setParameter("path", path); -} -void Command_DeckDelDir::extractParameters() -{ - Command::extractParameters(); - path = parameters["path"]; + insertItem(new SerializableItem_String("path", _path)); } Command_DeckDel::Command_DeckDel(int _deckId) - : Command("deck_del"), deckId(_deckId) + : Command("deck_del") { - setParameter("deck_id", deckId); -} -void Command_DeckDel::extractParameters() -{ - Command::extractParameters(); - deckId = parameters["deck_id"].toInt(); + insertItem(new SerializableItem_Int("deck_id", _deckId)); } Command_DeckDownload::Command_DeckDownload(int _deckId) - : Command("deck_download"), deckId(_deckId) + : Command("deck_download") { - setParameter("deck_id", deckId); -} -void Command_DeckDownload::extractParameters() -{ - Command::extractParameters(); - deckId = parameters["deck_id"].toInt(); + insertItem(new SerializableItem_Int("deck_id", _deckId)); } Command_ListChatChannels::Command_ListChatChannels() : Command("list_chat_channels") { } Command_ChatJoinChannel::Command_ChatJoinChannel(const QString &_channel) - : Command("chat_join_channel"), channel(_channel) + : Command("chat_join_channel") { - setParameter("channel", channel); -} -void Command_ChatJoinChannel::extractParameters() -{ - Command::extractParameters(); - channel = parameters["channel"]; + insertItem(new SerializableItem_String("channel", _channel)); } Command_ChatLeaveChannel::Command_ChatLeaveChannel(const QString &_channel) : ChatCommand("chat_leave_channel", _channel) { } Command_ChatSay::Command_ChatSay(const QString &_channel, const QString &_message) - : ChatCommand("chat_say", _channel), message(_message) + : ChatCommand("chat_say", _channel) { - setParameter("message", message); -} -void Command_ChatSay::extractParameters() -{ - ChatCommand::extractParameters(); - message = parameters["message"]; + insertItem(new SerializableItem_String("message", _message)); } Command_ListGames::Command_ListGames() : Command("list_games") { } Command_CreateGame::Command_CreateGame(const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed) - : Command("create_game"), description(_description), password(_password), maxPlayers(_maxPlayers), spectatorsAllowed(_spectatorsAllowed) + : Command("create_game") { - setParameter("description", description); - setParameter("password", password); - setParameter("max_players", maxPlayers); - setParameter("spectators_allowed", spectatorsAllowed); -} -void Command_CreateGame::extractParameters() -{ - Command::extractParameters(); - description = parameters["description"]; - password = parameters["password"]; - maxPlayers = parameters["max_players"].toInt(); - spectatorsAllowed = (parameters["spectators_allowed"] == "1"); + insertItem(new SerializableItem_String("description", _description)); + insertItem(new SerializableItem_String("password", _password)); + insertItem(new SerializableItem_Int("max_players", _maxPlayers)); + insertItem(new SerializableItem_Bool("spectators_allowed", _spectatorsAllowed)); } Command_JoinGame::Command_JoinGame(int _gameId, const QString &_password, bool _spectator) - : Command("join_game"), gameId(_gameId), password(_password), spectator(_spectator) + : Command("join_game") { - setParameter("game_id", gameId); - setParameter("password", password); - setParameter("spectator", spectator); -} -void Command_JoinGame::extractParameters() -{ - Command::extractParameters(); - gameId = parameters["game_id"].toInt(); - password = parameters["password"]; - spectator = (parameters["spectator"] == "1"); + insertItem(new SerializableItem_Int("game_id", _gameId)); + insertItem(new SerializableItem_String("password", _password)); + insertItem(new SerializableItem_Bool("spectator", _spectator)); } Command_LeaveGame::Command_LeaveGame(int _gameId) : GameCommand("leave_game", _gameId) { } Command_Say::Command_Say(int _gameId, const QString &_message) - : GameCommand("say", _gameId), message(_message) + : GameCommand("say", _gameId) { - setParameter("message", message); -} -void Command_Say::extractParameters() -{ - GameCommand::extractParameters(); - message = parameters["message"]; + insertItem(new SerializableItem_String("message", _message)); } Command_Shuffle::Command_Shuffle(int _gameId) : GameCommand("shuffle", _gameId) { } Command_RollDie::Command_RollDie(int _gameId, int _sides) - : GameCommand("roll_die", _gameId), sides(_sides) + : GameCommand("roll_die", _gameId) { - setParameter("sides", sides); -} -void Command_RollDie::extractParameters() -{ - GameCommand::extractParameters(); - sides = parameters["sides"].toInt(); + insertItem(new SerializableItem_Int("sides", _sides)); } Command_DrawCards::Command_DrawCards(int _gameId, int _number) - : GameCommand("draw_cards", _gameId), number(_number) + : GameCommand("draw_cards", _gameId) { - setParameter("number", number); -} -void Command_DrawCards::extractParameters() -{ - GameCommand::extractParameters(); - number = parameters["number"].toInt(); + insertItem(new SerializableItem_Int("number", _number)); } Command_MoveCard::Command_MoveCard(int _gameId, const QString &_startZone, int _cardId, const QString &_targetZone, int _x, int _y, bool _faceDown) - : GameCommand("move_card", _gameId), startZone(_startZone), cardId(_cardId), targetZone(_targetZone), x(_x), y(_y), faceDown(_faceDown) + : GameCommand("move_card", _gameId) { - setParameter("start_zone", startZone); - setParameter("card_id", cardId); - setParameter("target_zone", targetZone); - setParameter("x", x); - setParameter("y", y); - setParameter("face_down", faceDown); -} -void Command_MoveCard::extractParameters() -{ - GameCommand::extractParameters(); - startZone = parameters["start_zone"]; - cardId = parameters["card_id"].toInt(); - targetZone = parameters["target_zone"]; - x = parameters["x"].toInt(); - y = parameters["y"].toInt(); - faceDown = (parameters["face_down"] == "1"); + insertItem(new SerializableItem_String("start_zone", _startZone)); + insertItem(new SerializableItem_Int("card_id", _cardId)); + insertItem(new SerializableItem_String("target_zone", _targetZone)); + insertItem(new SerializableItem_Int("x", _x)); + insertItem(new SerializableItem_Int("y", _y)); + insertItem(new SerializableItem_Bool("face_down", _faceDown)); } Command_CreateToken::Command_CreateToken(int _gameId, const QString &_zone, const QString &_cardName, const QString &_pt, int _x, int _y) - : GameCommand("create_token", _gameId), zone(_zone), cardName(_cardName), pt(_pt), x(_x), y(_y) + : GameCommand("create_token", _gameId) { - setParameter("zone", zone); - setParameter("card_name", cardName); - setParameter("pt", pt); - setParameter("x", x); - setParameter("y", y); -} -void Command_CreateToken::extractParameters() -{ - GameCommand::extractParameters(); - zone = parameters["zone"]; - cardName = parameters["card_name"]; - pt = parameters["pt"]; - x = parameters["x"].toInt(); - y = parameters["y"].toInt(); + insertItem(new SerializableItem_String("zone", _zone)); + insertItem(new SerializableItem_String("card_name", _cardName)); + insertItem(new SerializableItem_String("pt", _pt)); + insertItem(new SerializableItem_Int("x", _x)); + insertItem(new SerializableItem_Int("y", _y)); } Command_CreateArrow::Command_CreateArrow(int _gameId, int _startPlayerId, const QString &_startZone, int _startCardId, int _targetPlayerId, const QString &_targetZone, int _targetCardId, const QColor &_color) - : GameCommand("create_arrow", _gameId), startPlayerId(_startPlayerId), startZone(_startZone), startCardId(_startCardId), targetPlayerId(_targetPlayerId), targetZone(_targetZone), targetCardId(_targetCardId), color(_color) + : GameCommand("create_arrow", _gameId) { - setParameter("start_player_id", startPlayerId); - setParameter("start_zone", startZone); - setParameter("start_card_id", startCardId); - setParameter("target_player_id", targetPlayerId); - setParameter("target_zone", targetZone); - setParameter("target_card_id", targetCardId); - setParameter("color", color); -} -void Command_CreateArrow::extractParameters() -{ - GameCommand::extractParameters(); - startPlayerId = parameters["start_player_id"].toInt(); - startZone = parameters["start_zone"]; - startCardId = parameters["start_card_id"].toInt(); - targetPlayerId = parameters["target_player_id"].toInt(); - targetZone = parameters["target_zone"]; - targetCardId = parameters["target_card_id"].toInt(); - color = ColorConverter::colorFromInt(parameters["color"].toInt()); + insertItem(new SerializableItem_Int("start_player_id", _startPlayerId)); + insertItem(new SerializableItem_String("start_zone", _startZone)); + insertItem(new SerializableItem_Int("start_card_id", _startCardId)); + insertItem(new SerializableItem_Int("target_player_id", _targetPlayerId)); + insertItem(new SerializableItem_String("target_zone", _targetZone)); + insertItem(new SerializableItem_Int("target_card_id", _targetCardId)); + insertItem(new SerializableItem_Color("color", _color)); } Command_DeleteArrow::Command_DeleteArrow(int _gameId, int _arrowId) - : GameCommand("delete_arrow", _gameId), arrowId(_arrowId) + : GameCommand("delete_arrow", _gameId) { - setParameter("arrow_id", arrowId); -} -void Command_DeleteArrow::extractParameters() -{ - GameCommand::extractParameters(); - arrowId = parameters["arrow_id"].toInt(); + insertItem(new SerializableItem_Int("arrow_id", _arrowId)); } Command_SetCardAttr::Command_SetCardAttr(int _gameId, const QString &_zone, int _cardId, const QString &_attrName, const QString &_attrValue) - : GameCommand("set_card_attr", _gameId), zone(_zone), cardId(_cardId), attrName(_attrName), attrValue(_attrValue) + : GameCommand("set_card_attr", _gameId) { - setParameter("zone", zone); - setParameter("card_id", cardId); - setParameter("attr_name", attrName); - setParameter("attr_value", attrValue); -} -void Command_SetCardAttr::extractParameters() -{ - GameCommand::extractParameters(); - zone = parameters["zone"]; - cardId = parameters["card_id"].toInt(); - attrName = parameters["attr_name"]; - attrValue = parameters["attr_value"]; + insertItem(new SerializableItem_String("zone", _zone)); + insertItem(new SerializableItem_Int("card_id", _cardId)); + insertItem(new SerializableItem_String("attr_name", _attrName)); + insertItem(new SerializableItem_String("attr_value", _attrValue)); } Command_ReadyStart::Command_ReadyStart(int _gameId) : GameCommand("ready_start", _gameId) { } Command_IncCounter::Command_IncCounter(int _gameId, int _counterId, int _delta) - : GameCommand("inc_counter", _gameId), counterId(_counterId), delta(_delta) + : GameCommand("inc_counter", _gameId) { - setParameter("counter_id", counterId); - setParameter("delta", delta); -} -void Command_IncCounter::extractParameters() -{ - GameCommand::extractParameters(); - counterId = parameters["counter_id"].toInt(); - delta = parameters["delta"].toInt(); + insertItem(new SerializableItem_Int("counter_id", _counterId)); + insertItem(new SerializableItem_Int("delta", _delta)); } Command_CreateCounter::Command_CreateCounter(int _gameId, const QString &_counterName, const QColor &_color, int _radius, int _value) - : GameCommand("create_counter", _gameId), counterName(_counterName), color(_color), radius(_radius), value(_value) + : GameCommand("create_counter", _gameId) { - setParameter("counter_name", counterName); - setParameter("color", color); - setParameter("radius", radius); - setParameter("value", value); -} -void Command_CreateCounter::extractParameters() -{ - GameCommand::extractParameters(); - counterName = parameters["counter_name"]; - color = ColorConverter::colorFromInt(parameters["color"].toInt()); - radius = parameters["radius"].toInt(); - value = parameters["value"].toInt(); + insertItem(new SerializableItem_String("counter_name", _counterName)); + insertItem(new SerializableItem_Color("color", _color)); + insertItem(new SerializableItem_Int("radius", _radius)); + insertItem(new SerializableItem_Int("value", _value)); } Command_SetCounter::Command_SetCounter(int _gameId, int _counterId, int _value) - : GameCommand("set_counter", _gameId), counterId(_counterId), value(_value) + : GameCommand("set_counter", _gameId) { - setParameter("counter_id", counterId); - setParameter("value", value); -} -void Command_SetCounter::extractParameters() -{ - GameCommand::extractParameters(); - counterId = parameters["counter_id"].toInt(); - value = parameters["value"].toInt(); + insertItem(new SerializableItem_Int("counter_id", _counterId)); + insertItem(new SerializableItem_Int("value", _value)); } Command_DelCounter::Command_DelCounter(int _gameId, int _counterId) - : GameCommand("del_counter", _gameId), counterId(_counterId) + : GameCommand("del_counter", _gameId) { - setParameter("counter_id", counterId); -} -void Command_DelCounter::extractParameters() -{ - GameCommand::extractParameters(); - counterId = parameters["counter_id"].toInt(); + insertItem(new SerializableItem_Int("counter_id", _counterId)); } Command_NextTurn::Command_NextTurn(int _gameId) : GameCommand("next_turn", _gameId) { } Command_SetActivePhase::Command_SetActivePhase(int _gameId, int _phase) - : GameCommand("set_active_phase", _gameId), phase(_phase) + : GameCommand("set_active_phase", _gameId) { - setParameter("phase", phase); -} -void Command_SetActivePhase::extractParameters() -{ - GameCommand::extractParameters(); - phase = parameters["phase"].toInt(); + insertItem(new SerializableItem_Int("phase", _phase)); } Command_DumpZone::Command_DumpZone(int _gameId, int _playerId, const QString &_zoneName, int _numberCards) - : GameCommand("dump_zone", _gameId), playerId(_playerId), zoneName(_zoneName), numberCards(_numberCards) + : GameCommand("dump_zone", _gameId) { - setParameter("player_id", playerId); - setParameter("zone_name", zoneName); - setParameter("number_cards", numberCards); -} -void Command_DumpZone::extractParameters() -{ - GameCommand::extractParameters(); - playerId = parameters["player_id"].toInt(); - zoneName = parameters["zone_name"]; - numberCards = parameters["number_cards"].toInt(); + insertItem(new SerializableItem_Int("player_id", _playerId)); + insertItem(new SerializableItem_String("zone_name", _zoneName)); + insertItem(new SerializableItem_Int("number_cards", _numberCards)); } Command_StopDumpZone::Command_StopDumpZone(int _gameId, int _playerId, const QString &_zoneName) - : GameCommand("stop_dump_zone", _gameId), playerId(_playerId), zoneName(_zoneName) + : GameCommand("stop_dump_zone", _gameId) { - setParameter("player_id", playerId); - setParameter("zone_name", zoneName); -} -void Command_StopDumpZone::extractParameters() -{ - GameCommand::extractParameters(); - playerId = parameters["player_id"].toInt(); - zoneName = parameters["zone_name"]; + insertItem(new SerializableItem_Int("player_id", _playerId)); + insertItem(new SerializableItem_String("zone_name", _zoneName)); } Event_Say::Event_Say(int _gameId, int _playerId, const QString &_message) - : GameEvent("say", _gameId, _playerId), message(_message) + : GameEvent("say", _gameId, _playerId) { - setParameter("message", message); -} -void Event_Say::extractParameters() -{ - GameEvent::extractParameters(); - message = parameters["message"]; + insertItem(new SerializableItem_String("message", _message)); } Event_Join::Event_Join(int _gameId, int _playerId, const QString &_playerName, bool _spectator) - : GameEvent("join", _gameId, _playerId), playerName(_playerName), spectator(_spectator) + : GameEvent("join", _gameId, _playerId) { - setParameter("player_name", playerName); - setParameter("spectator", spectator); -} -void Event_Join::extractParameters() -{ - GameEvent::extractParameters(); - playerName = parameters["player_name"]; - spectator = (parameters["spectator"] == "1"); + insertItem(new SerializableItem_String("player_name", _playerName)); + insertItem(new SerializableItem_Bool("spectator", _spectator)); } Event_Leave::Event_Leave(int _gameId, int _playerId) : GameEvent("leave", _gameId, _playerId) { } Event_DeckSelect::Event_DeckSelect(int _gameId, int _playerId, int _deckId) - : GameEvent("deck_select", _gameId, _playerId), deckId(_deckId) + : GameEvent("deck_select", _gameId, _playerId) { - setParameter("deck_id", deckId); -} -void Event_DeckSelect::extractParameters() -{ - GameEvent::extractParameters(); - deckId = parameters["deck_id"].toInt(); + insertItem(new SerializableItem_Int("deck_id", _deckId)); } Event_GameClosed::Event_GameClosed(int _gameId, int _playerId) : GameEvent("game_closed", _gameId, _playerId) @@ -396,210 +227,107 @@ Event_Shuffle::Event_Shuffle(int _gameId, int _playerId) { } Event_RollDie::Event_RollDie(int _gameId, int _playerId, int _sides, int _value) - : GameEvent("roll_die", _gameId, _playerId), sides(_sides), value(_value) + : GameEvent("roll_die", _gameId, _playerId) { - setParameter("sides", sides); - setParameter("value", value); -} -void Event_RollDie::extractParameters() -{ - GameEvent::extractParameters(); - sides = parameters["sides"].toInt(); - value = parameters["value"].toInt(); + insertItem(new SerializableItem_Int("sides", _sides)); + insertItem(new SerializableItem_Int("value", _value)); } Event_MoveCard::Event_MoveCard(int _gameId, int _playerId, int _cardId, const QString &_cardName, const QString &_startZone, int _position, const QString &_targetZone, int _x, int _y, bool _faceDown) - : GameEvent("move_card", _gameId, _playerId), cardId(_cardId), cardName(_cardName), startZone(_startZone), position(_position), targetZone(_targetZone), x(_x), y(_y), faceDown(_faceDown) + : GameEvent("move_card", _gameId, _playerId) { - setParameter("card_id", cardId); - setParameter("card_name", cardName); - setParameter("start_zone", startZone); - setParameter("position", position); - setParameter("target_zone", targetZone); - setParameter("x", x); - setParameter("y", y); - setParameter("face_down", faceDown); -} -void Event_MoveCard::extractParameters() -{ - GameEvent::extractParameters(); - cardId = parameters["card_id"].toInt(); - cardName = parameters["card_name"]; - startZone = parameters["start_zone"]; - position = parameters["position"].toInt(); - targetZone = parameters["target_zone"]; - x = parameters["x"].toInt(); - y = parameters["y"].toInt(); - faceDown = (parameters["face_down"] == "1"); + insertItem(new SerializableItem_Int("card_id", _cardId)); + insertItem(new SerializableItem_String("card_name", _cardName)); + insertItem(new SerializableItem_String("start_zone", _startZone)); + insertItem(new SerializableItem_Int("position", _position)); + insertItem(new SerializableItem_String("target_zone", _targetZone)); + insertItem(new SerializableItem_Int("x", _x)); + insertItem(new SerializableItem_Int("y", _y)); + insertItem(new SerializableItem_Bool("face_down", _faceDown)); } Event_CreateToken::Event_CreateToken(int _gameId, int _playerId, const QString &_zone, int _cardId, const QString &_cardName, const QString &_pt, int _x, int _y) - : GameEvent("create_token", _gameId, _playerId), zone(_zone), cardId(_cardId), cardName(_cardName), pt(_pt), x(_x), y(_y) + : GameEvent("create_token", _gameId, _playerId) { - setParameter("zone", zone); - setParameter("card_id", cardId); - setParameter("card_name", cardName); - setParameter("pt", pt); - setParameter("x", x); - setParameter("y", y); -} -void Event_CreateToken::extractParameters() -{ - GameEvent::extractParameters(); - zone = parameters["zone"]; - cardId = parameters["card_id"].toInt(); - cardName = parameters["card_name"]; - pt = parameters["pt"]; - x = parameters["x"].toInt(); - y = parameters["y"].toInt(); + insertItem(new SerializableItem_String("zone", _zone)); + insertItem(new SerializableItem_Int("card_id", _cardId)); + insertItem(new SerializableItem_String("card_name", _cardName)); + insertItem(new SerializableItem_String("pt", _pt)); + insertItem(new SerializableItem_Int("x", _x)); + insertItem(new SerializableItem_Int("y", _y)); } Event_DeleteArrow::Event_DeleteArrow(int _gameId, int _playerId, int _arrowId) - : GameEvent("delete_arrow", _gameId, _playerId), arrowId(_arrowId) + : GameEvent("delete_arrow", _gameId, _playerId) { - setParameter("arrow_id", arrowId); -} -void Event_DeleteArrow::extractParameters() -{ - GameEvent::extractParameters(); - arrowId = parameters["arrow_id"].toInt(); + insertItem(new SerializableItem_Int("arrow_id", _arrowId)); } Event_SetCardAttr::Event_SetCardAttr(int _gameId, int _playerId, const QString &_zone, int _cardId, const QString &_attrName, const QString &_attrValue) - : GameEvent("set_card_attr", _gameId, _playerId), zone(_zone), cardId(_cardId), attrName(_attrName), attrValue(_attrValue) + : GameEvent("set_card_attr", _gameId, _playerId) { - setParameter("zone", zone); - setParameter("card_id", cardId); - setParameter("attr_name", attrName); - setParameter("attr_value", attrValue); -} -void Event_SetCardAttr::extractParameters() -{ - GameEvent::extractParameters(); - zone = parameters["zone"]; - cardId = parameters["card_id"].toInt(); - attrName = parameters["attr_name"]; - attrValue = parameters["attr_value"]; + insertItem(new SerializableItem_String("zone", _zone)); + insertItem(new SerializableItem_Int("card_id", _cardId)); + insertItem(new SerializableItem_String("attr_name", _attrName)); + insertItem(new SerializableItem_String("attr_value", _attrValue)); } Event_SetCounter::Event_SetCounter(int _gameId, int _playerId, int _counterId, int _value) - : GameEvent("set_counter", _gameId, _playerId), counterId(_counterId), value(_value) + : GameEvent("set_counter", _gameId, _playerId) { - setParameter("counter_id", counterId); - setParameter("value", value); -} -void Event_SetCounter::extractParameters() -{ - GameEvent::extractParameters(); - counterId = parameters["counter_id"].toInt(); - value = parameters["value"].toInt(); + insertItem(new SerializableItem_Int("counter_id", _counterId)); + insertItem(new SerializableItem_Int("value", _value)); } Event_DelCounter::Event_DelCounter(int _gameId, int _playerId, int _counterId) - : GameEvent("del_counter", _gameId, _playerId), counterId(_counterId) + : GameEvent("del_counter", _gameId, _playerId) { - setParameter("counter_id", counterId); -} -void Event_DelCounter::extractParameters() -{ - GameEvent::extractParameters(); - counterId = parameters["counter_id"].toInt(); + insertItem(new SerializableItem_Int("counter_id", _counterId)); } Event_SetActivePlayer::Event_SetActivePlayer(int _gameId, int _playerId, int _activePlayerId) - : GameEvent("set_active_player", _gameId, _playerId), activePlayerId(_activePlayerId) + : GameEvent("set_active_player", _gameId, _playerId) { - setParameter("active_player_id", activePlayerId); -} -void Event_SetActivePlayer::extractParameters() -{ - GameEvent::extractParameters(); - activePlayerId = parameters["active_player_id"].toInt(); + insertItem(new SerializableItem_Int("active_player_id", _activePlayerId)); } Event_SetActivePhase::Event_SetActivePhase(int _gameId, int _playerId, int _phase) - : GameEvent("set_active_phase", _gameId, _playerId), phase(_phase) + : GameEvent("set_active_phase", _gameId, _playerId) { - setParameter("phase", phase); -} -void Event_SetActivePhase::extractParameters() -{ - GameEvent::extractParameters(); - phase = parameters["phase"].toInt(); + insertItem(new SerializableItem_Int("phase", _phase)); } Event_DumpZone::Event_DumpZone(int _gameId, int _playerId, int _zoneOwnerId, const QString &_zone, int _numberCards) - : GameEvent("dump_zone", _gameId, _playerId), zoneOwnerId(_zoneOwnerId), zone(_zone), numberCards(_numberCards) + : GameEvent("dump_zone", _gameId, _playerId) { - setParameter("zone_owner_id", zoneOwnerId); - setParameter("zone", zone); - setParameter("number_cards", numberCards); -} -void Event_DumpZone::extractParameters() -{ - GameEvent::extractParameters(); - zoneOwnerId = parameters["zone_owner_id"].toInt(); - zone = parameters["zone"]; - numberCards = parameters["number_cards"].toInt(); + insertItem(new SerializableItem_Int("zone_owner_id", _zoneOwnerId)); + insertItem(new SerializableItem_String("zone", _zone)); + insertItem(new SerializableItem_Int("number_cards", _numberCards)); } Event_StopDumpZone::Event_StopDumpZone(int _gameId, int _playerId, int _zoneOwnerId, const QString &_zone) - : GameEvent("stop_dump_zone", _gameId, _playerId), zoneOwnerId(_zoneOwnerId), zone(_zone) + : GameEvent("stop_dump_zone", _gameId, _playerId) { - setParameter("zone_owner_id", zoneOwnerId); - setParameter("zone", zone); -} -void Event_StopDumpZone::extractParameters() -{ - GameEvent::extractParameters(); - zoneOwnerId = parameters["zone_owner_id"].toInt(); - zone = parameters["zone"]; + insertItem(new SerializableItem_Int("zone_owner_id", _zoneOwnerId)); + insertItem(new SerializableItem_String("zone", _zone)); } Event_ServerMessage::Event_ServerMessage(const QString &_message) - : GenericEvent("server_message"), message(_message) + : GenericEvent("server_message") { - setParameter("message", message); -} -void Event_ServerMessage::extractParameters() -{ - GenericEvent::extractParameters(); - message = parameters["message"]; + insertItem(new SerializableItem_String("message", _message)); } Event_GameJoined::Event_GameJoined(int _gameId, int _playerId, bool _spectator) - : GenericEvent("game_joined"), gameId(_gameId), playerId(_playerId), spectator(_spectator) + : GenericEvent("game_joined") { - setParameter("game_id", gameId); - setParameter("player_id", playerId); - setParameter("spectator", spectator); -} -void Event_GameJoined::extractParameters() -{ - GenericEvent::extractParameters(); - gameId = parameters["game_id"].toInt(); - playerId = parameters["player_id"].toInt(); - spectator = (parameters["spectator"] == "1"); + insertItem(new SerializableItem_Int("game_id", _gameId)); + insertItem(new SerializableItem_Int("player_id", _playerId)); + insertItem(new SerializableItem_Bool("spectator", _spectator)); } Event_ChatJoinChannel::Event_ChatJoinChannel(const QString &_channel, const QString &_playerName) - : ChatEvent("chat_join_channel", _channel), playerName(_playerName) + : ChatEvent("chat_join_channel", _channel) { - setParameter("player_name", playerName); -} -void Event_ChatJoinChannel::extractParameters() -{ - ChatEvent::extractParameters(); - playerName = parameters["player_name"]; + insertItem(new SerializableItem_String("player_name", _playerName)); } Event_ChatLeaveChannel::Event_ChatLeaveChannel(const QString &_channel, const QString &_playerName) - : ChatEvent("chat_leave_channel", _channel), playerName(_playerName) + : ChatEvent("chat_leave_channel", _channel) { - setParameter("player_name", playerName); -} -void Event_ChatLeaveChannel::extractParameters() -{ - ChatEvent::extractParameters(); - playerName = parameters["player_name"]; + insertItem(new SerializableItem_String("player_name", _playerName)); } Event_ChatSay::Event_ChatSay(const QString &_channel, const QString &_playerName, const QString &_message) - : ChatEvent("chat_say", _channel), playerName(_playerName), message(_message) + : ChatEvent("chat_say", _channel) { - setParameter("player_name", playerName); - setParameter("message", message); -} -void Event_ChatSay::extractParameters() -{ - ChatEvent::extractParameters(); - playerName = parameters["player_name"]; - message = parameters["message"]; + insertItem(new SerializableItem_String("player_name", _playerName)); + insertItem(new SerializableItem_String("message", _message)); } void ProtocolItem::initializeHashAuto() { diff --git a/common/protocol_items.h b/common/protocol_items.h index 2afc3188..4892fbec 100644 --- a/common/protocol_items.h +++ b/common/protocol_items.h @@ -5,745 +5,502 @@ class Command_Ping : public Command { Q_OBJECT -private: public: Command_Ping(); - static ProtocolItem *newItem() { return new Command_Ping; } + static SerializableItem *newItem() { return new Command_Ping; } int getItemId() const { return ItemId_Command_Ping; } }; class Command_Login : public Command { Q_OBJECT -private: - QString username; - QString password; public: Command_Login(const QString &_username = QString(), const QString &_password = QString()); - QString getUsername() const { return username; } - QString getPassword() const { return password; } - static ProtocolItem *newItem() { return new Command_Login; } + QString getUsername() const { return static_cast(itemMap.value("username"))->getData(); }; + QString getPassword() const { return static_cast(itemMap.value("password"))->getData(); }; + static SerializableItem *newItem() { return new Command_Login; } int getItemId() const { return ItemId_Command_Login; } -protected: - void extractParameters(); }; class Command_DeckList : public Command { Q_OBJECT -private: public: Command_DeckList(); - static ProtocolItem *newItem() { return new Command_DeckList; } + static SerializableItem *newItem() { return new Command_DeckList; } int getItemId() const { return ItemId_Command_DeckList; } }; class Command_DeckNewDir : public Command { Q_OBJECT -private: - QString path; - QString dirName; public: Command_DeckNewDir(const QString &_path = QString(), const QString &_dirName = QString()); - QString getPath() const { return path; } - QString getDirName() const { return dirName; } - static ProtocolItem *newItem() { return new Command_DeckNewDir; } + QString getPath() const { return static_cast(itemMap.value("path"))->getData(); }; + QString getDirName() const { return static_cast(itemMap.value("dir_name"))->getData(); }; + static SerializableItem *newItem() { return new Command_DeckNewDir; } int getItemId() const { return ItemId_Command_DeckNewDir; } -protected: - void extractParameters(); }; class Command_DeckDelDir : public Command { Q_OBJECT -private: - QString path; public: Command_DeckDelDir(const QString &_path = QString()); - QString getPath() const { return path; } - static ProtocolItem *newItem() { return new Command_DeckDelDir; } + QString getPath() const { return static_cast(itemMap.value("path"))->getData(); }; + static SerializableItem *newItem() { return new Command_DeckDelDir; } int getItemId() const { return ItemId_Command_DeckDelDir; } -protected: - void extractParameters(); }; class Command_DeckDel : public Command { Q_OBJECT -private: - int deckId; public: Command_DeckDel(int _deckId = -1); - int getDeckId() const { return deckId; } - static ProtocolItem *newItem() { return new Command_DeckDel; } + int getDeckId() const { return static_cast(itemMap.value("deck_id"))->getData(); }; + static SerializableItem *newItem() { return new Command_DeckDel; } int getItemId() const { return ItemId_Command_DeckDel; } -protected: - void extractParameters(); }; class Command_DeckDownload : public Command { Q_OBJECT -private: - int deckId; public: Command_DeckDownload(int _deckId = -1); - int getDeckId() const { return deckId; } - static ProtocolItem *newItem() { return new Command_DeckDownload; } + int getDeckId() const { return static_cast(itemMap.value("deck_id"))->getData(); }; + static SerializableItem *newItem() { return new Command_DeckDownload; } int getItemId() const { return ItemId_Command_DeckDownload; } -protected: - void extractParameters(); }; class Command_ListChatChannels : public Command { Q_OBJECT -private: public: Command_ListChatChannels(); - static ProtocolItem *newItem() { return new Command_ListChatChannels; } + static SerializableItem *newItem() { return new Command_ListChatChannels; } int getItemId() const { return ItemId_Command_ListChatChannels; } }; class Command_ChatJoinChannel : public Command { Q_OBJECT -private: - QString channel; public: Command_ChatJoinChannel(const QString &_channel = QString()); - QString getChannel() const { return channel; } - static ProtocolItem *newItem() { return new Command_ChatJoinChannel; } + QString getChannel() const { return static_cast(itemMap.value("channel"))->getData(); }; + static SerializableItem *newItem() { return new Command_ChatJoinChannel; } int getItemId() const { return ItemId_Command_ChatJoinChannel; } -protected: - void extractParameters(); }; class Command_ChatLeaveChannel : public ChatCommand { Q_OBJECT -private: public: Command_ChatLeaveChannel(const QString &_channel = QString()); - static ProtocolItem *newItem() { return new Command_ChatLeaveChannel; } + static SerializableItem *newItem() { return new Command_ChatLeaveChannel; } int getItemId() const { return ItemId_Command_ChatLeaveChannel; } }; class Command_ChatSay : public ChatCommand { Q_OBJECT -private: - QString message; public: Command_ChatSay(const QString &_channel = QString(), const QString &_message = QString()); - QString getMessage() const { return message; } - static ProtocolItem *newItem() { return new Command_ChatSay; } + QString getMessage() const { return static_cast(itemMap.value("message"))->getData(); }; + static SerializableItem *newItem() { return new Command_ChatSay; } int getItemId() const { return ItemId_Command_ChatSay; } -protected: - void extractParameters(); }; class Command_ListGames : public Command { Q_OBJECT -private: public: Command_ListGames(); - static ProtocolItem *newItem() { return new Command_ListGames; } + static SerializableItem *newItem() { return new Command_ListGames; } int getItemId() const { return ItemId_Command_ListGames; } }; class Command_CreateGame : public Command { Q_OBJECT -private: - QString description; - QString password; - int maxPlayers; - bool spectatorsAllowed; public: Command_CreateGame(const QString &_description = QString(), const QString &_password = QString(), int _maxPlayers = -1, bool _spectatorsAllowed = false); - QString getDescription() const { return description; } - QString getPassword() const { return password; } - int getMaxPlayers() const { return maxPlayers; } - bool getSpectatorsAllowed() const { return spectatorsAllowed; } - static ProtocolItem *newItem() { return new Command_CreateGame; } + QString getDescription() const { return static_cast(itemMap.value("description"))->getData(); }; + QString getPassword() const { return static_cast(itemMap.value("password"))->getData(); }; + int getMaxPlayers() const { return static_cast(itemMap.value("max_players"))->getData(); }; + bool getSpectatorsAllowed() const { return static_cast(itemMap.value("spectators_allowed"))->getData(); }; + static SerializableItem *newItem() { return new Command_CreateGame; } int getItemId() const { return ItemId_Command_CreateGame; } -protected: - void extractParameters(); }; class Command_JoinGame : public Command { Q_OBJECT -private: - int gameId; - QString password; - bool spectator; public: Command_JoinGame(int _gameId = -1, const QString &_password = QString(), bool _spectator = false); - int getGameId() const { return gameId; } - QString getPassword() const { return password; } - bool getSpectator() const { return spectator; } - static ProtocolItem *newItem() { return new Command_JoinGame; } + int getGameId() const { return static_cast(itemMap.value("game_id"))->getData(); }; + QString getPassword() const { return static_cast(itemMap.value("password"))->getData(); }; + bool getSpectator() const { return static_cast(itemMap.value("spectator"))->getData(); }; + static SerializableItem *newItem() { return new Command_JoinGame; } int getItemId() const { return ItemId_Command_JoinGame; } -protected: - void extractParameters(); }; class Command_LeaveGame : public GameCommand { Q_OBJECT -private: public: Command_LeaveGame(int _gameId = -1); - static ProtocolItem *newItem() { return new Command_LeaveGame; } + static SerializableItem *newItem() { return new Command_LeaveGame; } int getItemId() const { return ItemId_Command_LeaveGame; } }; class Command_Say : public GameCommand { Q_OBJECT -private: - QString message; public: Command_Say(int _gameId = -1, const QString &_message = QString()); - QString getMessage() const { return message; } - static ProtocolItem *newItem() { return new Command_Say; } + QString getMessage() const { return static_cast(itemMap.value("message"))->getData(); }; + static SerializableItem *newItem() { return new Command_Say; } int getItemId() const { return ItemId_Command_Say; } -protected: - void extractParameters(); }; class Command_Shuffle : public GameCommand { Q_OBJECT -private: public: Command_Shuffle(int _gameId = -1); - static ProtocolItem *newItem() { return new Command_Shuffle; } + static SerializableItem *newItem() { return new Command_Shuffle; } int getItemId() const { return ItemId_Command_Shuffle; } }; class Command_RollDie : public GameCommand { Q_OBJECT -private: - int sides; public: Command_RollDie(int _gameId = -1, int _sides = -1); - int getSides() const { return sides; } - static ProtocolItem *newItem() { return new Command_RollDie; } + int getSides() const { return static_cast(itemMap.value("sides"))->getData(); }; + static SerializableItem *newItem() { return new Command_RollDie; } int getItemId() const { return ItemId_Command_RollDie; } -protected: - void extractParameters(); }; class Command_DrawCards : public GameCommand { Q_OBJECT -private: - int number; public: Command_DrawCards(int _gameId = -1, int _number = -1); - int getNumber() const { return number; } - static ProtocolItem *newItem() { return new Command_DrawCards; } + int getNumber() const { return static_cast(itemMap.value("number"))->getData(); }; + static SerializableItem *newItem() { return new Command_DrawCards; } int getItemId() const { return ItemId_Command_DrawCards; } -protected: - void extractParameters(); }; class Command_MoveCard : public GameCommand { Q_OBJECT -private: - QString startZone; - int cardId; - QString targetZone; - int x; - int y; - bool faceDown; public: Command_MoveCard(int _gameId = -1, const QString &_startZone = QString(), int _cardId = -1, const QString &_targetZone = QString(), int _x = -1, int _y = -1, bool _faceDown = false); - QString getStartZone() const { return startZone; } - int getCardId() const { return cardId; } - QString getTargetZone() const { return targetZone; } - int getX() const { return x; } - int getY() const { return y; } - bool getFaceDown() const { return faceDown; } - static ProtocolItem *newItem() { return new Command_MoveCard; } + QString getStartZone() const { return static_cast(itemMap.value("start_zone"))->getData(); }; + int getCardId() const { return static_cast(itemMap.value("card_id"))->getData(); }; + QString getTargetZone() const { return static_cast(itemMap.value("target_zone"))->getData(); }; + int getX() const { return static_cast(itemMap.value("x"))->getData(); }; + int getY() const { return static_cast(itemMap.value("y"))->getData(); }; + bool getFaceDown() const { return static_cast(itemMap.value("face_down"))->getData(); }; + static SerializableItem *newItem() { return new Command_MoveCard; } int getItemId() const { return ItemId_Command_MoveCard; } -protected: - void extractParameters(); }; class Command_CreateToken : public GameCommand { Q_OBJECT -private: - QString zone; - QString cardName; - QString pt; - int x; - int y; public: Command_CreateToken(int _gameId = -1, const QString &_zone = QString(), const QString &_cardName = QString(), const QString &_pt = QString(), int _x = -1, int _y = -1); - QString getZone() const { return zone; } - QString getCardName() const { return cardName; } - QString getPt() const { return pt; } - int getX() const { return x; } - int getY() const { return y; } - static ProtocolItem *newItem() { return new Command_CreateToken; } + QString getZone() const { return static_cast(itemMap.value("zone"))->getData(); }; + QString getCardName() const { return static_cast(itemMap.value("card_name"))->getData(); }; + QString getPt() const { return static_cast(itemMap.value("pt"))->getData(); }; + int getX() const { return static_cast(itemMap.value("x"))->getData(); }; + int getY() const { return static_cast(itemMap.value("y"))->getData(); }; + static SerializableItem *newItem() { return new Command_CreateToken; } int getItemId() const { return ItemId_Command_CreateToken; } -protected: - void extractParameters(); }; class Command_CreateArrow : public GameCommand { Q_OBJECT -private: - int startPlayerId; - QString startZone; - int startCardId; - int targetPlayerId; - QString targetZone; - int targetCardId; - QColor color; public: Command_CreateArrow(int _gameId = -1, int _startPlayerId = -1, const QString &_startZone = QString(), int _startCardId = -1, int _targetPlayerId = -1, const QString &_targetZone = QString(), int _targetCardId = -1, const QColor &_color = QColor()); - int getStartPlayerId() const { return startPlayerId; } - QString getStartZone() const { return startZone; } - int getStartCardId() const { return startCardId; } - int getTargetPlayerId() const { return targetPlayerId; } - QString getTargetZone() const { return targetZone; } - int getTargetCardId() const { return targetCardId; } - QColor getColor() const { return color; } - static ProtocolItem *newItem() { return new Command_CreateArrow; } + int getStartPlayerId() const { return static_cast(itemMap.value("start_player_id"))->getData(); }; + QString getStartZone() const { return static_cast(itemMap.value("start_zone"))->getData(); }; + int getStartCardId() const { return static_cast(itemMap.value("start_card_id"))->getData(); }; + int getTargetPlayerId() const { return static_cast(itemMap.value("target_player_id"))->getData(); }; + QString getTargetZone() const { return static_cast(itemMap.value("target_zone"))->getData(); }; + int getTargetCardId() const { return static_cast(itemMap.value("target_card_id"))->getData(); }; + QColor getColor() const { return static_cast(itemMap.value("color"))->getData(); }; + static SerializableItem *newItem() { return new Command_CreateArrow; } int getItemId() const { return ItemId_Command_CreateArrow; } -protected: - void extractParameters(); }; class Command_DeleteArrow : public GameCommand { Q_OBJECT -private: - int arrowId; public: Command_DeleteArrow(int _gameId = -1, int _arrowId = -1); - int getArrowId() const { return arrowId; } - static ProtocolItem *newItem() { return new Command_DeleteArrow; } + int getArrowId() const { return static_cast(itemMap.value("arrow_id"))->getData(); }; + static SerializableItem *newItem() { return new Command_DeleteArrow; } int getItemId() const { return ItemId_Command_DeleteArrow; } -protected: - void extractParameters(); }; class Command_SetCardAttr : public GameCommand { Q_OBJECT -private: - QString zone; - int cardId; - QString attrName; - QString attrValue; public: Command_SetCardAttr(int _gameId = -1, const QString &_zone = QString(), int _cardId = -1, const QString &_attrName = QString(), const QString &_attrValue = QString()); - QString getZone() const { return zone; } - int getCardId() const { return cardId; } - QString getAttrName() const { return attrName; } - QString getAttrValue() const { return attrValue; } - static ProtocolItem *newItem() { return new Command_SetCardAttr; } + QString getZone() const { return static_cast(itemMap.value("zone"))->getData(); }; + int getCardId() const { return static_cast(itemMap.value("card_id"))->getData(); }; + QString getAttrName() const { return static_cast(itemMap.value("attr_name"))->getData(); }; + QString getAttrValue() const { return static_cast(itemMap.value("attr_value"))->getData(); }; + static SerializableItem *newItem() { return new Command_SetCardAttr; } int getItemId() const { return ItemId_Command_SetCardAttr; } -protected: - void extractParameters(); }; class Command_ReadyStart : public GameCommand { Q_OBJECT -private: public: Command_ReadyStart(int _gameId = -1); - static ProtocolItem *newItem() { return new Command_ReadyStart; } + static SerializableItem *newItem() { return new Command_ReadyStart; } int getItemId() const { return ItemId_Command_ReadyStart; } }; class Command_IncCounter : public GameCommand { Q_OBJECT -private: - int counterId; - int delta; public: Command_IncCounter(int _gameId = -1, int _counterId = -1, int _delta = -1); - int getCounterId() const { return counterId; } - int getDelta() const { return delta; } - static ProtocolItem *newItem() { return new Command_IncCounter; } + int getCounterId() const { return static_cast(itemMap.value("counter_id"))->getData(); }; + int getDelta() const { return static_cast(itemMap.value("delta"))->getData(); }; + static SerializableItem *newItem() { return new Command_IncCounter; } int getItemId() const { return ItemId_Command_IncCounter; } -protected: - void extractParameters(); }; class Command_CreateCounter : public GameCommand { Q_OBJECT -private: - QString counterName; - QColor color; - int radius; - int value; public: Command_CreateCounter(int _gameId = -1, const QString &_counterName = QString(), const QColor &_color = QColor(), int _radius = -1, int _value = -1); - QString getCounterName() const { return counterName; } - QColor getColor() const { return color; } - int getRadius() const { return radius; } - int getValue() const { return value; } - static ProtocolItem *newItem() { return new Command_CreateCounter; } + QString getCounterName() const { return static_cast(itemMap.value("counter_name"))->getData(); }; + QColor getColor() const { return static_cast(itemMap.value("color"))->getData(); }; + int getRadius() const { return static_cast(itemMap.value("radius"))->getData(); }; + int getValue() const { return static_cast(itemMap.value("value"))->getData(); }; + static SerializableItem *newItem() { return new Command_CreateCounter; } int getItemId() const { return ItemId_Command_CreateCounter; } -protected: - void extractParameters(); }; class Command_SetCounter : public GameCommand { Q_OBJECT -private: - int counterId; - int value; public: Command_SetCounter(int _gameId = -1, int _counterId = -1, int _value = -1); - int getCounterId() const { return counterId; } - int getValue() const { return value; } - static ProtocolItem *newItem() { return new Command_SetCounter; } + int getCounterId() const { return static_cast(itemMap.value("counter_id"))->getData(); }; + int getValue() const { return static_cast(itemMap.value("value"))->getData(); }; + static SerializableItem *newItem() { return new Command_SetCounter; } int getItemId() const { return ItemId_Command_SetCounter; } -protected: - void extractParameters(); }; class Command_DelCounter : public GameCommand { Q_OBJECT -private: - int counterId; public: Command_DelCounter(int _gameId = -1, int _counterId = -1); - int getCounterId() const { return counterId; } - static ProtocolItem *newItem() { return new Command_DelCounter; } + int getCounterId() const { return static_cast(itemMap.value("counter_id"))->getData(); }; + static SerializableItem *newItem() { return new Command_DelCounter; } int getItemId() const { return ItemId_Command_DelCounter; } -protected: - void extractParameters(); }; class Command_NextTurn : public GameCommand { Q_OBJECT -private: public: Command_NextTurn(int _gameId = -1); - static ProtocolItem *newItem() { return new Command_NextTurn; } + static SerializableItem *newItem() { return new Command_NextTurn; } int getItemId() const { return ItemId_Command_NextTurn; } }; class Command_SetActivePhase : public GameCommand { Q_OBJECT -private: - int phase; public: Command_SetActivePhase(int _gameId = -1, int _phase = -1); - int getPhase() const { return phase; } - static ProtocolItem *newItem() { return new Command_SetActivePhase; } + int getPhase() const { return static_cast(itemMap.value("phase"))->getData(); }; + static SerializableItem *newItem() { return new Command_SetActivePhase; } int getItemId() const { return ItemId_Command_SetActivePhase; } -protected: - void extractParameters(); }; class Command_DumpZone : public GameCommand { Q_OBJECT -private: - int playerId; - QString zoneName; - int numberCards; public: Command_DumpZone(int _gameId = -1, int _playerId = -1, const QString &_zoneName = QString(), int _numberCards = -1); - int getPlayerId() const { return playerId; } - QString getZoneName() const { return zoneName; } - int getNumberCards() const { return numberCards; } - static ProtocolItem *newItem() { return new Command_DumpZone; } + int getPlayerId() const { return static_cast(itemMap.value("player_id"))->getData(); }; + QString getZoneName() const { return static_cast(itemMap.value("zone_name"))->getData(); }; + int getNumberCards() const { return static_cast(itemMap.value("number_cards"))->getData(); }; + static SerializableItem *newItem() { return new Command_DumpZone; } int getItemId() const { return ItemId_Command_DumpZone; } -protected: - void extractParameters(); }; class Command_StopDumpZone : public GameCommand { Q_OBJECT -private: - int playerId; - QString zoneName; public: Command_StopDumpZone(int _gameId = -1, int _playerId = -1, const QString &_zoneName = QString()); - int getPlayerId() const { return playerId; } - QString getZoneName() const { return zoneName; } - static ProtocolItem *newItem() { return new Command_StopDumpZone; } + int getPlayerId() const { return static_cast(itemMap.value("player_id"))->getData(); }; + QString getZoneName() const { return static_cast(itemMap.value("zone_name"))->getData(); }; + static SerializableItem *newItem() { return new Command_StopDumpZone; } int getItemId() const { return ItemId_Command_StopDumpZone; } -protected: - void extractParameters(); }; class Event_Say : public GameEvent { Q_OBJECT -private: - QString message; public: Event_Say(int _gameId = -1, int _playerId = -1, const QString &_message = QString()); - QString getMessage() const { return message; } - static ProtocolItem *newItem() { return new Event_Say; } + QString getMessage() const { return static_cast(itemMap.value("message"))->getData(); }; + static SerializableItem *newItem() { return new Event_Say; } int getItemId() const { return ItemId_Event_Say; } -protected: - void extractParameters(); }; class Event_Join : public GameEvent { Q_OBJECT -private: - QString playerName; - bool spectator; public: Event_Join(int _gameId = -1, int _playerId = -1, const QString &_playerName = QString(), bool _spectator = false); - QString getPlayerName() const { return playerName; } - bool getSpectator() const { return spectator; } - static ProtocolItem *newItem() { return new Event_Join; } + QString getPlayerName() const { return static_cast(itemMap.value("player_name"))->getData(); }; + bool getSpectator() const { return static_cast(itemMap.value("spectator"))->getData(); }; + static SerializableItem *newItem() { return new Event_Join; } int getItemId() const { return ItemId_Event_Join; } -protected: - void extractParameters(); }; class Event_Leave : public GameEvent { Q_OBJECT -private: public: Event_Leave(int _gameId = -1, int _playerId = -1); - static ProtocolItem *newItem() { return new Event_Leave; } + static SerializableItem *newItem() { return new Event_Leave; } int getItemId() const { return ItemId_Event_Leave; } }; class Event_DeckSelect : public GameEvent { Q_OBJECT -private: - int deckId; public: Event_DeckSelect(int _gameId = -1, int _playerId = -1, int _deckId = -1); - int getDeckId() const { return deckId; } - static ProtocolItem *newItem() { return new Event_DeckSelect; } + int getDeckId() const { return static_cast(itemMap.value("deck_id"))->getData(); }; + static SerializableItem *newItem() { return new Event_DeckSelect; } int getItemId() const { return ItemId_Event_DeckSelect; } -protected: - void extractParameters(); }; class Event_GameClosed : public GameEvent { Q_OBJECT -private: public: Event_GameClosed(int _gameId = -1, int _playerId = -1); - static ProtocolItem *newItem() { return new Event_GameClosed; } + static SerializableItem *newItem() { return new Event_GameClosed; } int getItemId() const { return ItemId_Event_GameClosed; } }; class Event_ReadyStart : public GameEvent { Q_OBJECT -private: public: Event_ReadyStart(int _gameId = -1, int _playerId = -1); - static ProtocolItem *newItem() { return new Event_ReadyStart; } + static SerializableItem *newItem() { return new Event_ReadyStart; } int getItemId() const { return ItemId_Event_ReadyStart; } }; class Event_GameStart : public GameEvent { Q_OBJECT -private: public: Event_GameStart(int _gameId = -1, int _playerId = -1); - static ProtocolItem *newItem() { return new Event_GameStart; } + static SerializableItem *newItem() { return new Event_GameStart; } int getItemId() const { return ItemId_Event_GameStart; } }; class Event_Shuffle : public GameEvent { Q_OBJECT -private: public: Event_Shuffle(int _gameId = -1, int _playerId = -1); - static ProtocolItem *newItem() { return new Event_Shuffle; } + static SerializableItem *newItem() { return new Event_Shuffle; } int getItemId() const { return ItemId_Event_Shuffle; } }; class Event_RollDie : public GameEvent { Q_OBJECT -private: - int sides; - int value; public: Event_RollDie(int _gameId = -1, int _playerId = -1, int _sides = -1, int _value = -1); - int getSides() const { return sides; } - int getValue() const { return value; } - static ProtocolItem *newItem() { return new Event_RollDie; } + int getSides() const { return static_cast(itemMap.value("sides"))->getData(); }; + int getValue() const { return static_cast(itemMap.value("value"))->getData(); }; + static SerializableItem *newItem() { return new Event_RollDie; } int getItemId() const { return ItemId_Event_RollDie; } -protected: - void extractParameters(); }; class Event_MoveCard : public GameEvent { Q_OBJECT -private: - int cardId; - QString cardName; - QString startZone; - int position; - QString targetZone; - int x; - int y; - bool faceDown; public: Event_MoveCard(int _gameId = -1, int _playerId = -1, int _cardId = -1, const QString &_cardName = QString(), const QString &_startZone = QString(), int _position = -1, const QString &_targetZone = QString(), int _x = -1, int _y = -1, bool _faceDown = false); - int getCardId() const { return cardId; } - QString getCardName() const { return cardName; } - QString getStartZone() const { return startZone; } - int getPosition() const { return position; } - QString getTargetZone() const { return targetZone; } - int getX() const { return x; } - int getY() const { return y; } - bool getFaceDown() const { return faceDown; } - static ProtocolItem *newItem() { return new Event_MoveCard; } + int getCardId() const { return static_cast(itemMap.value("card_id"))->getData(); }; + QString getCardName() const { return static_cast(itemMap.value("card_name"))->getData(); }; + QString getStartZone() const { return static_cast(itemMap.value("start_zone"))->getData(); }; + int getPosition() const { return static_cast(itemMap.value("position"))->getData(); }; + QString getTargetZone() const { return static_cast(itemMap.value("target_zone"))->getData(); }; + int getX() const { return static_cast(itemMap.value("x"))->getData(); }; + int getY() const { return static_cast(itemMap.value("y"))->getData(); }; + bool getFaceDown() const { return static_cast(itemMap.value("face_down"))->getData(); }; + static SerializableItem *newItem() { return new Event_MoveCard; } int getItemId() const { return ItemId_Event_MoveCard; } -protected: - void extractParameters(); }; class Event_CreateToken : public GameEvent { Q_OBJECT -private: - QString zone; - int cardId; - QString cardName; - QString pt; - int x; - int y; public: Event_CreateToken(int _gameId = -1, int _playerId = -1, const QString &_zone = QString(), int _cardId = -1, const QString &_cardName = QString(), const QString &_pt = QString(), int _x = -1, int _y = -1); - QString getZone() const { return zone; } - int getCardId() const { return cardId; } - QString getCardName() const { return cardName; } - QString getPt() const { return pt; } - int getX() const { return x; } - int getY() const { return y; } - static ProtocolItem *newItem() { return new Event_CreateToken; } + QString getZone() const { return static_cast(itemMap.value("zone"))->getData(); }; + int getCardId() const { return static_cast(itemMap.value("card_id"))->getData(); }; + QString getCardName() const { return static_cast(itemMap.value("card_name"))->getData(); }; + QString getPt() const { return static_cast(itemMap.value("pt"))->getData(); }; + int getX() const { return static_cast(itemMap.value("x"))->getData(); }; + int getY() const { return static_cast(itemMap.value("y"))->getData(); }; + static SerializableItem *newItem() { return new Event_CreateToken; } int getItemId() const { return ItemId_Event_CreateToken; } -protected: - void extractParameters(); }; class Event_DeleteArrow : public GameEvent { Q_OBJECT -private: - int arrowId; public: Event_DeleteArrow(int _gameId = -1, int _playerId = -1, int _arrowId = -1); - int getArrowId() const { return arrowId; } - static ProtocolItem *newItem() { return new Event_DeleteArrow; } + int getArrowId() const { return static_cast(itemMap.value("arrow_id"))->getData(); }; + static SerializableItem *newItem() { return new Event_DeleteArrow; } int getItemId() const { return ItemId_Event_DeleteArrow; } -protected: - void extractParameters(); }; class Event_SetCardAttr : public GameEvent { Q_OBJECT -private: - QString zone; - int cardId; - QString attrName; - QString attrValue; public: Event_SetCardAttr(int _gameId = -1, int _playerId = -1, const QString &_zone = QString(), int _cardId = -1, const QString &_attrName = QString(), const QString &_attrValue = QString()); - QString getZone() const { return zone; } - int getCardId() const { return cardId; } - QString getAttrName() const { return attrName; } - QString getAttrValue() const { return attrValue; } - static ProtocolItem *newItem() { return new Event_SetCardAttr; } + QString getZone() const { return static_cast(itemMap.value("zone"))->getData(); }; + int getCardId() const { return static_cast(itemMap.value("card_id"))->getData(); }; + QString getAttrName() const { return static_cast(itemMap.value("attr_name"))->getData(); }; + QString getAttrValue() const { return static_cast(itemMap.value("attr_value"))->getData(); }; + static SerializableItem *newItem() { return new Event_SetCardAttr; } int getItemId() const { return ItemId_Event_SetCardAttr; } -protected: - void extractParameters(); }; class Event_SetCounter : public GameEvent { Q_OBJECT -private: - int counterId; - int value; public: Event_SetCounter(int _gameId = -1, int _playerId = -1, int _counterId = -1, int _value = -1); - int getCounterId() const { return counterId; } - int getValue() const { return value; } - static ProtocolItem *newItem() { return new Event_SetCounter; } + int getCounterId() const { return static_cast(itemMap.value("counter_id"))->getData(); }; + int getValue() const { return static_cast(itemMap.value("value"))->getData(); }; + static SerializableItem *newItem() { return new Event_SetCounter; } int getItemId() const { return ItemId_Event_SetCounter; } -protected: - void extractParameters(); }; class Event_DelCounter : public GameEvent { Q_OBJECT -private: - int counterId; public: Event_DelCounter(int _gameId = -1, int _playerId = -1, int _counterId = -1); - int getCounterId() const { return counterId; } - static ProtocolItem *newItem() { return new Event_DelCounter; } + int getCounterId() const { return static_cast(itemMap.value("counter_id"))->getData(); }; + static SerializableItem *newItem() { return new Event_DelCounter; } int getItemId() const { return ItemId_Event_DelCounter; } -protected: - void extractParameters(); }; class Event_SetActivePlayer : public GameEvent { Q_OBJECT -private: - int activePlayerId; public: Event_SetActivePlayer(int _gameId = -1, int _playerId = -1, int _activePlayerId = -1); - int getActivePlayerId() const { return activePlayerId; } - static ProtocolItem *newItem() { return new Event_SetActivePlayer; } + int getActivePlayerId() const { return static_cast(itemMap.value("active_player_id"))->getData(); }; + static SerializableItem *newItem() { return new Event_SetActivePlayer; } int getItemId() const { return ItemId_Event_SetActivePlayer; } -protected: - void extractParameters(); }; class Event_SetActivePhase : public GameEvent { Q_OBJECT -private: - int phase; public: Event_SetActivePhase(int _gameId = -1, int _playerId = -1, int _phase = -1); - int getPhase() const { return phase; } - static ProtocolItem *newItem() { return new Event_SetActivePhase; } + int getPhase() const { return static_cast(itemMap.value("phase"))->getData(); }; + static SerializableItem *newItem() { return new Event_SetActivePhase; } int getItemId() const { return ItemId_Event_SetActivePhase; } -protected: - void extractParameters(); }; class Event_DumpZone : public GameEvent { Q_OBJECT -private: - int zoneOwnerId; - QString zone; - int numberCards; public: Event_DumpZone(int _gameId = -1, int _playerId = -1, int _zoneOwnerId = -1, const QString &_zone = QString(), int _numberCards = -1); - int getZoneOwnerId() const { return zoneOwnerId; } - QString getZone() const { return zone; } - int getNumberCards() const { return numberCards; } - static ProtocolItem *newItem() { return new Event_DumpZone; } + int getZoneOwnerId() const { return static_cast(itemMap.value("zone_owner_id"))->getData(); }; + QString getZone() const { return static_cast(itemMap.value("zone"))->getData(); }; + int getNumberCards() const { return static_cast(itemMap.value("number_cards"))->getData(); }; + static SerializableItem *newItem() { return new Event_DumpZone; } int getItemId() const { return ItemId_Event_DumpZone; } -protected: - void extractParameters(); }; class Event_StopDumpZone : public GameEvent { Q_OBJECT -private: - int zoneOwnerId; - QString zone; public: Event_StopDumpZone(int _gameId = -1, int _playerId = -1, int _zoneOwnerId = -1, const QString &_zone = QString()); - int getZoneOwnerId() const { return zoneOwnerId; } - QString getZone() const { return zone; } - static ProtocolItem *newItem() { return new Event_StopDumpZone; } + int getZoneOwnerId() const { return static_cast(itemMap.value("zone_owner_id"))->getData(); }; + QString getZone() const { return static_cast(itemMap.value("zone"))->getData(); }; + static SerializableItem *newItem() { return new Event_StopDumpZone; } int getItemId() const { return ItemId_Event_StopDumpZone; } -protected: - void extractParameters(); }; class Event_ServerMessage : public GenericEvent { Q_OBJECT -private: - QString message; public: Event_ServerMessage(const QString &_message = QString()); - QString getMessage() const { return message; } - static ProtocolItem *newItem() { return new Event_ServerMessage; } + QString getMessage() const { return static_cast(itemMap.value("message"))->getData(); }; + static SerializableItem *newItem() { return new Event_ServerMessage; } int getItemId() const { return ItemId_Event_ServerMessage; } -protected: - void extractParameters(); }; class Event_GameJoined : public GenericEvent { Q_OBJECT -private: - int gameId; - int playerId; - bool spectator; public: Event_GameJoined(int _gameId = -1, int _playerId = -1, bool _spectator = false); - int getGameId() const { return gameId; } - int getPlayerId() const { return playerId; } - bool getSpectator() const { return spectator; } - static ProtocolItem *newItem() { return new Event_GameJoined; } + int getGameId() const { return static_cast(itemMap.value("game_id"))->getData(); }; + int getPlayerId() const { return static_cast(itemMap.value("player_id"))->getData(); }; + bool getSpectator() const { return static_cast(itemMap.value("spectator"))->getData(); }; + static SerializableItem *newItem() { return new Event_GameJoined; } int getItemId() const { return ItemId_Event_GameJoined; } -protected: - void extractParameters(); }; class Event_ChatJoinChannel : public ChatEvent { Q_OBJECT -private: - QString playerName; public: Event_ChatJoinChannel(const QString &_channel = QString(), const QString &_playerName = QString()); - QString getPlayerName() const { return playerName; } - static ProtocolItem *newItem() { return new Event_ChatJoinChannel; } + QString getPlayerName() const { return static_cast(itemMap.value("player_name"))->getData(); }; + static SerializableItem *newItem() { return new Event_ChatJoinChannel; } int getItemId() const { return ItemId_Event_ChatJoinChannel; } -protected: - void extractParameters(); }; class Event_ChatLeaveChannel : public ChatEvent { Q_OBJECT -private: - QString playerName; public: Event_ChatLeaveChannel(const QString &_channel = QString(), const QString &_playerName = QString()); - QString getPlayerName() const { return playerName; } - static ProtocolItem *newItem() { return new Event_ChatLeaveChannel; } + QString getPlayerName() const { return static_cast(itemMap.value("player_name"))->getData(); }; + static SerializableItem *newItem() { return new Event_ChatLeaveChannel; } int getItemId() const { return ItemId_Event_ChatLeaveChannel; } -protected: - void extractParameters(); }; class Event_ChatSay : public ChatEvent { Q_OBJECT -private: - QString playerName; - QString message; public: Event_ChatSay(const QString &_channel = QString(), const QString &_playerName = QString(), const QString &_message = QString()); - QString getPlayerName() const { return playerName; } - QString getMessage() const { return message; } - static ProtocolItem *newItem() { return new Event_ChatSay; } + QString getPlayerName() const { return static_cast(itemMap.value("player_name"))->getData(); }; + QString getMessage() const { return static_cast(itemMap.value("message"))->getData(); }; + static SerializableItem *newItem() { return new Event_ChatSay; } int getItemId() const { return ItemId_Event_ChatSay; } -protected: - void extractParameters(); }; #endif diff --git a/common/protocol_mc.pl b/common/protocol_mc.pl index b4869222..774dcfc8 100755 --- a/common/protocol_mc.pl +++ b/common/protocol_mc.pl @@ -70,12 +70,9 @@ while () { $className = $namePrefix . '_' . $name2; $itemEnum .= "ItemId_$className = " . ++$itemId . ",\n"; $headerfileBuffer .= "class $className : public $baseClass {\n" - . "\tQ_OBJECT\n" - . "private:\n"; - $paramStr2 = ''; - $paramStr3 = ''; - $paramStr4 = ''; - $paramStr5 = ''; + . "\tQ_OBJECT\n"; + $constructorCode = ''; + $getFunctionCode = ''; while ($param = shift(@line)) { ($key, $value) = split(/,/, $param); ($prettyVarName = $value) =~ s/_(.)/\U$1\E/g; @@ -85,52 +82,44 @@ while () { if (!($constructorParamsCpp eq '')) { $constructorParamsCpp .= ', '; } - $paramStr2 .= ", $prettyVarName(_$prettyVarName)"; - $paramStr3 .= "\tsetParameter(\"$value\", $prettyVarName);\n"; + ($prettyVarName2 = $prettyVarName) =~ s/^(.)/\U$1\E/; if ($key eq 'b') { $dataType = 'bool'; $constructorParamsH .= "bool _$prettyVarName = false"; $constructorParamsCpp .= "bool _$prettyVarName"; - $paramStr5 .= "\t$prettyVarName = (parameters[\"$value\"] == \"1\");\n"; + $constructorCode .= "\tinsertItem(new SerializableItem_Bool(\"$value\", _$prettyVarName));\n"; + $getFunctionCode .= "\t$dataType get$prettyVarName2() const { return static_cast(itemMap.value(\"$value\"))->getData(); };\n"; } elsif ($key eq 's') { $dataType = 'QString'; $constructorParamsH .= "const QString &_$prettyVarName = QString()"; $constructorParamsCpp .= "const QString &_$prettyVarName"; - $paramStr5 .= "\t$prettyVarName = parameters[\"$value\"];\n"; + $constructorCode .= "\tinsertItem(new SerializableItem_String(\"$value\", _$prettyVarName));\n"; + $getFunctionCode .= "\t$dataType get$prettyVarName2() const { return static_cast(itemMap.value(\"$value\"))->getData(); };\n"; } elsif ($key eq 'i') { $dataType = 'int'; $constructorParamsH .= "int _$prettyVarName = -1"; $constructorParamsCpp .= "int _$prettyVarName"; - $paramStr5 .= "\t$prettyVarName = parameters[\"$value\"].toInt();\n"; + $constructorCode .= "\tinsertItem(new SerializableItem_Int(\"$value\", _$prettyVarName));\n"; + $getFunctionCode .= "\t$dataType get$prettyVarName2() const { return static_cast(itemMap.value(\"$value\"))->getData(); };\n"; } elsif ($key eq 'c') { $dataType = 'QColor'; $constructorParamsH .= "const QColor &_$prettyVarName = QColor()"; $constructorParamsCpp .= "const QColor &_$prettyVarName"; - $paramStr5 .= "\t$prettyVarName = ColorConverter::colorFromInt(parameters[\"$value\"].toInt());\n"; + $constructorCode .= "\tinsertItem(new SerializableItem_Color(\"$value\", _$prettyVarName));\n"; + $getFunctionCode .= "\t$dataType get$prettyVarName2() const { return static_cast(itemMap.value(\"$value\"))->getData(); };\n"; } - ($prettyVarName2 = $prettyVarName) =~ s/^(.)/\U$1\E/; - $paramStr4 .= "\t$dataType get$prettyVarName2() const { return $prettyVarName; }\n"; - $headerfileBuffer .= "\t$dataType $prettyVarName;\n"; } $headerfileBuffer .= "public:\n" . "\t$className($constructorParamsH);\n" - . $paramStr4 - . "\tstatic ProtocolItem *newItem() { return new $className; }\n" + . $getFunctionCode + . "\tstatic SerializableItem *newItem() { return new $className; }\n" . "\tint getItemId() const { return ItemId_$className; }\n" - . ($paramStr5 eq '' ? '' : "protected:\n\tvoid extractParameters();\n") . "};\n"; print cppfile $className . "::$className($constructorParamsCpp)\n" - . "\t: $parentConstructorCall$paramStr2\n" + . "\t: $parentConstructorCall\n" . "{\n" - . $paramStr3 + . $constructorCode . "}\n"; - if (!($paramStr5 eq '')) { - print cppfile "void $className" . "::extractParameters()\n" - . "{\n" - . "\t$baseClass" . "::extractParameters();\n" - . $paramStr5 - . "}\n"; - } $initializeHash .= "\titemNameHash.insert(\"$type$name1\", $className" . "::newItem);\n"; } close(file); diff --git a/common/serializable_item.cpp b/common/serializable_item.cpp new file mode 100644 index 00000000..c33a3913 --- /dev/null +++ b/common/serializable_item.cpp @@ -0,0 +1,157 @@ +#include "serializable_item.h" +#include +#include +#include + +QHash SerializableItem::itemNameHash; + +SerializableItem *SerializableItem::getNewItem(const QString &name) +{ + if (!itemNameHash.contains(name)) + return 0; + return itemNameHash.value(name)(); +} + +void SerializableItem::registerSerializableItem(const QString &name, NewItemFunction func) +{ + itemNameHash.insert(name, func); +} + +bool SerializableItem::read(QXmlStreamReader *xml) +{ + while (!xml->atEnd()) { + xml->readNext(); + readElement(xml); + if (xml->isEndElement() && (xml->name() == itemType)) + return true; + } + return false; +} + +void SerializableItem::write(QXmlStreamWriter *xml) +{ + xml->writeStartElement(itemType); + if (!itemSubType.isEmpty()) + xml->writeAttribute("type", itemSubType); + writeElement(xml); + xml->writeEndElement(); +} + +SerializableItem_Map::~SerializableItem_Map() +{ + QMapIterator mapIterator(itemMap); + while (mapIterator.hasNext()) + delete mapIterator.next().value(); + for (int i = 0; i < itemList.size(); ++i) + delete itemList[i]; +} + +void SerializableItem_Map::readElement(QXmlStreamReader *xml) +{ + if (currentItem) { + if (currentItem->read(xml)) + currentItem = 0; + } else if (xml->isEndElement() && (xml->name() == itemType)) + extractData(); + else if (xml->isStartElement()) { + QString childName = xml->name().toString(); + QString childSubType = xml->attributes().value("type").toString(); + qDebug() << "Map: started new item, name=" << childName << "subtype=" << childSubType; + currentItem = itemMap.value(childName); + if (!currentItem) { + qDebug() << "Item not found in map"; + currentItem = getNewItem(childName + childSubType); + itemList.append(currentItem); + if (!currentItem) { + qDebug() << "Item still not found"; + currentItem = new SerializableItem_Invalid(childName); + } + } + if (currentItem->read(xml)) + currentItem = 0; + } +} + +void SerializableItem_Map::writeElement(QXmlStreamWriter *xml) +{ + QMapIterator mapIterator(itemMap); + while (mapIterator.hasNext()) + mapIterator.next().value()->write(xml); + for (int i = 0; i < itemList.size(); ++i) + itemList[i]->write(xml); +} + +void SerializableItem_String::readElement(QXmlStreamReader *xml) +{ + if (xml->isCharacters() && !xml->isWhitespace()) + data = xml->text().toString(); +} + +void SerializableItem_String::writeElement(QXmlStreamWriter *xml) +{ + xml->writeCharacters(data); +} + +void SerializableItem_Int::readElement(QXmlStreamReader *xml) +{ + if (xml->isCharacters() && !xml->isWhitespace()) { + bool ok; + data = xml->text().toString().toInt(&ok); + if (!ok) + data = -1; + } +} + +void SerializableItem_Int::writeElement(QXmlStreamWriter *xml) +{ + xml->writeCharacters(QString::number(data)); +} + +void SerializableItem_Bool::readElement(QXmlStreamReader *xml) +{ + if (xml->isCharacters() && !xml->isWhitespace()) + data = xml->text().toString() == "1"; +} + +void SerializableItem_Bool::writeElement(QXmlStreamWriter *xml) +{ + xml->writeCharacters(data ? "1" : "0"); +} + +int SerializableItem_Color::colorToInt(const QColor &color) const +{ + return color.red() * 65536 + color.green() * 256 + color.blue(); +} + +QColor SerializableItem_Color::colorFromInt(int colorValue) const +{ + return QColor(colorValue / 65536, (colorValue % 65536) / 256, colorValue % 256); +} + +void SerializableItem_Color::readElement(QXmlStreamReader *xml) +{ + if (xml->isCharacters() && !xml->isWhitespace()) { + bool ok; + int colorValue = xml->text().toString().toInt(&ok); + data = ok ? colorFromInt(colorValue) : Qt::black; + } +} + +void SerializableItem_Color::writeElement(QXmlStreamWriter *xml) +{ + xml->writeCharacters(QString::number(colorToInt(data))); +} + +void SerializableItem_DateTime::readElement(QXmlStreamReader *xml) +{ + if (xml->isCharacters() && !xml->isWhitespace()) { + bool ok; + unsigned int dateTimeValue = xml->text().toString().toUInt(&ok); + data = ok ? QDateTime::fromTime_t(dateTimeValue) : QDateTime(); + } +} + +void SerializableItem_DateTime::writeElement(QXmlStreamWriter *xml) +{ + xml->writeCharacters(QString::number(data.toTime_t())); +} diff --git a/common/serializable_item.h b/common/serializable_item.h new file mode 100644 index 00000000..5003bd81 --- /dev/null +++ b/common/serializable_item.h @@ -0,0 +1,140 @@ +#ifndef SERIALIZABLE_ITEM_H +#define SERIALIZABLE_ITEM_H + +#include +#include +#include +#include +#include +#include + +class QXmlStreamReader; +class QXmlStreamWriter; + +class SerializableItem : public QObject { + Q_OBJECT +protected: + typedef SerializableItem *(*NewItemFunction)(); + static QHash itemNameHash; + + QString itemType, itemSubType; +public: + SerializableItem(const QString &_itemType, const QString &_itemSubType = QString()) + : QObject(), itemType(_itemType), itemSubType(_itemSubType) { } + static void registerSerializableItem(const QString &name, NewItemFunction func); + static SerializableItem *getNewItem(const QString &name); + const QString &getItemType() const { return itemType; } + const QString &getItemSubType() const { return itemSubType; } + virtual void readElement(QXmlStreamReader *xml) = 0; + virtual void writeElement(QXmlStreamWriter *xml) = 0; + bool read(QXmlStreamReader *xml); + void write(QXmlStreamWriter *xml); +}; + +class SerializableItem_Invalid : public SerializableItem { +public: + SerializableItem_Invalid(const QString &_itemType) : SerializableItem(_itemType) { } + void readElement(QXmlStreamReader * /*xml*/) { } + void writeElement(QXmlStreamWriter * /*xml*/) { } +}; + +class SerializableItem_Map : public SerializableItem { +private: + SerializableItem *currentItem; +protected: + QMap itemMap; + QList itemList; + virtual void extractData() { } + void insertItem(SerializableItem *item) + { + itemMap.insert(item->getItemType(), item); + } + template QList typecastItemList() const + { + QList result; + for (int i = 0; i < itemList.size(); ++i) { + T item = dynamic_cast(itemList[i]); + if (item) + result.append(item); + } + return result; + } +public: + SerializableItem_Map(const QString &_itemType, const QString &_itemSubType = QString()) + : SerializableItem(_itemType, _itemSubType), currentItem(0) + { + } + ~SerializableItem_Map(); + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); + void appendItem(SerializableItem *item) { itemList.append(item); } +}; + +class SerializableItem_String : public SerializableItem { +private: + QString data; +protected: + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); +public: + SerializableItem_String(const QString &_itemType, const QString &_data) + : SerializableItem(_itemType), data(_data) { } + const QString &getData() { return data; } + void setData(const QString &_data) { data = _data; } +}; + +class SerializableItem_Int : public SerializableItem { +private: + int data; +protected: + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); +public: + SerializableItem_Int(const QString &_itemType, int _data) + : SerializableItem(_itemType), data(_data) { } + int getData() { return data; } + void setData(int _data) { data = _data; } +}; + +class SerializableItem_Bool : public SerializableItem { +private: + bool data; +protected: + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); +public: + SerializableItem_Bool(const QString &_itemType, bool _data) + : SerializableItem(_itemType), data(_data) { } + bool getData() { return data; } + void setData(bool _data) { data = _data; } +}; + +class SerializableItem_Color : public SerializableItem { +private: + QColor data; + int colorToInt(const QColor &color) const; + QColor colorFromInt(int colorValue) const; +protected: + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); +public: + SerializableItem_Color(const QString &_itemType, const QColor &_data) + : SerializableItem(_itemType), data(_data) { } + const QColor &getData() { return data; } + void setData(const QColor &_data) { data = _data; } +}; + +class SerializableItem_DateTime : public SerializableItem { +private: + QDateTime data; +protected: + void readElement(QXmlStreamReader *xml); + void writeElement(QXmlStreamWriter *xml); +public: + SerializableItem_DateTime(const QString &_itemType, const QDateTime &_data) + : SerializableItem(_itemType), data(_data) { } + const QDateTime &getData() { return data; } + void setData(const QDateTime &_data) { data = _data; } +}; + +#endif diff --git a/common/server.cpp b/common/server.cpp index 86682a04..4ab47c10 100644 --- a/common/server.cpp +++ b/common/server.cpp @@ -61,10 +61,10 @@ Server_Game *Server::getGame(int gameId) const void Server::broadcastGameListUpdate(Server_Game *game) { - Event_ListGames *event = new Event_ListGames; + QList eventGameList; if (game->getPlayerCount()) // Game is open - event->addGame( + eventGameList.append(new ServerInfo_Game( game->getGameId(), game->getDescription(), !game->getPassword().isEmpty(), @@ -73,10 +73,11 @@ void Server::broadcastGameListUpdate(Server_Game *game) game->getCreatorName(), game->getSpectatorsAllowed(), game->getSpectatorCount() - ); + )); else // Game is closing - event->addGame(game->getGameId(), QString(), false, 0, game->getMaxPlayers(), QString(), false, 0); + eventGameList.append(new ServerInfo_Game(game->getGameId(), QString(), false, 0, game->getMaxPlayers(), QString(), false, 0)); + Event_ListGames *event = new Event_ListGames(eventGameList); for (int i = 0; i < clients.size(); i++) if (clients[i]->getAcceptsGameListChanges()) @@ -87,8 +88,9 @@ void Server::broadcastGameListUpdate(Server_Game *game) void Server::broadcastChannelUpdate() { Server_ChatChannel *channel = static_cast(sender()); - Event_ListChatChannels *event = new Event_ListChatChannels; - event->addChannel(channel->getName(), channel->getDescription(), channel->size(), channel->getAutoJoin()); + QList eventChannelList; + eventChannelList.append(new ServerInfo_ChatChannel(channel->getName(), channel->getDescription(), channel->size(), channel->getAutoJoin())); + Event_ListChatChannels *event = new Event_ListChatChannels(eventChannelList); for (int i = 0; i < clients.size(); ++i) if (clients[i]->getAcceptsChatChannelListChanges()) diff --git a/common/server_chatchannel.cpp b/common/server_chatchannel.cpp index 6a3679fc..f88a517e 100644 --- a/common/server_chatchannel.cpp +++ b/common/server_chatchannel.cpp @@ -11,9 +11,10 @@ void Server_ChatChannel::addClient(Server_ProtocolHandler *client) sendChatEvent(new Event_ChatJoinChannel(name, client->getPlayerName())); append(client); - Event_ChatListPlayers *eventCLP = new Event_ChatListPlayers(name); + QList eventUserList; for (int i = 0; i < size(); ++i) - eventCLP->addPlayer(at(i)->getPlayerName()); + eventUserList.append(new ServerInfo_ChatUser(at(i)->getPlayerName())); + Event_ChatListPlayers *eventCLP = new Event_ChatListPlayers(name, eventUserList); client->enqueueProtocolItem(eventCLP); client->enqueueProtocolItem(new Event_ChatSay(name, QString(), joinMessage)); diff --git a/common/server_protocolhandler.cpp b/common/server_protocolhandler.cpp index f38bfde9..d7861f6d 100644 --- a/common/server_protocolhandler.cpp +++ b/common/server_protocolhandler.cpp @@ -10,6 +10,7 @@ #include "server_counter.h" #include "server_game.h" #include "server_player.h" +#include "decklist.h" Server_ProtocolHandler::Server_ProtocolHandler(Server *_server, QObject *parent) : QObject(parent), server(_server), authState(PasswordWrong), acceptsGameListChanges(false) @@ -148,13 +149,13 @@ ResponseCode Server_ProtocolHandler::cmdListChatChannels(Command_ListChatChannel if (authState == PasswordWrong) return RespLoginNeeded; - Event_ListChatChannels *event = new Event_ListChatChannels; + QList eventChannelList; QMapIterator channelIterator(server->getChatChannels()); while (channelIterator.hasNext()) { Server_ChatChannel *c = channelIterator.next().value(); - event->addChannel(c->getName(), c->getDescription(), c->size(), c->getAutoJoin()); + eventChannelList.append(new ServerInfo_ChatChannel(c->getName(), c->getDescription(), c->size(), c->getAutoJoin())); } - sendProtocolItem(event); + sendProtocolItem(new Event_ListChatChannels(eventChannelList)); acceptsChatChannelListChanges = true; return RespOk; @@ -193,11 +194,11 @@ ResponseCode Server_ProtocolHandler::cmdChatSay(Command_ChatSay *cmd, Server_Cha ResponseCode Server_ProtocolHandler::cmdListGames(Command_ListGames * /*cmd*/) { - Event_ListGames *event = new Event_ListGames; const QList &gameList = server->getGames(); + QList eventGameList; for (int i = 0; i < gameList.size(); ++i) { Server_Game *g = gameList[i]; - event->addGame( + eventGameList.append(new ServerInfo_Game( g->getGameId(), g->getDescription(), !g->getPassword().isEmpty(), @@ -206,9 +207,9 @@ ResponseCode Server_ProtocolHandler::cmdListGames(Command_ListGames * /*cmd*/) g->getCreatorName(), g->getSpectatorsAllowed(), g->getSpectatorCount() - ); + )); } - sendProtocolItem(event); + sendProtocolItem(new Event_ListGames(eventGameList)); acceptsGameListChanges = true; return RespOk; @@ -253,7 +254,7 @@ ResponseCode Server_ProtocolHandler::cmdDeckSelect(Command_DeckSelect *cmd, Serv if (cmd->getDeckId() == -1) { if (!cmd->getDeck()) return RespInvalidData; - deck = cmd->getDeck(); + deck = new DeckList(cmd->getDeck()); } else { try { deck = getDeckFromDatabase(cmd->getDeckId()); @@ -265,7 +266,7 @@ ResponseCode Server_ProtocolHandler::cmdDeckSelect(Command_DeckSelect *cmd, Serv game->sendGameEvent(new Event_DeckSelect(-1, player->getPlayerId(), cmd->getDeckId())); - sendProtocolItem(new Response_DeckDownload(cmd->getCmdId(), RespOk, deck)); + sendProtocolItem(new Response_DeckDownload(cmd->getCmdId(), RespOk, new DeckList(deck))); return RespNothing; } @@ -427,7 +428,7 @@ ResponseCode Server_ProtocolHandler::cmdCreateArrow(Command_CreateArrow *cmd, Se Server_Arrow *arrow = new Server_Arrow(player->newArrowId(), startCard, targetCard, cmd->getColor()); player->addArrow(arrow); - game->sendGameEvent(new Event_CreateArrow(-1, player->getPlayerId(), new ServerInfo_Arrow( + game->sendGameEvent(new Event_CreateArrows(-1, player->getPlayerId(), QList() << new ServerInfo_Arrow( arrow->getId(), startPlayer->getPlayerId(), startZone->getName(), @@ -500,7 +501,7 @@ ResponseCode Server_ProtocolHandler::cmdCreateCounter(Command_CreateCounter *cmd { Server_Counter *c = new Server_Counter(player->newCounterId(), cmd->getCounterName(), cmd->getColor(), cmd->getRadius(), cmd->getValue()); player->addCounter(c); - game->sendGameEvent(new Event_CreateCounter(-1, player->getPlayerId(), new ServerInfo_Counter(c->getId(), c->getName(), c->getColor(), c->getRadius(), c->getCount()))); + game->sendGameEvent(new Event_CreateCounters(-1, player->getPlayerId(), QList() << new ServerInfo_Counter(c->getId(), c->getName(), c->getColor(), c->getRadius(), c->getCount()))); return RespOk; } diff --git a/servatrice/servatrice.pro b/servatrice/servatrice.pro index c0de29fe..67166963 100755 --- a/servatrice/servatrice.pro +++ b/servatrice/servatrice.pro @@ -14,6 +14,7 @@ QT += network sql HEADERS += src/servatrice.h \ src/serversocketinterface.h \ + ../common/serializable_item.h \ ../common/decklist.h \ ../common/protocol.h \ ../common/protocol_items.h \ @@ -33,6 +34,7 @@ HEADERS += src/servatrice.h \ SOURCES += src/main.cpp \ src/servatrice.cpp \ src/serversocketinterface.cpp \ + ../common/serializable_item.cpp \ ../common/decklist.cpp \ ../common/protocol.cpp \ ../common/protocol_items.cpp \ diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index 4cd34707..d535ae92 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -29,7 +29,7 @@ #include "server_player.h" ServerSocketInterface::ServerSocketInterface(Servatrice *_server, QTcpSocket *_socket, QObject *parent) - : Server_ProtocolHandler(_server, parent), servatrice(_server), socket(_socket), currentItem(0) + : Server_ProtocolHandler(_server, parent), servatrice(_server), socket(_socket), topLevelItem(0) { xmlWriter = new QXmlStreamWriter; xmlWriter->setDevice(socket); @@ -57,41 +57,31 @@ ServerSocketInterface::~ServerSocketInterface() delete socket; } -void ServerSocketInterface::itemFinishedReading() +void ServerSocketInterface::processProtocolItem(ProtocolItem *item) { - Command *command = qobject_cast(currentItem); - if (qobject_cast(command)) + Command *command = qobject_cast(item); + if (!command) sendProtocolItem(new ProtocolResponse(command->getCmdId(), RespInvalidCommand)); else processCommand(command); - currentItem = 0; } void ServerSocketInterface::readClient() { xmlReader->addData(socket->readAll()); - if (currentItem) { - if (!currentItem->read(xmlReader)) - return; - itemFinishedReading(); - } - while (!xmlReader->atEnd()) { - xmlReader->readNext(); - if (xmlReader->isStartElement()) { - QString itemType = xmlReader->name().toString(); - if (itemType == "cockatrice_client_stream") - continue; - QString itemName = xmlReader->attributes().value("name").toString(); - qDebug() << "parseXml: startElement: " << "type =" << itemType << ", name =" << itemName; - currentItem = ProtocolItem::getNewItem(itemType + itemName); - if (!currentItem) - currentItem = new InvalidCommand; - if (!currentItem->read(xmlReader)) - return; - itemFinishedReading(); + if (topLevelItem) + topLevelItem->read(xmlReader); + else + while (!xmlReader->atEnd()) { + xmlReader->readNext(); + if (xmlReader->isStartElement() && (xmlReader->name().toString() == "cockatrice_client_stream")) { + topLevelItem = new TopLevelProtocolItem; + connect(topLevelItem, SIGNAL(protocolItemReceived(ProtocolItem *)), this, SLOT(processProtocolItem(ProtocolItem *))); + + topLevelItem->read(xmlReader); + } } - } } void ServerSocketInterface::catchSocketError(QAbstractSocket::SocketError socketError) @@ -147,7 +137,7 @@ bool ServerSocketInterface::deckListHelper(DeckList_Directory *folder) while (query.next()) { DeckList_Directory *newFolder = new DeckList_Directory(query.value(1).toString(), query.value(0).toInt()); - folder->append(newFolder); + folder->appendItem(newFolder); if (!deckListHelper(newFolder)) return false; } @@ -160,7 +150,7 @@ bool ServerSocketInterface::deckListHelper(DeckList_Directory *folder) while (query.next()) { DeckList_File *newFile = new DeckList_File(query.value(1).toString(), query.value(0).toInt(), query.value(2).toDateTime()); - folder->append(newFile); + folder->appendItem(newFile); } return true; @@ -266,7 +256,7 @@ ResponseCode ServerSocketInterface::cmdDeckUpload(Command_DeckUpload *cmd) QString deckContents; QXmlStreamWriter deckWriter(&deckContents); deckWriter.writeStartDocument(); - cmd->getDeck()->writeElement(&deckWriter); + cmd->getDeck()->write(&deckWriter); deckWriter.writeEndDocument(); QString deckName = cmd->getDeck()->getName(); @@ -281,8 +271,6 @@ ResponseCode ServerSocketInterface::cmdDeckUpload(Command_DeckUpload *cmd) query.bindValue(":content", deckContents); servatrice->execSqlQuery(query); - delete cmd->getDeck(); - sendProtocolItem(new Response_DeckUpload(cmd->getCmdId(), RespOk, new DeckList_File(deckName, query.lastInsertId().toInt(), QDateTime::currentDateTime()))); return RespNothing; } @@ -302,8 +290,7 @@ DeckList *ServerSocketInterface::getDeckFromDatabase(int deckId) QXmlStreamReader deckReader(query.value(0).toString()); DeckList *deck = new DeckList; - if (!deck->loadFromXml(&deckReader)) - throw RespInvalidData; + deck->loadFromXml(&deckReader); return deck; } @@ -317,6 +304,5 @@ ResponseCode ServerSocketInterface::cmdDeckDownload(Command_DeckDownload *cmd) return r; } sendProtocolItem(new Response_DeckDownload(cmd->getCmdId(), RespOk, deck)); - delete deck; return RespNothing; } diff --git a/servatrice/src/serversocketinterface.h b/servatrice/src/serversocketinterface.h index 2dae2f2b..e4994955 100644 --- a/servatrice/src/serversocketinterface.h +++ b/servatrice/src/serversocketinterface.h @@ -28,6 +28,7 @@ class Servatrice; class QXmlStreamReader; class QXmlStreamWriter; class DeckList; +class TopLevelProtocolItem; class ServerSocketInterface : public Server_ProtocolHandler { @@ -35,12 +36,13 @@ class ServerSocketInterface : public Server_ProtocolHandler private slots: void readClient(); void catchSocketError(QAbstractSocket::SocketError socketError); + void processProtocolItem(ProtocolItem *item); private: Servatrice *servatrice; QTcpSocket *socket; QXmlStreamWriter *xmlWriter; QXmlStreamReader *xmlReader; - ProtocolItem *currentItem; + TopLevelProtocolItem *topLevelItem; int getDeckPathId(int basePathId, QStringList path); int getDeckPathId(const QString &path); @@ -53,8 +55,6 @@ private: ResponseCode cmdDeckUpload(Command_DeckUpload *cmd); DeckList *getDeckFromDatabase(int deckId); ResponseCode cmdDeckDownload(Command_DeckDownload *cmd); - - void itemFinishedReading(); public: ServerSocketInterface(Servatrice *_server, QTcpSocket *_socket, QObject *parent = 0); ~ServerSocketInterface();