From 67c4d089be15f2704bcdb76f4ed3dfceddafdc73 Mon Sep 17 00:00:00 2001 From: jfreake Date: Wed, 8 Jan 2014 11:54:02 -0400 Subject: [PATCH 01/10] Deck Load Mods and Movable Tabs Changes: Deck Load - Default to all types *.* Decklist - Strip "|edition" from .dec formats that include a pipe and the edition after the card name Tab_Supervisor - Make tabs movable (able to rearrange tabs) --- cockatrice/src/deck_loader.cpp | 8 ++++---- cockatrice/src/tab_supervisor.cpp | 1 + common/decklist.cpp | 4 ++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cockatrice/src/deck_loader.cpp b/cockatrice/src/deck_loader.cpp index b0e34d80..e4678711 100644 --- a/cockatrice/src/deck_loader.cpp +++ b/cockatrice/src/deck_loader.cpp @@ -4,9 +4,9 @@ #include "decklist.h" const QStringList DeckLoader::fileNameFilters = QStringList() + << QObject::tr("All files (*.*)") << QObject::tr("Cockatrice decks (*.cod)") - << QObject::tr("Plain text decks (*.dec *.mwDeck)") - << QObject::tr("All files (*.*)"); + << QObject::tr("Plain text decks (*.dec *.mwDeck)"); DeckLoader::DeckLoader() : DeckList(), @@ -94,8 +94,8 @@ bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) DeckLoader::FileFormat DeckLoader::getFormatFromNameFilter(const QString &selectedNameFilter) { switch (fileNameFilters.indexOf(selectedNameFilter)) { - case 0: return CockatriceFormat; - case 1: return PlainTextFormat; + case 1: return CockatriceFormat; + case 2: return PlainTextFormat; } return PlainTextFormat; } diff --git a/cockatrice/src/tab_supervisor.cpp b/cockatrice/src/tab_supervisor.cpp index fde4ff6e..f5a06d67 100644 --- a/cockatrice/src/tab_supervisor.cpp +++ b/cockatrice/src/tab_supervisor.cpp @@ -80,6 +80,7 @@ TabSupervisor::TabSupervisor(AbstractClient *_client, QWidget *parent) { tabChangedIcon = new QIcon(":/resources/icon_tab_changed.svg"); setElideMode(Qt::ElideRight); + setMovable(true); setIconSize(QSize(15, 15)); connect(this, SIGNAL(currentChanged(int)), this, SLOT(updateCurrent(int))); diff --git a/common/decklist.cpp b/common/decklist.cpp index 7c1430a6..57e1e188 100644 --- a/common/decklist.cpp +++ b/common/decklist.cpp @@ -449,8 +449,12 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) line.remove(rx); rx.setPattern("\\(.*\\)"); line.remove(rx); + //Filter out post card name editions + rx.setPattern("\\|.*"); + line.remove(rx); line = line.simplified(); + int i = line.indexOf(' '); bool ok; int number = line.left(i).toInt(&ok); From 504a56cf95c596a5fb314f7e4bab9a0b379ad917 Mon Sep 17 00:00:00 2001 From: jfreake Date: Wed, 8 Jan 2014 12:55:44 -0400 Subject: [PATCH 02/10] Right aligned the regex check decklist - Right aligned the regex check --- common/decklist.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/decklist.cpp b/common/decklist.cpp index 57e1e188..d9a3d7f3 100644 --- a/common/decklist.cpp +++ b/common/decklist.cpp @@ -450,7 +450,7 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) rx.setPattern("\\(.*\\)"); line.remove(rx); //Filter out post card name editions - rx.setPattern("\\|.*"); + rx.setPattern("\\|.*$"); line.remove(rx); line = line.simplified(); From 629668d7c0690a3431c214808740b844de134205 Mon Sep 17 00:00:00 2001 From: arxanas Date: Fri, 17 Jan 2014 20:30:06 -0500 Subject: [PATCH 03/10] Fix #34 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is @mcallahan's patch — see #35. I had to apply this diff by hand, because both `git` and `patch` refused to apply it and I didn't know how to resolve that. Consequently, there might be an error. --- cockatrice/src/deck_loader.cpp | 12 +++++------- cockatrice/src/deck_loader.h | 2 +- cockatrice/src/tab_deck_editor.cpp | 4 ++-- cockatrice/src/tab_game.cpp | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/cockatrice/src/deck_loader.cpp b/cockatrice/src/deck_loader.cpp index e4678711..5d8ff6e7 100644 --- a/cockatrice/src/deck_loader.cpp +++ b/cockatrice/src/deck_loader.cpp @@ -4,9 +4,8 @@ #include "decklist.h" const QStringList DeckLoader::fileNameFilters = QStringList() - << QObject::tr("All files (*.*)") - << QObject::tr("Cockatrice decks (*.cod)") - << QObject::tr("Plain text decks (*.dec *.mwDeck)"); + << QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)") + << QObject::tr("All files (*.*)"); DeckLoader::DeckLoader() : DeckList(), @@ -91,11 +90,10 @@ bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) return result; } -DeckLoader::FileFormat DeckLoader::getFormatFromNameFilter(const QString &selectedNameFilter) +DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) { - switch (fileNameFilters.indexOf(selectedNameFilter)) { - case 1: return CockatriceFormat; - case 2: return PlainTextFormat; + if (fileName.endsWith(".cod", Qt::CaseInsensitive)) { + return CockatriceFormat; } return PlainTextFormat; } diff --git a/cockatrice/src/deck_loader.h b/cockatrice/src/deck_loader.h index 53f9e583..892e4be4 100644 --- a/cockatrice/src/deck_loader.h +++ b/cockatrice/src/deck_loader.h @@ -23,7 +23,7 @@ public: FileFormat getLastFileFormat() const { return lastFileFormat; } int getLastRemoteDeckId() const { return lastRemoteDeckId; } - static FileFormat getFormatFromNameFilter(const QString &selectedNameFilter); + static FileFormat getFormatFromName(const QString &fileName); bool loadFromFile(const QString &fileName, FileFormat fmt); bool loadFromRemote(const QString &nativeString, int remoteDeckId); diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 216958ac..f7c035c8 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -385,7 +385,7 @@ void TabDeckEditor::actLoadDeck() return; QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); DeckLoader *l = new DeckLoader; if (l->loadFromFile(fileName, fmt)) @@ -438,7 +438,7 @@ bool TabDeckEditor::actSaveDeckAs() return false; QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); if (!deckModel->getDeckList()->saveToFile(fileName, fmt)) { QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); diff --git a/cockatrice/src/tab_game.cpp b/cockatrice/src/tab_game.cpp index 17d5d33c..4bbd31a2 100644 --- a/cockatrice/src/tab_game.cpp +++ b/cockatrice/src/tab_game.cpp @@ -154,7 +154,7 @@ void DeckViewContainer::loadLocalDeck() return; QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); DeckLoader deck; if (!deck.loadFromFile(fileName, fmt)) { QMessageBox::critical(this, tr("Error"), tr("The selected file could not be loaded.")); From 91138b7e846bf54eb3dd8f20e89849c465dd1c89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Thu, 23 Jan 2014 12:42:57 +0100 Subject: [PATCH 04/10] Improved Linux/BSD section in the usermanual. --- doc/usermanual/Usermanual.pdf | Bin 2875381 -> 2876322 bytes doc/usermanual/Usermanual.tex | 17 ++++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/doc/usermanual/Usermanual.pdf b/doc/usermanual/Usermanual.pdf index 596382275085d97c2a04d1b79301cc0c7a3e95bf..361bf1574566543bd6cd16b3fcdccaf193cfc75c 100644 GIT binary patch delta 47846 zcmXuoLvSWQ0tMjMwr$(CZQHj0*tV^SZQHh;Ow36p+}YaN!&m+K-qnZqUi#~Si^uDM z6DfeXGnjWtsR3~b-3UWWaN@54VdEMk)<-?r=weAc5zx$PN=QfK=vZ&QJCKpl2y|@` zzVY_Jz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Ty;n zeF`PMO7b$lriz2Bzl{y@2=y1)mn5ducz+EWxb|)#sSDPrNwx;ask@($04fP%{uT;b zQvo{c1~ca&%C-P=uMqD0W>sJOoi?~Q%1z=#MAA9C%9ADpW!))n&dW)5N0_f!&ttLffAVce+!WX(`4_aidhfe zh-;c`u7Y?JO;?4deP!?B&gj&Lj=`ZuR!%u z-wq@_Pgi6Dy!2}iYG{AdYd3k_O6SXOK>r241#~b}L@ioF`}3Sb<@a<%EL)ikk&f!n z0iUu?ZinayA%d9*!HTIVl$Ra=VG{7wXL-^wz}xD#5MI0k9fc?Q7`W=A6F>}{F#OzdfdKS+ zA4h&|^nVW!inkvI2h!L88wa|xpRf-59Q-Zd(CWXpLw>t*7#Bh;2zyx34o*5~qXE)X z(B2M&REMzDH#ph8ci*)1/.local/share/data/Cockatrice/Cockatrice}. \end{enumerate} @@ -233,6 +236,10 @@ The compilation works like already written above, but instead of invoking \shell \item If you want to build the server, use:\\ \shellcmd{cmake -DWITH\_SERVER=1 ..} \item If you want to build the server, but not the client, use:\\ \shellcmd{cmake -DWITH\_SERVER=1 -DWITHOUT\_CLIENT=1 ..} \end{itemize} +Further, the server has a dependency on libgcrypt, so you need to install it as well: +\begin{description} + \item[FreeBSD 10] \shellcmd{pkg install libgcrypt} +\end{description} There is more information on compiling and running Servatrice on CentOS 6 in chapter \ref{servatrice} on page \pageref{servatrice}. \section{Downloading Card Database Using the Oracle} From 96ec49936ed2d1c78847dabdb15ec8e303c8abc5 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Tue, 11 Feb 2014 01:52:06 -0500 Subject: [PATCH 05/10] Resolve all compiler warnings --- cockatrice/src/abstractclient.cpp | 1 + cockatrice/src/cardzone.cpp | 1 + cockatrice/src/player.cpp | 5 +++-- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/cockatrice/src/abstractclient.cpp b/cockatrice/src/abstractclient.cpp index de823716..0ffb7179 100644 --- a/cockatrice/src/abstractclient.cpp +++ b/cockatrice/src/abstractclient.cpp @@ -82,6 +82,7 @@ void AbstractClient::processProtocolItem(const ServerMessage &item) case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break; case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break; case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break; + default: break; } break; } diff --git a/cockatrice/src/cardzone.cpp b/cockatrice/src/cardzone.cpp index a5fa3e18..6ad653a6 100644 --- a/cockatrice/src/cardzone.cpp +++ b/cockatrice/src/cardzone.cpp @@ -143,6 +143,7 @@ QString CardZone::getTranslatedName(bool hisOwn, GrammaticalCase gc) const ? tr("his sideboard", "nominative, male owner") : tr("%1's sideboard", "nominative, male owner").arg(ownerName) ); + default: break; } return QString(); } diff --git a/cockatrice/src/player.cpp b/cockatrice/src/player.cpp index 7a31a08c..6d5720a6 100644 --- a/cockatrice/src/player.cpp +++ b/cockatrice/src/player.cpp @@ -1514,8 +1514,8 @@ void Player::playCard(CardItem *c, bool faceDown, bool tapped) CardInfo *ci = c->getInfo(); if ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || - (settingsCache->getPlayToStack() && ci->getTableRow() != 0) && - c->getZone()->getName().toStdString() != "stack") { + ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && + c->getZone()->getName().toStdString() != "stack")) { cmd.set_target_zone("stack"); cmd.set_x(0); cmd.set_y(0); @@ -1784,6 +1784,7 @@ void Player::cardMenuAction() commandList.append(cmd); break; } + default: break; } } else { From ac8c967d10d47162ac17a227f9575f57fe6d4f87 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Tue, 11 Feb 2014 01:53:04 -0500 Subject: [PATCH 06/10] Remove compiler warnings from TODO --- TODO.md | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/TODO.md b/TODO.md index c4285db3..0dc0d849 100644 --- a/TODO.md +++ b/TODO.md @@ -28,7 +28,6 @@ Note that "improve" and "write" always also means: "document and comment" * Rename the picture filenames to something more meaningful. * Create an index, lists of tables/figures/... - ## Storage * Find a better place for sets.xml than doc. @@ -41,24 +40,6 @@ Note that "improve" and "write" always also means: "document and comment" * Document everything!1!! * Coding guidelines -##Fix compile warnings -* (CMAKE_VERBOSE_MAKEFILE, compile with clang++), this could indicate missing program functionality: - -``` -cockatrice/src/abstractclient.cpp:72:12: warning: enumeration value 'SessionEvent_SessionEventType_SERVER_COMPLETE_LIST' not handled in switch [-Wswitch] - switch ((SessionEvent::SessionEventType) getPbExtension(event)) { -``` - -``` -cockatrice/Cockatrice.VanNostrand/cockatrice/src/player.cpp:1725:12: warning: 4 enumeration values not handled in switch: 'cmMoveToTopLibrary', 'cmMoveToBottomLibrary', 'cmMoveToGraveyard'... [-Wswitch] - switch (static_cast(a->data().toInt())) { -``` - -``` -cockatrice/src/cardzone.cpp:127:11: warning: enumeration values 'CaseTopCardsOfZone', 'CaseRevealZone', and 'CaseShuffleZone' not handled in switch [-Wswitch] - switch (gc) { -``` - ##Else * Update SFMT library (http://www.math.sci.hiroshima-u.ac.jp/~m-mat@math.sci.hiroshima-u.ac.jp/MT/SFMT/) in common/sfmt and adapt common/rng_sfmt.cpp From a171df744d477c7c293566a097d45148ec1aa40f Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Tue, 11 Feb 2014 10:47:51 -0500 Subject: [PATCH 07/10] Convert to 4-space indents --- cockatrice/src/abstractclient.cpp | 194 +- cockatrice/src/cardzone.cpp | 386 ++-- cockatrice/src/player.cpp | 3270 ++++++++++++++--------------- 3 files changed, 1925 insertions(+), 1925 deletions(-) diff --git a/cockatrice/src/abstractclient.cpp b/cockatrice/src/abstractclient.cpp index 0ffb7179..f2e8915b 100644 --- a/cockatrice/src/abstractclient.cpp +++ b/cockatrice/src/abstractclient.cpp @@ -20,31 +20,31 @@ #include "client_metatypes.h" AbstractClient::AbstractClient(QObject *parent) - : QObject(parent), nextCmdId(0), status(StatusDisconnected) + : QObject(parent), nextCmdId(0), status(StatusDisconnected) { - qRegisterMetaType("QVariant"); - qRegisterMetaType("CommandContainer"); - qRegisterMetaType("Response"); - qRegisterMetaType("Response::ResponseCode"); - qRegisterMetaType("ClientStatus"); - qRegisterMetaType("RoomEvent"); - qRegisterMetaType("GameEventContainer"); - qRegisterMetaType("Event_ServerIdentification"); - qRegisterMetaType("Event_ConnectionClosed"); - qRegisterMetaType("Event_ServerShutdown"); - qRegisterMetaType("Event_AddToList"); - qRegisterMetaType("Event_RemoveFromList"); - qRegisterMetaType("Event_UserJoined"); - qRegisterMetaType("Event_UserLeft"); - qRegisterMetaType("Event_ServerMessage"); - qRegisterMetaType("Event_ListRooms"); - qRegisterMetaType("Event_GameJoined"); - qRegisterMetaType("Event_UserMessage"); - qRegisterMetaType("ServerInfo_User"); - qRegisterMetaType >("QList"); - qRegisterMetaType("Event_ReplayAdded"); - - connect(this, SIGNAL(sigQueuePendingCommand(PendingCommand *)), this, SLOT(queuePendingCommand(PendingCommand *))); + qRegisterMetaType("QVariant"); + qRegisterMetaType("CommandContainer"); + qRegisterMetaType("Response"); + qRegisterMetaType("Response::ResponseCode"); + qRegisterMetaType("ClientStatus"); + qRegisterMetaType("RoomEvent"); + qRegisterMetaType("GameEventContainer"); + qRegisterMetaType("Event_ServerIdentification"); + qRegisterMetaType("Event_ConnectionClosed"); + qRegisterMetaType("Event_ServerShutdown"); + qRegisterMetaType("Event_AddToList"); + qRegisterMetaType("Event_RemoveFromList"); + qRegisterMetaType("Event_UserJoined"); + qRegisterMetaType("Event_UserLeft"); + qRegisterMetaType("Event_ServerMessage"); + qRegisterMetaType("Event_ListRooms"); + qRegisterMetaType("Event_GameJoined"); + qRegisterMetaType("Event_UserMessage"); + qRegisterMetaType("ServerInfo_User"); + qRegisterMetaType >("QList"); + qRegisterMetaType("Event_ReplayAdded"); + + connect(this, SIGNAL(sigQueuePendingCommand(PendingCommand *)), this, SLOT(queuePendingCommand(PendingCommand *))); } AbstractClient::~AbstractClient() @@ -53,110 +53,110 @@ AbstractClient::~AbstractClient() void AbstractClient::processProtocolItem(const ServerMessage &item) { - switch (item.message_type()) { - case ServerMessage::RESPONSE: { - const Response &response = item.response(); - const int cmdId = response.cmd_id(); - - PendingCommand *pend = pendingCommands.value(cmdId, 0); - if (!pend) - return; - pendingCommands.remove(cmdId); - - pend->processResponse(response); - pend->deleteLater(); - break; - } - case ServerMessage::SESSION_EVENT: { - const SessionEvent &event = item.session_event(); - switch ((SessionEvent::SessionEventType) getPbExtension(event)) { - case SessionEvent::SERVER_IDENTIFICATION: emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext)); break; - case SessionEvent::SERVER_MESSAGE: emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext)); break; - case SessionEvent::SERVER_SHUTDOWN: emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext)); break; - case SessionEvent::CONNECTION_CLOSED: emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext)); break; - case SessionEvent::USER_MESSAGE: emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext)); break; - case SessionEvent::LIST_ROOMS: emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext)); break; - case SessionEvent::ADD_TO_LIST: emit addToListEventReceived(event.GetExtension(Event_AddToList::ext)); break; - case SessionEvent::REMOVE_FROM_LIST: emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext)); break; - case SessionEvent::USER_JOINED: emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext)); break; - case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break; - case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break; - case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break; + switch (item.message_type()) { + case ServerMessage::RESPONSE: { + const Response &response = item.response(); + const int cmdId = response.cmd_id(); + + PendingCommand *pend = pendingCommands.value(cmdId, 0); + if (!pend) + return; + pendingCommands.remove(cmdId); + + pend->processResponse(response); + pend->deleteLater(); + break; + } + case ServerMessage::SESSION_EVENT: { + const SessionEvent &event = item.session_event(); + switch ((SessionEvent::SessionEventType) getPbExtension(event)) { + case SessionEvent::SERVER_IDENTIFICATION: emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext)); break; + case SessionEvent::SERVER_MESSAGE: emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext)); break; + case SessionEvent::SERVER_SHUTDOWN: emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext)); break; + case SessionEvent::CONNECTION_CLOSED: emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext)); break; + case SessionEvent::USER_MESSAGE: emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext)); break; + case SessionEvent::LIST_ROOMS: emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext)); break; + case SessionEvent::ADD_TO_LIST: emit addToListEventReceived(event.GetExtension(Event_AddToList::ext)); break; + case SessionEvent::REMOVE_FROM_LIST: emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext)); break; + case SessionEvent::USER_JOINED: emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext)); break; + case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break; + case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break; + case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break; default: break; - } - break; - } - case ServerMessage::GAME_EVENT_CONTAINER: { - emit gameEventContainerReceived(item.game_event_container()); - break; - } - case ServerMessage::ROOM_EVENT: { - emit roomEventReceived(item.room_event()); - break; - } - } + } + break; + } + case ServerMessage::GAME_EVENT_CONTAINER: { + emit gameEventContainerReceived(item.game_event_container()); + break; + } + case ServerMessage::ROOM_EVENT: { + emit roomEventReceived(item.room_event()); + break; + } + } } void AbstractClient::setStatus(const ClientStatus _status) { - QMutexLocker locker(&clientMutex); - if (_status != status) { - status = _status; - emit statusChanged(_status); - } + QMutexLocker locker(&clientMutex); + if (_status != status) { + status = _status; + emit statusChanged(_status); + } } void AbstractClient::sendCommand(const CommandContainer &cont) { - sendCommand(new PendingCommand(cont)); + sendCommand(new PendingCommand(cont)); } void AbstractClient::sendCommand(PendingCommand *pend) { - pend->moveToThread(thread()); - emit sigQueuePendingCommand(pend); + pend->moveToThread(thread()); + emit sigQueuePendingCommand(pend); } void AbstractClient::queuePendingCommand(PendingCommand *pend) { - // This function is always called from the client thread via signal/slot. - const int cmdId = getNewCmdId(); - pend->getCommandContainer().set_cmd_id(cmdId); - - pendingCommands.insert(cmdId, pend); - - sendCommandContainer(pend->getCommandContainer()); + // This function is always called from the client thread via signal/slot. + const int cmdId = getNewCmdId(); + pend->getCommandContainer().set_cmd_id(cmdId); + + pendingCommands.insert(cmdId, pend); + + sendCommandContainer(pend->getCommandContainer()); } PendingCommand *AbstractClient::prepareSessionCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - SessionCommand *c = cont.add_session_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + SessionCommand *c = cont.add_session_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *AbstractClient::prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId) { - CommandContainer cont; - RoomCommand *c = cont.add_room_command(); - cont.set_room_id(roomId); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + RoomCommand *c = cont.add_room_command(); + cont.set_room_id(roomId); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *AbstractClient::prepareModeratorCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - ModeratorCommand *c = cont.add_moderator_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + ModeratorCommand *c = cont.add_moderator_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *AbstractClient::prepareAdminCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - AdminCommand *c = cont.add_admin_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + AdminCommand *c = cont.add_admin_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } diff --git a/cockatrice/src/cardzone.cpp b/cockatrice/src/cardzone.cpp index 6ad653a6..f09cac1f 100644 --- a/cockatrice/src/cardzone.cpp +++ b/cockatrice/src/cardzone.cpp @@ -10,257 +10,257 @@ #include "pb/serverinfo_user.pb.h" CardZone::CardZone(Player *_p, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool _isView) - : AbstractGraphicsItem(parent), player(_p), name(_name), cards(_contentsKnown), view(NULL), menu(NULL), doubleClickAction(0), hasCardAttr(_hasCardAttr), isShufflable(_isShufflable), isView(_isView) + : AbstractGraphicsItem(parent), player(_p), name(_name), cards(_contentsKnown), view(NULL), menu(NULL), doubleClickAction(0), hasCardAttr(_hasCardAttr), isShufflable(_isShufflable), isView(_isView) { - if (!isView) - player->addZone(this); + if (!isView) + player->addZone(this); } CardZone::~CardZone() { - qDebug() << "CardZone destructor: " << name; - delete view; - clearContents(); + qDebug() << "CardZone destructor: " << name; + delete view; + clearContents(); } void CardZone::retranslateUi() { - for (int i = 0; i < cards.size(); ++i) - cards[i]->retranslateUi(); + for (int i = 0; i < cards.size(); ++i) + cards[i]->retranslateUi(); } void CardZone::clearContents() { - for (int i = 0; i < cards.size(); i++) { - // If an incorrectly implemented server doesn't return attached cards to whom they belong before dropping a player, - // we have to return them to avoid a crash. - const QList &attachedCards = cards[i]->getAttachedCards(); - for (int j = 0; j < attachedCards.size(); ++j) - attachedCards[j]->setParentItem(attachedCards[j]->getZone()); - - player->deleteCard(cards.at(i)); - } - cards.clear(); - emit cardCountChanged(); + for (int i = 0; i < cards.size(); i++) { + // If an incorrectly implemented server doesn't return attached cards to whom they belong before dropping a player, + // we have to return them to avoid a crash. + const QList &attachedCards = cards[i]->getAttachedCards(); + for (int j = 0; j < attachedCards.size(); ++j) + attachedCards[j]->setParentItem(attachedCards[j]->getZone()); + + player->deleteCard(cards.at(i)); + } + cards.clear(); + emit cardCountChanged(); } QString CardZone::getTranslatedName(bool hisOwn, GrammaticalCase gc) const { - QString ownerName = player->getName(); - bool female = player->getUserInfo()->gender() == ServerInfo_User::Female; - if (name == "hand") - return female - ? (hisOwn - ? tr("her hand", "nominative, female owner") - : tr("%1's hand", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his hand", "nominative, male owner") - : tr("%1's hand", "nominative, male owner").arg(ownerName) - ); - else if (name == "deck") - switch (gc) { - case CaseLookAtZone: - return female - ? (hisOwn - ? tr("her library", "look at zone, female owner") - : tr("%1's library", "look at zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "look at zone, male owner") - : tr("%1's library", "look at zone, male owner").arg(ownerName) - ); - case CaseTopCardsOfZone: - return female - ? (hisOwn - ? tr("of her library", "top cards of zone, female owner") - : tr("of %1's library", "top cards of zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("of his library", "top cards of zone, male owner") - : tr("of %1's library", "top cards of zone, male owner").arg(ownerName) - ); - case CaseRevealZone: - return female - ? (hisOwn - ? tr("her library", "reveal zone, female owner") - : tr("%1's library", "reveal zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "reveal zone, male owner") - : tr("%1's library", "reveal zone, male owner").arg(ownerName) - ); - case CaseShuffleZone: - return female - ? (hisOwn - ? tr("her library", "shuffle, female owner") - : tr("%1's library", "shuffle, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "shuffle, male owner") - : tr("%1's library", "shuffle, male owner").arg(ownerName) - ); - default: - return female - ? (hisOwn - ? tr("her library", "nominative, female owner") - : tr("%1's library", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "nominative, male owner") - : tr("%1's library", "nominative, male owner").arg(ownerName) - ); - } - else if (name == "grave") - return female - ? (hisOwn - ? tr("her graveyard", "nominative, female owner") - : tr("%1's graveyard", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his graveyard", "nominative, male owner") - : tr("%1's graveyard", "nominative, male owner").arg(ownerName) - ); - else if (name == "rfg") - return female - ? (hisOwn - ? tr("her exile", "nominative, female owner") - : tr("%1's exile", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his exile", "nominative, male owner") - : tr("%1's exile", "nominative, male owner").arg(ownerName) - ); - else if (name == "sb") - switch (gc) { - case CaseLookAtZone: - return female - ? (hisOwn - ? tr("her sideboard", "look at zone, female owner") - : tr("%1's sideboard", "look at zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his sideboard", "look at zone, male owner") - : tr("%1's sideboard", "look at zone, male owner").arg(ownerName) - ); - case CaseNominative: - return female - ? (hisOwn - ? tr("her sideboard", "nominative, female owner") - : tr("%1's sideboard", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his sideboard", "nominative, male owner") - : tr("%1's sideboard", "nominative, male owner").arg(ownerName) - ); + QString ownerName = player->getName(); + bool female = player->getUserInfo()->gender() == ServerInfo_User::Female; + if (name == "hand") + return female + ? (hisOwn + ? tr("her hand", "nominative, female owner") + : tr("%1's hand", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his hand", "nominative, male owner") + : tr("%1's hand", "nominative, male owner").arg(ownerName) + ); + else if (name == "deck") + switch (gc) { + case CaseLookAtZone: + return female + ? (hisOwn + ? tr("her library", "look at zone, female owner") + : tr("%1's library", "look at zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "look at zone, male owner") + : tr("%1's library", "look at zone, male owner").arg(ownerName) + ); + case CaseTopCardsOfZone: + return female + ? (hisOwn + ? tr("of her library", "top cards of zone, female owner") + : tr("of %1's library", "top cards of zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("of his library", "top cards of zone, male owner") + : tr("of %1's library", "top cards of zone, male owner").arg(ownerName) + ); + case CaseRevealZone: + return female + ? (hisOwn + ? tr("her library", "reveal zone, female owner") + : tr("%1's library", "reveal zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "reveal zone, male owner") + : tr("%1's library", "reveal zone, male owner").arg(ownerName) + ); + case CaseShuffleZone: + return female + ? (hisOwn + ? tr("her library", "shuffle, female owner") + : tr("%1's library", "shuffle, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "shuffle, male owner") + : tr("%1's library", "shuffle, male owner").arg(ownerName) + ); + default: + return female + ? (hisOwn + ? tr("her library", "nominative, female owner") + : tr("%1's library", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "nominative, male owner") + : tr("%1's library", "nominative, male owner").arg(ownerName) + ); + } + else if (name == "grave") + return female + ? (hisOwn + ? tr("her graveyard", "nominative, female owner") + : tr("%1's graveyard", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his graveyard", "nominative, male owner") + : tr("%1's graveyard", "nominative, male owner").arg(ownerName) + ); + else if (name == "rfg") + return female + ? (hisOwn + ? tr("her exile", "nominative, female owner") + : tr("%1's exile", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his exile", "nominative, male owner") + : tr("%1's exile", "nominative, male owner").arg(ownerName) + ); + else if (name == "sb") + switch (gc) { + case CaseLookAtZone: + return female + ? (hisOwn + ? tr("her sideboard", "look at zone, female owner") + : tr("%1's sideboard", "look at zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his sideboard", "look at zone, male owner") + : tr("%1's sideboard", "look at zone, male owner").arg(ownerName) + ); + case CaseNominative: + return female + ? (hisOwn + ? tr("her sideboard", "nominative, female owner") + : tr("%1's sideboard", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his sideboard", "nominative, male owner") + : tr("%1's sideboard", "nominative, male owner").arg(ownerName) + ); default: break; - } - return QString(); + } + return QString(); } void CardZone::mouseDoubleClickEvent(QGraphicsSceneMouseEvent */*event*/) { - if (doubleClickAction) - doubleClickAction->trigger(); + if (doubleClickAction) + doubleClickAction->trigger(); } bool CardZone::showContextMenu(const QPoint &screenPos) { - if (menu) { - menu->exec(screenPos); - return true; - } - return false; + if (menu) { + menu->exec(screenPos); + return true; + } + return false; } void CardZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::RightButton) { - if (showContextMenu(event->screenPos())) - event->accept(); - else - event->ignore(); - } else - event->ignore(); + if (event->button() == Qt::RightButton) { + if (showContextMenu(event->screenPos())) + event->accept(); + else + event->ignore(); + } else + event->ignore(); } void CardZone::addCard(CardItem *card, bool reorganize, int x, int y) { - if (view) - if ((x <= view->getCards().size()) || (view->getNumberCards() == -1)) - view->addCard(new CardItem(player, card->getName(), card->getId()), reorganize, x, y); + if (view) + if ((x <= view->getCards().size()) || (view->getNumberCards() == -1)) + view->addCard(new CardItem(player, card->getName(), card->getId()), reorganize, x, y); - card->setZone(this); - addCardImpl(card, x, y); + card->setZone(this); + addCardImpl(card, x, y); - if (reorganize) - reorganizeCards(); - - emit cardCountChanged(); + if (reorganize) + reorganizeCards(); + + emit cardCountChanged(); } CardItem *CardZone::getCard(int cardId, const QString &cardName) { - CardItem *c = cards.findCard(cardId, false); - if (!c) { - qDebug() << "CardZone::getCard: card id=" << cardId << "not found"; - return 0; - } - // If the card's id is -1, this zone is invisible, - // so we need to give the card an id and a name as it comes out. - // It can be assumed that in an invisible zone, all cards are equal. - if ((c->getId() == -1) || (c->getName().isEmpty())) { - c->setId(cardId); - c->setName(cardName); - } - return c; + CardItem *c = cards.findCard(cardId, false); + if (!c) { + qDebug() << "CardZone::getCard: card id=" << cardId << "not found"; + return 0; + } + // If the card's id is -1, this zone is invisible, + // so we need to give the card an id and a name as it comes out. + // It can be assumed that in an invisible zone, all cards are equal. + if ((c->getId() == -1) || (c->getName().isEmpty())) { + c->setId(cardId); + c->setName(cardName); + } + return c; } CardItem *CardZone::takeCard(int position, int cardId, bool /*canResize*/) { - if (position == -1) { - // position == -1 means either that the zone is indexed by card id - // or that it doesn't matter which card you take. - for (int i = 0; i < cards.size(); ++i) - if (cards[i]->getId() == cardId) { - position = i; - break; - } - if (position == -1) - position = 0; - } - if (position >= cards.size()) - return 0; + if (position == -1) { + // position == -1 means either that the zone is indexed by card id + // or that it doesn't matter which card you take. + for (int i = 0; i < cards.size(); ++i) + if (cards[i]->getId() == cardId) { + position = i; + break; + } + if (position == -1) + position = 0; + } + if (position >= cards.size()) + return 0; - CardItem *c = cards.takeAt(position); + CardItem *c = cards.takeAt(position); - if (view) - view->removeCard(position); + if (view) + view->removeCard(position); - c->setId(cardId); + c->setId(cardId); - reorganizeCards(); - emit cardCountChanged(); - return c; + reorganizeCards(); + emit cardCountChanged(); + return c; } void CardZone::removeCard(CardItem *card) { - cards.removeAt(cards.indexOf(card)); - reorganizeCards(); - emit cardCountChanged(); - player->deleteCard(card); + cards.removeAt(cards.indexOf(card)); + reorganizeCards(); + emit cardCountChanged(); + player->deleteCard(card); } void CardZone::moveAllToZone() { - QList data = static_cast(sender())->data().toList(); - QString targetZone = data[0].toString(); - int targetX = data[1].toInt(); - - Command_MoveCard cmd; - cmd.set_start_zone(getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(targetZone.toStdString()); - cmd.set_x(targetX); - - for (int i = 0; i < cards.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(cards[i]->getId()); - - player->sendGameCommand(cmd); + QList data = static_cast(sender())->data().toList(); + QString targetZone = data[0].toString(); + int targetX = data[1].toInt(); + + Command_MoveCard cmd; + cmd.set_start_zone(getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(targetZone.toStdString()); + cmd.set_x(targetX); + + for (int i = 0; i < cards.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(cards[i]->getId()); + + player->sendGameCommand(cmd); } QPointF CardZone::closestGridPoint(const QPointF &point) { - return point; + return point; } diff --git a/cockatrice/src/player.cpp b/cockatrice/src/player.cpp index 6d5720a6..35d5bea9 100644 --- a/cockatrice/src/player.cpp +++ b/cockatrice/src/player.cpp @@ -66,1368 +66,1368 @@ #include "pb/event_change_zone_properties.pb.h" PlayerArea::PlayerArea(QGraphicsItem *parentItem) - : QObject(), QGraphicsItem(parentItem) + : QObject(), QGraphicsItem(parentItem) { - setCacheMode(DeviceCoordinateCache); - connect(settingsCache, SIGNAL(playerBgPathChanged()), this, SLOT(updateBgPixmap())); - updateBgPixmap(); + setCacheMode(DeviceCoordinateCache); + connect(settingsCache, SIGNAL(playerBgPathChanged()), this, SLOT(updateBgPixmap())); + updateBgPixmap(); } void PlayerArea::updateBgPixmap() { - QString bgPath = settingsCache->getPlayerBgPath(); - if (bgPath.isEmpty()) - bgPixmapBrush = QBrush(QColor(200, 200, 200)); - else { - qDebug() << "loading" << bgPath; - bgPixmapBrush = QBrush(QPixmap(bgPath)); - } - update(); + QString bgPath = settingsCache->getPlayerBgPath(); + if (bgPath.isEmpty()) + bgPixmapBrush = QBrush(QColor(200, 200, 200)); + else { + qDebug() << "loading" << bgPath; + bgPixmapBrush = QBrush(QPixmap(bgPath)); + } + update(); } void PlayerArea::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - painter->fillRect(bRect, bgPixmapBrush); + painter->fillRect(bRect, bgPixmapBrush); } void PlayerArea::setSize(qreal width, qreal height) { - prepareGeometryChange(); - bRect = QRectF(0, 0, width, height); + prepareGeometryChange(); + bRect = QRectF(0, 0, width, height); } Player::Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent) - : QObject(_parent), - game(_parent), - shortcutsActive(false), - defaultNumberTopCards(3), - lastTokenDestroy(true), - id(_id), - active(false), - local(_local), - mirrored(false), - handVisible(false), - conceded(false), - dialogSemaphore(false), - deck(0) + : QObject(_parent), + game(_parent), + shortcutsActive(false), + defaultNumberTopCards(3), + lastTokenDestroy(true), + id(_id), + active(false), + local(_local), + mirrored(false), + handVisible(false), + conceded(false), + dialogSemaphore(false), + deck(0) { - userInfo = new ServerInfo_User; - userInfo->CopyFrom(info); - - connect(settingsCache, SIGNAL(horizontalHandChanged()), this, SLOT(rearrangeZones())); - - playerArea = new PlayerArea(this); - - playerTarget = new PlayerTarget(this, playerArea); - qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; - playerTarget->setPos(QPointF(avatarMargin, avatarMargin)); + userInfo = new ServerInfo_User; + userInfo->CopyFrom(info); + + connect(settingsCache, SIGNAL(horizontalHandChanged()), this, SLOT(rearrangeZones())); + + playerArea = new PlayerArea(this); + + playerTarget = new PlayerTarget(this, playerArea); + qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; + playerTarget->setPos(QPointF(avatarMargin, avatarMargin)); - PileZone *deck = new PileZone(this, "deck", true, false, playerArea); - QPointF base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); - deck->setPos(base); + PileZone *deck = new PileZone(this, "deck", true, false, playerArea); + QPointF base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); + deck->setPos(base); - qreal h = deck->boundingRect().width() + 5; + qreal h = deck->boundingRect().width() + 5; - HandCounter *handCounter = new HandCounter(playerArea); - handCounter->setPos(base + QPointF(0, h + 10)); - qreal h2 = handCounter->boundingRect().height(); - - PileZone *grave = new PileZone(this, "grave", false, true, playerArea); - grave->setPos(base + QPointF(0, h + h2 + 10)); + HandCounter *handCounter = new HandCounter(playerArea); + handCounter->setPos(base + QPointF(0, h + 10)); + qreal h2 = handCounter->boundingRect().height(); + + PileZone *grave = new PileZone(this, "grave", false, true, playerArea); + grave->setPos(base + QPointF(0, h + h2 + 10)); - PileZone *rfg = new PileZone(this, "rfg", false, true, playerArea); - rfg->setPos(base + QPointF(0, 2 * h + h2 + 10)); + PileZone *rfg = new PileZone(this, "rfg", false, true, playerArea); + rfg->setPos(base + QPointF(0, 2 * h + h2 + 10)); - PileZone *sb = new PileZone(this, "sb", false, false, playerArea); - sb->setVisible(false); + PileZone *sb = new PileZone(this, "sb", false, false, playerArea); + sb->setVisible(false); - table = new TableZone(this, this); - connect(table, SIGNAL(sizeChanged()), this, SLOT(updateBoundingRect())); - - stack = new StackZone(this, (int) table->boundingRect().height(), this); - - hand = new HandZone(this, _local || (_parent->getSpectator() && _parent->getSpectatorsSeeEverything()), (int) table->boundingRect().height(), this); - connect(hand, SIGNAL(cardCountChanged()), handCounter, SLOT(updateNumber())); - connect(handCounter, SIGNAL(showContextMenu(const QPoint &)), hand, SLOT(showContextMenu(const QPoint &))); - - updateBoundingRect(); + table = new TableZone(this, this); + connect(table, SIGNAL(sizeChanged()), this, SLOT(updateBoundingRect())); + + stack = new StackZone(this, (int) table->boundingRect().height(), this); + + hand = new HandZone(this, _local || (_parent->getSpectator() && _parent->getSpectatorsSeeEverything()), (int) table->boundingRect().height(), this); + connect(hand, SIGNAL(cardCountChanged()), handCounter, SLOT(updateNumber())); + connect(handCounter, SIGNAL(showContextMenu(const QPoint &)), hand, SLOT(showContextMenu(const QPoint &))); + + updateBoundingRect(); - if (local) { - connect(_parent, SIGNAL(playerAdded(Player *)), this, SLOT(addPlayer(Player *))); - connect(_parent, SIGNAL(playerRemoved(Player *)), this, SLOT(removePlayer(Player *))); - - aMoveHandToTopLibrary = new QAction(this); - aMoveHandToTopLibrary->setData(QList() << "deck" << 0); - aMoveHandToBottomLibrary = new QAction(this); - aMoveHandToBottomLibrary->setData(QList() << "deck" << -1); - aMoveHandToGrave = new QAction(this); - aMoveHandToGrave->setData(QList() << "grave" << 0); - aMoveHandToRfg = new QAction(this); - aMoveHandToRfg->setData(QList() << "rfg" << 0); - - connect(aMoveHandToTopLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - connect(aMoveHandToBottomLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - connect(aMoveHandToGrave, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - connect(aMoveHandToRfg, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + if (local) { + connect(_parent, SIGNAL(playerAdded(Player *)), this, SLOT(addPlayer(Player *))); + connect(_parent, SIGNAL(playerRemoved(Player *)), this, SLOT(removePlayer(Player *))); + + aMoveHandToTopLibrary = new QAction(this); + aMoveHandToTopLibrary->setData(QList() << "deck" << 0); + aMoveHandToBottomLibrary = new QAction(this); + aMoveHandToBottomLibrary->setData(QList() << "deck" << -1); + aMoveHandToGrave = new QAction(this); + aMoveHandToGrave->setData(QList() << "grave" << 0); + aMoveHandToRfg = new QAction(this); + aMoveHandToRfg->setData(QList() << "rfg" << 0); + + connect(aMoveHandToTopLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + connect(aMoveHandToBottomLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + connect(aMoveHandToGrave, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + connect(aMoveHandToRfg, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - aMoveGraveToTopLibrary = new QAction(this); - aMoveGraveToTopLibrary->setData(QList() << "deck" << 0); - aMoveGraveToBottomLibrary = new QAction(this); - aMoveGraveToBottomLibrary->setData(QList() << "deck" << -1); - aMoveGraveToHand = new QAction(this); - aMoveGraveToHand->setData(QList() << "hand" << 0); - aMoveGraveToRfg = new QAction(this); - aMoveGraveToRfg->setData(QList() << "rfg" << 0); - - connect(aMoveGraveToTopLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - connect(aMoveGraveToBottomLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - connect(aMoveGraveToHand, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - connect(aMoveGraveToRfg, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + aMoveGraveToTopLibrary = new QAction(this); + aMoveGraveToTopLibrary->setData(QList() << "deck" << 0); + aMoveGraveToBottomLibrary = new QAction(this); + aMoveGraveToBottomLibrary->setData(QList() << "deck" << -1); + aMoveGraveToHand = new QAction(this); + aMoveGraveToHand->setData(QList() << "hand" << 0); + aMoveGraveToRfg = new QAction(this); + aMoveGraveToRfg->setData(QList() << "rfg" << 0); + + connect(aMoveGraveToTopLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + connect(aMoveGraveToBottomLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + connect(aMoveGraveToHand, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + connect(aMoveGraveToRfg, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - aMoveRfgToTopLibrary = new QAction(this); - aMoveRfgToTopLibrary->setData(QList() << "deck" << 0); - aMoveRfgToBottomLibrary = new QAction(this); - aMoveRfgToBottomLibrary->setData(QList() << "deck" << -1); - aMoveRfgToHand = new QAction(this); - aMoveRfgToHand->setData(QList() << "hand" << 0); - aMoveRfgToGrave = new QAction(this); - aMoveRfgToGrave->setData(QList() << "grave" << 0); - - connect(aMoveRfgToTopLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - connect(aMoveRfgToBottomLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - connect(aMoveRfgToHand, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - connect(aMoveRfgToGrave, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + aMoveRfgToTopLibrary = new QAction(this); + aMoveRfgToTopLibrary->setData(QList() << "deck" << 0); + aMoveRfgToBottomLibrary = new QAction(this); + aMoveRfgToBottomLibrary->setData(QList() << "deck" << -1); + aMoveRfgToHand = new QAction(this); + aMoveRfgToHand->setData(QList() << "hand" << 0); + aMoveRfgToGrave = new QAction(this); + aMoveRfgToGrave->setData(QList() << "grave" << 0); + + connect(aMoveRfgToTopLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + connect(aMoveRfgToBottomLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + connect(aMoveRfgToHand, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + connect(aMoveRfgToGrave, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - aViewLibrary = new QAction(this); - connect(aViewLibrary, SIGNAL(triggered()), this, SLOT(actViewLibrary())); - aViewTopCards = new QAction(this); - connect(aViewTopCards, SIGNAL(triggered()), this, SLOT(actViewTopCards())); - aAlwaysRevealTopCard = new QAction(this); - aAlwaysRevealTopCard->setCheckable(true); - connect(aAlwaysRevealTopCard, SIGNAL(triggered()), this, SLOT(actAlwaysRevealTopCard())); - aOpenDeckInDeckEditor = new QAction(this); - aOpenDeckInDeckEditor->setEnabled(false); - connect(aOpenDeckInDeckEditor, SIGNAL(triggered()), this, SLOT(actOpenDeckInDeckEditor())); - } + aViewLibrary = new QAction(this); + connect(aViewLibrary, SIGNAL(triggered()), this, SLOT(actViewLibrary())); + aViewTopCards = new QAction(this); + connect(aViewTopCards, SIGNAL(triggered()), this, SLOT(actViewTopCards())); + aAlwaysRevealTopCard = new QAction(this); + aAlwaysRevealTopCard->setCheckable(true); + connect(aAlwaysRevealTopCard, SIGNAL(triggered()), this, SLOT(actAlwaysRevealTopCard())); + aOpenDeckInDeckEditor = new QAction(this); + aOpenDeckInDeckEditor->setEnabled(false); + connect(aOpenDeckInDeckEditor, SIGNAL(triggered()), this, SLOT(actOpenDeckInDeckEditor())); + } - aViewGraveyard = new QAction(this); - connect(aViewGraveyard, SIGNAL(triggered()), this, SLOT(actViewGraveyard())); + aViewGraveyard = new QAction(this); + connect(aViewGraveyard, SIGNAL(triggered()), this, SLOT(actViewGraveyard())); - aViewRfg = new QAction(this); - connect(aViewRfg, SIGNAL(triggered()), this, SLOT(actViewRfg())); + aViewRfg = new QAction(this); + connect(aViewRfg, SIGNAL(triggered()), this, SLOT(actViewRfg())); - if (local) { - aViewSideboard = new QAction(this); - connect(aViewSideboard, SIGNAL(triggered()), this, SLOT(actViewSideboard())); - - aDrawCard = new QAction(this); - connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); - aDrawCards = new QAction(this); - connect(aDrawCards, SIGNAL(triggered()), this, SLOT(actDrawCards())); - aUndoDraw = new QAction(this); - connect(aUndoDraw, SIGNAL(triggered()), this, SLOT(actUndoDraw())); - aShuffle = new QAction(this); - connect(aShuffle, SIGNAL(triggered()), this, SLOT(actShuffle())); + if (local) { + aViewSideboard = new QAction(this); + connect(aViewSideboard, SIGNAL(triggered()), this, SLOT(actViewSideboard())); + + aDrawCard = new QAction(this); + connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); + aDrawCards = new QAction(this); + connect(aDrawCards, SIGNAL(triggered()), this, SLOT(actDrawCards())); + aUndoDraw = new QAction(this); + connect(aUndoDraw, SIGNAL(triggered()), this, SLOT(actUndoDraw())); + aShuffle = new QAction(this); + connect(aShuffle, SIGNAL(triggered()), this, SLOT(actShuffle())); aMulligan = new QAction(this); connect(aMulligan, SIGNAL(triggered()), this, SLOT(actMulligan())); - aMoveTopCardsToGrave = new QAction(this); - connect(aMoveTopCardsToGrave, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToGrave())); - aMoveTopCardsToExile = new QAction(this); - connect(aMoveTopCardsToExile, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToExile())); - aMoveTopCardToBottom = new QAction(this); - connect(aMoveTopCardToBottom, SIGNAL(triggered()), this, SLOT(actMoveTopCardToBottom())); - } + aMoveTopCardsToGrave = new QAction(this); + connect(aMoveTopCardsToGrave, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToGrave())); + aMoveTopCardsToExile = new QAction(this); + connect(aMoveTopCardsToExile, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToExile())); + aMoveTopCardToBottom = new QAction(this); + connect(aMoveTopCardToBottom, SIGNAL(triggered()), this, SLOT(actMoveTopCardToBottom())); + } - playerMenu = new QMenu(QString()); - table->setMenu(playerMenu); + playerMenu = new QMenu(QString()); + table->setMenu(playerMenu); - if (local) { - handMenu = playerMenu->addMenu(QString()); + if (local) { + handMenu = playerMenu->addMenu(QString()); handMenu->addAction(aMulligan); - handMenu->addAction(aMoveHandToTopLibrary); - handMenu->addAction(aMoveHandToBottomLibrary); - handMenu->addAction(aMoveHandToGrave); - handMenu->addAction(aMoveHandToRfg); - handMenu->addSeparator(); - playerLists.append(mRevealHand = handMenu->addMenu(QString())); - playerLists.append(mRevealRandomHandCard = handMenu->addMenu(QString())); - hand->setMenu(handMenu); + handMenu->addAction(aMoveHandToTopLibrary); + handMenu->addAction(aMoveHandToBottomLibrary); + handMenu->addAction(aMoveHandToGrave); + handMenu->addAction(aMoveHandToRfg); + handMenu->addSeparator(); + playerLists.append(mRevealHand = handMenu->addMenu(QString())); + playerLists.append(mRevealRandomHandCard = handMenu->addMenu(QString())); + hand->setMenu(handMenu); - libraryMenu = playerMenu->addMenu(QString()); - libraryMenu->addAction(aDrawCard); - libraryMenu->addAction(aDrawCards); - libraryMenu->addAction(aUndoDraw); - libraryMenu->addSeparator(); - libraryMenu->addAction(aShuffle); - libraryMenu->addSeparator(); - libraryMenu->addAction(aViewLibrary); - libraryMenu->addAction(aViewTopCards); - libraryMenu->addSeparator(); - playerLists.append(mRevealLibrary = libraryMenu->addMenu(QString())); - playerLists.append(mRevealTopCard = libraryMenu->addMenu(QString())); - libraryMenu->addAction(aAlwaysRevealTopCard); - libraryMenu->addAction(aOpenDeckInDeckEditor); - libraryMenu->addSeparator(); - libraryMenu->addAction(aMoveTopCardsToGrave); - libraryMenu->addAction(aMoveTopCardsToExile); - libraryMenu->addAction(aMoveTopCardToBottom); - deck->setMenu(libraryMenu, aDrawCard); - } else { - handMenu = 0; - libraryMenu = 0; - } + libraryMenu = playerMenu->addMenu(QString()); + libraryMenu->addAction(aDrawCard); + libraryMenu->addAction(aDrawCards); + libraryMenu->addAction(aUndoDraw); + libraryMenu->addSeparator(); + libraryMenu->addAction(aShuffle); + libraryMenu->addSeparator(); + libraryMenu->addAction(aViewLibrary); + libraryMenu->addAction(aViewTopCards); + libraryMenu->addSeparator(); + playerLists.append(mRevealLibrary = libraryMenu->addMenu(QString())); + playerLists.append(mRevealTopCard = libraryMenu->addMenu(QString())); + libraryMenu->addAction(aAlwaysRevealTopCard); + libraryMenu->addAction(aOpenDeckInDeckEditor); + libraryMenu->addSeparator(); + libraryMenu->addAction(aMoveTopCardsToGrave); + libraryMenu->addAction(aMoveTopCardsToExile); + libraryMenu->addAction(aMoveTopCardToBottom); + deck->setMenu(libraryMenu, aDrawCard); + } else { + handMenu = 0; + libraryMenu = 0; + } - graveMenu = playerMenu->addMenu(QString()); - graveMenu->addAction(aViewGraveyard); - grave->setMenu(graveMenu, aViewGraveyard); + graveMenu = playerMenu->addMenu(QString()); + graveMenu->addAction(aViewGraveyard); + grave->setMenu(graveMenu, aViewGraveyard); - rfgMenu = playerMenu->addMenu(QString()); - rfgMenu->addAction(aViewRfg); - rfg->setMenu(rfgMenu, aViewRfg); + rfgMenu = playerMenu->addMenu(QString()); + rfgMenu->addAction(aViewRfg); + rfg->setMenu(rfgMenu, aViewRfg); - if (local) { - graveMenu->addSeparator(); - graveMenu->addAction(aMoveGraveToTopLibrary); - graveMenu->addAction(aMoveGraveToBottomLibrary); - graveMenu->addAction(aMoveGraveToHand); - graveMenu->addAction(aMoveGraveToRfg); + if (local) { + graveMenu->addSeparator(); + graveMenu->addAction(aMoveGraveToTopLibrary); + graveMenu->addAction(aMoveGraveToBottomLibrary); + graveMenu->addAction(aMoveGraveToHand); + graveMenu->addAction(aMoveGraveToRfg); - rfgMenu->addSeparator(); - rfgMenu->addAction(aMoveRfgToTopLibrary); - rfgMenu->addAction(aMoveRfgToBottomLibrary); - rfgMenu->addAction(aMoveRfgToHand); - rfgMenu->addAction(aMoveRfgToGrave); + rfgMenu->addSeparator(); + rfgMenu->addAction(aMoveRfgToTopLibrary); + rfgMenu->addAction(aMoveRfgToBottomLibrary); + rfgMenu->addAction(aMoveRfgToHand); + rfgMenu->addAction(aMoveRfgToGrave); - sbMenu = playerMenu->addMenu(QString()); - sbMenu->addAction(aViewSideboard); - sb->setMenu(sbMenu, aViewSideboard); + sbMenu = playerMenu->addMenu(QString()); + sbMenu->addAction(aViewSideboard); + sb->setMenu(sbMenu, aViewSideboard); - aUntapAll = new QAction(this); - connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); + aUntapAll = new QAction(this); + connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); - aRollDie = new QAction(this); - connect(aRollDie, SIGNAL(triggered()), this, SLOT(actRollDie())); - - aCreateToken = new QAction(this); - connect(aCreateToken, SIGNAL(triggered()), this, SLOT(actCreateToken())); - - aCreateAnotherToken = new QAction(this); - connect(aCreateAnotherToken, SIGNAL(triggered()), this, SLOT(actCreateAnotherToken())); - aCreateAnotherToken->setEnabled(false); - - createPredefinedTokenMenu = new QMenu(QString()); + aRollDie = new QAction(this); + connect(aRollDie, SIGNAL(triggered()), this, SLOT(actRollDie())); + + aCreateToken = new QAction(this); + connect(aCreateToken, SIGNAL(triggered()), this, SLOT(actCreateToken())); + + aCreateAnotherToken = new QAction(this); + connect(aCreateAnotherToken, SIGNAL(triggered()), this, SLOT(actCreateAnotherToken())); + aCreateAnotherToken->setEnabled(false); + + createPredefinedTokenMenu = new QMenu(QString()); - playerMenu->addSeparator(); - countersMenu = playerMenu->addMenu(QString()); - playerMenu->addSeparator(); - playerMenu->addAction(aUntapAll); - playerMenu->addSeparator(); - playerMenu->addAction(aRollDie); - playerMenu->addSeparator(); - playerMenu->addAction(aCreateToken); - playerMenu->addAction(aCreateAnotherToken); - playerMenu->addMenu(createPredefinedTokenMenu); - playerMenu->addSeparator(); - sayMenu = playerMenu->addMenu(QString()); - initSayMenu(); - - aCardMenu = new QAction(this); - playerMenu->addSeparator(); - playerMenu->addAction(aCardMenu); + playerMenu->addSeparator(); + countersMenu = playerMenu->addMenu(QString()); + playerMenu->addSeparator(); + playerMenu->addAction(aUntapAll); + playerMenu->addSeparator(); + playerMenu->addAction(aRollDie); + playerMenu->addSeparator(); + playerMenu->addAction(aCreateToken); + playerMenu->addAction(aCreateAnotherToken); + playerMenu->addMenu(createPredefinedTokenMenu); + playerMenu->addSeparator(); + sayMenu = playerMenu->addMenu(QString()); + initSayMenu(); + + aCardMenu = new QAction(this); + playerMenu->addSeparator(); + playerMenu->addAction(aCardMenu); - for (int i = 0; i < playerLists.size(); ++i) { - QAction *newAction = playerLists[i]->addAction(QString()); - newAction->setData(-1); - connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); - allPlayersActions.append(newAction); - playerLists[i]->addSeparator(); - } - } else { - countersMenu = 0; - sbMenu = 0; - aCreateAnotherToken = 0; - createPredefinedTokenMenu = 0; - aCardMenu = 0; - } - - aTap = new QAction(this); - aTap->setData(cmTap); - connect(aTap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aUntap = new QAction(this); - aUntap->setData(cmUntap); - connect(aUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aDoesntUntap = new QAction(this); - aDoesntUntap->setData(cmDoesntUntap); - connect(aDoesntUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aAttach = new QAction(this); - connect(aAttach, SIGNAL(triggered()), this, SLOT(actAttach())); - aUnattach = new QAction(this); - connect(aUnattach, SIGNAL(triggered()), this, SLOT(actUnattach())); - aDrawArrow = new QAction(this); - connect(aDrawArrow, SIGNAL(triggered()), this, SLOT(actDrawArrow())); - aIncP = new QAction(this); - connect(aIncP, SIGNAL(triggered()), this, SLOT(actIncP())); - aDecP = new QAction(this); - connect(aDecP, SIGNAL(triggered()), this, SLOT(actDecP())); - aIncT = new QAction(this); - connect(aIncT, SIGNAL(triggered()), this, SLOT(actIncT())); - aDecT = new QAction(this); - connect(aDecT, SIGNAL(triggered()), this, SLOT(actDecT())); - aIncPT = new QAction(this); - connect(aIncPT, SIGNAL(triggered()), this, SLOT(actIncPT())); - aDecPT = new QAction(this); - connect(aDecPT, SIGNAL(triggered()), this, SLOT(actDecPT())); - aSetPT = new QAction(this); - connect(aSetPT, SIGNAL(triggered()), this, SLOT(actSetPT())); - aSetAnnotation = new QAction(this); - connect(aSetAnnotation, SIGNAL(triggered()), this, SLOT(actSetAnnotation())); - aFlip = new QAction(this); - aFlip->setData(cmFlip); - connect(aFlip, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aPeek = new QAction(this); - aPeek->setData(cmPeek); - connect(aPeek, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aClone = new QAction(this); - aClone->setData(cmClone); - connect(aClone, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aMoveToTopLibrary = new QAction(this); - aMoveToTopLibrary->setData(cmMoveToTopLibrary); - aMoveToBottomLibrary = new QAction(this); - aMoveToBottomLibrary->setData(cmMoveToBottomLibrary); - aMoveToGraveyard = new QAction(this); - aMoveToGraveyard->setData(cmMoveToGraveyard); - aMoveToExile = new QAction(this); - aMoveToExile->setData(cmMoveToExile); - connect(aMoveToTopLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - connect(aMoveToBottomLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - connect(aMoveToGraveyard, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - connect(aMoveToExile, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - - aPlay = new QAction(this); - connect(aPlay, SIGNAL(triggered()), this, SLOT(actPlay())); - aHide = new QAction(this); - connect(aHide, SIGNAL(triggered()), this, SLOT(actHide())); - - for (int i = 0; i < 3; ++i) { - QAction *tempAddCounter = new QAction(this); - tempAddCounter->setData(9 + i * 1000); - QAction *tempRemoveCounter = new QAction(this); - tempRemoveCounter->setData(10 + i * 1000); - QAction *tempSetCounter = new QAction(this); - tempSetCounter->setData(11 + i * 1000); - aAddCounter.append(tempAddCounter); - aRemoveCounter.append(tempRemoveCounter); - aSetCounter.append(tempSetCounter); - connect(tempAddCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); - connect(tempRemoveCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); - connect(tempSetCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); - } + for (int i = 0; i < playerLists.size(); ++i) { + QAction *newAction = playerLists[i]->addAction(QString()); + newAction->setData(-1); + connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); + allPlayersActions.append(newAction); + playerLists[i]->addSeparator(); + } + } else { + countersMenu = 0; + sbMenu = 0; + aCreateAnotherToken = 0; + createPredefinedTokenMenu = 0; + aCardMenu = 0; + } + + aTap = new QAction(this); + aTap->setData(cmTap); + connect(aTap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aUntap = new QAction(this); + aUntap->setData(cmUntap); + connect(aUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aDoesntUntap = new QAction(this); + aDoesntUntap->setData(cmDoesntUntap); + connect(aDoesntUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aAttach = new QAction(this); + connect(aAttach, SIGNAL(triggered()), this, SLOT(actAttach())); + aUnattach = new QAction(this); + connect(aUnattach, SIGNAL(triggered()), this, SLOT(actUnattach())); + aDrawArrow = new QAction(this); + connect(aDrawArrow, SIGNAL(triggered()), this, SLOT(actDrawArrow())); + aIncP = new QAction(this); + connect(aIncP, SIGNAL(triggered()), this, SLOT(actIncP())); + aDecP = new QAction(this); + connect(aDecP, SIGNAL(triggered()), this, SLOT(actDecP())); + aIncT = new QAction(this); + connect(aIncT, SIGNAL(triggered()), this, SLOT(actIncT())); + aDecT = new QAction(this); + connect(aDecT, SIGNAL(triggered()), this, SLOT(actDecT())); + aIncPT = new QAction(this); + connect(aIncPT, SIGNAL(triggered()), this, SLOT(actIncPT())); + aDecPT = new QAction(this); + connect(aDecPT, SIGNAL(triggered()), this, SLOT(actDecPT())); + aSetPT = new QAction(this); + connect(aSetPT, SIGNAL(triggered()), this, SLOT(actSetPT())); + aSetAnnotation = new QAction(this); + connect(aSetAnnotation, SIGNAL(triggered()), this, SLOT(actSetAnnotation())); + aFlip = new QAction(this); + aFlip->setData(cmFlip); + connect(aFlip, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aPeek = new QAction(this); + aPeek->setData(cmPeek); + connect(aPeek, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aClone = new QAction(this); + aClone->setData(cmClone); + connect(aClone, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aMoveToTopLibrary = new QAction(this); + aMoveToTopLibrary->setData(cmMoveToTopLibrary); + aMoveToBottomLibrary = new QAction(this); + aMoveToBottomLibrary->setData(cmMoveToBottomLibrary); + aMoveToGraveyard = new QAction(this); + aMoveToGraveyard->setData(cmMoveToGraveyard); + aMoveToExile = new QAction(this); + aMoveToExile->setData(cmMoveToExile); + connect(aMoveToTopLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + connect(aMoveToBottomLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + connect(aMoveToGraveyard, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + connect(aMoveToExile, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + + aPlay = new QAction(this); + connect(aPlay, SIGNAL(triggered()), this, SLOT(actPlay())); + aHide = new QAction(this); + connect(aHide, SIGNAL(triggered()), this, SLOT(actHide())); + + for (int i = 0; i < 3; ++i) { + QAction *tempAddCounter = new QAction(this); + tempAddCounter->setData(9 + i * 1000); + QAction *tempRemoveCounter = new QAction(this); + tempRemoveCounter->setData(10 + i * 1000); + QAction *tempSetCounter = new QAction(this); + tempSetCounter->setData(11 + i * 1000); + aAddCounter.append(tempAddCounter); + aRemoveCounter.append(tempRemoveCounter); + aSetCounter.append(tempSetCounter); + connect(tempAddCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); + connect(tempRemoveCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); + connect(tempSetCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); + } - const QList &players = game->getPlayers().values(); - for (int i = 0; i < players.size(); ++i) - addPlayer(players[i]); - - rearrangeZones(); - retranslateUi(); + const QList &players = game->getPlayers().values(); + for (int i = 0; i < players.size(); ++i) + addPlayer(players[i]); + + rearrangeZones(); + retranslateUi(); } Player::~Player() { - qDebug() << "Player destructor:" << getName(); + qDebug() << "Player destructor:" << getName(); - static_cast(scene())->removePlayer(this); - - clear(); - QMapIterator i(zones); - while (i.hasNext()) - delete i.next().value(); - zones.clear(); - - delete playerMenu; - delete userInfo; + static_cast(scene())->removePlayer(this); + + clear(); + QMapIterator i(zones); + while (i.hasNext()) + delete i.next().value(); + zones.clear(); + + delete playerMenu; + delete userInfo; } void Player::clear() { - clearArrows(); - - QMapIterator i(zones); - while (i.hasNext()) - i.next().value()->clearContents(); - - clearCounters(); + clearArrows(); + + QMapIterator i(zones); + while (i.hasNext()) + i.next().value()->clearContents(); + + clearCounters(); } void Player::addPlayer(Player *player) { - if (player == this) - return; - for (int i = 0; i < playerLists.size(); ++i) { - QAction *newAction = playerLists[i]->addAction(player->getName()); - newAction->setData(player->getId()); - connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); - } + if (player == this) + return; + for (int i = 0; i < playerLists.size(); ++i) { + QAction *newAction = playerLists[i]->addAction(player->getName()); + newAction->setData(player->getId()); + connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); + } } void Player::removePlayer(Player *player) { - for (int i = 0; i < playerLists.size(); ++i) { - QList actionList = playerLists[i]->actions(); - for (int j = 0; j < actionList.size(); ++j) - if (actionList[j]->data().toInt() == player->getId()) { - playerLists[i]->removeAction(actionList[j]); - actionList[j]->deleteLater(); - } - } + for (int i = 0; i < playerLists.size(); ++i) { + QList actionList = playerLists[i]->actions(); + for (int j = 0; j < actionList.size(); ++j) + if (actionList[j]->data().toInt() == player->getId()) { + playerLists[i]->removeAction(actionList[j]); + actionList[j]->deleteLater(); + } + } } void Player::playerListActionTriggered() { - QAction *action = static_cast(sender()); - QMenu *menu = static_cast(action->parentWidget()); - - Command_RevealCards cmd; - const int otherPlayerId = action->data().toInt(); - if (otherPlayerId != -1) - cmd.set_player_id(otherPlayerId); - - if (menu == mRevealLibrary) { - cmd.set_zone_name("deck"); - cmd.set_grant_write_access(true); - } else if (menu == mRevealTopCard) { - cmd.set_zone_name("deck"); - cmd.set_card_id(0); - } else if (menu == mRevealHand) - cmd.set_zone_name("hand"); - else if (menu == mRevealRandomHandCard) { - cmd.set_zone_name("hand"); - cmd.set_card_id(-2); - } else - return; - - sendGameCommand(cmd); + QAction *action = static_cast(sender()); + QMenu *menu = static_cast(action->parentWidget()); + + Command_RevealCards cmd; + const int otherPlayerId = action->data().toInt(); + if (otherPlayerId != -1) + cmd.set_player_id(otherPlayerId); + + if (menu == mRevealLibrary) { + cmd.set_zone_name("deck"); + cmd.set_grant_write_access(true); + } else if (menu == mRevealTopCard) { + cmd.set_zone_name("deck"); + cmd.set_card_id(0); + } else if (menu == mRevealHand) + cmd.set_zone_name("hand"); + else if (menu == mRevealRandomHandCard) { + cmd.set_zone_name("hand"); + cmd.set_card_id(-2); + } else + return; + + sendGameCommand(cmd); } void Player::rearrangeZones() { - QPointF base = QPointF(CARD_HEIGHT + counterAreaWidth + 15, 0); - if (settingsCache->getHorizontalHand()) { - if (mirrored) { - if (hand->contentsKnown()) { - handVisible = true; - hand->setPos(base); - base += QPointF(0, hand->boundingRect().height()); - } else - handVisible = false; - - stack->setPos(base); - base += QPointF(stack->boundingRect().width(), 0); - - table->setPos(base); - } else { - stack->setPos(base); - - table->setPos(base.x() + stack->boundingRect().width(), 0); - base += QPointF(0, table->boundingRect().height()); - - if (hand->contentsKnown()) { - handVisible = true; - hand->setPos(base); - } else - handVisible = false; - } - hand->setWidth(table->getWidth() + stack->boundingRect().width()); - } else { - handVisible = true; - - hand->setPos(base); - base += QPointF(hand->boundingRect().width(), 0); - - stack->setPos(base); - base += QPointF(stack->boundingRect().width(), 0); - - table->setPos(base); - } - hand->setVisible(handVisible); - hand->updateOrientation(); - table->reorganizeCards(); - updateBoundingRect(); - rearrangeCounters(); + QPointF base = QPointF(CARD_HEIGHT + counterAreaWidth + 15, 0); + if (settingsCache->getHorizontalHand()) { + if (mirrored) { + if (hand->contentsKnown()) { + handVisible = true; + hand->setPos(base); + base += QPointF(0, hand->boundingRect().height()); + } else + handVisible = false; + + stack->setPos(base); + base += QPointF(stack->boundingRect().width(), 0); + + table->setPos(base); + } else { + stack->setPos(base); + + table->setPos(base.x() + stack->boundingRect().width(), 0); + base += QPointF(0, table->boundingRect().height()); + + if (hand->contentsKnown()) { + handVisible = true; + hand->setPos(base); + } else + handVisible = false; + } + hand->setWidth(table->getWidth() + stack->boundingRect().width()); + } else { + handVisible = true; + + hand->setPos(base); + base += QPointF(hand->boundingRect().width(), 0); + + stack->setPos(base); + base += QPointF(stack->boundingRect().width(), 0); + + table->setPos(base); + } + hand->setVisible(handVisible); + hand->updateOrientation(); + table->reorganizeCards(); + updateBoundingRect(); + rearrangeCounters(); } void Player::updateZones() { - table->reorganizeCards(); + table->reorganizeCards(); } void Player::updateBoundingRect() { - prepareGeometryChange(); - qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); - if (settingsCache->getHorizontalHand()) { - qreal handHeight = handVisible ? hand->boundingRect().height() : 0; - bRect = QRectF(0, 0, width + table->boundingRect().width(), table->boundingRect().height() + handHeight); - } else - bRect = QRectF(0, 0, width + hand->boundingRect().width() + table->boundingRect().width(), table->boundingRect().height()); - playerArea->setSize(CARD_HEIGHT + counterAreaWidth + 15, bRect.height()); - - emit sizeChanged(); + prepareGeometryChange(); + qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); + if (settingsCache->getHorizontalHand()) { + qreal handHeight = handVisible ? hand->boundingRect().height() : 0; + bRect = QRectF(0, 0, width + table->boundingRect().width(), table->boundingRect().height() + handHeight); + } else + bRect = QRectF(0, 0, width + hand->boundingRect().width() + table->boundingRect().width(), table->boundingRect().height()); + playerArea->setSize(CARD_HEIGHT + counterAreaWidth + 15, bRect.height()); + + emit sizeChanged(); } void Player::retranslateUi() { - aViewGraveyard->setText(tr("&View graveyard")); - aViewRfg->setText(tr("&View exile")); - playerMenu->setTitle(tr("Player \"%1\"").arg(QString::fromStdString(userInfo->name()))); - graveMenu->setTitle(tr("&Graveyard")); - rfgMenu->setTitle(tr("&Exile")); - - if (local) { - aMoveHandToTopLibrary->setText(tr("Move to &top of library")); - aMoveHandToBottomLibrary->setText(tr("Move to &bottom of library")); - aMoveHandToGrave->setText(tr("Move to &graveyard")); - aMoveHandToRfg->setText(tr("Move to &exile")); - aMoveGraveToTopLibrary->setText(tr("Move to &top of library")); - aMoveGraveToBottomLibrary->setText(tr("Move to &bottom of library")); - aMoveGraveToHand->setText(tr("Move to &hand")); - aMoveGraveToRfg->setText(tr("Move to &exile")); - aMoveRfgToTopLibrary->setText(tr("Move to &top of library")); - aMoveRfgToBottomLibrary->setText(tr("Move to &bottom of library")); - aMoveRfgToHand->setText(tr("Move to &hand")); - aMoveRfgToGrave->setText(tr("Move to &graveyard")); - aViewLibrary->setText(tr("&View library")); - aViewTopCards->setText(tr("View &top cards of library...")); - mRevealLibrary->setTitle(tr("Reveal &library to")); - mRevealTopCard->setTitle(tr("Reveal t&op card to")); - aAlwaysRevealTopCard->setText(tr("&Always reveal top card")); - aOpenDeckInDeckEditor->setText(tr("O&pen deck in deck editor")); - aViewSideboard->setText(tr("&View sideboard")); - aDrawCard->setText(tr("&Draw card")); - aDrawCards->setText(tr("D&raw cards...")); - aUndoDraw->setText(tr("&Undo last draw")); - aMulligan->setText(tr("Take &mulligan")); - aShuffle->setText(tr("&Shuffle")); - aMoveTopCardsToGrave->setText(tr("Move top cards to &graveyard...")); - aMoveTopCardsToExile->setText(tr("Move top cards to &exile...")); - aMoveTopCardToBottom->setText(tr("Put top card on &bottom")); - - handMenu->setTitle(tr("&Hand")); - mRevealHand->setTitle(tr("&Reveal to")); - mRevealRandomHandCard->setTitle(tr("Reveal r&andom card to")); - sbMenu->setTitle(tr("&Sideboard")); - libraryMenu->setTitle(tr("&Library")); - countersMenu->setTitle(tr("&Counters")); + aViewGraveyard->setText(tr("&View graveyard")); + aViewRfg->setText(tr("&View exile")); + playerMenu->setTitle(tr("Player \"%1\"").arg(QString::fromStdString(userInfo->name()))); + graveMenu->setTitle(tr("&Graveyard")); + rfgMenu->setTitle(tr("&Exile")); + + if (local) { + aMoveHandToTopLibrary->setText(tr("Move to &top of library")); + aMoveHandToBottomLibrary->setText(tr("Move to &bottom of library")); + aMoveHandToGrave->setText(tr("Move to &graveyard")); + aMoveHandToRfg->setText(tr("Move to &exile")); + aMoveGraveToTopLibrary->setText(tr("Move to &top of library")); + aMoveGraveToBottomLibrary->setText(tr("Move to &bottom of library")); + aMoveGraveToHand->setText(tr("Move to &hand")); + aMoveGraveToRfg->setText(tr("Move to &exile")); + aMoveRfgToTopLibrary->setText(tr("Move to &top of library")); + aMoveRfgToBottomLibrary->setText(tr("Move to &bottom of library")); + aMoveRfgToHand->setText(tr("Move to &hand")); + aMoveRfgToGrave->setText(tr("Move to &graveyard")); + aViewLibrary->setText(tr("&View library")); + aViewTopCards->setText(tr("View &top cards of library...")); + mRevealLibrary->setTitle(tr("Reveal &library to")); + mRevealTopCard->setTitle(tr("Reveal t&op card to")); + aAlwaysRevealTopCard->setText(tr("&Always reveal top card")); + aOpenDeckInDeckEditor->setText(tr("O&pen deck in deck editor")); + aViewSideboard->setText(tr("&View sideboard")); + aDrawCard->setText(tr("&Draw card")); + aDrawCards->setText(tr("D&raw cards...")); + aUndoDraw->setText(tr("&Undo last draw")); + aMulligan->setText(tr("Take &mulligan")); + aShuffle->setText(tr("&Shuffle")); + aMoveTopCardsToGrave->setText(tr("Move top cards to &graveyard...")); + aMoveTopCardsToExile->setText(tr("Move top cards to &exile...")); + aMoveTopCardToBottom->setText(tr("Put top card on &bottom")); + + handMenu->setTitle(tr("&Hand")); + mRevealHand->setTitle(tr("&Reveal to")); + mRevealRandomHandCard->setTitle(tr("Reveal r&andom card to")); + sbMenu->setTitle(tr("&Sideboard")); + libraryMenu->setTitle(tr("&Library")); + countersMenu->setTitle(tr("&Counters")); - aUntapAll->setText(tr("&Untap all permanents")); - aRollDie->setText(tr("R&oll die...")); - aCreateToken->setText(tr("&Create token...")); - aCreateAnotherToken->setText(tr("C&reate another token")); - createPredefinedTokenMenu->setTitle(tr("Cr&eate predefined token")); - sayMenu->setTitle(tr("S&ay")); - - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->retranslateUi(); + aUntapAll->setText(tr("&Untap all permanents")); + aRollDie->setText(tr("R&oll die...")); + aCreateToken->setText(tr("&Create token...")); + aCreateAnotherToken->setText(tr("C&reate another token")); + createPredefinedTokenMenu->setTitle(tr("Cr&eate predefined token")); + sayMenu->setTitle(tr("S&ay")); + + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->retranslateUi(); - aCardMenu->setText(tr("C&ard")); - - for (int i = 0; i < allPlayersActions.size(); ++i) - allPlayersActions[i]->setText(tr("&All players")); - } - - aPlay->setText(tr("&Play")); - aHide->setText(tr("&Hide")); - - aTap->setText(tr("&Tap")); - aUntap->setText(tr("&Untap")); - aDoesntUntap->setText(tr("Toggle &normal untapping")); - aFlip->setText(tr("&Flip")); - aPeek->setText(tr("&Peek at card face")); - aClone->setText(tr("&Clone")); - aClone->setShortcut(tr("Ctrl+J")); - aAttach->setText(tr("Attac&h to card...")); - aAttach->setShortcut(tr("Ctrl+A")); - aUnattach->setText(tr("Unattac&h")); - aDrawArrow->setText(tr("&Draw arrow...")); - aIncP->setText(tr("&Increase power")); - aIncP->setShortcut(tr("Ctrl++")); - aDecP->setText(tr("&Decrease power")); - aDecP->setShortcut(tr("Ctrl+-")); - aIncT->setText(tr("I&ncrease toughness")); - aIncT->setShortcut(tr("Alt++")); - aDecT->setText(tr("D&ecrease toughness")); - aDecT->setShortcut(tr("Alt+-")); - aIncPT->setText(tr("In&crease power and toughness")); - aIncPT->setShortcut(tr("Ctrl+Alt++")); - aDecPT->setText(tr("Dec&rease power and toughness")); - aDecPT->setShortcut(tr("Ctrl+Alt+-")); - aSetPT->setText(tr("Set &power and toughness...")); - aSetPT->setShortcut(tr("Ctrl+P")); - aSetAnnotation->setText(tr("&Set annotation...")); - QStringList counterColors; - counterColors.append(tr("red")); - counterColors.append(tr("yellow")); - counterColors.append(tr("green")); - for (int i = 0; i < aAddCounter.size(); ++i) - aAddCounter[i]->setText(tr("&Add counter (%1)").arg(counterColors[i])); - for (int i = 0; i < aRemoveCounter.size(); ++i) - aRemoveCounter[i]->setText(tr("&Remove counter (%1)").arg(counterColors[i])); - for (int i = 0; i < aSetCounter.size(); ++i) - aSetCounter[i]->setText(tr("&Set counters (%1)...").arg(counterColors[i])); - aMoveToTopLibrary->setText(tr("&top of library")); - aMoveToBottomLibrary->setText(tr("&bottom of library")); - aMoveToGraveyard->setText(tr("&graveyard")); - aMoveToGraveyard->setShortcut(tr("Ctrl+Del")); - aMoveToExile->setText(tr("&exile")); - - QMapIterator zoneIterator(zones); - while (zoneIterator.hasNext()) - zoneIterator.next().value()->retranslateUi(); + aCardMenu->setText(tr("C&ard")); + + for (int i = 0; i < allPlayersActions.size(); ++i) + allPlayersActions[i]->setText(tr("&All players")); + } + + aPlay->setText(tr("&Play")); + aHide->setText(tr("&Hide")); + + aTap->setText(tr("&Tap")); + aUntap->setText(tr("&Untap")); + aDoesntUntap->setText(tr("Toggle &normal untapping")); + aFlip->setText(tr("&Flip")); + aPeek->setText(tr("&Peek at card face")); + aClone->setText(tr("&Clone")); + aClone->setShortcut(tr("Ctrl+J")); + aAttach->setText(tr("Attac&h to card...")); + aAttach->setShortcut(tr("Ctrl+A")); + aUnattach->setText(tr("Unattac&h")); + aDrawArrow->setText(tr("&Draw arrow...")); + aIncP->setText(tr("&Increase power")); + aIncP->setShortcut(tr("Ctrl++")); + aDecP->setText(tr("&Decrease power")); + aDecP->setShortcut(tr("Ctrl+-")); + aIncT->setText(tr("I&ncrease toughness")); + aIncT->setShortcut(tr("Alt++")); + aDecT->setText(tr("D&ecrease toughness")); + aDecT->setShortcut(tr("Alt+-")); + aIncPT->setText(tr("In&crease power and toughness")); + aIncPT->setShortcut(tr("Ctrl+Alt++")); + aDecPT->setText(tr("Dec&rease power and toughness")); + aDecPT->setShortcut(tr("Ctrl+Alt+-")); + aSetPT->setText(tr("Set &power and toughness...")); + aSetPT->setShortcut(tr("Ctrl+P")); + aSetAnnotation->setText(tr("&Set annotation...")); + QStringList counterColors; + counterColors.append(tr("red")); + counterColors.append(tr("yellow")); + counterColors.append(tr("green")); + for (int i = 0; i < aAddCounter.size(); ++i) + aAddCounter[i]->setText(tr("&Add counter (%1)").arg(counterColors[i])); + for (int i = 0; i < aRemoveCounter.size(); ++i) + aRemoveCounter[i]->setText(tr("&Remove counter (%1)").arg(counterColors[i])); + for (int i = 0; i < aSetCounter.size(); ++i) + aSetCounter[i]->setText(tr("&Set counters (%1)...").arg(counterColors[i])); + aMoveToTopLibrary->setText(tr("&top of library")); + aMoveToBottomLibrary->setText(tr("&bottom of library")); + aMoveToGraveyard->setText(tr("&graveyard")); + aMoveToGraveyard->setShortcut(tr("Ctrl+Del")); + aMoveToExile->setText(tr("&exile")); + + QMapIterator zoneIterator(zones); + while (zoneIterator.hasNext()) + zoneIterator.next().value()->retranslateUi(); } void Player::setShortcutsActive() { - shortcutsActive = true; - - aViewSideboard->setShortcut(tr("Ctrl+F3")); - aViewLibrary->setShortcut(tr("F3")); - aViewTopCards->setShortcut(tr("Ctrl+W")); - aViewGraveyard->setShortcut(tr("F4")); - aDrawCard->setShortcut(tr("Ctrl+D")); - aDrawCards->setShortcut(tr("Ctrl+E")); - aUndoDraw->setShortcut(tr("Ctrl+Shift+D")); - aMulligan->setShortcut(tr("Ctrl+M")); - aShuffle->setShortcut(tr("Ctrl+S")); - aUntapAll->setShortcut(tr("Ctrl+U")); - aRollDie->setShortcut(tr("Ctrl+I")); - aCreateToken->setShortcut(tr("Ctrl+T")); - aCreateAnotherToken->setShortcut(tr("Ctrl+G")); + shortcutsActive = true; + + aViewSideboard->setShortcut(tr("Ctrl+F3")); + aViewLibrary->setShortcut(tr("F3")); + aViewTopCards->setShortcut(tr("Ctrl+W")); + aViewGraveyard->setShortcut(tr("F4")); + aDrawCard->setShortcut(tr("Ctrl+D")); + aDrawCards->setShortcut(tr("Ctrl+E")); + aUndoDraw->setShortcut(tr("Ctrl+Shift+D")); + aMulligan->setShortcut(tr("Ctrl+M")); + aShuffle->setShortcut(tr("Ctrl+S")); + aUntapAll->setShortcut(tr("Ctrl+U")); + aRollDie->setShortcut(tr("Ctrl+I")); + aCreateToken->setShortcut(tr("Ctrl+T")); + aCreateAnotherToken->setShortcut(tr("Ctrl+G")); - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->setShortcutsActive(); + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->setShortcutsActive(); } void Player::setShortcutsInactive() { - shortcutsActive = false; - - aViewSideboard->setShortcut(QKeySequence()); - aViewLibrary->setShortcut(QKeySequence()); - aViewTopCards->setShortcut(QKeySequence()); - aViewGraveyard->setShortcut(QKeySequence()); - aDrawCard->setShortcut(QKeySequence()); - aDrawCards->setShortcut(QKeySequence()); - aUndoDraw->setShortcut(QKeySequence()); - aMulligan->setShortcut(QKeySequence()); - aShuffle->setShortcut(QKeySequence()); - aUntapAll->setShortcut(QKeySequence()); - aRollDie->setShortcut(QKeySequence()); - aCreateToken->setShortcut(QKeySequence()); - aCreateAnotherToken->setShortcut(QKeySequence()); + shortcutsActive = false; + + aViewSideboard->setShortcut(QKeySequence()); + aViewLibrary->setShortcut(QKeySequence()); + aViewTopCards->setShortcut(QKeySequence()); + aViewGraveyard->setShortcut(QKeySequence()); + aDrawCard->setShortcut(QKeySequence()); + aDrawCards->setShortcut(QKeySequence()); + aUndoDraw->setShortcut(QKeySequence()); + aMulligan->setShortcut(QKeySequence()); + aShuffle->setShortcut(QKeySequence()); + aUntapAll->setShortcut(QKeySequence()); + aRollDie->setShortcut(QKeySequence()); + aCreateToken->setShortcut(QKeySequence()); + aCreateAnotherToken->setShortcut(QKeySequence()); - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->setShortcutsInactive(); + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->setShortcutsInactive(); } void Player::initSayMenu() { - sayMenu->clear(); + sayMenu->clear(); - QSettings settings; - settings.beginGroup("messages"); - int count = settings.value("count", 0).toInt(); - for (int i = 0; i < count; i++) { - QAction *newAction = new QAction(settings.value(QString("msg%1").arg(i)).toString(), this); - if (i <= 10) - newAction->setShortcut(QString("Ctrl+%1").arg((i + 1) % 10)); - connect(newAction, SIGNAL(triggered()), this, SLOT(actSayMessage())); - sayMenu->addAction(newAction); - } + QSettings settings; + settings.beginGroup("messages"); + int count = settings.value("count", 0).toInt(); + for (int i = 0; i < count; i++) { + QAction *newAction = new QAction(settings.value(QString("msg%1").arg(i)).toString(), this); + if (i <= 10) + newAction->setShortcut(QString("Ctrl+%1").arg((i + 1) % 10)); + connect(newAction, SIGNAL(triggered()), this, SLOT(actSayMessage())); + sayMenu->addAction(newAction); + } } void Player::setDeck(const DeckLoader &_deck) { - deck = new DeckLoader(_deck); - aOpenDeckInDeckEditor->setEnabled(deck); - - createPredefinedTokenMenu->clear(); - predefinedTokens.clear(); - InnerDecklistNode *tokenZone = dynamic_cast(deck->getRoot()->findChild("tokens")); - if (tokenZone) - for (int i = 0; i < tokenZone->size(); ++i) { - const QString tokenName = tokenZone->at(i)->getName(); - predefinedTokens.append(tokenName); - QAction *a = createPredefinedTokenMenu->addAction(tokenName); - if (i < 10) - a->setShortcut("Alt+" + QString::number((i + 1) % 10)); - connect(a, SIGNAL(triggered()), this, SLOT(actCreatePredefinedToken())); - } + deck = new DeckLoader(_deck); + aOpenDeckInDeckEditor->setEnabled(deck); + + createPredefinedTokenMenu->clear(); + predefinedTokens.clear(); + InnerDecklistNode *tokenZone = dynamic_cast(deck->getRoot()->findChild("tokens")); + if (tokenZone) + for (int i = 0; i < tokenZone->size(); ++i) { + const QString tokenName = tokenZone->at(i)->getName(); + predefinedTokens.append(tokenName); + QAction *a = createPredefinedTokenMenu->addAction(tokenName); + if (i < 10) + a->setShortcut("Alt+" + QString::number((i + 1) % 10)); + connect(a, SIGNAL(triggered()), this, SLOT(actCreatePredefinedToken())); + } } void Player::actViewLibrary() { - static_cast(scene())->toggleZoneView(this, "deck", -1); + static_cast(scene())->toggleZoneView(this, "deck", -1); } void Player::actViewTopCards() { - bool ok; - int number = QInputDialog::getInteger(0, tr("View top cards of library"), tr("Number of cards:"), defaultNumberTopCards, 1, 2000000000, 1, &ok); - if (ok) { - defaultNumberTopCards = number; - static_cast(scene())->toggleZoneView(this, "deck", number); - } + bool ok; + int number = QInputDialog::getInteger(0, tr("View top cards of library"), tr("Number of cards:"), defaultNumberTopCards, 1, 2000000000, 1, &ok); + if (ok) { + defaultNumberTopCards = number; + static_cast(scene())->toggleZoneView(this, "deck", number); + } } void Player::actAlwaysRevealTopCard() { - Command_ChangeZoneProperties cmd; - cmd.set_zone_name("deck"); - cmd.set_always_reveal_top_card(aAlwaysRevealTopCard->isChecked()); - - sendGameCommand(cmd); + Command_ChangeZoneProperties cmd; + cmd.set_zone_name("deck"); + cmd.set_always_reveal_top_card(aAlwaysRevealTopCard->isChecked()); + + sendGameCommand(cmd); } void Player::actOpenDeckInDeckEditor() { - emit openDeckEditor(deck); + emit openDeckEditor(deck); } void Player::actViewGraveyard() { - static_cast(scene())->toggleZoneView(this, "grave", -1); + static_cast(scene())->toggleZoneView(this, "grave", -1); } void Player::actViewRfg() { - static_cast(scene())->toggleZoneView(this, "rfg", -1); + static_cast(scene())->toggleZoneView(this, "rfg", -1); } void Player::actViewSideboard() { - static_cast(scene())->toggleZoneView(this, "sb", -1); + static_cast(scene())->toggleZoneView(this, "sb", -1); } void Player::actShuffle() { - sendGameCommand(Command_Shuffle()); + sendGameCommand(Command_Shuffle()); } void Player::actDrawCard() { - Command_DrawCards cmd; - cmd.set_number(1); - sendGameCommand(cmd); + Command_DrawCards cmd; + cmd.set_number(1); + sendGameCommand(cmd); } void Player::actMulligan() { - sendGameCommand(Command_Mulligan()); + sendGameCommand(Command_Mulligan()); } void Player::actDrawCards() { - int number = QInputDialog::getInteger(0, tr("Draw cards"), tr("Number:")); + int number = QInputDialog::getInteger(0, tr("Draw cards"), tr("Number:")); if (number) { - Command_DrawCards cmd; - cmd.set_number(number); - sendGameCommand(cmd); - } + Command_DrawCards cmd; + cmd.set_number(number); + sendGameCommand(cmd); + } } void Player::actUndoDraw() { - sendGameCommand(Command_UndoDraw()); + sendGameCommand(Command_UndoDraw()); } void Player::actMoveTopCardsToGrave() { - int number = QInputDialog::getInteger(0, tr("Move top cards to grave"), tr("Number:")); + int number = QInputDialog::getInteger(0, tr("Move top cards to grave"), tr("Number:")); if (!number) - return; + return; - const int maxCards = zones.value("deck")->getCards().size(); - if (number > maxCards) - number = maxCards; + const int maxCards = zones.value("deck")->getCards().size(); + if (number > maxCards) + number = maxCards; - Command_MoveCard cmd; - cmd.set_start_zone("deck"); - cmd.set_target_player_id(getId()); - cmd.set_target_zone("grave"); - cmd.set_x(0); - cmd.set_y(0); + Command_MoveCard cmd; + cmd.set_start_zone("deck"); + cmd.set_target_player_id(getId()); + cmd.set_target_zone("grave"); + cmd.set_x(0); + cmd.set_y(0); - for (int i = 0; i < number; ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(i); - - sendGameCommand(cmd); + for (int i = 0; i < number; ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(i); + + sendGameCommand(cmd); } void Player::actMoveTopCardsToExile() { - int number = QInputDialog::getInteger(0, tr("Move top cards to exile"), tr("Number:")); + int number = QInputDialog::getInteger(0, tr("Move top cards to exile"), tr("Number:")); if (!number) - return; + return; - const int maxCards = zones.value("deck")->getCards().size(); - if (number > maxCards) - number = maxCards; - - Command_MoveCard cmd; - cmd.set_start_zone("deck"); - cmd.set_target_player_id(getId()); - cmd.set_target_zone("rfg"); - cmd.set_x(0); - cmd.set_y(0); + const int maxCards = zones.value("deck")->getCards().size(); + if (number > maxCards) + number = maxCards; + + Command_MoveCard cmd; + cmd.set_start_zone("deck"); + cmd.set_target_player_id(getId()); + cmd.set_target_zone("rfg"); + cmd.set_x(0); + cmd.set_y(0); - for (int i = 0; i < number; ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(i); - - sendGameCommand(cmd); + for (int i = 0; i < number; ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(i); + + sendGameCommand(cmd); } void Player::actMoveTopCardToBottom() { - Command_MoveCard cmd; - cmd.set_start_zone("deck"); - cmd.mutable_cards_to_move()->add_card()->set_card_id(0); - cmd.set_target_player_id(getId()); - cmd.set_target_zone("deck"); - cmd.set_x(-1); - cmd.set_y(0); - - sendGameCommand(cmd); + Command_MoveCard cmd; + cmd.set_start_zone("deck"); + cmd.mutable_cards_to_move()->add_card()->set_card_id(0); + cmd.set_target_player_id(getId()); + cmd.set_target_zone("deck"); + cmd.set_x(-1); + cmd.set_y(0); + + sendGameCommand(cmd); } void Player::actUntapAll() { - Command_SetCardAttr cmd; - cmd.set_zone("table"); - cmd.set_attribute(AttrTapped); - cmd.set_attr_value("0"); - - sendGameCommand(cmd); + Command_SetCardAttr cmd; + cmd.set_zone("table"); + cmd.set_attribute(AttrTapped); + cmd.set_attr_value("0"); + + sendGameCommand(cmd); } void Player::actRollDie() { - bool ok; - int sides = QInputDialog::getInteger(0, tr("Roll die"), tr("Number of sides:"), 20, 2, 1000, 1, &ok); - if (ok) { - Command_RollDie cmd; - cmd.set_sides(sides); - sendGameCommand(cmd); - } + bool ok; + int sides = QInputDialog::getInteger(0, tr("Roll die"), tr("Number of sides:"), 20, 2, 1000, 1, &ok); + if (ok) { + Command_RollDie cmd; + cmd.set_sides(sides); + sendGameCommand(cmd); + } } void Player::actCreateToken() { - DlgCreateToken dlg(predefinedTokens); - if (!dlg.exec()) - return; - - lastTokenName = dlg.getName(); - lastTokenColor = dlg.getColor(); - lastTokenPT = dlg.getPT(); - lastTokenAnnotation = dlg.getAnnotation(); - lastTokenDestroy = dlg.getDestroy(); - aCreateAnotherToken->setEnabled(true); - - actCreateAnotherToken(); + DlgCreateToken dlg(predefinedTokens); + if (!dlg.exec()) + return; + + lastTokenName = dlg.getName(); + lastTokenColor = dlg.getColor(); + lastTokenPT = dlg.getPT(); + lastTokenAnnotation = dlg.getAnnotation(); + lastTokenDestroy = dlg.getDestroy(); + aCreateAnotherToken->setEnabled(true); + + actCreateAnotherToken(); } void Player::actCreateAnotherToken() { - Command_CreateToken cmd; - cmd.set_zone("table"); - cmd.set_card_name(lastTokenName.toStdString()); - cmd.set_color(lastTokenColor.toStdString()); - cmd.set_pt(lastTokenPT.toStdString()); - cmd.set_annotation(lastTokenAnnotation.toStdString()); - cmd.set_destroy_on_zone_change(lastTokenDestroy); - cmd.set_x(-1); - cmd.set_y(0); - - sendGameCommand(cmd); + Command_CreateToken cmd; + cmd.set_zone("table"); + cmd.set_card_name(lastTokenName.toStdString()); + cmd.set_color(lastTokenColor.toStdString()); + cmd.set_pt(lastTokenPT.toStdString()); + cmd.set_annotation(lastTokenAnnotation.toStdString()); + cmd.set_destroy_on_zone_change(lastTokenDestroy); + cmd.set_x(-1); + cmd.set_y(0); + + sendGameCommand(cmd); } void Player::actCreatePredefinedToken() { - QAction *action = static_cast(sender()); - CardInfo *cardInfo = db->getCard(action->text()); - - lastTokenName = cardInfo->getName(); - lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower(); - lastTokenPT = cardInfo->getPowTough(); - lastTokenAnnotation = cardInfo->getText(); - lastTokenDestroy = true; - aCreateAnotherToken->setEnabled(true); - - actCreateAnotherToken(); + QAction *action = static_cast(sender()); + CardInfo *cardInfo = db->getCard(action->text()); + + lastTokenName = cardInfo->getName(); + lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower(); + lastTokenPT = cardInfo->getPowTough(); + lastTokenAnnotation = cardInfo->getText(); + lastTokenDestroy = true; + aCreateAnotherToken->setEnabled(true); + + actCreateAnotherToken(); } void Player::actSayMessage() { - QAction *a = qobject_cast(sender()); - Command_GameSay cmd; - cmd.set_message(a->text().toStdString()); - sendGameCommand(cmd); + QAction *a = qobject_cast(sender()); + Command_GameSay cmd; + cmd.set_message(a->text().toStdString()); + sendGameCommand(cmd); } void Player::setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards) { - bool moveCardContext = context.HasExtension(Context_MoveCard::ext); - switch (attribute) { - case AttrTapped: { - bool tapped = avalue == "1"; - if (!(!tapped && card->getDoesntUntap() && allCards)) { - if (!allCards) - emit logSetTapped(this, card, tapped); - card->setTapped(tapped, !moveCardContext); - } - break; - } - case AttrAttacking: card->setAttacking(avalue == "1"); break; - case AttrFaceDown: card->setFaceDown(avalue == "1"); break; - case AttrColor: card->setColor(avalue); break; - case AttrAnnotation: { - emit logSetAnnotation(this, card, avalue); - card->setAnnotation(avalue); - break; - } - case AttrDoesntUntap: { - bool value = (avalue == "1"); - emit logSetDoesntUntap(this, card, value); - card->setDoesntUntap(value); - break; - } - case AttrPT: { - emit logSetPT(this, card, avalue); - card->setPT(avalue); - break; - } - } + bool moveCardContext = context.HasExtension(Context_MoveCard::ext); + switch (attribute) { + case AttrTapped: { + bool tapped = avalue == "1"; + if (!(!tapped && card->getDoesntUntap() && allCards)) { + if (!allCards) + emit logSetTapped(this, card, tapped); + card->setTapped(tapped, !moveCardContext); + } + break; + } + case AttrAttacking: card->setAttacking(avalue == "1"); break; + case AttrFaceDown: card->setFaceDown(avalue == "1"); break; + case AttrColor: card->setColor(avalue); break; + case AttrAnnotation: { + emit logSetAnnotation(this, card, avalue); + card->setAnnotation(avalue); + break; + } + case AttrDoesntUntap: { + bool value = (avalue == "1"); + emit logSetDoesntUntap(this, card, value); + card->setDoesntUntap(value); + break; + } + case AttrPT: { + emit logSetPT(this, card, avalue); + card->setPT(avalue); + break; + } + } } void Player::eventGameSay(const Event_GameSay &event) { - emit logSay(this, QString::fromStdString(event.message())); + emit logSay(this, QString::fromStdString(event.message())); } void Player::eventShuffle(const Event_Shuffle &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); - if (!zone) - return; - if (zone->getView()) - if (zone->getView()->getRevealZone()) - zone->getView()->setWriteableRevealZone(false); - emit logShuffle(this, zone); + CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); + if (!zone) + return; + if (zone->getView()) + if (zone->getView()->getRevealZone()) + zone->getView()->setWriteableRevealZone(false); + emit logShuffle(this, zone); } void Player::eventRollDie(const Event_RollDie &event) { - emit logRollDie(this, event.sides(), event.value()); + emit logRollDie(this, event.sides(), event.value()); } void Player::eventCreateArrow(const Event_CreateArrow &event) { - ArrowItem *arrow = addArrow(event.arrow_info()); - if (!arrow) - return; - - CardItem *startCard = static_cast(arrow->getStartItem()); - CardItem *targetCard = qgraphicsitem_cast(arrow->getTargetItem()); - if (targetCard) - emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), targetCard->getOwner(), targetCard->getName(), false); - else - emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), arrow->getTargetItem()->getOwner(), QString(), true); + ArrowItem *arrow = addArrow(event.arrow_info()); + if (!arrow) + return; + + CardItem *startCard = static_cast(arrow->getStartItem()); + CardItem *targetCard = qgraphicsitem_cast(arrow->getTargetItem()); + if (targetCard) + emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), targetCard->getOwner(), targetCard->getName(), false); + else + emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), arrow->getTargetItem()->getOwner(), QString(), true); } void Player::eventDeleteArrow(const Event_DeleteArrow &event) { - delArrow(event.arrow_id()); + delArrow(event.arrow_id()); } void Player::eventCreateToken(const Event_CreateToken &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; - CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id()); - card->setColor(QString::fromStdString(event.color())); - card->setPT(QString::fromStdString(event.pt())); - card->setAnnotation(QString::fromStdString(event.annotation())); - card->setDestroyOnZoneChange(event.destroy_on_zone_change()); + CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id()); + card->setColor(QString::fromStdString(event.color())); + card->setPT(QString::fromStdString(event.pt())); + card->setAnnotation(QString::fromStdString(event.annotation())); + card->setDestroyOnZoneChange(event.destroy_on_zone_change()); - emit logCreateToken(this, card->getName(), card->getPT()); - zone->addCard(card, true, event.x(), event.y()); + emit logCreateToken(this, card->getName(), card->getPT()); + zone->addCard(card, true, event.x(), event.y()); } void Player::eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; - if (!event.has_card_id()) { - const CardList &cards = zone->getCards(); - for (int i = 0; i < cards.size(); i++) - setCardAttrHelper(context, cards.at(i), event.attribute(), QString::fromStdString(event.attr_value()), true); - if (event.attribute() == AttrTapped) - emit logSetTapped(this, 0, event.attr_value() == "1"); - } else { - CardItem *card = zone->getCard(event.card_id(), QString()); - if (!card) { - qDebug() << "Player::eventSetCardAttr: card id=" << event.card_id() << "not found"; - return; - } - setCardAttrHelper(context, card, event.attribute(), QString::fromStdString(event.attr_value()), false); - } + if (!event.has_card_id()) { + const CardList &cards = zone->getCards(); + for (int i = 0; i < cards.size(); i++) + setCardAttrHelper(context, cards.at(i), event.attribute(), QString::fromStdString(event.attr_value()), true); + if (event.attribute() == AttrTapped) + emit logSetTapped(this, 0, event.attr_value() == "1"); + } else { + CardItem *card = zone->getCard(event.card_id(), QString()); + if (!card) { + qDebug() << "Player::eventSetCardAttr: card id=" << event.card_id() << "not found"; + return; + } + setCardAttrHelper(context, card, event.attribute(), QString::fromStdString(event.attr_value()), false); + } } void Player::eventSetCardCounter(const Event_SetCardCounter &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; - CardItem *card = zone->getCard(event.card_id(), QString()); - if (!card) - return; - - int oldValue = card->getCounters().value(event.counter_id(), 0); - card->setCounter(event.counter_id(), event.counter_value()); - emit logSetCardCounter(this, card->getName(), event.counter_id(), event.counter_value(), oldValue); + CardItem *card = zone->getCard(event.card_id(), QString()); + if (!card) + return; + + int oldValue = card->getCounters().value(event.counter_id(), 0); + card->setCounter(event.counter_id(), event.counter_value()); + emit logSetCardCounter(this, card->getName(), event.counter_id(), event.counter_value(), oldValue); } void Player::eventCreateCounter(const Event_CreateCounter &event) { - addCounter(event.counter_info()); + addCounter(event.counter_info()); } void Player::eventSetCounter(const Event_SetCounter &event) { - AbstractCounter *c = counters.value(event.counter_id(), 0); - if (!c) - return; - int oldValue = c->getValue(); - c->setValue(event.value()); - emit logSetCounter(this, c->getName(), event.value(), oldValue); + AbstractCounter *c = counters.value(event.counter_id(), 0); + if (!c) + return; + int oldValue = c->getValue(); + c->setValue(event.value()); + emit logSetCounter(this, c->getName(), event.value(), oldValue); } void Player::eventDelCounter(const Event_DelCounter &event) { - delCounter(event.counter_id()); + delCounter(event.counter_id()); } void Player::eventDumpZone(const Event_DumpZone &event) { - Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); - if (!zoneOwner) - return; - CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - emit logDumpZone(this, zone, event.number_cards()); + Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); + if (!zoneOwner) + return; + CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + emit logDumpZone(this, zone, event.number_cards()); } void Player::eventStopDumpZone(const Event_StopDumpZone &event) { - Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); - if (!zoneOwner) - return; - CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - emit logStopDumpZone(this, zone); + Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); + if (!zoneOwner) + return; + CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + emit logStopDumpZone(this, zone); } void Player::eventMoveCard(const Event_MoveCard &event, const GameEventContext &context) { - Player *startPlayer = game->getPlayers().value(event.start_player_id()); - if (!startPlayer) - return; - CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(event.start_zone()), 0); - Player *targetPlayer = game->getPlayers().value(event.target_player_id()); - if (!targetPlayer) - return; - CardZone *targetZone; - if (event.has_target_zone()) - targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); - else - targetZone = startZone; - if (!startZone || !targetZone) - return; - - int position = event.position(); - int x = event.x(); - int y = event.y(); + Player *startPlayer = game->getPlayers().value(event.start_player_id()); + if (!startPlayer) + return; + CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(event.start_zone()), 0); + Player *targetPlayer = game->getPlayers().value(event.target_player_id()); + if (!targetPlayer) + return; + CardZone *targetZone; + if (event.has_target_zone()) + targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); + else + targetZone = startZone; + if (!startZone || !targetZone) + return; + + int position = event.position(); + int x = event.x(); + int y = event.y(); - int logPosition = position; - int logX = x; - if (x == -1) - x = 0; - CardItem *card = startZone->takeCard(position, event.card_id(), startZone != targetZone); - if (!card) - return; - if (startZone != targetZone) - card->deleteCardInfoPopup(); - if (event.has_card_name()) - card->setName(QString::fromStdString(event.card_name())); - - if (card->getAttachedTo() && (startZone != targetZone)) { - CardItem *parentCard = card->getAttachedTo(); - card->setAttachedTo(0); - parentCard->getZone()->reorganizeCards(); - } + int logPosition = position; + int logX = x; + if (x == -1) + x = 0; + CardItem *card = startZone->takeCard(position, event.card_id(), startZone != targetZone); + if (!card) + return; + if (startZone != targetZone) + card->deleteCardInfoPopup(); + if (event.has_card_name()) + card->setName(QString::fromStdString(event.card_name())); + + if (card->getAttachedTo() && (startZone != targetZone)) { + CardItem *parentCard = card->getAttachedTo(); + card->setAttachedTo(0); + parentCard->getZone()->reorganizeCards(); + } - card->deleteDragItem(); + card->deleteDragItem(); - card->setId(event.new_card_id()); - card->setFaceDown(event.face_down()); - if (startZone != targetZone) { - card->setBeingPointedAt(false); - card->setHovered(false); - - const QList &attachedCards = card->getAttachedCards(); - for (int i = 0; i < attachedCards.size(); ++i) - attachedCards[i]->setParentItem(targetZone); - - if (startZone->getPlayer() != targetZone->getPlayer()) - card->setOwner(targetZone->getPlayer()); - } + card->setId(event.new_card_id()); + card->setFaceDown(event.face_down()); + if (startZone != targetZone) { + card->setBeingPointedAt(false); + card->setHovered(false); + + const QList &attachedCards = card->getAttachedCards(); + for (int i = 0; i < attachedCards.size(); ++i) + attachedCards[i]->setParentItem(targetZone); + + if (startZone->getPlayer() != targetZone->getPlayer()) + card->setOwner(targetZone->getPlayer()); + } - // The log event has to be sent before the card is added to the target zone - // because the addCard function can modify the card object. - if (context.HasExtension(Context_UndoDraw::ext)) - emit logUndoDraw(this, card->getName()); - else - emit logMoveCard(this, card, startZone, logPosition, targetZone, logX); + // The log event has to be sent before the card is added to the target zone + // because the addCard function can modify the card object. + if (context.HasExtension(Context_UndoDraw::ext)) + emit logUndoDraw(this, card->getName()); + else + emit logMoveCard(this, card, startZone, logPosition, targetZone, logX); - targetZone->addCard(card, true, x, y); + targetZone->addCard(card, true, x, y); - // Look at all arrows from and to the card. - // If the card was moved to another zone, delete the arrows, otherwise update them. - QMapIterator playerIterator(game->getPlayers()); - while (playerIterator.hasNext()) { - Player *p = playerIterator.next().value(); + // Look at all arrows from and to the card. + // If the card was moved to another zone, delete the arrows, otherwise update them. + QMapIterator playerIterator(game->getPlayers()); + while (playerIterator.hasNext()) { + Player *p = playerIterator.next().value(); - QList arrowsToDelete; - QMapIterator arrowIterator(p->getArrows()); - while (arrowIterator.hasNext()) { - ArrowItem *arrow = arrowIterator.next().value(); - if ((arrow->getStartItem() == card) || (arrow->getTargetItem() == card)) { - if (startZone == targetZone) - arrow->updatePath(); - else - arrowsToDelete.append(arrow); - } - } - for (int i = 0; i < arrowsToDelete.size(); ++i) - arrowsToDelete[i]->delArrow(); - } + QList arrowsToDelete; + QMapIterator arrowIterator(p->getArrows()); + while (arrowIterator.hasNext()) { + ArrowItem *arrow = arrowIterator.next().value(); + if ((arrow->getStartItem() == card) || (arrow->getTargetItem() == card)) { + if (startZone == targetZone) + arrow->updatePath(); + else + arrowsToDelete.append(arrow); + } + } + for (int i = 0; i < arrowsToDelete.size(); ++i) + arrowsToDelete[i]->delArrow(); + } } void Player::eventFlipCard(const Event_FlipCard &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - CardItem *card = zone->getCard(event.card_id(), QString::fromStdString(event.card_name())); - if (!card) - return; - emit logFlipCard(this, card->getName(), event.face_down()); - card->setFaceDown(event.face_down()); + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + CardItem *card = zone->getCard(event.card_id(), QString::fromStdString(event.card_name())); + if (!card) + return; + emit logFlipCard(this, card->getName(), event.face_down()); + card->setFaceDown(event.face_down()); } void Player::eventDestroyCard(const Event_DestroyCard &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - - CardItem *card = zone->getCard(event.card_id(), QString()); - if (!card) - return; - - QList attachedCards = card->getAttachedCards(); - // This list is always empty except for buggy server implementations. - for (int i = 0; i < attachedCards.size(); ++i) - attachedCards[i]->setAttachedTo(0); - - emit logDestroyCard(this, card->getName()); - zone->takeCard(-1, event.card_id(), true); - card->deleteLater(); + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + + CardItem *card = zone->getCard(event.card_id(), QString()); + if (!card) + return; + + QList attachedCards = card->getAttachedCards(); + // This list is always empty except for buggy server implementations. + for (int i = 0; i < attachedCards.size(); ++i) + attachedCards[i]->setAttachedTo(0); + + emit logDestroyCard(this, card->getName()); + zone->takeCard(-1, event.card_id(), true); + card->deleteLater(); } void Player::eventAttachCard(const Event_AttachCard &event) { - const QMap &playerList = game->getPlayers(); - Player *targetPlayer = 0; - CardZone *targetZone = 0; - CardItem *targetCard = 0; - if (event.has_target_player_id()) { - targetPlayer = playerList.value(event.target_player_id(), 0); - if (targetPlayer) { - targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); - if (targetZone) - targetCard = targetZone->getCard(event.target_card_id(), QString()); - } - } - - CardZone *startZone = getZones().value(QString::fromStdString(event.start_zone()), 0); - if (!startZone) - return; - - CardItem *startCard = startZone->getCard(event.card_id(), QString()); - if (!startCard) - return; - - CardItem *oldParent = startCard->getAttachedTo(); - - startCard->setAttachedTo(targetCard); - - startZone->reorganizeCards(); - if ((startZone != targetZone) && targetZone) - targetZone->reorganizeCards(); - if (oldParent) - oldParent->getZone()->reorganizeCards(); - - if (targetCard) - emit logAttachCard(this, startCard->getName(), targetPlayer, targetCard->getName()); - else - emit logUnattachCard(this, startCard->getName()); + const QMap &playerList = game->getPlayers(); + Player *targetPlayer = 0; + CardZone *targetZone = 0; + CardItem *targetCard = 0; + if (event.has_target_player_id()) { + targetPlayer = playerList.value(event.target_player_id(), 0); + if (targetPlayer) { + targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); + if (targetZone) + targetCard = targetZone->getCard(event.target_card_id(), QString()); + } + } + + CardZone *startZone = getZones().value(QString::fromStdString(event.start_zone()), 0); + if (!startZone) + return; + + CardItem *startCard = startZone->getCard(event.card_id(), QString()); + if (!startCard) + return; + + CardItem *oldParent = startCard->getAttachedTo(); + + startCard->setAttachedTo(targetCard); + + startZone->reorganizeCards(); + if ((startZone != targetZone) && targetZone) + targetZone->reorganizeCards(); + if (oldParent) + oldParent->getZone()->reorganizeCards(); + + if (targetCard) + emit logAttachCard(this, startCard->getName(), targetPlayer, targetCard->getName()); + else + emit logUnattachCard(this, startCard->getName()); } void Player::eventDrawCards(const Event_DrawCards &event) { - CardZone *deck = zones.value("deck"); - CardZone *hand = zones.value("hand"); - - const int listSize = event.cards_size(); - if (listSize) { - for (int i = 0; i < listSize; ++i) { - const ServerInfo_Card &cardInfo = event.cards(i); - CardItem *card = deck->takeCard(0, cardInfo.id()); - card->setName(QString::fromStdString(cardInfo.name())); - hand->addCard(card, false, -1); - } - } else { - const int number = event.number(); - for (int i = 0; i < number; ++i) - hand->addCard(deck->takeCard(0, -1), false, -1); - } - - hand->reorganizeCards(); - deck->reorganizeCards(); - emit logDrawCards(this, event.number()); + CardZone *deck = zones.value("deck"); + CardZone *hand = zones.value("hand"); + + const int listSize = event.cards_size(); + if (listSize) { + for (int i = 0; i < listSize; ++i) { + const ServerInfo_Card &cardInfo = event.cards(i); + CardItem *card = deck->takeCard(0, cardInfo.id()); + card->setName(QString::fromStdString(cardInfo.name())); + hand->addCard(card, false, -1); + } + } else { + const int number = event.number(); + for (int i = 0; i < number; ++i) + hand->addCard(deck->takeCard(0, -1), false, -1); + } + + hand->reorganizeCards(); + deck->reorganizeCards(); + emit logDrawCards(this, event.number()); } void Player::eventRevealCards(const Event_RevealCards &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); - if (!zone) - return; - Player *otherPlayer = 0; - if (event.has_other_player_id()) { - otherPlayer = game->getPlayers().value(event.other_player_id()); - if (!otherPlayer) - return; - } - - bool peeking = false; - QList cardList; - const int cardListSize = event.cards_size(); - for (int i = 0; i < cardListSize; ++i) { - const ServerInfo_Card *temp = &event.cards(i); - if (temp->face_down()) - peeking = true; - cardList.append(temp); - } - - if (peeking) { - for (int i = 0; i < cardList.size(); ++i) { - QString cardName = QString::fromStdString(cardList.at(i)->name()); - CardItem *card = zone->getCard(cardList.at(i)->id(), QString()); - if (!card) - continue; - card->setName(cardName); - emit logRevealCards(this, zone, cardList.at(i)->id(), cardName, this, true); - } - } else { - bool showZoneView = true; - QString cardName; - if (cardList.size() == 1) { - cardName = QString::fromStdString(cardList.first()->name()); - if ((event.card_id() == 0) && dynamic_cast(zone)) { - zone->getCards().first()->setName(cardName); - zone->update(); - showZoneView = false; - } - } - if (showZoneView && !cardList.isEmpty()) - static_cast(scene())->addRevealedZoneView(this, zone, cardList, event.grant_write_access()); - - emit logRevealCards(this, zone, event.card_id(), cardName, otherPlayer, false); - } + CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); + if (!zone) + return; + Player *otherPlayer = 0; + if (event.has_other_player_id()) { + otherPlayer = game->getPlayers().value(event.other_player_id()); + if (!otherPlayer) + return; + } + + bool peeking = false; + QList cardList; + const int cardListSize = event.cards_size(); + for (int i = 0; i < cardListSize; ++i) { + const ServerInfo_Card *temp = &event.cards(i); + if (temp->face_down()) + peeking = true; + cardList.append(temp); + } + + if (peeking) { + for (int i = 0; i < cardList.size(); ++i) { + QString cardName = QString::fromStdString(cardList.at(i)->name()); + CardItem *card = zone->getCard(cardList.at(i)->id(), QString()); + if (!card) + continue; + card->setName(cardName); + emit logRevealCards(this, zone, cardList.at(i)->id(), cardName, this, true); + } + } else { + bool showZoneView = true; + QString cardName; + if (cardList.size() == 1) { + cardName = QString::fromStdString(cardList.first()->name()); + if ((event.card_id() == 0) && dynamic_cast(zone)) { + zone->getCards().first()->setName(cardName); + zone->update(); + showZoneView = false; + } + } + if (showZoneView && !cardList.isEmpty()) + static_cast(scene())->addRevealedZoneView(this, zone, cardList, event.grant_write_access()); + + emit logRevealCards(this, zone, event.card_id(), cardName, otherPlayer, false); + } } void Player::eventChangeZoneProperties(const Event_ChangeZoneProperties &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); - if (!zone) - return; - - if (event.has_always_reveal_top_card()) { - zone->setAlwaysRevealTopCard(event.always_reveal_top_card()); - emit logAlwaysRevealTopCard(this, zone, event.always_reveal_top_card()); - } + CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); + if (!zone) + return; + + if (event.has_always_reveal_top_card()) { + zone->setAlwaysRevealTopCard(event.always_reveal_top_card()); + emit logAlwaysRevealTopCard(this, zone, event.always_reveal_top_card()); + } } void Player::processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context) { - switch (type) { - case GameEvent::GAME_SAY: eventGameSay(event.GetExtension(Event_GameSay::ext)); break; - case GameEvent::SHUFFLE: eventShuffle(event.GetExtension(Event_Shuffle::ext)); break; - case GameEvent::ROLL_DIE: eventRollDie(event.GetExtension(Event_RollDie::ext)); break; - case GameEvent::CREATE_ARROW: eventCreateArrow(event.GetExtension(Event_CreateArrow::ext)); break; - case GameEvent::DELETE_ARROW: eventDeleteArrow(event.GetExtension(Event_DeleteArrow::ext)); break; - case GameEvent::CREATE_TOKEN: eventCreateToken(event.GetExtension(Event_CreateToken::ext)); break; - case GameEvent::SET_CARD_ATTR: eventSetCardAttr(event.GetExtension(Event_SetCardAttr::ext), context); break; - case GameEvent::SET_CARD_COUNTER: eventSetCardCounter(event.GetExtension(Event_SetCardCounter::ext)); break; - case GameEvent::CREATE_COUNTER: eventCreateCounter(event.GetExtension(Event_CreateCounter::ext)); break; - case GameEvent::SET_COUNTER: eventSetCounter(event.GetExtension(Event_SetCounter::ext)); break; - case GameEvent::DEL_COUNTER: eventDelCounter(event.GetExtension(Event_DelCounter::ext)); break; - case GameEvent::DUMP_ZONE: eventDumpZone(event.GetExtension(Event_DumpZone::ext)); break; - case GameEvent::STOP_DUMP_ZONE: eventStopDumpZone(event.GetExtension(Event_StopDumpZone::ext)); break; - case GameEvent::MOVE_CARD: eventMoveCard(event.GetExtension(Event_MoveCard::ext), context); break; - case GameEvent::FLIP_CARD: eventFlipCard(event.GetExtension(Event_FlipCard::ext)); break; - case GameEvent::DESTROY_CARD: eventDestroyCard(event.GetExtension(Event_DestroyCard::ext)); break; - case GameEvent::ATTACH_CARD: eventAttachCard(event.GetExtension(Event_AttachCard::ext)); break; - case GameEvent::DRAW_CARDS: eventDrawCards(event.GetExtension(Event_DrawCards::ext)); break; - case GameEvent::REVEAL_CARDS: eventRevealCards(event.GetExtension(Event_RevealCards::ext)); break; - case GameEvent::CHANGE_ZONE_PROPERTIES: eventChangeZoneProperties(event.GetExtension(Event_ChangeZoneProperties::ext)); break; - default: { - qDebug() << "unhandled game event"; - } - } + switch (type) { + case GameEvent::GAME_SAY: eventGameSay(event.GetExtension(Event_GameSay::ext)); break; + case GameEvent::SHUFFLE: eventShuffle(event.GetExtension(Event_Shuffle::ext)); break; + case GameEvent::ROLL_DIE: eventRollDie(event.GetExtension(Event_RollDie::ext)); break; + case GameEvent::CREATE_ARROW: eventCreateArrow(event.GetExtension(Event_CreateArrow::ext)); break; + case GameEvent::DELETE_ARROW: eventDeleteArrow(event.GetExtension(Event_DeleteArrow::ext)); break; + case GameEvent::CREATE_TOKEN: eventCreateToken(event.GetExtension(Event_CreateToken::ext)); break; + case GameEvent::SET_CARD_ATTR: eventSetCardAttr(event.GetExtension(Event_SetCardAttr::ext), context); break; + case GameEvent::SET_CARD_COUNTER: eventSetCardCounter(event.GetExtension(Event_SetCardCounter::ext)); break; + case GameEvent::CREATE_COUNTER: eventCreateCounter(event.GetExtension(Event_CreateCounter::ext)); break; + case GameEvent::SET_COUNTER: eventSetCounter(event.GetExtension(Event_SetCounter::ext)); break; + case GameEvent::DEL_COUNTER: eventDelCounter(event.GetExtension(Event_DelCounter::ext)); break; + case GameEvent::DUMP_ZONE: eventDumpZone(event.GetExtension(Event_DumpZone::ext)); break; + case GameEvent::STOP_DUMP_ZONE: eventStopDumpZone(event.GetExtension(Event_StopDumpZone::ext)); break; + case GameEvent::MOVE_CARD: eventMoveCard(event.GetExtension(Event_MoveCard::ext), context); break; + case GameEvent::FLIP_CARD: eventFlipCard(event.GetExtension(Event_FlipCard::ext)); break; + case GameEvent::DESTROY_CARD: eventDestroyCard(event.GetExtension(Event_DestroyCard::ext)); break; + case GameEvent::ATTACH_CARD: eventAttachCard(event.GetExtension(Event_AttachCard::ext)); break; + case GameEvent::DRAW_CARDS: eventDrawCards(event.GetExtension(Event_DrawCards::ext)); break; + case GameEvent::REVEAL_CARDS: eventRevealCards(event.GetExtension(Event_RevealCards::ext)); break; + case GameEvent::CHANGE_ZONE_PROPERTIES: eventChangeZoneProperties(event.GetExtension(Event_ChangeZoneProperties::ext)); break; + default: { + qDebug() << "unhandled game event"; + } + } } void Player::setActive(bool _active) { - active = _active; - table->setActive(active); - update(); + active = _active; + table->setActive(active); + update(); } QRectF Player::boundingRect() const { - return bRect; + return bRect; } void Player::paint(QPainter * /*painter*/, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) @@ -1436,759 +1436,759 @@ void Player::paint(QPainter * /*painter*/, const QStyleOptionGraphicsItem */*opt void Player::processPlayerInfo(const ServerInfo_Player &info) { - clearCounters(); - clearArrows(); - - QMapIterator zoneIt(zones); - while (zoneIt.hasNext()) - zoneIt.next().value()->clearContents(); - - const int zoneListSize = info.zone_list_size(); - for (int i = 0; i < zoneListSize; ++i) { - const ServerInfo_Zone &zoneInfo = info.zone_list(i); - CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); - if (!zone) - continue; - - const int cardListSize = zoneInfo.card_list_size(); - if (!cardListSize) { - for (int j = 0; j < zoneInfo.card_count(); ++j) - zone->addCard(new CardItem(this), false, -1); - } else { - for (int j = 0; j < cardListSize; ++j) { - const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); - CardItem *card = new CardItem(this); - card->processCardInfo(cardInfo); - zone->addCard(card, false, cardInfo.x(), cardInfo.y()); - } - } - if (zoneInfo.has_always_reveal_top_card()) - zone->setAlwaysRevealTopCard(zoneInfo.always_reveal_top_card()); - - zone->reorganizeCards(); - } - - const int counterListSize = info.counter_list_size(); - for (int i = 0; i < counterListSize; ++i) - addCounter(info.counter_list(i)); - - setConceded(info.properties().conceded()); + clearCounters(); + clearArrows(); + + QMapIterator zoneIt(zones); + while (zoneIt.hasNext()) + zoneIt.next().value()->clearContents(); + + const int zoneListSize = info.zone_list_size(); + for (int i = 0; i < zoneListSize; ++i) { + const ServerInfo_Zone &zoneInfo = info.zone_list(i); + CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); + if (!zone) + continue; + + const int cardListSize = zoneInfo.card_list_size(); + if (!cardListSize) { + for (int j = 0; j < zoneInfo.card_count(); ++j) + zone->addCard(new CardItem(this), false, -1); + } else { + for (int j = 0; j < cardListSize; ++j) { + const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); + CardItem *card = new CardItem(this); + card->processCardInfo(cardInfo); + zone->addCard(card, false, cardInfo.x(), cardInfo.y()); + } + } + if (zoneInfo.has_always_reveal_top_card()) + zone->setAlwaysRevealTopCard(zoneInfo.always_reveal_top_card()); + + zone->reorganizeCards(); + } + + const int counterListSize = info.counter_list_size(); + for (int i = 0; i < counterListSize; ++i) + addCounter(info.counter_list(i)); + + setConceded(info.properties().conceded()); } void Player::processCardAttachment(const ServerInfo_Player &info) { - const int zoneListSize = info.zone_list_size(); - for (int i = 0; i < zoneListSize; ++i) { - const ServerInfo_Zone &zoneInfo = info.zone_list(i); - CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); - if (!zone) - continue; - - const int cardListSize = zoneInfo.card_list_size(); - for (int j = 0; j < cardListSize; ++j) { - const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); - if (cardInfo.has_attach_player_id()) { - CardItem *startCard = zone->getCard(cardInfo.id(), QString()); - CardItem *targetCard = game->getCard(cardInfo.attach_player_id(), QString::fromStdString(cardInfo.attach_zone()), cardInfo.attach_card_id()); - if (!targetCard) - continue; - - startCard->setAttachedTo(targetCard); - } - } - } - - const int arrowListSize = info.arrow_list_size(); - for (int i = 0; i < arrowListSize; ++i) - addArrow(info.arrow_list(i)); + const int zoneListSize = info.zone_list_size(); + for (int i = 0; i < zoneListSize; ++i) { + const ServerInfo_Zone &zoneInfo = info.zone_list(i); + CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); + if (!zone) + continue; + + const int cardListSize = zoneInfo.card_list_size(); + for (int j = 0; j < cardListSize; ++j) { + const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); + if (cardInfo.has_attach_player_id()) { + CardItem *startCard = zone->getCard(cardInfo.id(), QString()); + CardItem *targetCard = game->getCard(cardInfo.attach_player_id(), QString::fromStdString(cardInfo.attach_zone()), cardInfo.attach_card_id()); + if (!targetCard) + continue; + + startCard->setAttachedTo(targetCard); + } + } + } + + const int arrowListSize = info.arrow_list_size(); + for (int i = 0; i < arrowListSize; ++i) + addArrow(info.arrow_list(i)); } void Player::playCard(CardItem *c, bool faceDown, bool tapped) { - Command_MoveCard cmd; - cmd.set_start_player_id(c->getZone()->getPlayer()->getId()); - cmd.set_start_zone(c->getZone()->getName().toStdString()); - cmd.set_target_player_id(getId()); - CardToMove *cardToMove = cmd.mutable_cards_to_move()->add_card(); - cardToMove->set_card_id(c->getId()); - - CardInfo *ci = c->getInfo(); - if ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || - ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && - c->getZone()->getName().toStdString() != "stack")) { - cmd.set_target_zone("stack"); - cmd.set_x(0); - cmd.set_y(0); - } else { - QPoint gridPoint = QPoint(-1, 2 - ci->getTableRow()); - cardToMove->set_face_down(faceDown); - cardToMove->set_pt(ci->getPowTough().toStdString()); - cardToMove->set_tapped(tapped); - if(ci->getTableRow() != 3) - cmd.set_target_zone("table"); - cmd.set_x(gridPoint.x()); - cmd.set_y(gridPoint.y()); - } - sendGameCommand(cmd); + Command_MoveCard cmd; + cmd.set_start_player_id(c->getZone()->getPlayer()->getId()); + cmd.set_start_zone(c->getZone()->getName().toStdString()); + cmd.set_target_player_id(getId()); + CardToMove *cardToMove = cmd.mutable_cards_to_move()->add_card(); + cardToMove->set_card_id(c->getId()); + + CardInfo *ci = c->getInfo(); + if ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || + ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && + c->getZone()->getName().toStdString() != "stack")) { + cmd.set_target_zone("stack"); + cmd.set_x(0); + cmd.set_y(0); + } else { + QPoint gridPoint = QPoint(-1, 2 - ci->getTableRow()); + cardToMove->set_face_down(faceDown); + cardToMove->set_pt(ci->getPowTough().toStdString()); + cardToMove->set_tapped(tapped); + if(ci->getTableRow() != 3) + cmd.set_target_zone("table"); + cmd.set_x(gridPoint.x()); + cmd.set_y(gridPoint.y()); + } + sendGameCommand(cmd); } void Player::addCard(CardItem *c) { - emit newCardAdded(c); + emit newCardAdded(c); } void Player::deleteCard(CardItem *c) { - if (dialogSemaphore) - cardsToDelete.append(c); - else - c->deleteLater(); + if (dialogSemaphore) + cardsToDelete.append(c); + else + c->deleteLater(); } void Player::addZone(CardZone *z) { - zones.insert(z->getName(), z); + zones.insert(z->getName(), z); } AbstractCounter *Player::addCounter(const ServerInfo_Counter &counter) { - return addCounter(counter.id(), QString::fromStdString(counter.name()), convertColorToQColor(counter.counter_color()), counter.radius(), counter.count()); + return addCounter(counter.id(), QString::fromStdString(counter.name()), convertColorToQColor(counter.counter_color()), counter.radius(), counter.count()); } AbstractCounter *Player::addCounter(int counterId, const QString &name, QColor color, int radius, int value) { - qDebug() << "addCounter:" << getName() << counterId << name; - if (counters.contains(counterId)) - return 0; - - AbstractCounter *c; - if (name == "life") - c = playerTarget->addCounter(counterId, name, value); - else - c = new GeneralCounter(this, counterId, name, color, radius, value, this); - counters.insert(counterId, c); - if (countersMenu) - countersMenu->addMenu(c->getMenu()); - if (shortcutsActive) - c->setShortcutsActive(); - rearrangeCounters(); - return c; + qDebug() << "addCounter:" << getName() << counterId << name; + if (counters.contains(counterId)) + return 0; + + AbstractCounter *c; + if (name == "life") + c = playerTarget->addCounter(counterId, name, value); + else + c = new GeneralCounter(this, counterId, name, color, radius, value, this); + counters.insert(counterId, c); + if (countersMenu) + countersMenu->addMenu(c->getMenu()); + if (shortcutsActive) + c->setShortcutsActive(); + rearrangeCounters(); + return c; } void Player::delCounter(int counterId) { - AbstractCounter *c = counters.value(counterId, 0); - if (!c) - return; - - c->delCounter(); - counters.remove(counterId); - rearrangeCounters(); + AbstractCounter *c = counters.value(counterId, 0); + if (!c) + return; + + c->delCounter(); + counters.remove(counterId); + rearrangeCounters(); } void Player::clearCounters() { - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->delCounter(); - counters.clear(); + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->delCounter(); + counters.clear(); } ArrowItem *Player::addArrow(const ServerInfo_Arrow &arrow) { - const QMap &playerList = game->getPlayers(); - Player *startPlayer = playerList.value(arrow.start_player_id(), 0); - Player *targetPlayer = playerList.value(arrow.target_player_id(), 0); - if (!startPlayer || !targetPlayer) - return 0; - - CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(arrow.start_zone()), 0); - CardZone *targetZone = 0; - if (arrow.has_target_zone()) - targetZone = targetPlayer->getZones().value(QString::fromStdString(arrow.target_zone()), 0); - if (!startZone || (!targetZone && arrow.has_target_zone())) - return 0; - - CardItem *startCard = startZone->getCard(arrow.start_card_id(), QString()); - CardItem *targetCard = 0; - if (targetZone) - targetCard = targetZone->getCard(arrow.target_card_id(), QString()); - if (!startCard || (!targetCard && arrow.has_target_card_id())) - return 0; - - if (targetCard) - return addArrow(arrow.id(), startCard, targetCard, convertColorToQColor(arrow.arrow_color())); - else - return addArrow(arrow.id(), startCard, targetPlayer->getPlayerTarget(), convertColorToQColor(arrow.arrow_color())); + const QMap &playerList = game->getPlayers(); + Player *startPlayer = playerList.value(arrow.start_player_id(), 0); + Player *targetPlayer = playerList.value(arrow.target_player_id(), 0); + if (!startPlayer || !targetPlayer) + return 0; + + CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(arrow.start_zone()), 0); + CardZone *targetZone = 0; + if (arrow.has_target_zone()) + targetZone = targetPlayer->getZones().value(QString::fromStdString(arrow.target_zone()), 0); + if (!startZone || (!targetZone && arrow.has_target_zone())) + return 0; + + CardItem *startCard = startZone->getCard(arrow.start_card_id(), QString()); + CardItem *targetCard = 0; + if (targetZone) + targetCard = targetZone->getCard(arrow.target_card_id(), QString()); + if (!startCard || (!targetCard && arrow.has_target_card_id())) + return 0; + + if (targetCard) + return addArrow(arrow.id(), startCard, targetCard, convertColorToQColor(arrow.arrow_color())); + else + return addArrow(arrow.id(), startCard, targetPlayer->getPlayerTarget(), convertColorToQColor(arrow.arrow_color())); } ArrowItem *Player::addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color) { - ArrowItem *arrow = new ArrowItem(this, arrowId, startCard, targetItem, color); - arrows.insert(arrowId, arrow); - scene()->addItem(arrow); - return arrow; + ArrowItem *arrow = new ArrowItem(this, arrowId, startCard, targetItem, color); + arrows.insert(arrowId, arrow); + scene()->addItem(arrow); + return arrow; } void Player::delArrow(int arrowId) { - ArrowItem *a = arrows.value(arrowId, 0); - if (!a) - return; - a->delArrow(); + ArrowItem *a = arrows.value(arrowId, 0); + if (!a) + return; + a->delArrow(); } void Player::removeArrow(ArrowItem *arrow) { - if (arrow->getId() != -1) - arrows.remove(arrow->getId()); + if (arrow->getId() != -1) + arrows.remove(arrow->getId()); } void Player::clearArrows() { - QMapIterator arrowIterator(arrows); - while (arrowIterator.hasNext()) - arrowIterator.next().value()->delArrow(); - arrows.clear(); + QMapIterator arrowIterator(arrows); + while (arrowIterator.hasNext()) + arrowIterator.next().value()->delArrow(); + arrows.clear(); } void Player::rearrangeCounters() { - qreal marginTop = 80; - - // Determine total height of bounding rectangles - qreal totalHeight = 0; - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) { - counterIterator.next(); - if (counterIterator.value()->getShownInCounterArea()) - totalHeight += counterIterator.value()->boundingRect().height(); - } - - const qreal padding = 5; - qreal y = boundingRect().y() + marginTop; - - // Place objects - for (counterIterator.toFront(); counterIterator.hasNext(); ) { - AbstractCounter *c = counterIterator.next().value(); + qreal marginTop = 80; + + // Determine total height of bounding rectangles + qreal totalHeight = 0; + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) { + counterIterator.next(); + if (counterIterator.value()->getShownInCounterArea()) + totalHeight += counterIterator.value()->boundingRect().height(); + } + + const qreal padding = 5; + qreal y = boundingRect().y() + marginTop; + + // Place objects + for (counterIterator.toFront(); counterIterator.hasNext(); ) { + AbstractCounter *c = counterIterator.next().value(); - if (!c->getShownInCounterArea()) - continue; - - QRectF br = c->boundingRect(); - c->setPos((counterAreaWidth - br.width()) / 2, y); - y += br.height() + padding; - } + if (!c->getShownInCounterArea()) + continue; + + QRectF br = c->boundingRect(); + c->setPos((counterAreaWidth - br.width()) / 2, y); + y += br.height() + padding; + } } PendingCommand * Player::prepareGameCommand(const google::protobuf::Message &cmd) { - return game->prepareGameCommand(cmd); + return game->prepareGameCommand(cmd); } PendingCommand * Player::prepareGameCommand(const QList &cmdList) { - return game->prepareGameCommand(cmdList); + return game->prepareGameCommand(cmdList); } void Player::sendGameCommand(const google::protobuf::Message &command) { - game->sendGameCommand(command, id); + game->sendGameCommand(command, id); } void Player::sendGameCommand(PendingCommand *pend) { - game->sendGameCommand(pend, id); + game->sendGameCommand(pend, id); } bool Player::clearCardsToDelete() { - if (cardsToDelete.isEmpty()) - return false; - - for (int i = 0; i < cardsToDelete.size(); ++i) - cardsToDelete[i]->deleteLater(); - cardsToDelete.clear(); - - return true; + if (cardsToDelete.isEmpty()) + return false; + + for (int i = 0; i < cardsToDelete.size(); ++i) + cardsToDelete[i]->deleteLater(); + cardsToDelete.clear(); + + return true; } void Player::cardMenuAction() { - QAction *a = static_cast(sender()); - QList sel = scene()->selectedItems(); - QList cardList; - while (!sel.isEmpty()) - cardList.append(qgraphicsitem_cast(sel.takeFirst())); - - QList< const ::google::protobuf::Message * > commandList; - if (a->data().toInt() <= (int) cmClone) - for (int i = 0; i < cardList.size(); ++i) { - CardItem *card = cardList[i]; - switch (static_cast(a->data().toInt())) { - case cmTap: - if (!card->getTapped()) { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrTapped); - cmd->set_attr_value("1"); - commandList.append(cmd); - } - break; - case cmUntap: - if (card->getTapped()) { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrTapped); - cmd->set_attr_value("0"); - commandList.append(cmd); - } - break; - case cmDoesntUntap: { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrDoesntUntap); - cmd->set_attr_value(card->getDoesntUntap() ? "0" : "1"); - commandList.append(cmd); - break; - } - case cmFlip: { - Command_FlipCard *cmd = new Command_FlipCard; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_face_down(!card->getFaceDown()); - commandList.append(cmd); - break; - } - case cmPeek: { - Command_RevealCards *cmd = new Command_RevealCards; - cmd->set_zone_name(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_player_id(id); - commandList.append(cmd); - break; - } - case cmClone: { - Command_CreateToken *cmd = new Command_CreateToken; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_name(card->getName().toStdString()); - cmd->set_color(card->getColor().toStdString()); - cmd->set_pt(card->getPT().toStdString()); - cmd->set_annotation(card->getAnnotation().toStdString()); - cmd->set_destroy_on_zone_change(true); - cmd->set_x(-1); - cmd->set_y(card->getGridPoint().y()); - commandList.append(cmd); - break; - } + QAction *a = static_cast(sender()); + QList sel = scene()->selectedItems(); + QList cardList; + while (!sel.isEmpty()) + cardList.append(qgraphicsitem_cast(sel.takeFirst())); + + QList< const ::google::protobuf::Message * > commandList; + if (a->data().toInt() <= (int) cmClone) + for (int i = 0; i < cardList.size(); ++i) { + CardItem *card = cardList[i]; + switch (static_cast(a->data().toInt())) { + case cmTap: + if (!card->getTapped()) { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrTapped); + cmd->set_attr_value("1"); + commandList.append(cmd); + } + break; + case cmUntap: + if (card->getTapped()) { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrTapped); + cmd->set_attr_value("0"); + commandList.append(cmd); + } + break; + case cmDoesntUntap: { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrDoesntUntap); + cmd->set_attr_value(card->getDoesntUntap() ? "0" : "1"); + commandList.append(cmd); + break; + } + case cmFlip: { + Command_FlipCard *cmd = new Command_FlipCard; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_face_down(!card->getFaceDown()); + commandList.append(cmd); + break; + } + case cmPeek: { + Command_RevealCards *cmd = new Command_RevealCards; + cmd->set_zone_name(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_player_id(id); + commandList.append(cmd); + break; + } + case cmClone: { + Command_CreateToken *cmd = new Command_CreateToken; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_name(card->getName().toStdString()); + cmd->set_color(card->getColor().toStdString()); + cmd->set_pt(card->getPT().toStdString()); + cmd->set_annotation(card->getAnnotation().toStdString()); + cmd->set_destroy_on_zone_change(true); + cmd->set_x(-1); + cmd->set_y(card->getGridPoint().y()); + commandList.append(cmd); + break; + } default: break; - } - } - else { - ListOfCardsToMove idList; - for (int i = 0; i < cardList.size(); ++i) - idList.add_card()->set_card_id(cardList[i]->getId()); - int startPlayerId = cardList[0]->getZone()->getPlayer()->getId(); - QString startZone = cardList[0]->getZone()->getName(); - - switch (static_cast(a->data().toInt())) { - case cmMoveToTopLibrary: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("deck"); - cmd->set_x(0); - cmd->set_y(0); - commandList.append(cmd); - break; - } - case cmMoveToBottomLibrary: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("deck"); - cmd->set_x(-1); - cmd->set_y(0); - commandList.append(cmd); - break; - } - case cmMoveToGraveyard: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("grave"); - cmd->set_x(0); - cmd->set_y(0); - commandList.append(cmd); - break; - } - case cmMoveToExile: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("rfg"); - cmd->set_x(0); - cmd->set_y(0); - commandList.append(cmd); - break; - } - default: ; - } - } - game->sendGameCommand(prepareGameCommand(commandList)); + } + } + else { + ListOfCardsToMove idList; + for (int i = 0; i < cardList.size(); ++i) + idList.add_card()->set_card_id(cardList[i]->getId()); + int startPlayerId = cardList[0]->getZone()->getPlayer()->getId(); + QString startZone = cardList[0]->getZone()->getName(); + + switch (static_cast(a->data().toInt())) { + case cmMoveToTopLibrary: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("deck"); + cmd->set_x(0); + cmd->set_y(0); + commandList.append(cmd); + break; + } + case cmMoveToBottomLibrary: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("deck"); + cmd->set_x(-1); + cmd->set_y(0); + commandList.append(cmd); + break; + } + case cmMoveToGraveyard: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("grave"); + cmd->set_x(0); + cmd->set_y(0); + commandList.append(cmd); + break; + } + case cmMoveToExile: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("rfg"); + cmd->set_x(0); + cmd->set_y(0); + commandList.append(cmd); + break; + } + default: ; + } + } + game->sendGameCommand(prepareGameCommand(commandList)); } void Player::actIncPT(int deltaP, int deltaT) { - QString ptString = "+" + QString::number(deltaP) + "/+" + QString::number(deltaT); - - QList< const ::google::protobuf::Message * > commandList; - QListIterator j(scene()->selectedItems()); - while (j.hasNext()) { - CardItem *card = static_cast(j.next()); - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrPT); - cmd->set_attr_value(ptString.toStdString()); - commandList.append(cmd); - } - sendGameCommand(prepareGameCommand(commandList)); + QString ptString = "+" + QString::number(deltaP) + "/+" + QString::number(deltaT); + + QList< const ::google::protobuf::Message * > commandList; + QListIterator j(scene()->selectedItems()); + while (j.hasNext()) { + CardItem *card = static_cast(j.next()); + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrPT); + cmd->set_attr_value(ptString.toStdString()); + commandList.append(cmd); + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actSetPT() { - QString oldPT; - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (!card->getPT().isEmpty()) - oldPT = card->getPT(); - } - bool ok; - dialogSemaphore = true; - QString pt = QInputDialog::getText(0, tr("Set power/toughness"), tr("Please enter the new PT:"), QLineEdit::Normal, oldPT, &ok); - dialogSemaphore = false; - if (clearCardsToDelete()) - return; - if (!ok) - return; - - QList< const ::google::protobuf::Message * > commandList; - QListIterator j(scene()->selectedItems()); - while (j.hasNext()) { - CardItem *card = static_cast(j.next()); - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrPT); - cmd->set_attr_value(pt.toStdString()); - commandList.append(cmd); - } - sendGameCommand(prepareGameCommand(commandList)); + QString oldPT; + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (!card->getPT().isEmpty()) + oldPT = card->getPT(); + } + bool ok; + dialogSemaphore = true; + QString pt = QInputDialog::getText(0, tr("Set power/toughness"), tr("Please enter the new PT:"), QLineEdit::Normal, oldPT, &ok); + dialogSemaphore = false; + if (clearCardsToDelete()) + return; + if (!ok) + return; + + QList< const ::google::protobuf::Message * > commandList; + QListIterator j(scene()->selectedItems()); + while (j.hasNext()) { + CardItem *card = static_cast(j.next()); + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrPT); + cmd->set_attr_value(pt.toStdString()); + commandList.append(cmd); + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actDrawArrow() { - game->getActiveCard()->drawArrow(Qt::red); + game->getActiveCard()->drawArrow(Qt::red); } void Player::actIncP() { - actIncPT(1, 0); + actIncPT(1, 0); } void Player::actDecP() { - actIncPT(-1, 0); + actIncPT(-1, 0); } void Player::actIncT() { - actIncPT(0, 1); + actIncPT(0, 1); } void Player::actDecT() { - actIncPT(0, -1); + actIncPT(0, -1); } void Player::actIncPT() { - actIncPT(1, 1); + actIncPT(1, 1); } void Player::actDecPT() { - actIncPT(-1, -1); + actIncPT(-1, -1); } void Player::actSetAnnotation() { - QString oldAnnotation; - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (!card->getAnnotation().isEmpty()) - oldAnnotation = card->getAnnotation(); - } - - bool ok; - dialogSemaphore = true; - QString annotation = QInputDialog::getText(0, tr("Set annotation"), tr("Please enter the new annotation:"), QLineEdit::Normal, oldAnnotation, &ok); - dialogSemaphore = false; - if (clearCardsToDelete()) - return; - if (!ok) - return; - - QList< const ::google::protobuf::Message * > commandList; - i.toFront(); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrAnnotation); - cmd->set_attr_value(annotation.toStdString()); - commandList.append(cmd); - } - sendGameCommand(prepareGameCommand(commandList)); + QString oldAnnotation; + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (!card->getAnnotation().isEmpty()) + oldAnnotation = card->getAnnotation(); + } + + bool ok; + dialogSemaphore = true; + QString annotation = QInputDialog::getText(0, tr("Set annotation"), tr("Please enter the new annotation:"), QLineEdit::Normal, oldAnnotation, &ok); + dialogSemaphore = false; + if (clearCardsToDelete()) + return; + if (!ok) + return; + + QList< const ::google::protobuf::Message * > commandList; + i.toFront(); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrAnnotation); + cmd->set_attr_value(annotation.toStdString()); + commandList.append(cmd); + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actAttach() { - ArrowAttachItem *arrow = new ArrowAttachItem(game->getActiveCard()); - scene()->addItem(arrow); - arrow->grabMouse(); + ArrowAttachItem *arrow = new ArrowAttachItem(game->getActiveCard()); + scene()->addItem(arrow); + arrow->grabMouse(); } void Player::actUnattach() { - Command_AttachCard cmd; - cmd.set_start_zone(game->getActiveCard()->getZone()->getName().toStdString()); - cmd.set_card_id(game->getActiveCard()->getId()); - sendGameCommand(cmd); + Command_AttachCard cmd; + cmd.set_start_zone(game->getActiveCard()->getZone()->getName().toStdString()); + cmd.set_card_id(game->getActiveCard()->getId()); + sendGameCommand(cmd); } void Player::actCardCounterTrigger() { - QAction *a = static_cast(sender()); - int counterId = a->data().toInt() / 1000; - int action = a->data().toInt() % 1000; - QList< const ::google::protobuf::Message * > commandList; - switch (action) { - case 9: { - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (card->getCounters().value(counterId, 0) < MAX_COUNTERS_ON_CARD) { - Command_SetCardCounter *cmd = new Command_SetCardCounter; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_counter_id(counterId); - cmd->set_counter_value(card->getCounters().value(counterId, 0) + 1); - commandList.append(cmd); - } - } - break; - } - case 10: { - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (card->getCounters().value(counterId, 0)) { - Command_SetCardCounter *cmd = new Command_SetCardCounter; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_counter_id(counterId); - cmd->set_counter_value(card->getCounters().value(counterId, 0) - 1); - commandList.append(cmd); - } - } - break; - } - case 11: { - bool ok; - dialogSemaphore = true; - int number = QInputDialog::getInteger(0, tr("Set counters"), tr("Number:"), 0, 0, MAX_COUNTERS_ON_CARD, 1, &ok); - dialogSemaphore = false; - if (clearCardsToDelete()) - return; - if (!ok) - return; - - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - Command_SetCardCounter *cmd = new Command_SetCardCounter; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_counter_id(counterId); - cmd->set_counter_value(number); - commandList.append(cmd); - } - break; - } - default: ; - } - sendGameCommand(prepareGameCommand(commandList)); + QAction *a = static_cast(sender()); + int counterId = a->data().toInt() / 1000; + int action = a->data().toInt() % 1000; + QList< const ::google::protobuf::Message * > commandList; + switch (action) { + case 9: { + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (card->getCounters().value(counterId, 0) < MAX_COUNTERS_ON_CARD) { + Command_SetCardCounter *cmd = new Command_SetCardCounter; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_counter_id(counterId); + cmd->set_counter_value(card->getCounters().value(counterId, 0) + 1); + commandList.append(cmd); + } + } + break; + } + case 10: { + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (card->getCounters().value(counterId, 0)) { + Command_SetCardCounter *cmd = new Command_SetCardCounter; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_counter_id(counterId); + cmd->set_counter_value(card->getCounters().value(counterId, 0) - 1); + commandList.append(cmd); + } + } + break; + } + case 11: { + bool ok; + dialogSemaphore = true; + int number = QInputDialog::getInteger(0, tr("Set counters"), tr("Number:"), 0, 0, MAX_COUNTERS_ON_CARD, 1, &ok); + dialogSemaphore = false; + if (clearCardsToDelete()) + return; + if (!ok) + return; + + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + Command_SetCardCounter *cmd = new Command_SetCardCounter; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_counter_id(counterId); + cmd->set_counter_value(number); + commandList.append(cmd); + } + break; + } + default: ; + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actPlay() { - playCard(game->getActiveCard(), false, game->getActiveCard()->getInfo()->getCipt()); + playCard(game->getActiveCard(), false, game->getActiveCard()->getInfo()->getCipt()); } void Player::actHide() { - game->getActiveCard()->getZone()->removeCard(game->getActiveCard()); + game->getActiveCard()->getZone()->removeCard(game->getActiveCard()); } void Player::updateCardMenu(CardItem *card) { - QMenu *cardMenu = card->getCardMenu(); - QMenu *ptMenu = card->getPTMenu(); - QMenu *moveMenu = card->getMoveMenu(); - - cardMenu->clear(); - - bool revealedCard = false; - bool writeableCard = getLocal(); - if (card->getZone()) - if (card->getZone()->getIsView()) { - ZoneViewZone *view = static_cast(card->getZone()); - if (view->getRevealZone()) { - if (view->getWriteableRevealZone()) - writeableCard = true; - else - revealedCard = true; - } - } - - if (revealedCard) - cardMenu->addAction(aHide); - else if (writeableCard) { - if (moveMenu->isEmpty()) { - moveMenu->addAction(aMoveToTopLibrary); - moveMenu->addAction(aMoveToBottomLibrary); - moveMenu->addAction(aMoveToGraveyard); - moveMenu->addAction(aMoveToExile); - } - - if (card->getZone()) { - if (card->getZone()->getName() == "table") { - if (ptMenu->isEmpty()) { - ptMenu->addAction(aIncP); - ptMenu->addAction(aDecP); - ptMenu->addSeparator(); - ptMenu->addAction(aIncT); - ptMenu->addAction(aDecT); - ptMenu->addSeparator(); - ptMenu->addAction(aIncPT); - ptMenu->addAction(aDecPT); - ptMenu->addSeparator(); - ptMenu->addAction(aSetPT); - } - - cardMenu->addAction(aTap); - cardMenu->addAction(aUntap); - cardMenu->addAction(aDoesntUntap); - cardMenu->addAction(aFlip); - if (card->getFaceDown()) - cardMenu->addAction(aPeek); - cardMenu->addSeparator(); - cardMenu->addAction(aAttach); - if (card->getAttachedTo()) - cardMenu->addAction(aUnattach); - cardMenu->addAction(aDrawArrow); - cardMenu->addSeparator(); - cardMenu->addMenu(ptMenu); - cardMenu->addAction(aSetAnnotation); - cardMenu->addSeparator(); - cardMenu->addAction(aClone); - cardMenu->addMenu(moveMenu); - - for (int i = 0; i < aAddCounter.size(); ++i) { - cardMenu->addSeparator(); - cardMenu->addAction(aAddCounter[i]); - cardMenu->addAction(aRemoveCounter[i]); - cardMenu->addAction(aSetCounter[i]); - } - cardMenu->addSeparator(); - } else if (card->getZone()->getName() == "stack") { - cardMenu->addAction(aDrawArrow); - cardMenu->addMenu(moveMenu); - } else { - cardMenu->addAction(aPlay); - cardMenu->addMenu(moveMenu); - } - } else - cardMenu->addMenu(moveMenu); - } + QMenu *cardMenu = card->getCardMenu(); + QMenu *ptMenu = card->getPTMenu(); + QMenu *moveMenu = card->getMoveMenu(); + + cardMenu->clear(); + + bool revealedCard = false; + bool writeableCard = getLocal(); + if (card->getZone()) + if (card->getZone()->getIsView()) { + ZoneViewZone *view = static_cast(card->getZone()); + if (view->getRevealZone()) { + if (view->getWriteableRevealZone()) + writeableCard = true; + else + revealedCard = true; + } + } + + if (revealedCard) + cardMenu->addAction(aHide); + else if (writeableCard) { + if (moveMenu->isEmpty()) { + moveMenu->addAction(aMoveToTopLibrary); + moveMenu->addAction(aMoveToBottomLibrary); + moveMenu->addAction(aMoveToGraveyard); + moveMenu->addAction(aMoveToExile); + } + + if (card->getZone()) { + if (card->getZone()->getName() == "table") { + if (ptMenu->isEmpty()) { + ptMenu->addAction(aIncP); + ptMenu->addAction(aDecP); + ptMenu->addSeparator(); + ptMenu->addAction(aIncT); + ptMenu->addAction(aDecT); + ptMenu->addSeparator(); + ptMenu->addAction(aIncPT); + ptMenu->addAction(aDecPT); + ptMenu->addSeparator(); + ptMenu->addAction(aSetPT); + } + + cardMenu->addAction(aTap); + cardMenu->addAction(aUntap); + cardMenu->addAction(aDoesntUntap); + cardMenu->addAction(aFlip); + if (card->getFaceDown()) + cardMenu->addAction(aPeek); + cardMenu->addSeparator(); + cardMenu->addAction(aAttach); + if (card->getAttachedTo()) + cardMenu->addAction(aUnattach); + cardMenu->addAction(aDrawArrow); + cardMenu->addSeparator(); + cardMenu->addMenu(ptMenu); + cardMenu->addAction(aSetAnnotation); + cardMenu->addSeparator(); + cardMenu->addAction(aClone); + cardMenu->addMenu(moveMenu); + + for (int i = 0; i < aAddCounter.size(); ++i) { + cardMenu->addSeparator(); + cardMenu->addAction(aAddCounter[i]); + cardMenu->addAction(aRemoveCounter[i]); + cardMenu->addAction(aSetCounter[i]); + } + cardMenu->addSeparator(); + } else if (card->getZone()->getName() == "stack") { + cardMenu->addAction(aDrawArrow); + cardMenu->addMenu(moveMenu); + } else { + cardMenu->addAction(aPlay); + cardMenu->addMenu(moveMenu); + } + } else + cardMenu->addMenu(moveMenu); + } } void Player::setCardMenu(QMenu *menu) { - if (aCardMenu) - aCardMenu->setMenu(menu); + if (aCardMenu) + aCardMenu->setMenu(menu); } QMenu *Player::getCardMenu() const { - if (aCardMenu) - return aCardMenu->menu(); - return 0; + if (aCardMenu) + return aCardMenu->menu(); + return 0; } QString Player::getName() const { - return QString::fromStdString(userInfo->name()); + return QString::fromStdString(userInfo->name()); } qreal Player::getMinimumWidth() const { - qreal result = table->getMinimumWidth() + CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); - if (!settingsCache->getHorizontalHand()) - result += hand->boundingRect().width(); - return result; + qreal result = table->getMinimumWidth() + CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); + if (!settingsCache->getHorizontalHand()) + result += hand->boundingRect().width(); + return result; } void Player::setConceded(bool _conceded) { - conceded = _conceded; - setVisible(!conceded); - if (conceded) { - clear(); - emit gameConceded(); - } + conceded = _conceded; + setVisible(!conceded); + if (conceded) { + clear(); + emit gameConceded(); + } } void Player::setMirrored(bool _mirrored) { - if (mirrored != _mirrored) { - mirrored = _mirrored; - rearrangeZones(); - } + if (mirrored != _mirrored) { + mirrored = _mirrored; + rearrangeZones(); + } } void Player::processSceneSizeChange(int newPlayerWidth) { - qreal tableWidth = newPlayerWidth - CARD_HEIGHT - 15 - counterAreaWidth - stack->boundingRect().width(); - if (!settingsCache->getHorizontalHand()) - tableWidth -= hand->boundingRect().width(); - - table->setWidth(tableWidth); - hand->setWidth(tableWidth + stack->boundingRect().width()); + qreal tableWidth = newPlayerWidth - CARD_HEIGHT - 15 - counterAreaWidth - stack->boundingRect().width(); + if (!settingsCache->getHorizontalHand()) + tableWidth -= hand->boundingRect().width(); + + table->setWidth(tableWidth); + hand->setWidth(tableWidth + stack->boundingRect().width()); } From 1bc48a78491d8a666d1a833930dc3ab4a5741fb2 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Tue, 11 Feb 2014 11:14:19 -0500 Subject: [PATCH 08/10] Convert rest of source to 4-space indent --- cockatrice/src/abstractcarddragitem.cpp | 50 +- cockatrice/src/abstractcarddragitem.h | 30 +- cockatrice/src/abstractcarditem.cpp | 326 ++-- cockatrice/src/abstractcarditem.h | 94 +- cockatrice/src/abstractclient.h | 104 +- cockatrice/src/abstractcounter.cpp | 176 +- cockatrice/src/abstractcounter.h | 62 +- cockatrice/src/abstractgraphicsitem.cpp | 80 +- cockatrice/src/abstractgraphicsitem.h | 18 +- cockatrice/src/arrowitem.cpp | 412 ++-- cockatrice/src/arrowitem.h | 68 +- cockatrice/src/arrowtarget.cpp | 22 +- cockatrice/src/arrowtarget.h | 38 +- cockatrice/src/carddatabase.cpp | 1116 +++++------ cockatrice/src/carddatabase.h | 298 +-- cockatrice/src/carddatabasemodel.cpp | 204 +- cockatrice/src/carddatabasemodel.h | 60 +- cockatrice/src/carddragitem.cpp | 124 +- cockatrice/src/carddragitem.h | 22 +- cockatrice/src/cardinfowidget.cpp | 294 +-- cockatrice/src/cardinfowidget.h | 60 +- cockatrice/src/carditem.cpp | 542 +++--- cockatrice/src/carditem.h | 126 +- cockatrice/src/cardlist.cpp | 78 +- cockatrice/src/cardlist.h | 14 +- cockatrice/src/cardzone.h | 92 +- cockatrice/src/chatview.cpp | 396 ++-- cockatrice/src/chatview.h | 56 +- cockatrice/src/counter_general.cpp | 40 +- cockatrice/src/counter_general.h | 12 +- cockatrice/src/deck_loader.cpp | 120 +- cockatrice/src/deck_loader.h | 40 +- cockatrice/src/decklistmodel.cpp | 562 +++--- cockatrice/src/decklistmodel.h | 80 +- cockatrice/src/deckstats_interface.cpp | 66 +- cockatrice/src/deckstats_interface.h | 10 +- cockatrice/src/deckview.cpp | 674 +++---- cockatrice/src/deckview.h | 134 +- cockatrice/src/dlg_cardsearch.cpp | 130 +- cockatrice/src/dlg_cardsearch.h | 16 +- cockatrice/src/dlg_connect.cpp | 100 +- cockatrice/src/dlg_connect.h | 20 +- cockatrice/src/dlg_create_token.cpp | 228 +-- cockatrice/src/dlg_create_token.h | 38 +- cockatrice/src/dlg_creategame.cpp | 298 +-- cockatrice/src/dlg_creategame.h | 36 +- cockatrice/src/dlg_edit_tokens.cpp | 260 +-- cockatrice/src/dlg_edit_tokens.h | 34 +- cockatrice/src/dlg_filter_games.cpp | 210 +- cockatrice/src/dlg_filter_games.h | 46 +- .../src/dlg_load_deck_from_clipboard.cpp | 64 +- cockatrice/src/dlg_load_deck_from_clipboard.h | 16 +- cockatrice/src/dlg_load_remote_deck.cpp | 34 +- cockatrice/src/dlg_load_remote_deck.h | 14 +- cockatrice/src/dlg_settings.cpp | 1070 +++++------ cockatrice/src/dlg_settings.h | 158 +- cockatrice/src/gamescene.cpp | 336 ++-- cockatrice/src/gamescene.h | 76 +- cockatrice/src/gameselector.cpp | 266 +-- cockatrice/src/gameselector.h | 34 +- cockatrice/src/gamesmodel.cpp | 252 +-- cockatrice/src/gamesmodel.h | 74 +- cockatrice/src/gameview.cpp | 56 +- cockatrice/src/gameview.h | 20 +- cockatrice/src/handcounter.cpp | 52 +- cockatrice/src/handcounter.h | 22 +- cockatrice/src/handzone.cpp | 198 +- cockatrice/src/handzone.h | 24 +- cockatrice/src/localclient.cpp | 24 +- cockatrice/src/localclient.h | 14 +- cockatrice/src/localserver.cpp | 24 +- cockatrice/src/localserver.h | 24 +- cockatrice/src/localserverinterface.cpp | 6 +- cockatrice/src/localserverinterface.h | 16 +- cockatrice/src/main.cpp | 188 +- cockatrice/src/messagelogwidget.cpp | 1318 ++++++------- cockatrice/src/messagelogwidget.h | 138 +- cockatrice/src/pending_command.h | 34 +- cockatrice/src/phasestoolbar.cpp | 304 +-- cockatrice/src/phasestoolbar.h | 84 +- cockatrice/src/pilezone.cpp | 126 +- cockatrice/src/pilezone.h | 24 +- cockatrice/src/pixmapgenerator.cpp | 234 +-- cockatrice/src/pixmapgenerator.h | 36 +- cockatrice/src/player.h | 440 ++--- cockatrice/src/playerlistwidget.cpp | 226 +-- cockatrice/src/playerlistwidget.h | 44 +- cockatrice/src/playertarget.cpp | 206 +- cockatrice/src/playertarget.h | 34 +- cockatrice/src/qt-json/json.cpp | 40 +- cockatrice/src/remoteclient.cpp | 310 +-- cockatrice/src/remoteclient.h | 68 +- cockatrice/src/remotedecklist_treewidget.cpp | 374 ++-- cockatrice/src/remotedecklist_treewidget.h | 150 +- .../src/remotereplaylist_treewidget.cpp | 388 ++-- cockatrice/src/remotereplaylist_treewidget.h | 134 +- cockatrice/src/replay_timeline_widget.cpp | 116 +- cockatrice/src/replay_timeline_widget.h | 42 +- cockatrice/src/selectzone.cpp | 68 +- cockatrice/src/selectzone.h | 12 +- cockatrice/src/setsmodel.cpp | 96 +- cockatrice/src/setsmodel.h | 36 +- cockatrice/src/settingscache.cpp | 224 +-- cockatrice/src/settingscache.h | 198 +- cockatrice/src/soundengine.cpp | 92 +- cockatrice/src/soundengine.h | 30 +- cockatrice/src/stackzone.cpp | 138 +- cockatrice/src/stackzone.h | 20 +- cockatrice/src/tab.cpp | 30 +- cockatrice/src/tab.h | 36 +- cockatrice/src/tab_admin.cpp | 164 +- cockatrice/src/tab_admin.h | 46 +- cockatrice/src/tab_deck_editor.cpp | 780 ++++---- cockatrice/src/tab_deck_editor.h | 128 +- cockatrice/src/tab_deck_storage.cpp | 514 ++--- cockatrice/src/tab_deck_storage.h | 60 +- cockatrice/src/tab_game.cpp | 1684 ++++++++--------- cockatrice/src/tab_game.h | 282 +-- cockatrice/src/tab_message.cpp | 98 +- cockatrice/src/tab_message.h | 46 +- cockatrice/src/tab_replays.cpp | 382 ++-- cockatrice/src/tab_replays.h | 60 +- cockatrice/src/tab_room.cpp | 246 +-- cockatrice/src/tab_room.h | 84 +- cockatrice/src/tab_server.cpp | 204 +- cockatrice/src/tab_server.h | 42 +- cockatrice/src/tab_supervisor.cpp | 630 +++--- cockatrice/src/tab_supervisor.h | 120 +- cockatrice/src/tab_userlists.cpp | 200 +- cockatrice/src/tab_userlists.h | 44 +- cockatrice/src/tablezone.cpp | 454 ++--- cockatrice/src/tablezone.h | 68 +- cockatrice/src/user_context_menu.cpp | 312 +-- cockatrice/src/user_context_menu.h | 40 +- cockatrice/src/userinfobox.cpp | 144 +- cockatrice/src/userinfobox.h | 18 +- cockatrice/src/userlist.cpp | 394 ++-- cockatrice/src/userlist.h | 98 +- cockatrice/src/window_main.cpp | 512 ++--- cockatrice/src/window_main.h | 78 +- cockatrice/src/window_sets.cpp | 36 +- cockatrice/src/window_sets.h | 10 +- cockatrice/src/zoneviewwidget.cpp | 276 +-- cockatrice/src/zoneviewwidget.h | 64 +- cockatrice/src/zoneviewzone.cpp | 216 +-- cockatrice/src/zoneviewzone.h | 58 +- 146 files changed, 12810 insertions(+), 12810 deletions(-) diff --git a/cockatrice/src/abstractcarddragitem.cpp b/cockatrice/src/abstractcarddragitem.cpp index ac640046..14724db3 100644 --- a/cockatrice/src/abstractcarddragitem.cpp +++ b/cockatrice/src/abstractcarddragitem.cpp @@ -5,47 +5,47 @@ #include AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag) - : QGraphicsItem(), item(_item), hotSpot(_hotSpot) + : QGraphicsItem(), item(_item), hotSpot(_hotSpot) { - if (parentDrag) { - parentDrag->addChildDrag(this); - setZValue(2000000007 + hotSpot.x() * 1000000 + hotSpot.y() * 1000 + 1000); - } else { - if ((hotSpot.x() < 0) || (hotSpot.y() < 0)) { - qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); - hotSpot = QPointF(); - } else if ((hotSpot.x() > CARD_WIDTH) || (hotSpot.y() > CARD_HEIGHT)) { - qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); - hotSpot = QPointF(CARD_WIDTH, CARD_HEIGHT); - } - setCursor(Qt::ClosedHandCursor); - setZValue(2000000007); - } - if (item->getTapped()) - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + if (parentDrag) { + parentDrag->addChildDrag(this); + setZValue(2000000007 + hotSpot.x() * 1000000 + hotSpot.y() * 1000 + 1000); + } else { + if ((hotSpot.x() < 0) || (hotSpot.y() < 0)) { + qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); + hotSpot = QPointF(); + } else if ((hotSpot.x() > CARD_WIDTH) || (hotSpot.y() > CARD_HEIGHT)) { + qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); + hotSpot = QPointF(CARD_WIDTH, CARD_HEIGHT); + } + setCursor(Qt::ClosedHandCursor); + setZValue(2000000007); + } + if (item->getTapped()) + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } AbstractCardDragItem::~AbstractCardDragItem() { - qDebug("CardDragItem destructor"); - for (int i = 0; i < childDrags.size(); i++) - delete childDrags[i]; + qDebug("CardDragItem destructor"); + for (int i = 0; i < childDrags.size(); i++) + delete childDrags[i]; } void AbstractCardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - item->paint(painter, option, widget); + item->paint(painter, option, widget); } void AbstractCardDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - event->accept(); - updatePosition(event->scenePos()); + event->accept(); + updatePosition(event->scenePos()); } void AbstractCardDragItem::addChildDrag(AbstractCardDragItem *child) { - childDrags << child; + childDrags << child; } diff --git a/cockatrice/src/abstractcarddragitem.h b/cockatrice/src/abstractcarddragitem.h index 047c4f55..e574f6c2 100644 --- a/cockatrice/src/abstractcarddragitem.h +++ b/cockatrice/src/abstractcarddragitem.h @@ -8,24 +8,24 @@ class CardZone; class CardInfo; class AbstractCardDragItem : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - AbstractCardItem *item; - QPointF hotSpot; - QList childDrags; + AbstractCardItem *item; + QPointF hotSpot; + QList childDrags; public: - enum { Type = typeCardDrag }; - int type() const { return Type; } - AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); - ~AbstractCardDragItem(); - QRectF boundingRect() const { return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - AbstractCardItem *getItem() const { return item; } - QPointF getHotSpot() const { return hotSpot; } - void addChildDrag(AbstractCardDragItem *child); - virtual void updatePosition(const QPointF &cursorScenePos) = 0; + enum { Type = typeCardDrag }; + int type() const { return Type; } + AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); + ~AbstractCardDragItem(); + QRectF boundingRect() const { return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + AbstractCardItem *getItem() const { return item; } + QPointF getHotSpot() const { return hotSpot; } + void addChildDrag(AbstractCardDragItem *child); + virtual void updatePosition(const QPointF &cursorScenePos) = 0; protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); }; #endif diff --git a/cockatrice/src/abstractcarditem.cpp b/cockatrice/src/abstractcarditem.cpp index 724a21fe..7b624572 100644 --- a/cockatrice/src/abstractcarditem.cpp +++ b/cockatrice/src/abstractcarditem.cpp @@ -12,245 +12,245 @@ #include AbstractCardItem::AbstractCardItem(const QString &_name, Player *_owner, int _id, QGraphicsItem *parent) - : ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0) + : ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0) { - setCursor(Qt::OpenHandCursor); - setFlag(ItemIsSelectable); - setCacheMode(DeviceCoordinateCache); - - connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated())); - connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate())); - cardInfoUpdated(); + setCursor(Qt::OpenHandCursor); + setFlag(ItemIsSelectable); + setCacheMode(DeviceCoordinateCache); + + connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated())); + connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate())); + cardInfoUpdated(); } AbstractCardItem::~AbstractCardItem() { - emit deleteCardInfoPopup(name); + emit deleteCardInfoPopup(name); } QRectF AbstractCardItem::boundingRect() const { - return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); + return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } void AbstractCardItem::pixmapUpdated() { - update(); - emit sigPixmapUpdated(); + update(); + emit sigPixmapUpdated(); } void AbstractCardItem::cardInfoUpdated() { - info = db->getCard(name); - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); + info = db->getCard(name); + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); } void AbstractCardItem::setRealZValue(qreal _zValue) { - realZValue = _zValue; - setZValue(_zValue); + realZValue = _zValue; + setZValue(_zValue); } QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const { - return QSizeF( - painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(), - painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length() - ); + return QSizeF( + painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(), + painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length() + ); } void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle) { - QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); - - painter->resetTransform(); - - QTransform pixmapTransform; - pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); - pixmapTransform.rotate(angle); - pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2); - painter->setTransform(pixmapTransform); + QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); + + painter->resetTransform(); + + QTransform pixmapTransform; + pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); + pixmapTransform.rotate(angle); + pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2); + painter->setTransform(pixmapTransform); - QFont f; - int fontSize = round(translatedSize.height() / 8); - if (fontSize < 9) - fontSize = 9; - if (fontSize > 10) - fontSize = 10; - f.setPixelSize(fontSize); + QFont f; + int fontSize = round(translatedSize.height() / 8); + if (fontSize < 9) + fontSize = 9; + if (fontSize > 10) + fontSize = 10; + f.setPixelSize(fontSize); - painter->setFont(f); + painter->setFont(f); } void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle) { - qreal scaleFactor = translatedSize.width() / boundingRect().width(); - - CardInfo *imageSource = facedown ? db->getCard() : info; - QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize()); - painter->save(); - QColor bgColor = Qt::transparent; - if (translatedPixmap) { - painter->save(); - transformPainter(painter, translatedSize, angle); - painter->drawPixmap(QPointF(0, 0), *translatedPixmap); - painter->restore(); - } else { - QString colorStr; - if (!color.isEmpty()) - colorStr = color; - else if (info->getColors().size() > 1) - colorStr = "m"; - else if (!info->getColors().isEmpty()) - colorStr = info->getColors().first().toLower(); - - if (colorStr == "b") - bgColor = QColor(0, 0, 0); - else if (colorStr == "u") - bgColor = QColor(0, 140, 180); - else if (colorStr == "w") - bgColor = QColor(255, 250, 140); - else if (colorStr == "r") - bgColor = QColor(230, 0, 0); - else if (colorStr == "g") - bgColor = QColor(0, 160, 0); - else if (colorStr == "m") - bgColor = QColor(250, 190, 30); - else - bgColor = QColor(230, 230, 230); - } - painter->setBrush(bgColor); - QPen pen(Qt::black); - pen.setWidth(2); - painter->setPen(pen); - painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2)); - - if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) { - painter->save(); - transformPainter(painter, translatedSize, angle); - painter->setPen(Qt::white); - painter->setBackground(Qt::black); - painter->setBackgroundMode(Qt::OpaqueMode); - QString nameStr; - if (facedown) - nameStr = "# " + QString::number(id); - else - nameStr = name; - painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr); - painter->restore(); - } - - painter->restore(); + qreal scaleFactor = translatedSize.width() / boundingRect().width(); + + CardInfo *imageSource = facedown ? db->getCard() : info; + QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize()); + painter->save(); + QColor bgColor = Qt::transparent; + if (translatedPixmap) { + painter->save(); + transformPainter(painter, translatedSize, angle); + painter->drawPixmap(QPointF(0, 0), *translatedPixmap); + painter->restore(); + } else { + QString colorStr; + if (!color.isEmpty()) + colorStr = color; + else if (info->getColors().size() > 1) + colorStr = "m"; + else if (!info->getColors().isEmpty()) + colorStr = info->getColors().first().toLower(); + + if (colorStr == "b") + bgColor = QColor(0, 0, 0); + else if (colorStr == "u") + bgColor = QColor(0, 140, 180); + else if (colorStr == "w") + bgColor = QColor(255, 250, 140); + else if (colorStr == "r") + bgColor = QColor(230, 0, 0); + else if (colorStr == "g") + bgColor = QColor(0, 160, 0); + else if (colorStr == "m") + bgColor = QColor(250, 190, 30); + else + bgColor = QColor(230, 230, 230); + } + painter->setBrush(bgColor); + QPen pen(Qt::black); + pen.setWidth(2); + painter->setPen(pen); + painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2)); + + if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) { + painter->save(); + transformPainter(painter, translatedSize, angle); + painter->setPen(Qt::white); + painter->setBackground(Qt::black); + painter->setBackgroundMode(Qt::OpaqueMode); + QString nameStr; + if (facedown) + nameStr = "# " + QString::number(id); + else + nameStr = name; + painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr); + painter->restore(); + } + + painter->restore(); } void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - painter->save(); + painter->save(); - QSizeF translatedSize = getTranslatedSize(painter); - paintPicture(painter, translatedSize, tapAngle); - - painter->save(); - painter->setRenderHint(QPainter::Antialiasing, false); - transformPainter(painter, translatedSize, tapAngle); - if (isSelected()) { - painter->setPen(Qt::red); - painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); - } else if (isHovered) { - painter->setPen(Qt::yellow); - painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); - } - painter->restore(); + QSizeF translatedSize = getTranslatedSize(painter); + paintPicture(painter, translatedSize, tapAngle); + + painter->save(); + painter->setRenderHint(QPainter::Antialiasing, false); + transformPainter(painter, translatedSize, tapAngle); + if (isSelected()) { + painter->setPen(Qt::red); + painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); + } else if (isHovered) { + painter->setPen(Qt::yellow); + painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); + } + painter->restore(); - painter->restore(); + painter->restore(); } void AbstractCardItem::setName(const QString &_name) { - if (name == _name) - return; - - emit deleteCardInfoPopup(name); - disconnect(info, 0, this, 0); - name = _name; - info = db->getCard(name); - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); - update(); + if (name == _name) + return; + + emit deleteCardInfoPopup(name); + disconnect(info, 0, this, 0); + name = _name; + info = db->getCard(name); + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); + update(); } void AbstractCardItem::setHovered(bool _hovered) { - if (isHovered == _hovered) - return; - - if (_hovered) - processHoverEvent(); - isHovered = _hovered; - setZValue(_hovered ? 2000000004 : realZValue); - update(); + if (isHovered == _hovered) + return; + + if (_hovered) + processHoverEvent(); + isHovered = _hovered; + setZValue(_hovered ? 2000000004 : realZValue); + update(); } void AbstractCardItem::setColor(const QString &_color) { - color = _color; - update(); + color = _color; + update(); } void AbstractCardItem::setTapped(bool _tapped, bool canAnimate) { - if (tapped == _tapped) - return; - - tapped = _tapped; - if (settingsCache->getTapAnimation() && canAnimate) - static_cast(scene())->registerAnimationItem(this); - else { - tapAngle = tapped ? 90 : 0; - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); - update(); - } + if (tapped == _tapped) + return; + + tapped = _tapped; + if (settingsCache->getTapAnimation() && canAnimate) + static_cast(scene())->registerAnimationItem(this); + else { + tapAngle = tapped ? 90 : 0; + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + update(); + } } void AbstractCardItem::setFaceDown(bool _facedown) { - facedown = _facedown; - update(); - emit updateCardMenu(this); + facedown = _facedown; + update(); + emit updateCardMenu(this); } void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (!isSelected()) { - scene()->clearSelection(); - setSelected(true); - } - if (event->button() == Qt::LeftButton) - setCursor(Qt::ClosedHandCursor); - else if (event->button() == Qt::MidButton) - emit showCardInfoPopup(event->screenPos(), name); - event->accept(); + if (!isSelected()) { + scene()->clearSelection(); + setSelected(true); + } + if (event->button() == Qt::LeftButton) + setCursor(Qt::ClosedHandCursor); + else if (event->button() == Qt::MidButton) + emit showCardInfoPopup(event->screenPos(), name); + event->accept(); } void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::MidButton) - emit deleteCardInfoPopup(name); - - // This function ensures the parent function doesn't mess around with our selection. - event->accept(); + if (event->button() == Qt::MidButton) + emit deleteCardInfoPopup(name); + + // This function ensures the parent function doesn't mess around with our selection. + event->accept(); } void AbstractCardItem::processHoverEvent() { - emit hovered(this); + emit hovered(this); } QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged) { - update(); - return value; - } else - return QGraphicsItem::itemChange(change, value); + if (change == ItemSelectedHasChanged) { + update(); + return value; + } else + return QGraphicsItem::itemChange(change, value); } diff --git a/cockatrice/src/abstractcarditem.h b/cockatrice/src/abstractcarditem.h index 9a11fad1..7f68ddcd 100644 --- a/cockatrice/src/abstractcarditem.h +++ b/cockatrice/src/abstractcarditem.h @@ -12,59 +12,59 @@ const int CARD_WIDTH = 72; const int CARD_HEIGHT = 102; class AbstractCardItem : public ArrowTarget { - Q_OBJECT + Q_OBJECT protected: - CardInfo *info; - CardInfoWidget *infoWidget; - int id; - QString name; - bool tapped; - bool facedown; - int tapAngle; - QString color; + CardInfo *info; + CardInfoWidget *infoWidget; + int id; + QString name; + bool tapped; + bool facedown; + int tapAngle; + QString color; private: - bool isHovered; - qreal realZValue; + bool isHovered; + qreal realZValue; private slots: - void pixmapUpdated(); - void cardInfoUpdated(); - void callUpdate() { update(); } + void pixmapUpdated(); + void cardInfoUpdated(); + void callUpdate() { update(); } signals: - void hovered(AbstractCardItem *card); - void showCardInfoPopup(QPoint pos, QString cardName); - void deleteCardInfoPopup(QString cardName); - void updateCardMenu(AbstractCardItem *card); - void sigPixmapUpdated(); + void hovered(AbstractCardItem *card); + void showCardInfoPopup(QPoint pos, QString cardName); + void deleteCardInfoPopup(QString cardName); + void updateCardMenu(AbstractCardItem *card); + void sigPixmapUpdated(); public: - enum { Type = typeCard }; - int type() const { return Type; } - AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0); - ~AbstractCardItem(); - QRectF boundingRect() const; - QSizeF getTranslatedSize(QPainter *painter) const; - void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - CardInfo *getInfo() const { return info; } - int getId() const { return id; } - void setId(int _id) { id = _id; } - QString getName() const { return name; } - void setName(const QString &_name = QString()); - qreal getRealZValue() const { return realZValue; } - void setRealZValue(qreal _zValue); - void setHovered(bool _hovered); - QString getColor() const { return color; } - void setColor(const QString &_color); - bool getTapped() const { return tapped; } - void setTapped(bool _tapped, bool canAnimate = false); - bool getFaceDown() const { return facedown; } - void setFaceDown(bool _facedown); - void processHoverEvent(); - void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); } + enum { Type = typeCard }; + int type() const { return Type; } + AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0); + ~AbstractCardItem(); + QRectF boundingRect() const; + QSizeF getTranslatedSize(QPainter *painter) const; + void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + CardInfo *getInfo() const { return info; } + int getId() const { return id; } + void setId(int _id) { id = _id; } + QString getName() const { return name; } + void setName(const QString &_name = QString()); + qreal getRealZValue() const { return realZValue; } + void setRealZValue(qreal _zValue); + void setHovered(bool _hovered); + QString getColor() const { return color; } + void setColor(const QString &_color); + bool getTapped() const { return tapped; } + void setTapped(bool _tapped, bool canAnimate = false); + bool getFaceDown() const { return facedown; } + void setFaceDown(bool _facedown); + void processHoverEvent(); + void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); } protected: - void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); + void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); }; #endif diff --git a/cockatrice/src/abstractclient.h b/cockatrice/src/abstractclient.h index 507c3fdd..130c85b5 100644 --- a/cockatrice/src/abstractclient.h +++ b/cockatrice/src/abstractclient.h @@ -26,67 +26,67 @@ class Event_ServerShutdown; class Event_ReplayAdded; enum ClientStatus { - StatusDisconnected, - StatusDisconnecting, - StatusConnecting, - StatusAwaitingWelcome, - StatusLoggingIn, - StatusLoggedIn, + StatusDisconnected, + StatusDisconnecting, + StatusConnecting, + StatusAwaitingWelcome, + StatusLoggingIn, + StatusLoggedIn, }; class AbstractClient : public QObject { - Q_OBJECT + Q_OBJECT signals: - void statusChanged(ClientStatus _status); - - // Room events - void roomEventReceived(const RoomEvent &event); - // Game events - void gameEventContainerReceived(const GameEventContainer &event); - // Session events - void serverIdentificationEventReceived(const Event_ServerIdentification &event); - void connectionClosedEventReceived(const Event_ConnectionClosed &event); - void serverShutdownEventReceived(const Event_ServerShutdown &event); - void addToListEventReceived(const Event_AddToList &event); - void removeFromListEventReceived(const Event_RemoveFromList &event); - void userJoinedEventReceived(const Event_UserJoined &event); - void userLeftEventReceived(const Event_UserLeft &event); - void serverMessageEventReceived(const Event_ServerMessage &event); - void listRoomsEventReceived(const Event_ListRooms &event); - void gameJoinedEventReceived(const Event_GameJoined &event); - void userMessageEventReceived(const Event_UserMessage &event); - void userInfoChanged(const ServerInfo_User &userInfo); - void buddyListReceived(const QList &buddyList); - void ignoreListReceived(const QList &ignoreList); - void replayAddedEventReceived(const Event_ReplayAdded &event); - - void sigQueuePendingCommand(PendingCommand *pend); + void statusChanged(ClientStatus _status); + + // Room events + void roomEventReceived(const RoomEvent &event); + // Game events + void gameEventContainerReceived(const GameEventContainer &event); + // Session events + void serverIdentificationEventReceived(const Event_ServerIdentification &event); + void connectionClosedEventReceived(const Event_ConnectionClosed &event); + void serverShutdownEventReceived(const Event_ServerShutdown &event); + void addToListEventReceived(const Event_AddToList &event); + void removeFromListEventReceived(const Event_RemoveFromList &event); + void userJoinedEventReceived(const Event_UserJoined &event); + void userLeftEventReceived(const Event_UserLeft &event); + void serverMessageEventReceived(const Event_ServerMessage &event); + void listRoomsEventReceived(const Event_ListRooms &event); + void gameJoinedEventReceived(const Event_GameJoined &event); + void userMessageEventReceived(const Event_UserMessage &event); + void userInfoChanged(const ServerInfo_User &userInfo); + void buddyListReceived(const QList &buddyList); + void ignoreListReceived(const QList &ignoreList); + void replayAddedEventReceived(const Event_ReplayAdded &event); + + void sigQueuePendingCommand(PendingCommand *pend); private: - int nextCmdId; - mutable QMutex clientMutex; - ClientStatus status; + int nextCmdId; + mutable QMutex clientMutex; + ClientStatus status; private slots: - void queuePendingCommand(PendingCommand *pend); + void queuePendingCommand(PendingCommand *pend); protected slots: - void processProtocolItem(const ServerMessage &item); + void processProtocolItem(const ServerMessage &item); protected: - QMap pendingCommands; - QString userName, password; - void setStatus(ClientStatus _status); - int getNewCmdId() { return nextCmdId++; } - virtual void sendCommandContainer(const CommandContainer &cont) = 0; + QMap pendingCommands; + QString userName, password; + void setStatus(ClientStatus _status); + int getNewCmdId() { return nextCmdId++; } + virtual void sendCommandContainer(const CommandContainer &cont) = 0; public: - AbstractClient(QObject *parent = 0); - ~AbstractClient(); - - ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; } - void sendCommand(const CommandContainer &cont); - void sendCommand(PendingCommand *pend); - - static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd); - static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId); - static PendingCommand *prepareModeratorCommand(const ::google::protobuf::Message &cmd); - static PendingCommand *prepareAdminCommand(const ::google::protobuf::Message &cmd); + AbstractClient(QObject *parent = 0); + ~AbstractClient(); + + ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; } + void sendCommand(const CommandContainer &cont); + void sendCommand(PendingCommand *pend); + + static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd); + static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId); + static PendingCommand *prepareModeratorCommand(const ::google::protobuf::Message &cmd); + static PendingCommand *prepareAdminCommand(const ::google::protobuf::Message &cmd); }; #endif diff --git a/cockatrice/src/abstractcounter.cpp b/cockatrice/src/abstractcounter.cpp index 42e506fd..73fc9466 100644 --- a/cockatrice/src/abstractcounter.cpp +++ b/cockatrice/src/abstractcounter.cpp @@ -9,137 +9,137 @@ #include "pb/command_set_counter.pb.h" AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent) - : QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) + : QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) { - setAcceptsHoverEvents(true); - - if (player->getLocal()) { - menu = new QMenu(name); - aSet = new QAction(this); - connect(aSet, SIGNAL(triggered()), this, SLOT(setCounter())); - menu->addAction(aSet); - menu->addSeparator(); - for (int i = -10; i <= 10; ++i) - if (i == 0) - menu->addSeparator(); - else { - QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this); - if (i == -1) - aDec = aIncrement; - else if (i == 1) - aInc = aIncrement; - aIncrement->setData(i); - connect(aIncrement, SIGNAL(triggered()), this, SLOT(incrementCounter())); - menu->addAction(aIncrement); - } - } else - menu = 0; - - retranslateUi(); + setAcceptsHoverEvents(true); + + if (player->getLocal()) { + menu = new QMenu(name); + aSet = new QAction(this); + connect(aSet, SIGNAL(triggered()), this, SLOT(setCounter())); + menu->addAction(aSet); + menu->addSeparator(); + for (int i = -10; i <= 10; ++i) + if (i == 0) + menu->addSeparator(); + else { + QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this); + if (i == -1) + aDec = aIncrement; + else if (i == 1) + aInc = aIncrement; + aIncrement->setData(i); + connect(aIncrement, SIGNAL(triggered()), this, SLOT(incrementCounter())); + menu->addAction(aIncrement); + } + } else + menu = 0; + + retranslateUi(); } AbstractCounter::~AbstractCounter() { - delete menu; + delete menu; } void AbstractCounter::delCounter() { - if (dialogSemaphore) - deleteAfterDialog = true; - else - deleteLater(); + if (dialogSemaphore) + deleteAfterDialog = true; + else + deleteLater(); } void AbstractCounter::retranslateUi() { - if (menu) { - aSet->setText(tr("&Set counter...")); - } + if (menu) { + aSet->setText(tr("&Set counter...")); + } } void AbstractCounter::setShortcutsActive() { - if (name == "life") { - aSet->setShortcut(tr("Ctrl+L")); - aDec->setShortcut(tr("F11")); - aInc->setShortcut(tr("F12")); - } + if (name == "life") { + aSet->setShortcut(tr("Ctrl+L")); + aDec->setShortcut(tr("F11")); + aInc->setShortcut(tr("F12")); + } } void AbstractCounter::setShortcutsInactive() { - if (name == "life") { - aSet->setShortcut(QKeySequence()); - aDec->setShortcut(QKeySequence()); - aInc->setShortcut(QKeySequence()); - } + if (name == "life") { + aSet->setShortcut(QKeySequence()); + aDec->setShortcut(QKeySequence()); + aInc->setShortcut(QKeySequence()); + } } void AbstractCounter::setValue(int _value) { - value = _value; - update(); + value = _value; + update(); } void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - Command_IncCounter cmd; - cmd.set_counter_id(id); - cmd.set_delta(1); - player->sendGameCommand(cmd); - event->accept(); - } else if (event->button() == Qt::RightButton) { - Command_IncCounter cmd; - cmd.set_counter_id(id); - cmd.set_delta(-1); - player->sendGameCommand(cmd); - event->accept(); - } else if (event->button() == Qt::MidButton) { - if (menu) - menu->exec(event->screenPos()); - event->accept(); - } else - event->ignore(); + if (event->button() == Qt::LeftButton) { + Command_IncCounter cmd; + cmd.set_counter_id(id); + cmd.set_delta(1); + player->sendGameCommand(cmd); + event->accept(); + } else if (event->button() == Qt::RightButton) { + Command_IncCounter cmd; + cmd.set_counter_id(id); + cmd.set_delta(-1); + player->sendGameCommand(cmd); + event->accept(); + } else if (event->button() == Qt::MidButton) { + if (menu) + menu->exec(event->screenPos()); + event->accept(); + } else + event->ignore(); } void AbstractCounter::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/) { - hovered = true; - update(); + hovered = true; + update(); } void AbstractCounter::hoverLeaveEvent(QGraphicsSceneHoverEvent * /*event*/) { - hovered = false; - update(); + hovered = false; + update(); } void AbstractCounter::incrementCounter() { - const int delta = static_cast(sender())->data().toInt(); - Command_IncCounter cmd; - cmd.set_counter_id(id); - cmd.set_delta(delta); - player->sendGameCommand(cmd); + const int delta = static_cast(sender())->data().toInt(); + Command_IncCounter cmd; + cmd.set_counter_id(id); + cmd.set_delta(delta); + player->sendGameCommand(cmd); } void AbstractCounter::setCounter() { - bool ok; - dialogSemaphore = true; - int newValue = QInputDialog::getInteger(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok); - if (deleteAfterDialog) { - deleteLater(); - return; - } - dialogSemaphore = false; - if (!ok) - return; - - Command_SetCounter cmd; - cmd.set_counter_id(id); - cmd.set_value(newValue); - player->sendGameCommand(cmd); + bool ok; + dialogSemaphore = true; + int newValue = QInputDialog::getInteger(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok); + if (deleteAfterDialog) { + deleteLater(); + return; + } + dialogSemaphore = false; + if (!ok) + return; + + Command_SetCounter cmd; + cmd.set_counter_id(id); + cmd.set_value(newValue); + player->sendGameCommand(cmd); } diff --git a/cockatrice/src/abstractcounter.h b/cockatrice/src/abstractcounter.h index 6a4a4188..713c11c5 100644 --- a/cockatrice/src/abstractcounter.h +++ b/cockatrice/src/abstractcounter.h @@ -8,41 +8,41 @@ class QMenu; class QAction; class AbstractCounter : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - Player *player; - int id; - QString name; - int value; - bool hovered; - - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); + Player *player; + int id; + QString name; + int value; + bool hovered; + + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); private: - QAction *aSet, *aDec, *aInc; - QMenu *menu; - bool dialogSemaphore, deleteAfterDialog; - bool shownInCounterArea; + QAction *aSet, *aDec, *aInc; + QMenu *menu; + bool dialogSemaphore, deleteAfterDialog; + bool shownInCounterArea; private slots: - void incrementCounter(); - void setCounter(); + void incrementCounter(); + void setCounter(); public: - AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent = 0); - ~AbstractCounter(); - - QMenu *getMenu() const { return menu; } - void retranslateUi(); - - int getId() const { return id; } - QString getName() const { return name; } - bool getShownInCounterArea() const { return shownInCounterArea; } - int getValue() const { return value; } - void setValue(int _value); - void delCounter(); - - void setShortcutsActive(); - void setShortcutsInactive(); + AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent = 0); + ~AbstractCounter(); + + QMenu *getMenu() const { return menu; } + void retranslateUi(); + + int getId() const { return id; } + QString getName() const { return name; } + bool getShownInCounterArea() const { return shownInCounterArea; } + int getValue() const { return value; } + void setValue(int _value); + void delCounter(); + + void setShortcutsActive(); + void setShortcutsInactive(); }; #endif diff --git a/cockatrice/src/abstractgraphicsitem.cpp b/cockatrice/src/abstractgraphicsitem.cpp index 47b21bbc..c0cc330c 100644 --- a/cockatrice/src/abstractgraphicsitem.cpp +++ b/cockatrice/src/abstractgraphicsitem.cpp @@ -3,48 +3,48 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QColor &color, int position, int count, QPainter *painter) { - painter->save(); + painter->save(); - QString numStr = QString::number(number); - QFont font("Serif"); - font.setPixelSize(fontSize); - font.setWeight(QFont::Bold); - - QFontMetrics fm(font); - double w = fm.width(numStr) * 1.3; - double h = fm.height() * 1.3; - if (w < h) - w = h; + QString numStr = QString::number(number); + QFont font("Serif"); + font.setPixelSize(fontSize); + font.setWeight(QFont::Bold); + + QFontMetrics fm(font); + double w = fm.width(numStr) * 1.3; + double h = fm.height() * 1.3; + if (w < h) + w = h; - painter->setPen(QColor(255, 255, 255, 0)); - QRadialGradient grad(QPointF(0.5, 0.5), 0.5); - grad.setCoordinateMode(QGradient::ObjectBoundingMode); - QColor color1(color), color2(color); - color1.setAlpha(255); - color2.setAlpha(0); - grad.setColorAt(0, color1); - grad.setColorAt(0.8, color1); - grad.setColorAt(1, color2); - painter->setBrush(QBrush(grad)); - - QRectF textRect; - if (position == -1) - textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); - else { - qreal xOffset = 10; - qreal yOffset = 20; - qreal spacing = 2; - if (position < 2) - textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h); - else - textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h); - } - - painter->drawEllipse(textRect); + painter->setPen(QColor(255, 255, 255, 0)); + QRadialGradient grad(QPointF(0.5, 0.5), 0.5); + grad.setCoordinateMode(QGradient::ObjectBoundingMode); + QColor color1(color), color2(color); + color1.setAlpha(255); + color2.setAlpha(0); + grad.setColorAt(0, color1); + grad.setColorAt(0.8, color1); + grad.setColorAt(1, color2); + painter->setBrush(QBrush(grad)); + + QRectF textRect; + if (position == -1) + textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); + else { + qreal xOffset = 10; + qreal yOffset = 20; + qreal spacing = 2; + if (position < 2) + textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h); + else + textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h); + } + + painter->drawEllipse(textRect); - painter->setPen(Qt::black); - painter->setFont(font); - painter->drawText(textRect, Qt::AlignCenter, numStr); + painter->setPen(Qt::black); + painter->setFont(font); + painter->drawText(textRect, Qt::AlignCenter, numStr); - painter->restore(); + painter->restore(); } diff --git a/cockatrice/src/abstractgraphicsitem.h b/cockatrice/src/abstractgraphicsitem.h index 2bb094d3..83cbf0db 100644 --- a/cockatrice/src/abstractgraphicsitem.h +++ b/cockatrice/src/abstractgraphicsitem.h @@ -4,20 +4,20 @@ #include enum GraphicsItemType { - typeCard = QGraphicsItem::UserType + 1, - typeCardDrag = QGraphicsItem::UserType + 2, - typeZone = QGraphicsItem::UserType + 3, - typePlayerTarget = QGraphicsItem::UserType + 4, - typeDeckViewCardContainer = QGraphicsItem::UserType + 5, - typeOther = QGraphicsItem::UserType + 6 + typeCard = QGraphicsItem::UserType + 1, + typeCardDrag = QGraphicsItem::UserType + 2, + typeZone = QGraphicsItem::UserType + 3, + typePlayerTarget = QGraphicsItem::UserType + 4, + typeDeckViewCardContainer = QGraphicsItem::UserType + 5, + typeOther = QGraphicsItem::UserType + 6 }; class AbstractGraphicsItem : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter); + void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter); public: - AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { } + AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { } }; #endif diff --git a/cockatrice/src/arrowitem.cpp b/cockatrice/src/arrowitem.cpp index 037645d5..a27b451a 100644 --- a/cockatrice/src/arrowitem.cpp +++ b/cockatrice/src/arrowitem.cpp @@ -17,127 +17,127 @@ ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &_color) : QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color), fullColor(true) { - qDebug() << "ArrowItem constructor: startItem=" << static_cast(startItem); - setZValue(2000000005); - - if (startItem) - startItem->addArrowFrom(this); - if (targetItem) - targetItem->addArrowTo(this); - - if (startItem && targetItem) - updatePath(); + qDebug() << "ArrowItem constructor: startItem=" << static_cast(startItem); + setZValue(2000000005); + + if (startItem) + startItem->addArrowFrom(this); + if (targetItem) + targetItem->addArrowTo(this); + + if (startItem && targetItem) + updatePath(); } ArrowItem::~ArrowItem() { - qDebug() << "ArrowItem destructor"; + qDebug() << "ArrowItem destructor"; } void ArrowItem::delArrow() { - if (startItem) { - startItem->removeArrowFrom(this); - startItem = 0; - } - - if (targetItem) { - targetItem->setBeingPointedAt(false); - targetItem->removeArrowTo(this); - targetItem = 0; - } - - player->removeArrow(this); - deleteLater(); + if (startItem) { + startItem->removeArrowFrom(this); + startItem = 0; + } + + if (targetItem) { + targetItem->setBeingPointedAt(false); + targetItem->removeArrowTo(this); + targetItem = 0; + } + + player->removeArrow(this); + deleteLater(); } void ArrowItem::updatePath() { - if (!targetItem) - return; - - QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); - updatePath(endPoint); + if (!targetItem) + return; + + QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); + updatePath(endPoint); } void ArrowItem::updatePath(const QPointF &endPoint) { - const double arrowWidth = 15.0; - const double headWidth = 40.0; - const double headLength = headWidth / sqrt(2); - const double phi = 15; - - if (!startItem) - return; - - QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); - QLineF line(startPoint, endPoint); - qreal lineLength = line.length(); - - prepareGeometryChange(); - if (lineLength < 30) - path = QPainterPath(); - else { - QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength); - - QPainterPath centerLine; - centerLine.moveTo(0, 0); - centerLine.quadTo(c, QPointF(lineLength, 0)); - - double percentage = 1 - headLength / lineLength; - QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage); - QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001)); - qreal alpha = testLine.angle() - 90; - QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); - QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); - QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); - QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); - - path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); - path.quadTo(c, endPoint1); - path.lineTo(point1); - path.lineTo(QPointF(lineLength, 0)); - path.lineTo(point2); - path.lineTo(endPoint2); - path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); - path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); - } - - setPos(startPoint); - setTransform(QTransform().rotate(-line.angle())); + const double arrowWidth = 15.0; + const double headWidth = 40.0; + const double headLength = headWidth / sqrt(2); + const double phi = 15; + + if (!startItem) + return; + + QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); + QLineF line(startPoint, endPoint); + qreal lineLength = line.length(); + + prepareGeometryChange(); + if (lineLength < 30) + path = QPainterPath(); + else { + QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength); + + QPainterPath centerLine; + centerLine.moveTo(0, 0); + centerLine.quadTo(c, QPointF(lineLength, 0)); + + double percentage = 1 - headLength / lineLength; + QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage); + QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001)); + qreal alpha = testLine.angle() - 90; + QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); + QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); + QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); + QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); + + path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); + path.quadTo(c, endPoint1); + path.lineTo(point1); + path.lineTo(QPointF(lineLength, 0)); + path.lineTo(point2); + path.lineTo(endPoint2); + path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); + path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); + } + + setPos(startPoint); + setTransform(QTransform().rotate(-line.angle())); } void ArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QColor paintColor(color); - if (fullColor) - paintColor.setAlpha(200); - else - paintColor.setAlpha(150); - painter->setBrush(paintColor); - painter->drawPath(path); + QColor paintColor(color); + if (fullColor) + paintColor.setAlpha(200); + else + paintColor.setAlpha(150); + painter->setBrush(paintColor); + painter->drawPath(path); } void ArrowItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (!player->getLocal()) { - event->ignore(); - return; - } - - QList colliding = scene()->items(event->scenePos()); - for (int i = 0; i < colliding.size(); ++i) - if (qgraphicsitem_cast(colliding[i])) { - event->ignore(); - return; - } - - event->accept(); - if (event->button() == Qt::RightButton) { - Command_DeleteArrow cmd; - cmd.set_arrow_id(id); - player->sendGameCommand(cmd); - } + if (!player->getLocal()) { + event->ignore(); + return; + } + + QList colliding = scene()->items(event->scenePos()); + for (int i = 0; i < colliding.size(); ++i) + if (qgraphicsitem_cast(colliding[i])) { + event->ignore(); + return; + } + + event->accept(); + if (event->button() == Qt::RightButton) { + Command_DeleteArrow cmd; + cmd.set_arrow_id(id); + player->sendGameCommand(cmd); + } } ArrowDragItem::ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color) @@ -147,85 +147,85 @@ ArrowDragItem::ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QCol void ArrowDragItem::addChildArrow(ArrowDragItem *childArrow) { - childArrows.append(childArrow); + childArrows.append(childArrow); } void ArrowDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - // This ensures that if a mouse move event happens after a call to delArrow(), - // the event will be discarded as it would create some stray pointers. - if (!startItem) - return; - - QPointF endPos = event->scenePos(); - - QList colliding = scene()->items(endPos); - ArrowTarget *cursorItem = 0; - qreal cursorItemZ = -1; - for (int i = colliding.size() - 1; i >= 0; i--) - if (qgraphicsitem_cast(colliding.at(i)) || qgraphicsitem_cast(colliding.at(i))) - if (colliding.at(i)->zValue() > cursorItemZ) { - cursorItem = static_cast(colliding.at(i)); - cursorItemZ = cursorItem->zValue(); - } - if ((cursorItem != targetItem) && targetItem) { - targetItem->setBeingPointedAt(false); - targetItem->removeArrowTo(this); - } + // This ensures that if a mouse move event happens after a call to delArrow(), + // the event will be discarded as it would create some stray pointers. + if (!startItem) + return; + + QPointF endPos = event->scenePos(); + + QList colliding = scene()->items(endPos); + ArrowTarget *cursorItem = 0; + qreal cursorItemZ = -1; + for (int i = colliding.size() - 1; i >= 0; i--) + if (qgraphicsitem_cast(colliding.at(i)) || qgraphicsitem_cast(colliding.at(i))) + if (colliding.at(i)->zValue() > cursorItemZ) { + cursorItem = static_cast(colliding.at(i)); + cursorItemZ = cursorItem->zValue(); + } + if ((cursorItem != targetItem) && targetItem) { + targetItem->setBeingPointedAt(false); + targetItem->removeArrowTo(this); + } if (!cursorItem) { - fullColor = false; - targetItem = 0; - updatePath(endPos); - } else { - if (cursorItem != targetItem) { - fullColor = true; - if (cursorItem != startItem) { - cursorItem->setBeingPointedAt(true); - cursorItem->addArrowTo(this); - } - targetItem = cursorItem; - } - updatePath(); - } - update(); - - for (int i = 0; i < childArrows.size(); ++i) - childArrows[i]->mouseMoveEvent(event); + fullColor = false; + targetItem = 0; + updatePath(endPos); + } else { + if (cursorItem != targetItem) { + fullColor = true; + if (cursorItem != startItem) { + cursorItem->setBeingPointedAt(true); + cursorItem->addArrowTo(this); + } + targetItem = cursorItem; + } + updatePath(); + } + update(); + + for (int i = 0; i < childArrows.size(); ++i) + childArrows[i]->mouseMoveEvent(event); } void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (!startItem) - return; - - if (targetItem && (targetItem != startItem)) { - CardZone *startZone = static_cast(startItem)->getZone(); - // For now, we can safely assume that the start item is always a card. - // The target item can be a player as well. - CardItem *startCard = qgraphicsitem_cast(startItem); - CardItem *targetCard = qgraphicsitem_cast(targetItem); + if (!startItem) + return; + + if (targetItem && (targetItem != startItem)) { + CardZone *startZone = static_cast(startItem)->getZone(); + // For now, we can safely assume that the start item is always a card. + // The target item can be a player as well. + CardItem *startCard = qgraphicsitem_cast(startItem); + CardItem *targetCard = qgraphicsitem_cast(targetItem); - Command_CreateArrow cmd; - cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color)); - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_start_card_id(startCard->getId()); + Command_CreateArrow cmd; + cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color)); + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_start_card_id(startCard->getId()); - if (targetCard) { - CardZone *targetZone = targetCard->getZone(); - cmd.set_target_player_id(targetZone->getPlayer()->getId()); - cmd.set_target_zone(targetZone->getName().toStdString()); - cmd.set_target_card_id(targetCard->getId()); - } else { - PlayerTarget *targetPlayer = qgraphicsitem_cast(targetItem); - cmd.set_target_player_id(targetPlayer->getOwner()->getId()); - } - player->sendGameCommand(cmd); - } - delArrow(); + if (targetCard) { + CardZone *targetZone = targetCard->getZone(); + cmd.set_target_player_id(targetZone->getPlayer()->getId()); + cmd.set_target_zone(targetZone->getName().toStdString()); + cmd.set_target_card_id(targetCard->getId()); + } else { + PlayerTarget *targetPlayer = qgraphicsitem_cast(targetItem); + cmd.set_target_player_id(targetPlayer->getOwner()->getId()); + } + player->sendGameCommand(cmd); + } + delArrow(); - for (int i = 0; i < childArrows.size(); ++i) - childArrows[i]->mouseReleaseEvent(event); + for (int i = 0; i < childArrows.size(); ++i) + childArrows[i]->mouseReleaseEvent(event); } ArrowAttachItem::ArrowAttachItem(ArrowTarget *_startItem) @@ -235,57 +235,57 @@ ArrowAttachItem::ArrowAttachItem(ArrowTarget *_startItem) void ArrowAttachItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (!startItem) - return; + if (!startItem) + return; - QPointF endPos = event->scenePos(); - - QList colliding = scene()->items(endPos); + QPointF endPos = event->scenePos(); + + QList colliding = scene()->items(endPos); ArrowTarget *cursorItem = 0; - qreal cursorItemZ = -1; + qreal cursorItemZ = -1; for (int i = colliding.size() - 1; i >= 0; i--) if (qgraphicsitem_cast(colliding.at(i))) - if (colliding.at(i)->zValue() > cursorItemZ) { - cursorItem = static_cast(colliding.at(i)); - cursorItemZ = cursorItem->zValue(); - } - - if ((cursorItem != targetItem) && targetItem) - targetItem->setBeingPointedAt(false); + if (colliding.at(i)->zValue() > cursorItemZ) { + cursorItem = static_cast(colliding.at(i)); + cursorItemZ = cursorItem->zValue(); + } + + if ((cursorItem != targetItem) && targetItem) + targetItem->setBeingPointedAt(false); if (!cursorItem) { - fullColor = false; - targetItem = 0; - updatePath(endPos); - } else { - fullColor = true; - if (cursorItem != startItem) - cursorItem->setBeingPointedAt(true); - targetItem = cursorItem; - updatePath(); - } - update(); + fullColor = false; + targetItem = 0; + updatePath(endPos); + } else { + fullColor = true; + if (cursorItem != startItem) + cursorItem->setBeingPointedAt(true); + targetItem = cursorItem; + updatePath(); + } + update(); } void ArrowAttachItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * /*event*/) { - if (!startItem) - return; + if (!startItem) + return; - if (targetItem && (targetItem != startItem)) { - CardItem *startCard = qgraphicsitem_cast(startItem); - CardZone *startZone = startCard->getZone(); - CardItem *targetCard = qgraphicsitem_cast(targetItem); - CardZone *targetZone = targetCard->getZone(); - - Command_AttachCard cmd; - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_card_id(startCard->getId()); - cmd.set_target_player_id(targetZone->getPlayer()->getId()); - cmd.set_target_zone(targetZone->getName().toStdString()); - cmd.set_target_card_id(targetCard->getId()); + if (targetItem && (targetItem != startItem)) { + CardItem *startCard = qgraphicsitem_cast(startItem); + CardZone *startZone = startCard->getZone(); + CardItem *targetCard = qgraphicsitem_cast(targetItem); + CardZone *targetZone = targetCard->getZone(); + + Command_AttachCard cmd; + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_card_id(startCard->getId()); + cmd.set_target_player_id(targetZone->getPlayer()->getId()); + cmd.set_target_zone(targetZone->getName().toStdString()); + cmd.set_target_card_id(targetCard->getId()); - player->sendGameCommand(cmd); - } - - delArrow(); + player->sendGameCommand(cmd); + } + + delArrow(); } diff --git a/cockatrice/src/arrowitem.h b/cockatrice/src/arrowitem.h index f97c83e7..67517404 100644 --- a/cockatrice/src/arrowitem.h +++ b/cockatrice/src/arrowitem.h @@ -10,54 +10,54 @@ class Player; class ArrowTarget; class ArrowItem : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT private: - QPainterPath path; - QMenu *menu; + QPainterPath path; + QMenu *menu; protected: - Player *player; - int id; - ArrowTarget *startItem, *targetItem; - QColor color; - bool fullColor; - void mousePressEvent(QGraphicsSceneMouseEvent *event); + Player *player; + int id; + ArrowTarget *startItem, *targetItem; + QColor color; + bool fullColor; + void mousePressEvent(QGraphicsSceneMouseEvent *event); public: - ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color); - ~ArrowItem(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QRectF boundingRect() const { return path.boundingRect(); } - QPainterPath shape() const { return path; } - void updatePath(); - void updatePath(const QPointF &endPoint); - - int getId() const { return id; } - Player *getPlayer() const { return player; } - void setStartItem(ArrowTarget *_item) { startItem = _item; } - void setTargetItem(ArrowTarget *_item) { targetItem = _item; } - ArrowTarget *getStartItem() const { return startItem; } - ArrowTarget *getTargetItem() const { return targetItem; } - void delArrow(); + ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color); + ~ArrowItem(); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QRectF boundingRect() const { return path.boundingRect(); } + QPainterPath shape() const { return path; } + void updatePath(); + void updatePath(const QPointF &endPoint); + + int getId() const { return id; } + Player *getPlayer() const { return player; } + void setStartItem(ArrowTarget *_item) { startItem = _item; } + void setTargetItem(ArrowTarget *_item) { targetItem = _item; } + ArrowTarget *getStartItem() const { return startItem; } + ArrowTarget *getTargetItem() const { return targetItem; } + void delArrow(); }; class ArrowDragItem : public ArrowItem { - Q_OBJECT + Q_OBJECT private: - QList childArrows; + QList childArrows; public: - ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color); - void addChildArrow(ArrowDragItem *childArrow); + ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color); + void addChildArrow(ArrowDragItem *childArrow); protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; class ArrowAttachItem : public ArrowItem { - Q_OBJECT + Q_OBJECT public: - ArrowAttachItem(ArrowTarget *_startItem); + ArrowAttachItem(ArrowTarget *_startItem); protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; #endif // ARROWITEM_H diff --git a/cockatrice/src/arrowtarget.cpp b/cockatrice/src/arrowtarget.cpp index 1740eb95..f20405a5 100644 --- a/cockatrice/src/arrowtarget.cpp +++ b/cockatrice/src/arrowtarget.cpp @@ -3,24 +3,24 @@ #include "player.h" ArrowTarget::ArrowTarget(Player *_owner, QGraphicsItem *parent) - : AbstractGraphicsItem(parent), owner(_owner), beingPointedAt(false) + : AbstractGraphicsItem(parent), owner(_owner), beingPointedAt(false) { } ArrowTarget::~ArrowTarget() { - for (int i = 0; i < arrowsFrom.size(); ++i) { - arrowsFrom[i]->setStartItem(0); - arrowsFrom[i]->delArrow(); - } - for (int i = 0; i < arrowsTo.size(); ++i) { - arrowsTo[i]->setTargetItem(0); - arrowsTo[i]->delArrow(); - } + for (int i = 0; i < arrowsFrom.size(); ++i) { + arrowsFrom[i]->setStartItem(0); + arrowsFrom[i]->delArrow(); + } + for (int i = 0; i < arrowsTo.size(); ++i) { + arrowsTo[i]->setTargetItem(0); + arrowsTo[i]->delArrow(); + } } void ArrowTarget::setBeingPointedAt(bool _beingPointedAt) { - beingPointedAt = _beingPointedAt; - update(); + beingPointedAt = _beingPointedAt; + update(); } diff --git a/cockatrice/src/arrowtarget.h b/cockatrice/src/arrowtarget.h index ce3ca55c..31fcf157 100644 --- a/cockatrice/src/arrowtarget.h +++ b/cockatrice/src/arrowtarget.h @@ -8,28 +8,28 @@ class Player; class ArrowItem; class ArrowTarget : public AbstractGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - Player *owner; + Player *owner; private: - bool beingPointedAt; - QList arrowsFrom, arrowsTo; + bool beingPointedAt; + QList arrowsFrom, arrowsTo; public: - ArrowTarget(Player *_owner, QGraphicsItem *parent = 0); - ~ArrowTarget(); - - Player *getOwner() const { return owner; } - - void setBeingPointedAt(bool _beingPointedAt); - bool getBeingPointedAt() const { return beingPointedAt; } - - const QList &getArrowsFrom() const { return arrowsFrom; } - void addArrowFrom(ArrowItem *arrow) { arrowsFrom.append(arrow); } - void removeArrowFrom(ArrowItem *arrow) { arrowsFrom.removeAt(arrowsFrom.indexOf(arrow)); } - - const QList &getArrowsTo() const { return arrowsTo; } - void addArrowTo(ArrowItem *arrow) { arrowsTo.append(arrow); } - void removeArrowTo(ArrowItem *arrow) { arrowsTo.removeAt(arrowsTo.indexOf(arrow)); } + ArrowTarget(Player *_owner, QGraphicsItem *parent = 0); + ~ArrowTarget(); + + Player *getOwner() const { return owner; } + + void setBeingPointedAt(bool _beingPointedAt); + bool getBeingPointedAt() const { return beingPointedAt; } + + const QList &getArrowsFrom() const { return arrowsFrom; } + void addArrowFrom(ArrowItem *arrow) { arrowsFrom.append(arrow); } + void removeArrowFrom(ArrowItem *arrow) { arrowsFrom.removeAt(arrowsFrom.indexOf(arrow)); } + + const QList &getArrowsTo() const { return arrowsTo; } + void addArrowTo(ArrowItem *arrow) { arrowsTo.append(arrow); } + void removeArrowTo(ArrowItem *arrow) { arrowsTo.removeAt(arrowsTo.indexOf(arrow)); } }; #endif diff --git a/cockatrice/src/carddatabase.cpp b/cockatrice/src/carddatabase.cpp index 8a0280a9..e5c60e52 100644 --- a/cockatrice/src/carddatabase.cpp +++ b/cockatrice/src/carddatabase.cpp @@ -17,782 +17,782 @@ const int CardDatabase::versionNeeded = 2; CardSet::CardSet(const QString &_shortName, const QString &_longName) - : shortName(_shortName), longName(_longName) + : shortName(_shortName), longName(_longName) { - updateSortKey(); + updateSortKey(); } QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardSet *set) { - xml.writeStartElement("set"); - xml.writeTextElement("name", set->getShortName()); - xml.writeTextElement("longname", set->getLongName()); - xml.writeEndElement(); + xml.writeStartElement("set"); + xml.writeTextElement("name", set->getShortName()); + xml.writeTextElement("longname", set->getLongName()); + xml.writeEndElement(); - return xml; + return xml; } void CardSet::setSortKey(unsigned int _sortKey) { - sortKey = _sortKey; + sortKey = _sortKey; - QSettings settings; - settings.beginGroup("sets"); - settings.beginGroup(shortName); - settings.setValue("sortkey", sortKey); + QSettings settings; + settings.beginGroup("sets"); + settings.beginGroup(shortName); + settings.setValue("sortkey", sortKey); } void CardSet::updateSortKey() { - QSettings settings; - settings.beginGroup("sets"); - settings.beginGroup(shortName); - sortKey = settings.value("sortkey", 0).toInt(); + QSettings settings; + settings.beginGroup("sets"); + settings.beginGroup(shortName); + sortKey = settings.value("sortkey", 0).toInt(); } class SetList::CompareFunctor { public: - inline bool operator()(CardSet *a, CardSet *b) const - { - return a->getSortKey() < b->getSortKey(); - } + inline bool operator()(CardSet *a, CardSet *b) const + { + return a->getSortKey() < b->getSortKey(); + } }; void SetList::sortByKey() { - qSort(begin(), end(), CompareFunctor()); + qSort(begin(), end(), CompareFunctor()); } PictureToLoad::PictureToLoad(CardInfo *_card, bool _stripped, bool _hq) - : card(_card), stripped(_stripped), setIndex(0), hq(_hq) + : card(_card), stripped(_stripped), setIndex(0), hq(_hq) { - if (card) { - sortedSets = card->getSets(); - sortedSets.sortByKey(); - } + if (card) { + sortedSets = card->getSets(); + sortedSets.sortByKey(); + } } bool PictureToLoad::nextSet() { - if (setIndex == sortedSets.size() - 1) - return false; - ++setIndex; - return true; + if (setIndex == sortedSets.size() - 1) + return false; + ++setIndex; + return true; } PictureLoader::PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent) - : QObject(parent), _picsPath(__picsPath), picDownload(_picDownload), downloadRunning(false), loadQueueRunning(false) + : QObject(parent), _picsPath(__picsPath), picDownload(_picDownload), downloadRunning(false), loadQueueRunning(false) { - connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection); - - networkManager = new QNetworkAccessManager(this); - connect(networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(picDownloadFinished(QNetworkReply *))); + connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection); + + networkManager = new QNetworkAccessManager(this); + connect(networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(picDownloadFinished(QNetworkReply *))); } PictureLoader::~PictureLoader() { - // This does not work with the destroyed() signal as this destructor is called after the main event loop is done. - thread()->quit(); + // This does not work with the destroyed() signal as this destructor is called after the main event loop is done. + thread()->quit(); } void PictureLoader::processLoadQueue() { - if (loadQueueRunning) - return; - - loadQueueRunning = true; - forever { - mutex.lock(); - if (loadQueue.isEmpty()) { - mutex.unlock(); - loadQueueRunning = false; - return; - } - PictureToLoad ptl = loadQueue.takeFirst(); - mutex.unlock(); - QString correctedName = ptl.getCard()->getCorrectedName(); - QString picsPath = _picsPath; - QString setName = ptl.getSetName(); - - QImage image; - if (!image.load(QString("%1/%2/%3.full.jpg").arg(picsPath).arg(setName).arg(correctedName))) - if (!image.load(QString("%1/%2/%3%4.full.jpg").arg(picsPath).arg(setName).arg(correctedName).arg(1))) - if (!image.load(QString("%1/%2/%3/%4.full.jpg").arg(picsPath).arg("downloadedPics").arg(setName).arg(correctedName))) { - if (picDownload) { - cardsToDownload.append(ptl); - if (!downloadRunning) - startNextPicDownload(); - } else { - if (ptl.nextSet()) - loadQueue.prepend(ptl); - else - emit imageLoaded(ptl.getCard(), QImage()); - } - continue; - } - - emit imageLoaded(ptl.getCard(), image); - } + if (loadQueueRunning) + return; + + loadQueueRunning = true; + forever { + mutex.lock(); + if (loadQueue.isEmpty()) { + mutex.unlock(); + loadQueueRunning = false; + return; + } + PictureToLoad ptl = loadQueue.takeFirst(); + mutex.unlock(); + QString correctedName = ptl.getCard()->getCorrectedName(); + QString picsPath = _picsPath; + QString setName = ptl.getSetName(); + + QImage image; + if (!image.load(QString("%1/%2/%3.full.jpg").arg(picsPath).arg(setName).arg(correctedName))) + if (!image.load(QString("%1/%2/%3%4.full.jpg").arg(picsPath).arg(setName).arg(correctedName).arg(1))) + if (!image.load(QString("%1/%2/%3/%4.full.jpg").arg(picsPath).arg("downloadedPics").arg(setName).arg(correctedName))) { + if (picDownload) { + cardsToDownload.append(ptl); + if (!downloadRunning) + startNextPicDownload(); + } else { + if (ptl.nextSet()) + loadQueue.prepend(ptl); + else + emit imageLoaded(ptl.getCard(), QImage()); + } + continue; + } + + emit imageLoaded(ptl.getCard(), image); + } } void PictureLoader::startNextPicDownload() { - if (cardsToDownload.isEmpty()) { - cardBeingDownloaded = 0; - downloadRunning = false; - return; - } - - downloadRunning = true; - - cardBeingDownloaded = cardsToDownload.takeFirst(); - QString picUrl; - if (cardBeingDownloaded.getStripped()) - picUrl = cardBeingDownloaded.getCard()->getPicURLSt(cardBeingDownloaded.getSetName()); - else if (cardBeingDownloaded.getHq()) { - picUrl = cardBeingDownloaded.getCard()->getPicURLHq(cardBeingDownloaded.getSetName()); - if (picUrl.isEmpty()) { - picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); - cardBeingDownloaded.setHq(false); - } - } else - picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); - QUrl url(picUrl); - - QNetworkRequest req(url); - qDebug() << "starting picture download:" << req.url(); - networkManager->get(req); + if (cardsToDownload.isEmpty()) { + cardBeingDownloaded = 0; + downloadRunning = false; + return; + } + + downloadRunning = true; + + cardBeingDownloaded = cardsToDownload.takeFirst(); + QString picUrl; + if (cardBeingDownloaded.getStripped()) + picUrl = cardBeingDownloaded.getCard()->getPicURLSt(cardBeingDownloaded.getSetName()); + else if (cardBeingDownloaded.getHq()) { + picUrl = cardBeingDownloaded.getCard()->getPicURLHq(cardBeingDownloaded.getSetName()); + if (picUrl.isEmpty()) { + picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); + cardBeingDownloaded.setHq(false); + } + } else + picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); + QUrl url(picUrl); + + QNetworkRequest req(url); + qDebug() << "starting picture download:" << req.url(); + networkManager->get(req); } void PictureLoader::picDownloadFinished(QNetworkReply *reply) { - QString picsPath = _picsPath; - const QByteArray &picData = reply->readAll(); - QImage testImage; - if (testImage.loadFromData(picData)) { - if (!QDir(QString(picsPath + "/downloadedPics/")).exists()) { - QDir dir(picsPath); - if (!dir.exists()) - return; - dir.mkdir("downloadedPics"); - } - if (!QDir(QString(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName())).exists()) { - QDir dir(QString(picsPath + "/downloadedPics")); - dir.mkdir(cardBeingDownloaded.getSetName()); - } - - QString suffix; - if (!cardBeingDownloaded.getStripped()) - suffix = ".full"; - - QFile newPic(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName() + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + suffix + ".jpg"); - if (!newPic.open(QIODevice::WriteOnly)) - return; - newPic.write(picData); - newPic.close(); - - emit imageLoaded(cardBeingDownloaded.getCard(), testImage); - } else if (cardBeingDownloaded.getHq()) { - qDebug() << "HQ: received invalid picture. URL:" << reply->request().url(); - cardBeingDownloaded.setHq(false); - cardsToDownload.prepend(cardBeingDownloaded); - } else { - qDebug() << "LQ: received invalid picture. URL:" << reply->request().url(); - if (cardBeingDownloaded.nextSet()) { - cardBeingDownloaded.setHq(true); - mutex.lock(); - loadQueue.prepend(cardBeingDownloaded); - mutex.unlock(); - emit startLoadQueue(); - } else - emit imageLoaded(cardBeingDownloaded.getCard(), QImage()); - } - - reply->deleteLater(); - startNextPicDownload(); + QString picsPath = _picsPath; + const QByteArray &picData = reply->readAll(); + QImage testImage; + if (testImage.loadFromData(picData)) { + if (!QDir(QString(picsPath + "/downloadedPics/")).exists()) { + QDir dir(picsPath); + if (!dir.exists()) + return; + dir.mkdir("downloadedPics"); + } + if (!QDir(QString(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName())).exists()) { + QDir dir(QString(picsPath + "/downloadedPics")); + dir.mkdir(cardBeingDownloaded.getSetName()); + } + + QString suffix; + if (!cardBeingDownloaded.getStripped()) + suffix = ".full"; + + QFile newPic(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName() + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + suffix + ".jpg"); + if (!newPic.open(QIODevice::WriteOnly)) + return; + newPic.write(picData); + newPic.close(); + + emit imageLoaded(cardBeingDownloaded.getCard(), testImage); + } else if (cardBeingDownloaded.getHq()) { + qDebug() << "HQ: received invalid picture. URL:" << reply->request().url(); + cardBeingDownloaded.setHq(false); + cardsToDownload.prepend(cardBeingDownloaded); + } else { + qDebug() << "LQ: received invalid picture. URL:" << reply->request().url(); + if (cardBeingDownloaded.nextSet()) { + cardBeingDownloaded.setHq(true); + mutex.lock(); + loadQueue.prepend(cardBeingDownloaded); + mutex.unlock(); + emit startLoadQueue(); + } else + emit imageLoaded(cardBeingDownloaded.getCard(), QImage()); + } + + reply->deleteLater(); + startNextPicDownload(); } void PictureLoader::loadImage(CardInfo *card, bool stripped) { - QMutexLocker locker(&mutex); - - loadQueue.append(PictureToLoad(card, stripped)); - emit startLoadQueue(); + QMutexLocker locker(&mutex); + + loadQueue.append(PictureToLoad(card, stripped)); + emit startLoadQueue(); } void PictureLoader::setPicsPath(const QString &path) { - QMutexLocker locker(&mutex); - _picsPath = path; + QMutexLocker locker(&mutex); + _picsPath = path; } void PictureLoader::setPicDownload(bool _picDownload) { - QMutexLocker locker(&mutex); - picDownload = _picDownload; + QMutexLocker locker(&mutex); + picDownload = _picDownload; } CardInfo::CardInfo(CardDatabase *_db, - const QString &_name, - bool _isToken, - const QString &_manacost, - const QString &_cardtype, - const QString &_powtough, - const QString &_text, - const QStringList &_colors, - int _loyalty, - bool _cipt, - int _tableRow, - const SetList &_sets, - const QMap &_picURLs, - const QMap &_picURLsHq, - const QMap &_picURLsSt) - : db(_db), - name(_name), - isToken(_isToken), - sets(_sets), - manacost(_manacost), - cardtype(_cardtype), - powtough(_powtough), - text(_text), - colors(_colors), - loyalty(_loyalty), - picURLs(_picURLs), - picURLsHq(_picURLsHq), - picURLsSt(_picURLsSt), - cipt(_cipt), - tableRow(_tableRow), - pixmap(NULL) + const QString &_name, + bool _isToken, + const QString &_manacost, + const QString &_cardtype, + const QString &_powtough, + const QString &_text, + const QStringList &_colors, + int _loyalty, + bool _cipt, + int _tableRow, + const SetList &_sets, + const QMap &_picURLs, + const QMap &_picURLsHq, + const QMap &_picURLsSt) + : db(_db), + name(_name), + isToken(_isToken), + sets(_sets), + manacost(_manacost), + cardtype(_cardtype), + powtough(_powtough), + text(_text), + colors(_colors), + loyalty(_loyalty), + picURLs(_picURLs), + picURLsHq(_picURLsHq), + picURLsSt(_picURLsSt), + cipt(_cipt), + tableRow(_tableRow), + pixmap(NULL) { - for (int i = 0; i < sets.size(); i++) - sets[i]->append(this); + for (int i = 0; i < sets.size(); i++) + sets[i]->append(this); } CardInfo::~CardInfo() { - clearPixmapCache(); + clearPixmapCache(); } QString CardInfo::getMainCardType() const { - QString result = getCardType(); - /* - Legendary Artifact Creature - Golem - Instant // Instant - */ + QString result = getCardType(); + /* + Legendary Artifact Creature - Golem + Instant // Instant + */ - int pos; - if ((pos = result.indexOf('-')) != -1) - result.remove(pos, result.length()); - if ((pos = result.indexOf("//")) != -1) - result.remove(pos, result.length()); - result = result.simplified(); - /* - Legendary Artifact Creature - Instant - */ + int pos; + if ((pos = result.indexOf('-')) != -1) + result.remove(pos, result.length()); + if ((pos = result.indexOf("//")) != -1) + result.remove(pos, result.length()); + result = result.simplified(); + /* + Legendary Artifact Creature + Instant + */ - if ((pos = result.lastIndexOf(' ')) != -1) - result = result.mid(pos + 1); - /* - Creature - Instant - */ + if ((pos = result.lastIndexOf(' ')) != -1) + result = result.mid(pos + 1); + /* + Creature + Instant + */ - return result; + return result; } QString CardInfo::getCorrectedName() const { - QString result = name; - // Fire // Ice, Circle of Protection: Red, "Ach! Hans, Run!", Who/What/When/Where/Why, Question Elemental? - return result.remove(" // ").remove(':').remove('"').remove('?').replace('/', ' '); + QString result = name; + // Fire // Ice, Circle of Protection: Red, "Ach! Hans, Run!", Who/What/When/Where/Why, Question Elemental? + return result.remove(" // ").remove(':').remove('"').remove('?').replace('/', ' '); } void CardInfo::addToSet(CardSet *set) { - set->append(this); - sets << set; + set->append(this); + sets << set; } QString CardInfo::getPicURL() const { - SetList sortedSets = sets; - sortedSets.sortByKey(); - return picURLs.value(sortedSets.first()->getShortName()); + SetList sortedSets = sets; + sortedSets.sortByKey(); + return picURLs.value(sortedSets.first()->getShortName()); } QPixmap *CardInfo::loadPixmap() { - if (pixmap) - return pixmap; - pixmap = new QPixmap(); - - if (getName().isEmpty()) { - pixmap->load(settingsCache->getCardBackPicturePath()); - return pixmap; - } - db->loadImage(this); - return pixmap; + if (pixmap) + return pixmap; + pixmap = new QPixmap(); + + if (getName().isEmpty()) { + pixmap->load(settingsCache->getCardBackPicturePath()); + return pixmap; + } + db->loadImage(this); + return pixmap; } void CardInfo::imageLoaded(const QImage &image) { - if (!image.isNull()) { - *pixmap = QPixmap::fromImage(image); - emit pixmapUpdated(); - } + if (!image.isNull()) { + *pixmap = QPixmap::fromImage(image); + emit pixmapUpdated(); + } } QPixmap *CardInfo::getPixmap(QSize size) { - QPixmap *cachedPixmap = scaledPixmapCache.value(size.width()); - if (cachedPixmap) - return cachedPixmap; - QPixmap *bigPixmap = loadPixmap(); - QPixmap *result; - if (bigPixmap->isNull()) { - if (!getName().isEmpty()) - return 0; - else { - result = new QPixmap(size); - result->fill(Qt::transparent); - QSvgRenderer svg(QString(":/back.svg")); - QPainter painter(result); - svg.render(&painter, QRectF(0, 0, size.width(), size.height())); - } - } else - result = new QPixmap(bigPixmap->scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - scaledPixmapCache.insert(size.width(), result); - return result; + QPixmap *cachedPixmap = scaledPixmapCache.value(size.width()); + if (cachedPixmap) + return cachedPixmap; + QPixmap *bigPixmap = loadPixmap(); + QPixmap *result; + if (bigPixmap->isNull()) { + if (!getName().isEmpty()) + return 0; + else { + result = new QPixmap(size); + result->fill(Qt::transparent); + QSvgRenderer svg(QString(":/back.svg")); + QPainter painter(result); + svg.render(&painter, QRectF(0, 0, size.width(), size.height())); + } + } else + result = new QPixmap(bigPixmap->scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + scaledPixmapCache.insert(size.width(), result); + return result; } void CardInfo::clearPixmapCache() { - if (pixmap) { - qDebug() << "Deleting pixmap for" << name; - delete pixmap; - pixmap = 0; - QMapIterator i(scaledPixmapCache); - while (i.hasNext()) { - i.next(); - qDebug() << " Deleting cached pixmap for width" << i.key(); - delete i.value(); - } - scaledPixmapCache.clear(); - } + if (pixmap) { + qDebug() << "Deleting pixmap for" << name; + delete pixmap; + pixmap = 0; + QMapIterator i(scaledPixmapCache); + while (i.hasNext()) { + i.next(); + qDebug() << " Deleting cached pixmap for width" << i.key(); + delete i.value(); + } + scaledPixmapCache.clear(); + } } void CardInfo::clearPixmapCacheMiss() { - if (!pixmap) - return; - if (pixmap->isNull()) - clearPixmapCache(); + if (!pixmap) + return; + if (pixmap->isNull()) + clearPixmapCache(); } void CardInfo::updatePixmapCache() { - qDebug() << "Updating pixmap cache for" << name; - clearPixmapCache(); - loadPixmap(); - - emit pixmapUpdated(); + qDebug() << "Updating pixmap cache for" << name; + clearPixmapCache(); + loadPixmap(); + + emit pixmapUpdated(); } QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfo *info) { - xml.writeStartElement("card"); - xml.writeTextElement("name", info->getName()); + xml.writeStartElement("card"); + xml.writeTextElement("name", info->getName()); - const SetList &sets = info->getSets(); - for (int i = 0; i < sets.size(); i++) { - xml.writeStartElement("set"); - xml.writeAttribute("picURL", info->getPicURL(sets[i]->getShortName())); - xml.writeAttribute("picURLHq", info->getPicURLHq(sets[i]->getShortName())); - xml.writeAttribute("picURLSt", info->getPicURLSt(sets[i]->getShortName())); - xml.writeCharacters(sets[i]->getShortName()); - xml.writeEndElement(); - } - const QStringList &colors = info->getColors(); - for (int i = 0; i < colors.size(); i++) - xml.writeTextElement("color", colors[i]); + const SetList &sets = info->getSets(); + for (int i = 0; i < sets.size(); i++) { + xml.writeStartElement("set"); + xml.writeAttribute("picURL", info->getPicURL(sets[i]->getShortName())); + xml.writeAttribute("picURLHq", info->getPicURLHq(sets[i]->getShortName())); + xml.writeAttribute("picURLSt", info->getPicURLSt(sets[i]->getShortName())); + xml.writeCharacters(sets[i]->getShortName()); + xml.writeEndElement(); + } + const QStringList &colors = info->getColors(); + for (int i = 0; i < colors.size(); i++) + xml.writeTextElement("color", colors[i]); - xml.writeTextElement("manacost", info->getManaCost()); - xml.writeTextElement("type", info->getCardType()); - if (!info->getPowTough().isEmpty()) - xml.writeTextElement("pt", info->getPowTough()); - xml.writeTextElement("tablerow", QString::number(info->getTableRow())); - xml.writeTextElement("text", info->getText()); - if (info->getMainCardType() == "Planeswalker") - xml.writeTextElement("loyalty", QString::number(info->getLoyalty())); - if (info->getCipt()) - xml.writeTextElement("cipt", "1"); - if (info->getIsToken()) - xml.writeTextElement("token", "1"); - xml.writeEndElement(); // card + xml.writeTextElement("manacost", info->getManaCost()); + xml.writeTextElement("type", info->getCardType()); + if (!info->getPowTough().isEmpty()) + xml.writeTextElement("pt", info->getPowTough()); + xml.writeTextElement("tablerow", QString::number(info->getTableRow())); + xml.writeTextElement("text", info->getText()); + if (info->getMainCardType() == "Planeswalker") + xml.writeTextElement("loyalty", QString::number(info->getLoyalty())); + if (info->getCipt()) + xml.writeTextElement("cipt", "1"); + if (info->getIsToken()) + xml.writeTextElement("token", "1"); + xml.writeEndElement(); // card - return xml; + return xml; } CardDatabase::CardDatabase(QObject *parent) - : QObject(parent), loadSuccess(false), noCard(0) + : QObject(parent), loadSuccess(false), noCard(0) { - connect(settingsCache, SIGNAL(picsPathChanged()), this, SLOT(picsPathChanged())); - connect(settingsCache, SIGNAL(cardDatabasePathChanged()), this, SLOT(loadCardDatabase())); - connect(settingsCache, SIGNAL(tokenDatabasePathChanged()), this, SLOT(loadTokenDatabase())); - connect(settingsCache, SIGNAL(picDownloadChanged()), this, SLOT(picDownloadChanged())); - - loadCardDatabase(); - loadTokenDatabase(); - - pictureLoaderThread = new QThread; - pictureLoader = new PictureLoader(settingsCache->getPicsPath(), settingsCache->getPicDownload()); - pictureLoader->moveToThread(pictureLoaderThread); - connect(pictureLoader, SIGNAL(imageLoaded(CardInfo *, const QImage &)), this, SLOT(imageLoaded(CardInfo *, const QImage &))); - pictureLoaderThread->start(QThread::LowPriority); + connect(settingsCache, SIGNAL(picsPathChanged()), this, SLOT(picsPathChanged())); + connect(settingsCache, SIGNAL(cardDatabasePathChanged()), this, SLOT(loadCardDatabase())); + connect(settingsCache, SIGNAL(tokenDatabasePathChanged()), this, SLOT(loadTokenDatabase())); + connect(settingsCache, SIGNAL(picDownloadChanged()), this, SLOT(picDownloadChanged())); + + loadCardDatabase(); + loadTokenDatabase(); + + pictureLoaderThread = new QThread; + pictureLoader = new PictureLoader(settingsCache->getPicsPath(), settingsCache->getPicDownload()); + pictureLoader->moveToThread(pictureLoaderThread); + connect(pictureLoader, SIGNAL(imageLoaded(CardInfo *, const QImage &)), this, SLOT(imageLoaded(CardInfo *, const QImage &))); + pictureLoaderThread->start(QThread::LowPriority); - noCard = new CardInfo(this); - noCard->loadPixmap(); // cache pixmap for card back - connect(settingsCache, SIGNAL(cardBackPicturePathChanged()), noCard, SLOT(updatePixmapCache())); + noCard = new CardInfo(this); + noCard->loadPixmap(); // cache pixmap for card back + connect(settingsCache, SIGNAL(cardBackPicturePathChanged()), noCard, SLOT(updatePixmapCache())); } CardDatabase::~CardDatabase() { - clear(); - delete noCard; - - pictureLoader->deleteLater(); - pictureLoaderThread->wait(); - delete pictureLoaderThread; + clear(); + delete noCard; + + pictureLoader->deleteLater(); + pictureLoaderThread->wait(); + delete pictureLoaderThread; } void CardDatabase::clear() { - QHashIterator setIt(setHash); - while (setIt.hasNext()) { - setIt.next(); - delete setIt.value(); - } - setHash.clear(); - - QHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - delete i.value(); - } - cardHash.clear(); + QHashIterator setIt(setHash); + while (setIt.hasNext()) { + setIt.next(); + delete setIt.value(); + } + setHash.clear(); + + QHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + delete i.value(); + } + cardHash.clear(); } void CardDatabase::addCard(CardInfo *card) { - cardHash.insert(card->getName(), card); - emit cardAdded(card); + cardHash.insert(card->getName(), card); + emit cardAdded(card); } void CardDatabase::removeCard(CardInfo *card) { - cardHash.remove(card->getName()); - emit cardRemoved(card); + cardHash.remove(card->getName()); + emit cardRemoved(card); } CardInfo *CardDatabase::getCard(const QString &cardName, bool createIfNotFound) { - if (cardName.isEmpty()) - return noCard; - else if (cardHash.contains(cardName)) - return cardHash.value(cardName); - else if (createIfNotFound) { - CardInfo *newCard = new CardInfo(this, cardName, true); - newCard->addToSet(getSet("TK")); - cardHash.insert(cardName, newCard); - return newCard; - } else - return 0; + if (cardName.isEmpty()) + return noCard; + else if (cardHash.contains(cardName)) + return cardHash.value(cardName); + else if (createIfNotFound) { + CardInfo *newCard = new CardInfo(this, cardName, true); + newCard->addToSet(getSet("TK")); + cardHash.insert(cardName, newCard); + return newCard; + } else + return 0; } CardSet *CardDatabase::getSet(const QString &setName) { - if (setHash.contains(setName)) - return setHash.value(setName); - else { - CardSet *newSet = new CardSet(setName); - setHash.insert(setName, newSet); - return newSet; - } + if (setHash.contains(setName)) + return setHash.value(setName); + else { + CardSet *newSet = new CardSet(setName); + setHash.insert(setName, newSet); + return newSet; + } } SetList CardDatabase::getSetList() const { - SetList result; - QHashIterator i(setHash); - while (i.hasNext()) { - i.next(); - result << i.value(); - } - return result; + SetList result; + QHashIterator i(setHash); + while (i.hasNext()) { + i.next(); + result << i.value(); + } + return result; } void CardDatabase::clearPixmapCache() { - QHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - i.value()->clearPixmapCache(); - } - if (noCard) - noCard->clearPixmapCache(); + QHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + i.value()->clearPixmapCache(); + } + if (noCard) + noCard->clearPixmapCache(); } void CardDatabase::loadSetsFromXml(QXmlStreamReader &xml) { - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "set") { - QString shortName, longName; - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "name") - shortName = xml.readElementText(); - else if (xml.name() == "longname") - longName = xml.readElementText(); - } - setHash.insert(shortName, new CardSet(shortName, longName)); - } - } + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "set") { + QString shortName, longName; + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "name") + shortName = xml.readElementText(); + else if (xml.name() == "longname") + longName = xml.readElementText(); + } + setHash.insert(shortName, new CardSet(shortName, longName)); + } + } } void CardDatabase::loadCardsFromXml(QXmlStreamReader &xml) { - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "card") { - QString name, manacost, type, pt, text; - QStringList colors; - QMap picURLs, picURLsHq, picURLsSt; - SetList sets; - int tableRow = 0; - int loyalty = 0; - bool cipt = false; - bool isToken = false; - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "name") - name = xml.readElementText(); - else if (xml.name() == "manacost") - manacost = xml.readElementText(); - else if (xml.name() == "type") - type = xml.readElementText(); - else if (xml.name() == "pt") - pt = xml.readElementText(); - else if (xml.name() == "text") - text = xml.readElementText(); - else if (xml.name() == "set") { - QString picURL = xml.attributes().value("picURL").toString(); - QString picURLHq = xml.attributes().value("picURLHq").toString(); - QString picURLSt = xml.attributes().value("picURLSt").toString(); - QString setName = xml.readElementText(); - sets.append(getSet(setName)); - picURLs.insert(setName, picURL); - picURLsHq.insert(setName, picURLHq); - picURLsSt.insert(setName, picURLSt); - } else if (xml.name() == "color") - colors << xml.readElementText(); - else if (xml.name() == "tablerow") - tableRow = xml.readElementText().toInt(); - else if (xml.name() == "cipt") - cipt = (xml.readElementText() == "1"); - else if (xml.name() == "loyalty") - loyalty = xml.readElementText().toInt(); - else if (xml.name() == "token") - isToken = xml.readElementText().toInt(); - } - cardHash.insert(name, new CardInfo(this, name, isToken, manacost, type, pt, text, colors, loyalty, cipt, tableRow, sets, picURLs, picURLsHq, picURLsSt)); - } - } + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "card") { + QString name, manacost, type, pt, text; + QStringList colors; + QMap picURLs, picURLsHq, picURLsSt; + SetList sets; + int tableRow = 0; + int loyalty = 0; + bool cipt = false; + bool isToken = false; + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "name") + name = xml.readElementText(); + else if (xml.name() == "manacost") + manacost = xml.readElementText(); + else if (xml.name() == "type") + type = xml.readElementText(); + else if (xml.name() == "pt") + pt = xml.readElementText(); + else if (xml.name() == "text") + text = xml.readElementText(); + else if (xml.name() == "set") { + QString picURL = xml.attributes().value("picURL").toString(); + QString picURLHq = xml.attributes().value("picURLHq").toString(); + QString picURLSt = xml.attributes().value("picURLSt").toString(); + QString setName = xml.readElementText(); + sets.append(getSet(setName)); + picURLs.insert(setName, picURL); + picURLsHq.insert(setName, picURLHq); + picURLsSt.insert(setName, picURLSt); + } else if (xml.name() == "color") + colors << xml.readElementText(); + else if (xml.name() == "tablerow") + tableRow = xml.readElementText().toInt(); + else if (xml.name() == "cipt") + cipt = (xml.readElementText() == "1"); + else if (xml.name() == "loyalty") + loyalty = xml.readElementText().toInt(); + else if (xml.name() == "token") + isToken = xml.readElementText().toInt(); + } + cardHash.insert(name, new CardInfo(this, name, isToken, manacost, type, pt, text, colors, loyalty, cipt, tableRow, sets, picURLs, picURLsHq, picURLsSt)); + } + } } bool CardDatabase::loadFromFile(const QString &fileName, bool tokens) { - QFile file(fileName); - file.open(QIODevice::ReadOnly); - if (!file.isOpen()) - return false; - - if (tokens) { - QMutableHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - if (i.value()->getIsToken()) { - delete i.value(); - i.remove(); - } - } - } else { - QHashIterator setIt(setHash); - while (setIt.hasNext()) { - setIt.next(); - delete setIt.value(); - } - setHash.clear(); - - QMutableHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - if (!i.value()->getIsToken()) { - delete i.value(); - i.remove(); - } - } - cardHash.clear(); - } + QFile file(fileName); + file.open(QIODevice::ReadOnly); + if (!file.isOpen()) + return false; + + if (tokens) { + QMutableHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + if (i.value()->getIsToken()) { + delete i.value(); + i.remove(); + } + } + } else { + QHashIterator setIt(setHash); + while (setIt.hasNext()) { + setIt.next(); + delete setIt.value(); + } + setHash.clear(); + + QMutableHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + if (!i.value()->getIsToken()) { + delete i.value(); + i.remove(); + } + } + cardHash.clear(); + } - QXmlStreamReader xml(&file); - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::StartElement) { - if (xml.name() != "cockatrice_carddatabase") - return false; - if (xml.attributes().value("version").toString().toInt() < versionNeeded) - return false; - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "sets") - loadSetsFromXml(xml); - else if (xml.name() == "cards") - loadCardsFromXml(xml); - } - } - } - qDebug() << cardHash.size() << "cards in" << setHash.size() << "sets loaded"; - return !cardHash.isEmpty(); + QXmlStreamReader xml(&file); + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::StartElement) { + if (xml.name() != "cockatrice_carddatabase") + return false; + if (xml.attributes().value("version").toString().toInt() < versionNeeded) + return false; + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "sets") + loadSetsFromXml(xml); + else if (xml.name() == "cards") + loadCardsFromXml(xml); + } + } + } + qDebug() << cardHash.size() << "cards in" << setHash.size() << "sets loaded"; + return !cardHash.isEmpty(); } bool CardDatabase::saveToFile(const QString &fileName, bool tokens) { - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) - return false; - QXmlStreamWriter xml(&file); + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly)) + return false; + QXmlStreamWriter xml(&file); - xml.setAutoFormatting(true); - xml.writeStartDocument(); - xml.writeStartElement("cockatrice_carddatabase"); - xml.writeAttribute("version", QString::number(versionNeeded)); + xml.setAutoFormatting(true); + xml.writeStartDocument(); + xml.writeStartElement("cockatrice_carddatabase"); + xml.writeAttribute("version", QString::number(versionNeeded)); - if (!tokens) { - xml.writeStartElement("sets"); - QHashIterator setIterator(setHash); - while (setIterator.hasNext()) - xml << setIterator.next().value(); - xml.writeEndElement(); // sets - } + if (!tokens) { + xml.writeStartElement("sets"); + QHashIterator setIterator(setHash); + while (setIterator.hasNext()) + xml << setIterator.next().value(); + xml.writeEndElement(); // sets + } - xml.writeStartElement("cards"); - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) { - CardInfo *card = cardIterator.next().value(); - if (card->getIsToken() == tokens) - xml << card; - } - xml.writeEndElement(); // cards + xml.writeStartElement("cards"); + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) { + CardInfo *card = cardIterator.next().value(); + if (card->getIsToken() == tokens) + xml << card; + } + xml.writeEndElement(); // cards - xml.writeEndElement(); // cockatrice_carddatabase - xml.writeEndDocument(); + xml.writeEndElement(); // cockatrice_carddatabase + xml.writeEndDocument(); - return true; + return true; } void CardDatabase::picDownloadChanged() { - pictureLoader->setPicDownload(settingsCache->getPicDownload()); - if (settingsCache->getPicDownload()) { - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) - cardIterator.next().value()->clearPixmapCacheMiss(); - } + pictureLoader->setPicDownload(settingsCache->getPicDownload()); + if (settingsCache->getPicDownload()) { + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) + cardIterator.next().value()->clearPixmapCacheMiss(); + } } bool CardDatabase::loadCardDatabase(const QString &path, bool tokens) { - bool tempLoadSuccess = false; - if (!path.isEmpty()) - tempLoadSuccess = loadFromFile(path, tokens); - - if (tempLoadSuccess) { - SetList allSets; - QHashIterator setsIterator(setHash); - while (setsIterator.hasNext()) - allSets.append(setsIterator.next().value()); - allSets.sortByKey(); - for (int i = 0; i < allSets.size(); ++i) - allSets[i]->setSortKey(i); - - emit cardListChanged(); - } - - if (!tokens) - loadSuccess = tempLoadSuccess; - - return tempLoadSuccess; + bool tempLoadSuccess = false; + if (!path.isEmpty()) + tempLoadSuccess = loadFromFile(path, tokens); + + if (tempLoadSuccess) { + SetList allSets; + QHashIterator setsIterator(setHash); + while (setsIterator.hasNext()) + allSets.append(setsIterator.next().value()); + allSets.sortByKey(); + for (int i = 0; i < allSets.size(); ++i) + allSets[i]->setSortKey(i); + + emit cardListChanged(); + } + + if (!tokens) + loadSuccess = tempLoadSuccess; + + return tempLoadSuccess; } void CardDatabase::loadCardDatabase() { - loadCardDatabase(settingsCache->getCardDatabasePath(), false); + loadCardDatabase(settingsCache->getCardDatabasePath(), false); } void CardDatabase::loadTokenDatabase() { - loadCardDatabase(settingsCache->getTokenDatabasePath(), true); + loadCardDatabase(settingsCache->getTokenDatabasePath(), true); } QStringList CardDatabase::getAllColors() const { - QSet colors; - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) { - const QStringList &cardColors = cardIterator.next().value()->getColors(); - if (cardColors.isEmpty()) - colors.insert("X"); - else - for (int i = 0; i < cardColors.size(); ++i) - colors.insert(cardColors[i]); - } - return colors.toList(); + QSet colors; + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) { + const QStringList &cardColors = cardIterator.next().value()->getColors(); + if (cardColors.isEmpty()) + colors.insert("X"); + else + for (int i = 0; i < cardColors.size(); ++i) + colors.insert(cardColors[i]); + } + return colors.toList(); } QStringList CardDatabase::getAllMainCardTypes() const { - QSet types; - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) - types.insert(cardIterator.next().value()->getMainCardType()); - return types.toList(); + QSet types; + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) + types.insert(cardIterator.next().value()->getMainCardType()); + return types.toList(); } void CardDatabase::cacheCardPixmaps(const QStringList &cardNames) { - for (int i = 0; i < cardNames.size(); ++i) - getCard(cardNames[i])->loadPixmap(); + for (int i = 0; i < cardNames.size(); ++i) + getCard(cardNames[i])->loadPixmap(); } void CardDatabase::loadImage(CardInfo *card) { - pictureLoader->loadImage(card, false); + pictureLoader->loadImage(card, false); } void CardDatabase::imageLoaded(CardInfo *card, QImage image) { - card->imageLoaded(image); + card->imageLoaded(image); } void CardDatabase::picsPathChanged() { - pictureLoader->setPicsPath(settingsCache->getPicsPath()); - clearPixmapCache(); + pictureLoader->setPicsPath(settingsCache->getPicsPath()); + clearPixmapCache(); } diff --git a/cockatrice/src/carddatabase.h b/cockatrice/src/carddatabase.h index 1f87d276..9d3f33f3 100644 --- a/cockatrice/src/carddatabase.h +++ b/cockatrice/src/carddatabase.h @@ -22,191 +22,191 @@ typedef QMap QStringMap; class CardSet : public QList { private: - QString shortName, longName; - unsigned int sortKey; + QString shortName, longName; + unsigned int sortKey; public: - CardSet(const QString &_shortName = QString(), const QString &_longName = QString()); - QString getShortName() const { return shortName; } - QString getLongName() const { return longName; } - int getSortKey() const { return sortKey; } - void setSortKey(unsigned int _sortKey); - void updateSortKey(); + CardSet(const QString &_shortName = QString(), const QString &_longName = QString()); + QString getShortName() const { return shortName; } + QString getLongName() const { return longName; } + int getSortKey() const { return sortKey; } + void setSortKey(unsigned int _sortKey); + void updateSortKey(); }; class SetList : public QList { private: - class CompareFunctor; + class CompareFunctor; public: - void sortByKey(); + void sortByKey(); }; class PictureToLoad { private: - CardInfo *card; - bool stripped; - SetList sortedSets; - int setIndex; - bool hq; + CardInfo *card; + bool stripped; + SetList sortedSets; + int setIndex; + bool hq; public: - PictureToLoad(CardInfo *_card = 0, bool _stripped = false, bool _hq = true); - CardInfo *getCard() const { return card; } - bool getStripped() const { return stripped; } - QString getSetName() const { return sortedSets[setIndex]->getShortName(); } - bool nextSet(); - - bool getHq() const { return hq; } - void setHq(bool _hq) { hq = _hq; } - + PictureToLoad(CardInfo *_card = 0, bool _stripped = false, bool _hq = true); + CardInfo *getCard() const { return card; } + bool getStripped() const { return stripped; } + QString getSetName() const { return sortedSets[setIndex]->getShortName(); } + bool nextSet(); + + bool getHq() const { return hq; } + void setHq(bool _hq) { hq = _hq; } + }; class PictureLoader : public QObject { - Q_OBJECT + Q_OBJECT private: - QString _picsPath; - QList loadQueue; - QMutex mutex; - QNetworkAccessManager *networkManager; - QList cardsToDownload; - PictureToLoad cardBeingDownloaded; - bool picDownload, downloadRunning, loadQueueRunning; - void startNextPicDownload(); + QString _picsPath; + QList loadQueue; + QMutex mutex; + QNetworkAccessManager *networkManager; + QList cardsToDownload; + PictureToLoad cardBeingDownloaded; + bool picDownload, downloadRunning, loadQueueRunning; + void startNextPicDownload(); public: - PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent = 0); - ~PictureLoader(); - void setPicsPath(const QString &path); - void setPicDownload(bool _picDownload); - void loadImage(CardInfo *card, bool stripped); + PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent = 0); + ~PictureLoader(); + void setPicsPath(const QString &path); + void setPicDownload(bool _picDownload); + void loadImage(CardInfo *card, bool stripped); private slots: - void picDownloadFinished(QNetworkReply *reply); + void picDownloadFinished(QNetworkReply *reply); public slots: - void processLoadQueue(); + void processLoadQueue(); signals: - void startLoadQueue(); - void imageLoaded(CardInfo *card, const QImage &image); + void startLoadQueue(); + void imageLoaded(CardInfo *card, const QImage &image); }; class CardInfo : public QObject { - Q_OBJECT + Q_OBJECT private: - CardDatabase *db; + CardDatabase *db; - QString name; - bool isToken; - SetList sets; - QString manacost; - QString cardtype; - QString powtough; - QString text; - QStringList colors; - int loyalty; - QMap picURLs, picURLsHq, picURLsSt; - bool cipt; - int tableRow; - QPixmap *pixmap; - QMap scaledPixmapCache; + QString name; + bool isToken; + SetList sets; + QString manacost; + QString cardtype; + QString powtough; + QString text; + QStringList colors; + int loyalty; + QMap picURLs, picURLsHq, picURLsSt; + bool cipt; + int tableRow; + QPixmap *pixmap; + QMap scaledPixmapCache; public: - CardInfo(CardDatabase *_db, - const QString &_name = QString(), - bool _isToken = false, - const QString &_manacost = QString(), - const QString &_cardtype = QString(), - const QString &_powtough = QString(), - const QString &_text = QString(), - const QStringList &_colors = QStringList(), - int _loyalty = 0, - bool _cipt = false, - int _tableRow = 0, - const SetList &_sets = SetList(), - const QStringMap &_picURLs = QStringMap(), - const QStringMap &_picURLsHq = QStringMap(), - const QStringMap &_picURLsSt = QStringMap()); - ~CardInfo(); - const QString &getName() const { return name; } - bool getIsToken() const { return isToken; } - const SetList &getSets() const { return sets; } - const QString &getManaCost() const { return manacost; } - const QString &getCardType() const { return cardtype; } - const QString &getPowTough() const { return powtough; } - const QString &getText() const { return text; } - const int &getLoyalty() const { return loyalty; } - bool getCipt() const { return cipt; } - void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); } - void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); } - void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); } - void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); } - void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); } - const QStringList &getColors() const { return colors; } - QString getPicURL(const QString &set) const { return picURLs.value(set); } - QString getPicURLHq(const QString &set) const { return picURLsHq.value(set); } - QString getPicURLSt(const QString &set) const { return picURLsSt.value(set); } - QString getPicURL() const; - const QMap &getPicURLs() const { return picURLs; } - QString getMainCardType() const; - QString getCorrectedName() const; - int getTableRow() const { return tableRow; } - void setTableRow(int _tableRow) { tableRow = _tableRow; } - void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); } - void setPicURL(const QString &_set, const QString &_picURL) { picURLs.insert(_set, _picURL); } - void setPicURLHq(const QString &_set, const QString &_picURL) { picURLsHq.insert(_set, _picURL); } - void setPicURLSt(const QString &_set, const QString &_picURL) { picURLsSt.insert(_set, _picURL); } - void addToSet(CardSet *set); - QPixmap *loadPixmap(); - QPixmap *getPixmap(QSize size); - void clearPixmapCache(); - void clearPixmapCacheMiss(); - void imageLoaded(const QImage &image); + CardInfo(CardDatabase *_db, + const QString &_name = QString(), + bool _isToken = false, + const QString &_manacost = QString(), + const QString &_cardtype = QString(), + const QString &_powtough = QString(), + const QString &_text = QString(), + const QStringList &_colors = QStringList(), + int _loyalty = 0, + bool _cipt = false, + int _tableRow = 0, + const SetList &_sets = SetList(), + const QStringMap &_picURLs = QStringMap(), + const QStringMap &_picURLsHq = QStringMap(), + const QStringMap &_picURLsSt = QStringMap()); + ~CardInfo(); + const QString &getName() const { return name; } + bool getIsToken() const { return isToken; } + const SetList &getSets() const { return sets; } + const QString &getManaCost() const { return manacost; } + const QString &getCardType() const { return cardtype; } + const QString &getPowTough() const { return powtough; } + const QString &getText() const { return text; } + const int &getLoyalty() const { return loyalty; } + bool getCipt() const { return cipt; } + void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); } + void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); } + void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); } + void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); } + void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); } + const QStringList &getColors() const { return colors; } + QString getPicURL(const QString &set) const { return picURLs.value(set); } + QString getPicURLHq(const QString &set) const { return picURLsHq.value(set); } + QString getPicURLSt(const QString &set) const { return picURLsSt.value(set); } + QString getPicURL() const; + const QMap &getPicURLs() const { return picURLs; } + QString getMainCardType() const; + QString getCorrectedName() const; + int getTableRow() const { return tableRow; } + void setTableRow(int _tableRow) { tableRow = _tableRow; } + void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); } + void setPicURL(const QString &_set, const QString &_picURL) { picURLs.insert(_set, _picURL); } + void setPicURLHq(const QString &_set, const QString &_picURL) { picURLsHq.insert(_set, _picURL); } + void setPicURLSt(const QString &_set, const QString &_picURL) { picURLsSt.insert(_set, _picURL); } + void addToSet(CardSet *set); + QPixmap *loadPixmap(); + QPixmap *getPixmap(QSize size); + void clearPixmapCache(); + void clearPixmapCacheMiss(); + void imageLoaded(const QImage &image); public slots: - void updatePixmapCache(); + void updatePixmapCache(); signals: - void pixmapUpdated(); - void cardInfoChanged(CardInfo *card); + void pixmapUpdated(); + void cardInfoChanged(CardInfo *card); }; class CardDatabase : public QObject { - Q_OBJECT + Q_OBJECT protected: - QHash cardHash; - QHash setHash; - bool loadSuccess; - CardInfo *noCard; - - QThread *pictureLoaderThread; - PictureLoader *pictureLoader; + QHash cardHash; + QHash setHash; + bool loadSuccess; + CardInfo *noCard; + + QThread *pictureLoaderThread; + PictureLoader *pictureLoader; private: - static const int versionNeeded; - void loadCardsFromXml(QXmlStreamReader &xml); - void loadSetsFromXml(QXmlStreamReader &xml); + static const int versionNeeded; + void loadCardsFromXml(QXmlStreamReader &xml); + void loadSetsFromXml(QXmlStreamReader &xml); public: - CardDatabase(QObject *parent = 0); - ~CardDatabase(); - void clear(); - void addCard(CardInfo *card); - void removeCard(CardInfo *card); - CardInfo *getCard(const QString &cardName = QString(), bool createIfNotFound = true); - CardSet *getSet(const QString &setName); - QList getCardList() const { return cardHash.values(); } - SetList getSetList() const; - bool loadFromFile(const QString &fileName, bool tokens = false); - bool saveToFile(const QString &fileName, bool tokens = false); - QStringList getAllColors() const; - QStringList getAllMainCardTypes() const; - bool getLoadSuccess() const { return loadSuccess; } - void cacheCardPixmaps(const QStringList &cardNames); - void loadImage(CardInfo *card); + CardDatabase(QObject *parent = 0); + ~CardDatabase(); + void clear(); + void addCard(CardInfo *card); + void removeCard(CardInfo *card); + CardInfo *getCard(const QString &cardName = QString(), bool createIfNotFound = true); + CardSet *getSet(const QString &setName); + QList getCardList() const { return cardHash.values(); } + SetList getSetList() const; + bool loadFromFile(const QString &fileName, bool tokens = false); + bool saveToFile(const QString &fileName, bool tokens = false); + QStringList getAllColors() const; + QStringList getAllMainCardTypes() const; + bool getLoadSuccess() const { return loadSuccess; } + void cacheCardPixmaps(const QStringList &cardNames); + void loadImage(CardInfo *card); public slots: - void clearPixmapCache(); - bool loadCardDatabase(const QString &path, bool tokens = false); + void clearPixmapCache(); + bool loadCardDatabase(const QString &path, bool tokens = false); private slots: - void imageLoaded(CardInfo *card, QImage image); - void picDownloadChanged(); - void picsPathChanged(); - - void loadCardDatabase(); - void loadTokenDatabase(); + void imageLoaded(CardInfo *card, QImage image); + void picDownloadChanged(); + void picsPathChanged(); + + void loadCardDatabase(); + void loadTokenDatabase(); signals: - void cardListChanged(); - void cardAdded(CardInfo *card); - void cardRemoved(CardInfo *card); + void cardListChanged(); + void cardAdded(CardInfo *card); + void cardRemoved(CardInfo *card); }; #endif diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index d63f6bde..08051764 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -1,12 +1,12 @@ #include "carddatabasemodel.h" CardDatabaseModel::CardDatabaseModel(CardDatabase *_db, QObject *parent) - : QAbstractListModel(parent), db(_db) + : QAbstractListModel(parent), db(_db) { - connect(db, SIGNAL(cardListChanged()), this, SLOT(updateCardList())); - connect(db, SIGNAL(cardAdded(CardInfo *)), this, SLOT(cardAdded(CardInfo *))); - connect(db, SIGNAL(cardRemoved(CardInfo *)), this, SLOT(cardRemoved(CardInfo *))); - updateCardList(); + connect(db, SIGNAL(cardListChanged()), this, SLOT(updateCardList())); + connect(db, SIGNAL(cardAdded(CardInfo *)), this, SLOT(cardAdded(CardInfo *))); + connect(db, SIGNAL(cardRemoved(CardInfo *)), this, SLOT(cardRemoved(CardInfo *))); + updateCardList(); } CardDatabaseModel::~CardDatabaseModel() @@ -15,143 +15,143 @@ CardDatabaseModel::~CardDatabaseModel() int CardDatabaseModel::rowCount(const QModelIndex &/*parent*/) const { - return cardList.size(); + return cardList.size(); } int CardDatabaseModel::columnCount(const QModelIndex &/*parent*/) const { - return 5; + return 5; } QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if ((index.row() >= cardList.size()) || (index.column() >= 5)) - return QVariant(); - if (role != Qt::DisplayRole) - return QVariant(); + if (!index.isValid()) + return QVariant(); + if ((index.row() >= cardList.size()) || (index.column() >= 5)) + return QVariant(); + if (role != Qt::DisplayRole) + return QVariant(); - CardInfo *card = cardList.at(index.row()); - switch (index.column()){ - case 0: return card->getName(); - case 1: { - QStringList setList; - const QList &sets = card->getSets(); - for (int i = 0; i < sets.size(); i++) - setList << sets[i]->getShortName(); - return setList.join(", "); - } - case 2: return card->getManaCost(); - case 3: return card->getCardType(); - case 4: return card->getPowTough(); - default: return QVariant(); - } + CardInfo *card = cardList.at(index.row()); + switch (index.column()){ + case 0: return card->getName(); + case 1: { + QStringList setList; + const QList &sets = card->getSets(); + for (int i = 0; i < sets.size(); i++) + setList << sets[i]->getShortName(); + return setList.join(", "); + } + case 2: return card->getManaCost(); + case 3: return card->getCardType(); + case 4: return card->getPowTough(); + default: return QVariant(); + } } QVariant CardDatabaseModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole) - return QVariant(); - if (orientation != Qt::Horizontal) - return QVariant(); - switch (section) { - case 0: return QString(tr("Name")); - case 1: return QString(tr("Sets")); - case 2: return QString(tr("Mana cost")); - case 3: return QString(tr("Card type")); - case 4: return QString(tr("P/T")); - default: return QVariant(); - } + if (role != Qt::DisplayRole) + return QVariant(); + if (orientation != Qt::Horizontal) + return QVariant(); + switch (section) { + case 0: return QString(tr("Name")); + case 1: return QString(tr("Sets")); + case 2: return QString(tr("Mana cost")); + case 3: return QString(tr("Card type")); + case 4: return QString(tr("P/T")); + default: return QVariant(); + } } void CardDatabaseModel::updateCardList() { - for (int i = 0; i < cardList.size(); ++i) - disconnect(cardList[i], 0, this, 0); - - cardList = db->getCardList(); - for (int i = 0; i < cardList.size(); ++i) - connect(cardList[i], SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); - - reset(); + for (int i = 0; i < cardList.size(); ++i) + disconnect(cardList[i], 0, this, 0); + + cardList = db->getCardList(); + for (int i = 0; i < cardList.size(); ++i) + connect(cardList[i], SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); + + reset(); } void CardDatabaseModel::cardInfoChanged(CardInfo *card) { - const int row = cardList.indexOf(card); - if (row == -1) - return; - - emit dataChanged(index(row, 0), index(row, 4)); + const int row = cardList.indexOf(card); + if (row == -1) + return; + + emit dataChanged(index(row, 0), index(row, 4)); } void CardDatabaseModel::cardAdded(CardInfo *card) { - beginInsertRows(QModelIndex(), cardList.size(), cardList.size()); - cardList.append(card); - connect(card, SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); - endInsertRows(); + beginInsertRows(QModelIndex(), cardList.size(), cardList.size()); + cardList.append(card); + connect(card, SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); + endInsertRows(); } void CardDatabaseModel::cardRemoved(CardInfo *card) { - const int row = cardList.indexOf(card); - if (row == -1) - return; - - beginRemoveRows(QModelIndex(), row, row); - cardList.removeAt(row); - endRemoveRows(); + const int row = cardList.indexOf(card); + if (row == -1) + return; + + beginRemoveRows(QModelIndex(), row, row); + cardList.removeAt(row); + endRemoveRows(); } CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) - : QSortFilterProxyModel(parent), - isToken(ShowAll) + : QSortFilterProxyModel(parent), + isToken(ShowAll) { - setFilterCaseSensitivity(Qt::CaseInsensitive); - setSortCaseSensitivity(Qt::CaseInsensitive); + setFilterCaseSensitivity(Qt::CaseInsensitive); + setSortCaseSensitivity(Qt::CaseInsensitive); } bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { - CardInfo const *info = static_cast(sourceModel())->getCard(sourceRow); - - if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) - return false; - - if (!cardNameBeginning.isEmpty()) - if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive)) - return false; - - if (!cardName.isEmpty()) - if (!info->getName().contains(cardName, Qt::CaseInsensitive)) - return false; - - if (!cardNameSet.isEmpty()) - if (!cardNameSet.contains(info->getName())) - return false; - - if (!cardText.isEmpty()) - if (!info->getText().contains(cardText, Qt::CaseInsensitive)) - return false; - - if (!cardColors.isEmpty()) - if (QSet::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X"))) - return false; - - if (!cardTypes.isEmpty()) - if (!cardTypes.contains(info->getMainCardType())) - return false; + CardInfo const *info = static_cast(sourceModel())->getCard(sourceRow); + + if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) + return false; + + if (!cardNameBeginning.isEmpty()) + if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive)) + return false; + + if (!cardName.isEmpty()) + if (!info->getName().contains(cardName, Qt::CaseInsensitive)) + return false; + + if (!cardNameSet.isEmpty()) + if (!cardNameSet.contains(info->getName())) + return false; + + if (!cardText.isEmpty()) + if (!info->getText().contains(cardText, Qt::CaseInsensitive)) + return false; + + if (!cardColors.isEmpty()) + if (QSet::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X"))) + return false; + + if (!cardTypes.isEmpty()) + if (!cardTypes.contains(info->getMainCardType())) + return false; - return true; + return true; } void CardDatabaseDisplayModel::clearSearch() { - cardName.clear(); - cardText.clear(); - cardTypes.clear(); - cardColors.clear(); - invalidateFilter(); + cardName.clear(); + cardText.clear(); + cardTypes.clear(); + cardColors.clear(); + invalidateFilter(); } diff --git a/cockatrice/src/carddatabasemodel.h b/cockatrice/src/carddatabasemodel.h index b2998bfe..51c9467b 100644 --- a/cockatrice/src/carddatabasemodel.h +++ b/cockatrice/src/carddatabasemodel.h @@ -8,46 +8,46 @@ #include "carddatabase.h" class CardDatabaseModel : public QAbstractListModel { - Q_OBJECT + Q_OBJECT public: - CardDatabaseModel(CardDatabase *_db, QObject *parent = 0); - ~CardDatabaseModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - CardDatabase *getDatabase() const { return db; } - CardInfo *getCard(int index) const { return cardList[index]; } + CardDatabaseModel(CardDatabase *_db, QObject *parent = 0); + ~CardDatabaseModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + CardDatabase *getDatabase() const { return db; } + CardInfo *getCard(int index) const { return cardList[index]; } private: - QList cardList; - CardDatabase *db; + QList cardList; + CardDatabase *db; private slots: - void updateCardList(); - void cardAdded(CardInfo *card); - void cardRemoved(CardInfo *card); - void cardInfoChanged(CardInfo *card); + void updateCardList(); + void cardAdded(CardInfo *card); + void cardRemoved(CardInfo *card); + void cardInfoChanged(CardInfo *card); }; class CardDatabaseDisplayModel : public QSortFilterProxyModel { - Q_OBJECT + Q_OBJECT public: - enum FilterBool { ShowTrue, ShowFalse, ShowAll }; + enum FilterBool { ShowTrue, ShowFalse, ShowAll }; private: - FilterBool isToken; - QString cardNameBeginning, cardName, cardText; - QSet cardNameSet, cardTypes, cardColors; + FilterBool isToken; + QString cardNameBeginning, cardName, cardText; + QSet cardNameSet, cardTypes, cardColors; public: - CardDatabaseDisplayModel(QObject *parent = 0); - void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } - void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } - void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } - void setCardNameSet(const QSet &_cardNameSet) { cardNameSet = _cardNameSet; invalidate(); } - void setCardText(const QString &_cardText) { cardText = _cardText; invalidate(); } - void setCardTypes(const QSet &_cardTypes) { cardTypes = _cardTypes; invalidate(); } - void setCardColors(const QSet &_cardColors) { cardColors = _cardColors; invalidate(); } - void clearSearch(); + CardDatabaseDisplayModel(QObject *parent = 0); + void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } + void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } + void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } + void setCardNameSet(const QSet &_cardNameSet) { cardNameSet = _cardNameSet; invalidate(); } + void setCardText(const QString &_cardText) { cardText = _cardText; invalidate(); } + void setCardTypes(const QSet &_cardTypes) { cardTypes = _cardTypes; invalidate(); } + void setCardColors(const QSet &_cardColors) { cardColors = _cardColors; invalidate(); } + void clearSearch(); protected: - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; #endif diff --git a/cockatrice/src/carddragitem.cpp b/cockatrice/src/carddragitem.cpp index 8df7790b..0ddb9109 100644 --- a/cockatrice/src/carddragitem.cpp +++ b/cockatrice/src/carddragitem.cpp @@ -9,82 +9,82 @@ #include CardDragItem::CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag) - : AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0) + : AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0) { } void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - AbstractCardDragItem::paint(painter, option, widget); - - if (occupied) - painter->fillRect(boundingRect(), QColor(200, 0, 0, 100)); + AbstractCardDragItem::paint(painter, option, widget); + + if (occupied) + painter->fillRect(boundingRect(), QColor(200, 0, 0, 100)); } void CardDragItem::updatePosition(const QPointF &cursorScenePos) { - QList colliding = scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, static_cast(scene())->getViewTransform()); + QList colliding = scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, static_cast(scene())->getViewTransform()); - CardZone *cardZone = 0; - ZoneViewZone *zoneViewZone = 0; - for (int i = colliding.size() - 1; i >= 0; i--) { - CardZone *temp = qgraphicsitem_cast(colliding.at(i)); - if (!cardZone) - cardZone = temp; - if (!zoneViewZone) - zoneViewZone = qobject_cast(temp); - } - CardZone *cursorZone = 0; - if (zoneViewZone) - cursorZone = zoneViewZone; - else if (cardZone) - cursorZone = cardZone; - if (!cursorZone) - return; - currentZone = cursorZone; - - QPointF zonePos = currentZone->scenePos(); - QPointF cursorPosInZone = cursorScenePos - zonePos; - QPointF cardTopLeft = cursorPosInZone - hotSpot; - QPointF closestGridPoint = cursorZone->closestGridPoint(cardTopLeft); - QPointF newPos = zonePos + closestGridPoint; - - if (newPos != pos()) { - for (int i = 0; i < childDrags.size(); i++) - childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); - setPos(newPos); - - bool newOccupied = false; - TableZone *table = qobject_cast(cursorZone); - if (table) - if (table->getCardFromCoords(closestGridPoint)) - newOccupied = true; - if (newOccupied != occupied) { - occupied = newOccupied; - update(); - } - } + CardZone *cardZone = 0; + ZoneViewZone *zoneViewZone = 0; + for (int i = colliding.size() - 1; i >= 0; i--) { + CardZone *temp = qgraphicsitem_cast(colliding.at(i)); + if (!cardZone) + cardZone = temp; + if (!zoneViewZone) + zoneViewZone = qobject_cast(temp); + } + CardZone *cursorZone = 0; + if (zoneViewZone) + cursorZone = zoneViewZone; + else if (cardZone) + cursorZone = cardZone; + if (!cursorZone) + return; + currentZone = cursorZone; + + QPointF zonePos = currentZone->scenePos(); + QPointF cursorPosInZone = cursorScenePos - zonePos; + QPointF cardTopLeft = cursorPosInZone - hotSpot; + QPointF closestGridPoint = cursorZone->closestGridPoint(cardTopLeft); + QPointF newPos = zonePos + closestGridPoint; + + if (newPos != pos()) { + for (int i = 0; i < childDrags.size(); i++) + childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); + setPos(newPos); + + bool newOccupied = false; + TableZone *table = qobject_cast(cursorZone); + if (table) + if (table->getCardFromCoords(closestGridPoint)) + newOccupied = true; + if (newOccupied != occupied) { + occupied = newOccupied; + update(); + } + } } void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - setCursor(Qt::OpenHandCursor); - QGraphicsScene *sc = scene(); - QPointF sp = pos(); - sc->removeItem(this); + setCursor(Qt::OpenHandCursor); + QGraphicsScene *sc = scene(); + QPointF sp = pos(); + sc->removeItem(this); - QList dragItemList; - CardZone *startZone = static_cast(item)->getZone(); - if (currentZone && !(static_cast(item)->getAttachedTo() && (startZone == currentZone))) { - dragItemList.append(this); - for (int i = 0; i < childDrags.size(); i++) { - CardDragItem *c = static_cast(childDrags[i]); - if (!(static_cast(c->item)->getAttachedTo() && (startZone == currentZone)) && !c->occupied) - dragItemList.append(c); - sc->removeItem(c); - } - } - currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint()); + QList dragItemList; + CardZone *startZone = static_cast(item)->getZone(); + if (currentZone && !(static_cast(item)->getAttachedTo() && (startZone == currentZone))) { + dragItemList.append(this); + for (int i = 0; i < childDrags.size(); i++) { + CardDragItem *c = static_cast(childDrags[i]); + if (!(static_cast(c->item)->getAttachedTo() && (startZone == currentZone)) && !c->occupied) + dragItemList.append(c); + sc->removeItem(c); + } + } + currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint()); - event->accept(); + event->accept(); } diff --git a/cockatrice/src/carddragitem.h b/cockatrice/src/carddragitem.h index eec2f487..ea81998f 100644 --- a/cockatrice/src/carddragitem.h +++ b/cockatrice/src/carddragitem.h @@ -6,20 +6,20 @@ class CardItem; class CardDragItem : public AbstractCardDragItem { - Q_OBJECT + Q_OBJECT private: - int id; - bool faceDown; - bool occupied; - CardZone *currentZone; + int id; + bool faceDown; + bool occupied; + CardZone *currentZone; public: - CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0); - int getId() const { return id; } - bool getFaceDown() const { return faceDown; } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void updatePosition(const QPointF &cursorScenePos); + CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0); + int getId() const { return id; } + bool getFaceDown() const { return faceDown; } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void updatePosition(const QPointF &cursorScenePos); protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; #endif diff --git a/cockatrice/src/cardinfowidget.cpp b/cockatrice/src/cardinfowidget.cpp index e0ad1b7e..6b5e995a 100644 --- a/cockatrice/src/cardinfowidget.cpp +++ b/cockatrice/src/cardinfowidget.cpp @@ -12,209 +12,209 @@ #include "settingscache.h" CardInfoWidget::CardInfoWidget(ResizeMode _mode, const QString &cardName, QWidget *parent, Qt::WindowFlags flags) - : QFrame(parent, flags) - , pixmapWidth(0) - , aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH) - , minimized(settingsCache->getCardInfoMinimized()) // Initialize the cardinfo view status from cache. - , mode(_mode) - , info(0) + : QFrame(parent, flags) + , pixmapWidth(0) + , aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH) + , minimized(settingsCache->getCardInfoMinimized()) // Initialize the cardinfo view status from cache. + , mode(_mode) + , info(0) { - if (mode == ModeGameTab) { - // Create indexed list of status views for card. - const QStringList cardInfoStatus = QStringList() << tr("Show card only") << tr("Show text only") << tr("Show full info"); - - // Create droplist for cardinfo view selection, and set right current index. - dropList = new QComboBox(); - dropList->addItems(cardInfoStatus); - dropList->setCurrentIndex(minimized); - connect(dropList, SIGNAL(currentIndexChanged(int)), this, SLOT(minimizeClicked(int))); - } + if (mode == ModeGameTab) { + // Create indexed list of status views for card. + const QStringList cardInfoStatus = QStringList() << tr("Show card only") << tr("Show text only") << tr("Show full info"); + + // Create droplist for cardinfo view selection, and set right current index. + dropList = new QComboBox(); + dropList->addItems(cardInfoStatus); + dropList->setCurrentIndex(minimized); + connect(dropList, SIGNAL(currentIndexChanged(int)), this, SLOT(minimizeClicked(int))); + } - cardPicture = new QLabel; - cardPicture->setAlignment(Qt::AlignCenter); + cardPicture = new QLabel; + cardPicture->setAlignment(Qt::AlignCenter); - nameLabel1 = new QLabel; - nameLabel2 = new QLabel; - nameLabel2->setWordWrap(true); - manacostLabel1 = new QLabel; - manacostLabel2 = new QLabel; - manacostLabel2->setWordWrap(true); - cardtypeLabel1 = new QLabel; - cardtypeLabel2 = new QLabel; - cardtypeLabel2->setWordWrap(true); - powtoughLabel1 = new QLabel; - powtoughLabel2 = new QLabel; - loyaltyLabel1 = new QLabel; - loyaltyLabel2 = new QLabel; + nameLabel1 = new QLabel; + nameLabel2 = new QLabel; + nameLabel2->setWordWrap(true); + manacostLabel1 = new QLabel; + manacostLabel2 = new QLabel; + manacostLabel2->setWordWrap(true); + cardtypeLabel1 = new QLabel; + cardtypeLabel2 = new QLabel; + cardtypeLabel2->setWordWrap(true); + powtoughLabel1 = new QLabel; + powtoughLabel2 = new QLabel; + loyaltyLabel1 = new QLabel; + loyaltyLabel2 = new QLabel; - textLabel = new QTextEdit(); - textLabel->setReadOnly(true); + textLabel = new QTextEdit(); + textLabel->setReadOnly(true); - QGridLayout *grid = new QGridLayout(this); - int row = 0; - if (mode == ModeGameTab) - grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight); - grid->addWidget(cardPicture, row++, 0, 1, 2); - grid->addWidget(nameLabel1, row, 0); - grid->addWidget(nameLabel2, row++, 1); - grid->addWidget(manacostLabel1, row, 0); - grid->addWidget(manacostLabel2, row++, 1); - grid->addWidget(cardtypeLabel1, row, 0); - grid->addWidget(cardtypeLabel2, row++, 1); - grid->addWidget(powtoughLabel1, row, 0); - grid->addWidget(powtoughLabel2, row++, 1); - grid->addWidget(loyaltyLabel1, row, 0); - grid->addWidget(loyaltyLabel2, row++, 1); - grid->addWidget(textLabel, row, 0, -1, 2); - grid->setRowStretch(row, 1); - grid->setColumnStretch(1, 1); + QGridLayout *grid = new QGridLayout(this); + int row = 0; + if (mode == ModeGameTab) + grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight); + grid->addWidget(cardPicture, row++, 0, 1, 2); + grid->addWidget(nameLabel1, row, 0); + grid->addWidget(nameLabel2, row++, 1); + grid->addWidget(manacostLabel1, row, 0); + grid->addWidget(manacostLabel2, row++, 1); + grid->addWidget(cardtypeLabel1, row, 0); + grid->addWidget(cardtypeLabel2, row++, 1); + grid->addWidget(powtoughLabel1, row, 0); + grid->addWidget(powtoughLabel2, row++, 1); + grid->addWidget(loyaltyLabel1, row, 0); + grid->addWidget(loyaltyLabel2, row++, 1); + grid->addWidget(textLabel, row, 0, -1, 2); + grid->setRowStretch(row, 1); + grid->setColumnStretch(1, 1); - retranslateUi(); - setFrameStyle(QFrame::Panel | QFrame::Raised); - if (mode == ModeGameTab) { - textLabel->setMinimumHeight(100); - setFixedWidth(sizeHint().width()); - } else if (mode == ModePopUp) { - QDesktopWidget desktopWidget; - pixmapWidth = desktopWidget.screenGeometry().height() / 3 / aspectRatio; - setFixedWidth(pixmapWidth + 150); - } else - setFixedWidth(250); - - setCard(db->getCard(cardName)); - setMinimized(settingsCache->getCardInfoMinimized()); + retranslateUi(); + setFrameStyle(QFrame::Panel | QFrame::Raised); + if (mode == ModeGameTab) { + textLabel->setMinimumHeight(100); + setFixedWidth(sizeHint().width()); + } else if (mode == ModePopUp) { + QDesktopWidget desktopWidget; + pixmapWidth = desktopWidget.screenGeometry().height() / 3 / aspectRatio; + setFixedWidth(pixmapWidth + 150); + } else + setFixedWidth(250); + + setCard(db->getCard(cardName)); + setMinimized(settingsCache->getCardInfoMinimized()); } void CardInfoWidget::minimizeClicked(int newMinimized) { - // Set new status, and store it in the settings cache. - setMinimized(newMinimized); - settingsCache->setCardInfoMinimized(newMinimized); + // Set new status, and store it in the settings cache. + setMinimized(newMinimized); + settingsCache->setCardInfoMinimized(newMinimized); } bool CardInfoWidget::shouldShowPowTough() { -// return (!info->getPowTough().isEmpty() && (minimized != 0)); - return (minimized != 0); +// return (!info->getPowTough().isEmpty() && (minimized != 0)); + return (minimized != 0); } bool CardInfoWidget::shouldShowLoyalty() { -// return ((info->getLoyalty() > 0) && (minimized != 0)); - return (minimized != 0); +// return ((info->getLoyalty() > 0) && (minimized != 0)); + return (minimized != 0); } void CardInfoWidget::setMinimized(int _minimized) { - minimized = _minimized; + minimized = _minimized; - // Toggle oracle fields according to selected view. - bool showAll = ((minimized == 1) || (minimized == 2)); - bool showPowTough = info ? (showAll && shouldShowPowTough()) : true; - bool showLoyalty = info ? (showAll && shouldShowLoyalty()) : true; - if (mode == ModeGameTab) { - nameLabel1->setVisible(showAll); - nameLabel2->setVisible(showAll); - manacostLabel1->setVisible(showAll); - manacostLabel2->setVisible(showAll); - cardtypeLabel1->setVisible(showAll); - cardtypeLabel2->setVisible(showAll); - powtoughLabel1->setVisible(showPowTough); - powtoughLabel2->setVisible(showPowTough); - loyaltyLabel1->setVisible(showLoyalty); - loyaltyLabel2->setVisible(showLoyalty); - textLabel->setVisible(showAll); - } + // Toggle oracle fields according to selected view. + bool showAll = ((minimized == 1) || (minimized == 2)); + bool showPowTough = info ? (showAll && shouldShowPowTough()) : true; + bool showLoyalty = info ? (showAll && shouldShowLoyalty()) : true; + if (mode == ModeGameTab) { + nameLabel1->setVisible(showAll); + nameLabel2->setVisible(showAll); + manacostLabel1->setVisible(showAll); + manacostLabel2->setVisible(showAll); + cardtypeLabel1->setVisible(showAll); + cardtypeLabel2->setVisible(showAll); + powtoughLabel1->setVisible(showPowTough); + powtoughLabel2->setVisible(showPowTough); + loyaltyLabel1->setVisible(showLoyalty); + loyaltyLabel2->setVisible(showLoyalty); + textLabel->setVisible(showAll); + } - cardPicture->hide(); - cardHeightOffset = minimumSizeHint().height() + 10; - - // Set the picture to be shown only at "card only" (0) and "full info" (2) - if (mode == ModeGameTab) { - cardPicture->setVisible((minimized == 0) || (minimized == 2)); + cardPicture->hide(); + cardHeightOffset = minimumSizeHint().height() + 10; + + // Set the picture to be shown only at "card only" (0) and "full info" (2) + if (mode == ModeGameTab) { + cardPicture->setVisible((minimized == 0) || (minimized == 2)); - if (minimized == 0) - setMaximumHeight(cardHeightOffset + width() * aspectRatio); - else - setMaximumHeight(1000000); - } else - cardPicture->show(); - resize(width(), sizeHint().height()); + if (minimized == 0) + setMaximumHeight(cardHeightOffset + width() * aspectRatio); + else + setMaximumHeight(1000000); + } else + cardPicture->show(); + resize(width(), sizeHint().height()); } void CardInfoWidget::setCard(CardInfo *card) { - if (info) - disconnect(info, 0, this, 0); - info = card; - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); - connect(info, SIGNAL(destroyed()), this, SLOT(clear())); + if (info) + disconnect(info, 0, this, 0); + info = card; + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); + connect(info, SIGNAL(destroyed()), this, SLOT(clear())); - updatePixmap(); - nameLabel2->setText(card->getName()); - manacostLabel2->setText(card->getManaCost()); - cardtypeLabel2->setText(card->getCardType()); - powtoughLabel2->setText(card->getPowTough()); - loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); - textLabel->setText(card->getText()); + updatePixmap(); + nameLabel2->setText(card->getName()); + manacostLabel2->setText(card->getManaCost()); + cardtypeLabel2->setText(card->getCardType()); + powtoughLabel2->setText(card->getPowTough()); + loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); + textLabel->setText(card->getText()); - powtoughLabel1->setVisible(shouldShowPowTough()); - powtoughLabel2->setVisible(shouldShowPowTough()); - loyaltyLabel1->setVisible(shouldShowLoyalty()); - loyaltyLabel2->setVisible(shouldShowLoyalty()); + powtoughLabel1->setVisible(shouldShowPowTough()); + powtoughLabel2->setVisible(shouldShowPowTough()); + loyaltyLabel1->setVisible(shouldShowLoyalty()); + loyaltyLabel2->setVisible(shouldShowLoyalty()); } void CardInfoWidget::setCard(const QString &cardName) { - setCard(db->getCard(cardName)); + setCard(db->getCard(cardName)); } void CardInfoWidget::setCard(AbstractCardItem *card) { - setCard(card->getInfo()); + setCard(card->getInfo()); } void CardInfoWidget::clear() { - setCard(db->getCard()); + setCard(db->getCard()); } void CardInfoWidget::updatePixmap() { - if (pixmapWidth == 0) - return; - - QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); - if (resizedPixmap) - cardPicture->setPixmap(*resizedPixmap); - else - cardPicture->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); + if (pixmapWidth == 0) + return; + + QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); + if (resizedPixmap) + cardPicture->setPixmap(*resizedPixmap); + else + cardPicture->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); } void CardInfoWidget::retranslateUi() { - nameLabel1->setText(tr("Name:")); - manacostLabel1->setText(tr("Mana cost:")); - cardtypeLabel1->setText(tr("Card type:")); - powtoughLabel1->setText(tr("P / T:")); - loyaltyLabel1->setText(tr("Loyalty:")); + nameLabel1->setText(tr("Name:")); + manacostLabel1->setText(tr("Mana cost:")); + cardtypeLabel1->setText(tr("Card type:")); + powtoughLabel1->setText(tr("P / T:")); + loyaltyLabel1->setText(tr("Loyalty:")); } void CardInfoWidget::resizeEvent(QResizeEvent * /*event*/) { - if (mode == ModePopUp) - return; - if ((minimized == 1) && (mode == ModeGameTab)) { - pixmapWidth = 0; - return; - } - qreal newPixmapWidth = qMax((qreal) 100.0, qMin((qreal) cardPicture->width(), (qreal) ((height() - cardHeightOffset) / aspectRatio))); - if (newPixmapWidth != pixmapWidth) { - pixmapWidth = newPixmapWidth; - updatePixmap(); - } + if (mode == ModePopUp) + return; + if ((minimized == 1) && (mode == ModeGameTab)) { + pixmapWidth = 0; + return; + } + qreal newPixmapWidth = qMax((qreal) 100.0, qMin((qreal) cardPicture->width(), (qreal) ((height() - cardHeightOffset) / aspectRatio))); + if (newPixmapWidth != pixmapWidth) { + pixmapWidth = newPixmapWidth; + updatePixmap(); + } } QString CardInfoWidget::getCardName() const { - return nameLabel2->text(); + return nameLabel2->text(); } diff --git a/cockatrice/src/cardinfowidget.h b/cockatrice/src/cardinfowidget.h index f04395b3..ecfd6eca 100644 --- a/cockatrice/src/cardinfowidget.h +++ b/cockatrice/src/cardinfowidget.h @@ -14,51 +14,51 @@ class QResizeEvent; class QMouseEvent; class CardInfoWidget : public QFrame { - Q_OBJECT + Q_OBJECT public: - enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp }; + enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp }; private: - int pixmapWidth; - qreal cardHeightOffset; - qreal aspectRatio; - // XXX: Why isn't this an eunm? - int minimized; // 0 - card, 1 - oracle only, 2 - full - ResizeMode mode; + int pixmapWidth; + qreal cardHeightOffset; + qreal aspectRatio; + // XXX: Why isn't this an eunm? + int minimized; // 0 - card, 1 - oracle only, 2 - full + ResizeMode mode; - QComboBox *dropList; - QLabel *cardPicture; - QLabel *nameLabel1, *nameLabel2; - QLabel *manacostLabel1, *manacostLabel2; - QLabel *cardtypeLabel1, *cardtypeLabel2; - QLabel *powtoughLabel1, *powtoughLabel2; - QLabel *loyaltyLabel1, *loyaltyLabel2; - QTextEdit *textLabel; + QComboBox *dropList; + QLabel *cardPicture; + QLabel *nameLabel1, *nameLabel2; + QLabel *manacostLabel1, *manacostLabel2; + QLabel *cardtypeLabel1, *cardtypeLabel2; + QLabel *powtoughLabel1, *powtoughLabel2; + QLabel *loyaltyLabel1, *loyaltyLabel2; + QTextEdit *textLabel; - bool shouldShowPowTough(); - bool shouldShowLoyalty(); + bool shouldShowPowTough(); + bool shouldShowLoyalty(); - CardInfo *info; - void setMinimized(int _minimized); + CardInfo *info; + void setMinimized(int _minimized); public: - CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); - void retranslateUi(); - QString getCardName() const; + CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); + void retranslateUi(); + QString getCardName() const; public slots: - void setCard(CardInfo *card); - void setCard(const QString &cardName); - void setCard(AbstractCardItem *card); + void setCard(CardInfo *card); + void setCard(const QString &cardName); + void setCard(AbstractCardItem *card); private slots: - void clear(); - void updatePixmap(); - void minimizeClicked(int newMinimized); + void clear(); + void updatePixmap(); + void minimizeClicked(int newMinimized); protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); }; #endif diff --git a/cockatrice/src/carditem.cpp b/cockatrice/src/carditem.cpp index a6696198..a6b582ad 100644 --- a/cockatrice/src/carditem.cpp +++ b/cockatrice/src/carditem.cpp @@ -18,374 +18,374 @@ #include "pb/serverinfo_card.pb.h" CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _revealedCard, QGraphicsItem *parent) - : AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0) + : AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0) { - owner->addCard(this); - - cardMenu = new QMenu; - ptMenu = new QMenu; - moveMenu = new QMenu; - - retranslateUi(); - emit updateCardMenu(this); + owner->addCard(this); + + cardMenu = new QMenu; + ptMenu = new QMenu; + moveMenu = new QMenu; + + retranslateUi(); + emit updateCardMenu(this); } CardItem::~CardItem() { - prepareDelete(); - - if (scene()) - static_cast(scene())->unregisterAnimationItem(this); - - delete cardMenu; - delete ptMenu; - delete moveMenu; - - deleteDragItem(); + prepareDelete(); + + if (scene()) + static_cast(scene())->unregisterAnimationItem(this); + + delete cardMenu; + delete ptMenu; + delete moveMenu; + + deleteDragItem(); } void CardItem::prepareDelete() { - if (owner) { - if (owner->getCardMenu() == cardMenu) { - owner->setCardMenu(0); - owner->getGame()->setActiveCard(0); - } - owner = 0; - } - - while (!attachedCards.isEmpty()) { - attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards() - attachedCards.first()->setAttachedTo(0); - } - - if (attachedTo) { - attachedTo->removeAttachedCard(this); - attachedTo = 0; - } + if (owner) { + if (owner->getCardMenu() == cardMenu) { + owner->setCardMenu(0); + owner->getGame()->setActiveCard(0); + } + owner = 0; + } + + while (!attachedCards.isEmpty()) { + attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards() + attachedCards.first()->setAttachedTo(0); + } + + if (attachedTo) { + attachedTo->removeAttachedCard(this); + attachedTo = 0; + } } void CardItem::deleteLater() { - prepareDelete(); - AbstractCardItem::deleteLater(); + prepareDelete(); + AbstractCardItem::deleteLater(); } void CardItem::setZone(CardZone *_zone) { - zone = _zone; - emit updateCardMenu(this); + zone = _zone; + emit updateCardMenu(this); } void CardItem::retranslateUi() { - moveMenu->setTitle(tr("&Move to")); - ptMenu->setTitle(tr("&Power / toughness")); + moveMenu->setTitle(tr("&Move to")); + ptMenu->setTitle(tr("&Power / toughness")); } void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - painter->save(); - AbstractCardItem::paint(painter, option, widget); - - int i = 0; - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) { - counterIterator.next(); - QColor color; - color.setHsv(counterIterator.key() * 60, 150, 255); - - paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter); - ++i; - } - - QSizeF translatedSize = getTranslatedSize(painter); - qreal scaleFactor = translatedSize.width() / boundingRect().width(); - - if (!pt.isEmpty()) { - painter->save(); - - transformPainter(painter, translatedSize, tapAngle); - painter->setBackground(Qt::black); - painter->setBackgroundMode(Qt::OpaqueMode); - painter->setPen(Qt::white); - - painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt); - painter->restore(); - } - if (!annotation.isEmpty()) { - painter->save(); + painter->save(); + AbstractCardItem::paint(painter, option, widget); + + int i = 0; + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) { + counterIterator.next(); + QColor color; + color.setHsv(counterIterator.key() * 60, 150, 255); + + paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter); + ++i; + } + + QSizeF translatedSize = getTranslatedSize(painter); + qreal scaleFactor = translatedSize.width() / boundingRect().width(); + + if (!pt.isEmpty()) { + painter->save(); + + transformPainter(painter, translatedSize, tapAngle); + painter->setBackground(Qt::black); + painter->setBackgroundMode(Qt::OpaqueMode); + painter->setPen(Qt::white); + + painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt); + painter->restore(); + } + if (!annotation.isEmpty()) { + painter->save(); - transformPainter(painter, translatedSize, tapAngle); - painter->setBackground(Qt::black); - painter->setBackgroundMode(Qt::OpaqueMode); - painter->setPen(Qt::white); - - painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation); - painter->restore(); - } - if (getBeingPointedAt()) - painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); - painter->restore(); + transformPainter(painter, translatedSize, tapAngle); + painter->setBackground(Qt::black); + painter->setBackgroundMode(Qt::OpaqueMode); + painter->setPen(Qt::white); + + painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation); + painter->restore(); + } + if (getBeingPointedAt()) + painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); + painter->restore(); } void CardItem::setAttacking(bool _attacking) { - attacking = _attacking; - update(); + attacking = _attacking; + update(); } void CardItem::setCounter(int _id, int _value) { - if (_value) - counters.insert(_id, _value); - else - counters.remove(_id); - update(); + if (_value) + counters.insert(_id, _value); + else + counters.remove(_id); + update(); } void CardItem::setAnnotation(const QString &_annotation) { - annotation = _annotation; - update(); + annotation = _annotation; + update(); } void CardItem::setDoesntUntap(bool _doesntUntap) { - doesntUntap = _doesntUntap; + doesntUntap = _doesntUntap; } void CardItem::setPT(const QString &_pt) { - pt = _pt; - update(); + pt = _pt; + update(); } void CardItem::setAttachedTo(CardItem *_attachedTo) { - if (attachedTo) - attachedTo->removeAttachedCard(this); - - gridPoint.setX(-1); - attachedTo = _attachedTo; - if (attachedTo) { - setParentItem(attachedTo->getZone()); - attachedTo->addAttachedCard(this); - if (zone != attachedTo->getZone()) - attachedTo->getZone()->reorganizeCards(); - } else - setParentItem(zone); + if (attachedTo) + attachedTo->removeAttachedCard(this); + + gridPoint.setX(-1); + attachedTo = _attachedTo; + if (attachedTo) { + setParentItem(attachedTo->getZone()); + attachedTo->addAttachedCard(this); + if (zone != attachedTo->getZone()) + attachedTo->getZone()->reorganizeCards(); + } else + setParentItem(zone); - if (zone) - zone->reorganizeCards(); - - emit updateCardMenu(this); + if (zone) + zone->reorganizeCards(); + + emit updateCardMenu(this); } void CardItem::resetState() { - attacking = false; - facedown = false; - counters.clear(); - pt.clear(); - annotation.clear(); - attachedTo = 0; - attachedCards.clear(); - setTapped(false, false); - setDoesntUntap(false); - if (scene()) - static_cast(scene())->unregisterAnimationItem(this); - update(); + attacking = false; + facedown = false; + counters.clear(); + pt.clear(); + annotation.clear(); + attachedTo = 0; + attachedCards.clear(); + setTapped(false, false); + setDoesntUntap(false); + if (scene()) + static_cast(scene())->unregisterAnimationItem(this); + update(); } void CardItem::processCardInfo(const ServerInfo_Card &info) { - counters.clear(); - const int counterListSize = info.counter_list_size(); - for (int i = 0; i < counterListSize; ++i) { - const ServerInfo_CardCounter &counterInfo = info.counter_list(i); - counters.insert(counterInfo.id(), counterInfo.value()); - } - - setId(info.id()); - setName(QString::fromStdString(info.name())); - setAttacking(info.attacking()); - setFaceDown(info.face_down()); - setPT(QString::fromStdString(info.pt())); - setAnnotation(QString::fromStdString(info.annotation())); - setColor(QString::fromStdString(info.color())); - setTapped(info.tapped()); - setDestroyOnZoneChange(info.destroy_on_zone_change()); - setDoesntUntap(info.doesnt_untap()); + counters.clear(); + const int counterListSize = info.counter_list_size(); + for (int i = 0; i < counterListSize; ++i) { + const ServerInfo_CardCounter &counterInfo = info.counter_list(i); + counters.insert(counterInfo.id(), counterInfo.value()); + } + + setId(info.id()); + setName(QString::fromStdString(info.name())); + setAttacking(info.attacking()); + setFaceDown(info.face_down()); + setPT(QString::fromStdString(info.pt())); + setAnnotation(QString::fromStdString(info.annotation())); + setColor(QString::fromStdString(info.color())); + setTapped(info.tapped()); + setDestroyOnZoneChange(info.destroy_on_zone_change()); + setDoesntUntap(info.doesnt_untap()); } CardDragItem *CardItem::createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown) { - deleteDragItem(); - dragItem = new CardDragItem(this, _id, _pos, faceDown); - dragItem->setVisible(false); - scene()->addItem(dragItem); - dragItem->updatePosition(_scenePos); - dragItem->setVisible(true); + deleteDragItem(); + dragItem = new CardDragItem(this, _id, _pos, faceDown); + dragItem->setVisible(false); + scene()->addItem(dragItem); + dragItem->updatePosition(_scenePos); + dragItem->setVisible(true); - return dragItem; + return dragItem; } void CardItem::deleteDragItem() { - dragItem->deleteLater(); - dragItem = NULL; + dragItem->deleteLater(); + dragItem = NULL; } void CardItem::drawArrow(const QColor &arrowColor) { - if (static_cast(owner->parent())->getSpectator()) - return; - - Player *arrowOwner = static_cast(owner->parent())->getActiveLocalPlayer(); - ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor); - scene()->addItem(arrow); - arrow->grabMouse(); - - QListIterator itemIterator(scene()->selectedItems()); - while (itemIterator.hasNext()) { - CardItem *c = qgraphicsitem_cast(itemIterator.next()); - if (!c || (c == this)) - continue; - if (c->getZone() != zone) - continue; - - ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor); - scene()->addItem(childArrow); - arrow->addChildArrow(childArrow); - } + if (static_cast(owner->parent())->getSpectator()) + return; + + Player *arrowOwner = static_cast(owner->parent())->getActiveLocalPlayer(); + ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor); + scene()->addItem(arrow); + arrow->grabMouse(); + + QListIterator itemIterator(scene()->selectedItems()); + while (itemIterator.hasNext()) { + CardItem *c = qgraphicsitem_cast(itemIterator.next()); + if (!c || (c == this)) + continue; + if (c->getZone() != zone) + continue; + + ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor); + scene()->addItem(childArrow); + arrow->addChildArrow(childArrow); + } } void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (event->buttons().testFlag(Qt::RightButton)) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) - return; - - QColor arrowColor = Qt::red; - if (event->modifiers().testFlag(Qt::ControlModifier)) - arrowColor = Qt::yellow; - else if (event->modifiers().testFlag(Qt::AltModifier)) - arrowColor = Qt::blue; - else if (event->modifiers().testFlag(Qt::ShiftModifier)) - arrowColor = Qt::green; - - drawArrow(arrowColor); - } else if (event->buttons().testFlag(Qt::LeftButton)) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) - return; - if (zone->getIsView()) { - const ZoneViewZone *const view = static_cast(zone); - if (view->getRevealZone() && !view->getWriteableRevealZone()) - return; - } else if (!owner->getLocal()) - return; - - bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); - - createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown); - dragItem->grabMouse(); - - QList sel = scene()->selectedItems(); - int j = 0; - for (int i = 0; i < sel.size(); i++) { - CardItem *c = (CardItem *) sel.at(i); - if ((c == this) || (c->getZone() != zone)) - continue; - ++j; - QPointF childPos; - if (zone->getHasCardAttr()) - childPos = c->pos() - pos(); - else - childPos = QPointF(j * CARD_WIDTH / 2, 0); - CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem); - drag->setPos(dragItem->pos() + childPos); - scene()->addItem(drag); - } - } - setCursor(Qt::OpenHandCursor); + if (event->buttons().testFlag(Qt::RightButton)) { + if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + return; + + QColor arrowColor = Qt::red; + if (event->modifiers().testFlag(Qt::ControlModifier)) + arrowColor = Qt::yellow; + else if (event->modifiers().testFlag(Qt::AltModifier)) + arrowColor = Qt::blue; + else if (event->modifiers().testFlag(Qt::ShiftModifier)) + arrowColor = Qt::green; + + drawArrow(arrowColor); + } else if (event->buttons().testFlag(Qt::LeftButton)) { + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + return; + if (zone->getIsView()) { + const ZoneViewZone *const view = static_cast(zone); + if (view->getRevealZone() && !view->getWriteableRevealZone()) + return; + } else if (!owner->getLocal()) + return; + + bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); + + createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown); + dragItem->grabMouse(); + + QList sel = scene()->selectedItems(); + int j = 0; + for (int i = 0; i < sel.size(); i++) { + CardItem *c = (CardItem *) sel.at(i); + if ((c == this) || (c->getZone() != zone)) + continue; + ++j; + QPointF childPos; + if (zone->getHasCardAttr()) + childPos = c->pos() - pos(); + else + childPos = QPointF(j * CARD_WIDTH / 2, 0); + CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem); + drag->setPos(dragItem->pos() + childPos); + scene()->addItem(drag); + } + } + setCursor(Qt::OpenHandCursor); } void CardItem::playCard(bool faceDown) { - // Do nothing if the card belongs to another player - if (!owner->getLocal()) - return; + // Do nothing if the card belongs to another player + if (!owner->getLocal()) + return; - TableZone *tz = qobject_cast(zone); - if (tz) - tz->toggleTapped(); - else - zone->getPlayer()->playCard(this, faceDown, info->getCipt()); + TableZone *tz = qobject_cast(zone); + if (tz) + tz->toggleTapped(); + else + zone->getPlayer()->playCard(this, faceDown, info->getCipt()); } void CardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::RightButton) { - if (cardMenu) - if (!cardMenu->isEmpty()) - cardMenu->exec(event->screenPos()); - } else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) { - - bool hideCard = false; - if (zone->getIsView()) { - ZoneViewZone *view = static_cast(zone); - if (view->getRevealZone() && !view->getWriteableRevealZone()) - hideCard = true; - } - if (hideCard) - zone->removeCard(this); - else - playCard(event->modifiers().testFlag(Qt::ShiftModifier)); - } + if (event->button() == Qt::RightButton) { + if (cardMenu) + if (!cardMenu->isEmpty()) + cardMenu->exec(event->screenPos()); + } else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) { + + bool hideCard = false; + if (zone->getIsView()) { + ZoneViewZone *view = static_cast(zone); + if (view->getRevealZone() && !view->getWriteableRevealZone()) + hideCard = true; + } + if (hideCard) + zone->removeCard(this); + else + playCard(event->modifiers().testFlag(Qt::ShiftModifier)); + } - setCursor(Qt::OpenHandCursor); - AbstractCardItem::mouseReleaseEvent(event); + setCursor(Qt::OpenHandCursor); + AbstractCardItem::mouseReleaseEvent(event); } void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { - if (settingsCache->getDoubleClickToPlay()) { - if (revealedCard) - zone->removeCard(this); - else - playCard(event->modifiers().testFlag(Qt::ShiftModifier)); - } - event->accept(); + if (settingsCache->getDoubleClickToPlay()) { + if (revealedCard) + zone->removeCard(this); + else + playCard(event->modifiers().testFlag(Qt::ShiftModifier)); + } + event->accept(); } bool CardItem::animationEvent() { - int delta = 18; - if (!tapped) - delta *= -1; - - tapAngle += delta; - - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); - setHovered(false); - update(); + int delta = 18; + if (!tapped) + delta *= -1; + + tapAngle += delta; + + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + setHovered(false); + update(); - if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0))) - return false; - return true; + if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0))) + return false; + return true; } QVariant CardItem::itemChange(GraphicsItemChange change, const QVariant &value) { - if ((change == ItemSelectedHasChanged) && owner) { - if (value == true) { - owner->setCardMenu(cardMenu); - owner->getGame()->setActiveCard(this); - } else if (owner->getCardMenu() == cardMenu) { - owner->setCardMenu(0); - owner->getGame()->setActiveCard(0); - } - } - return QGraphicsItem::itemChange(change, value); + if ((change == ItemSelectedHasChanged) && owner) { + if (value == true) { + owner->setCardMenu(cardMenu); + owner->getGame()->setActiveCard(this); + } else if (owner->getCardMenu() == cardMenu) { + owner->setCardMenu(0); + owner->getGame()->setActiveCard(0); + } + } + return QGraphicsItem::itemChange(change, value); } diff --git a/cockatrice/src/carditem.h b/cockatrice/src/carditem.h index 99473f3c..9952550d 100644 --- a/cockatrice/src/carditem.h +++ b/cockatrice/src/carditem.h @@ -14,75 +14,75 @@ class QColor; const int MAX_COUNTERS_ON_CARD = 999; class CardItem : public AbstractCardItem { - Q_OBJECT + Q_OBJECT private: - CardZone *zone; - bool revealedCard; - bool attacking; - QMap counters; - QString annotation; - QString pt; - bool destroyOnZoneChange; - bool doesntUntap; - QPoint gridPoint; - CardDragItem *dragItem; - CardItem *attachedTo; - QList attachedCards; - - QMenu *cardMenu, *ptMenu, *moveMenu; + CardZone *zone; + bool revealedCard; + bool attacking; + QMap counters; + QString annotation; + QString pt; + bool destroyOnZoneChange; + bool doesntUntap; + QPoint gridPoint; + CardDragItem *dragItem; + CardItem *attachedTo; + QList attachedCards; + + QMenu *cardMenu, *ptMenu, *moveMenu; - void prepareDelete(); + void prepareDelete(); public slots: - void deleteLater(); + void deleteLater(); public: - enum { Type = typeCard }; - int type() const { return Type; } - CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0); - ~CardItem(); - void retranslateUi(); - CardZone *getZone() const { return zone; } - void setZone(CardZone *_zone); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QPoint getGridPoint() const { return gridPoint; } - void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; } - QPoint getGridPos() const { return gridPoint; } - Player *getOwner() const { return owner; } - void setOwner(Player *_owner) { owner = _owner; } - bool getRevealedCard() const { return revealedCard; } - bool getAttacking() const { return attacking; } - void setAttacking(bool _attacking); - const QMap &getCounters() const { return counters; } - void setCounter(int _id, int _value); - QString getAnnotation() const { return annotation; } - void setAnnotation(const QString &_annotation); - bool getDoesntUntap() const { return doesntUntap; } - void setDoesntUntap(bool _doesntUntap); - QString getPT() const { return pt; } - void setPT(const QString &_pt); - bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } - void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } - CardItem *getAttachedTo() const { return attachedTo; } - void setAttachedTo(CardItem *_attachedTo); - void addAttachedCard(CardItem *card) { attachedCards.append(card); } - void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } - const QList &getAttachedCards() const { return attachedCards; } - void resetState(); - void processCardInfo(const ServerInfo_Card &info); + enum { Type = typeCard }; + int type() const { return Type; } + CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0); + ~CardItem(); + void retranslateUi(); + CardZone *getZone() const { return zone; } + void setZone(CardZone *_zone); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QPoint getGridPoint() const { return gridPoint; } + void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; } + QPoint getGridPos() const { return gridPoint; } + Player *getOwner() const { return owner; } + void setOwner(Player *_owner) { owner = _owner; } + bool getRevealedCard() const { return revealedCard; } + bool getAttacking() const { return attacking; } + void setAttacking(bool _attacking); + const QMap &getCounters() const { return counters; } + void setCounter(int _id, int _value); + QString getAnnotation() const { return annotation; } + void setAnnotation(const QString &_annotation); + bool getDoesntUntap() const { return doesntUntap; } + void setDoesntUntap(bool _doesntUntap); + QString getPT() const { return pt; } + void setPT(const QString &_pt); + bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } + void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } + CardItem *getAttachedTo() const { return attachedTo; } + void setAttachedTo(CardItem *_attachedTo); + void addAttachedCard(CardItem *card) { attachedCards.append(card); } + void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } + const QList &getAttachedCards() const { return attachedCards; } + void resetState(); + void processCardInfo(const ServerInfo_Card &info); - QMenu *getCardMenu() const { return cardMenu; } - QMenu *getPTMenu() const { return ptMenu; } - QMenu *getMoveMenu() const { return moveMenu; } - - bool animationEvent(); - CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown); - void deleteDragItem(); - void drawArrow(const QColor &arrowColor); - void playCard(bool faceDown); + QMenu *getCardMenu() const { return cardMenu; } + QMenu *getPTMenu() const { return ptMenu; } + QMenu *getMoveMenu() const { return moveMenu; } + + bool animationEvent(); + CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown); + void deleteDragItem(); + void drawArrow(const QColor &arrowColor); + void playCard(bool faceDown); protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - QVariant itemChange(GraphicsItemChange change, const QVariant &value); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); }; #endif diff --git a/cockatrice/src/cardlist.cpp b/cockatrice/src/cardlist.cpp index e4d809ef..34466265 100644 --- a/cockatrice/src/cardlist.cpp +++ b/cockatrice/src/cardlist.cpp @@ -3,57 +3,57 @@ #include "carddatabase.h" CardList::CardList(bool _contentsKnown) - : QList(), contentsKnown(_contentsKnown) + : QList(), contentsKnown(_contentsKnown) { } CardItem *CardList::findCard(const int id, const bool remove, int *position) { - if (!contentsKnown) { - if (empty()) - return 0; - CardItem *temp = at(0); - if (remove) - removeAt(0); - if (position) - *position = id; - return temp; - } else - for (int i = 0; i < size(); i++) { - CardItem *temp = at(i); - if (temp->getId() == id) { - if (remove) - removeAt(i); - if (position) - *position = i; - return temp; - } - } - return 0; + if (!contentsKnown) { + if (empty()) + return 0; + CardItem *temp = at(0); + if (remove) + removeAt(0); + if (position) + *position = id; + return temp; + } else + for (int i = 0; i < size(); i++) { + CardItem *temp = at(i); + if (temp->getId() == id) { + if (remove) + removeAt(i); + if (position) + *position = i; + return temp; + } + } + return 0; } class CardList::compareFunctor { private: - int flags; + int flags; public: - compareFunctor(int _flags) : flags(_flags) - { - } - inline bool operator()(CardItem *a, CardItem *b) const - { - if (flags & SortByType) { - QString t1 = a->getInfo()->getMainCardType(); - QString t2 = b->getInfo()->getMainCardType(); - if ((t1 == t2) && (flags & SortByName)) - return a->getName() < b->getName(); - return t1 < t2; - } else - return a->getName() < b->getName(); - } + compareFunctor(int _flags) : flags(_flags) + { + } + inline bool operator()(CardItem *a, CardItem *b) const + { + if (flags & SortByType) { + QString t1 = a->getInfo()->getMainCardType(); + QString t2 = b->getInfo()->getMainCardType(); + if ((t1 == t2) && (flags & SortByName)) + return a->getName() < b->getName(); + return t1 < t2; + } else + return a->getName() < b->getName(); + } }; void CardList::sort(int flags) { - compareFunctor cf(flags); - qSort(begin(), end(), cf); + compareFunctor cf(flags); + qSort(begin(), end(), cf); } diff --git a/cockatrice/src/cardlist.h b/cockatrice/src/cardlist.h index 101973af..d148ca6d 100644 --- a/cockatrice/src/cardlist.h +++ b/cockatrice/src/cardlist.h @@ -7,15 +7,15 @@ class CardItem; class CardList : public QList { private: - class compareFunctor; + class compareFunctor; protected: - bool contentsKnown; + bool contentsKnown; public: - enum SortFlags { SortByName = 1, SortByType = 2 }; - CardList(bool _contentsKnown); - CardItem *findCard(const int id, const bool remove, int *position = NULL); - bool getContentsKnown() const { return contentsKnown; } - void sort(int flags = SortByName); + enum SortFlags { SortByName = 1, SortByType = 2 }; + CardList(bool _contentsKnown); + CardItem *findCard(const int id, const bool remove, int *position = NULL); + bool getContentsKnown() const { return contentsKnown; } + void sort(int flags = SortByName); }; #endif diff --git a/cockatrice/src/cardzone.h b/cockatrice/src/cardzone.h index 0da4d251..adaf0141 100644 --- a/cockatrice/src/cardzone.h +++ b/cockatrice/src/cardzone.h @@ -14,56 +14,56 @@ class QPainter; class CardDragItem; class CardZone : public AbstractGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - Player *player; - QString name; - CardList cards; - ZoneViewZone *view; - QMenu *menu; - QAction *doubleClickAction; - bool hasCardAttr; - bool isShufflable; - bool isView; - bool alwaysRevealTopCard; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - virtual void addCardImpl(CardItem *card, int x, int y) = 0; + Player *player; + QString name; + CardList cards; + ZoneViewZone *view; + QMenu *menu; + QAction *doubleClickAction; + bool hasCardAttr; + bool isShufflable; + bool isView; + bool alwaysRevealTopCard; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + virtual void addCardImpl(CardItem *card, int x, int y) = 0; signals: - void cardCountChanged(); + void cardCountChanged(); public slots: - void moveAllToZone(); - bool showContextMenu(const QPoint &screenPos); + void moveAllToZone(); + bool showContextMenu(const QPoint &screenPos); public: - enum { Type = typeZone }; - int type() const { return Type; } - virtual void handleDropEvent(const QList &dragItem, CardZone *startZone, const QPoint &dropPoint) = 0; - CardZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool _isView = false); - ~CardZone(); - void retranslateUi(); - void clearContents(); - bool getHasCardAttr() const { return hasCardAttr; } - bool getIsShufflable() const { return isShufflable; } - QMenu *getMenu() const { return menu; } - void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; } - QString getName() const { return name; } - QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const; - Player *getPlayer() const { return player; } - bool contentsKnown() const { return cards.getContentsKnown(); } - const CardList &getCards() const { return cards; } - void addCard(CardItem *card, bool reorganize, int x, int y = -1); - // getCard() finds a card by id. - CardItem *getCard(int cardId, const QString &cardName); - // takeCard() finds a card by position and removes it from the zone and from all of its views. - virtual CardItem *takeCard(int position, int cardId, bool canResize = true); - void removeCard(CardItem *card); - ZoneViewZone *getView() const { return view; } - void setView(ZoneViewZone *_view) { view = _view; } - virtual void reorganizeCards() = 0; - virtual QPointF closestGridPoint(const QPointF &point); - bool getIsView() const { return isView; } - bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } - void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } + enum { Type = typeZone }; + int type() const { return Type; } + virtual void handleDropEvent(const QList &dragItem, CardZone *startZone, const QPoint &dropPoint) = 0; + CardZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool _isView = false); + ~CardZone(); + void retranslateUi(); + void clearContents(); + bool getHasCardAttr() const { return hasCardAttr; } + bool getIsShufflable() const { return isShufflable; } + QMenu *getMenu() const { return menu; } + void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; } + QString getName() const { return name; } + QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const; + Player *getPlayer() const { return player; } + bool contentsKnown() const { return cards.getContentsKnown(); } + const CardList &getCards() const { return cards; } + void addCard(CardItem *card, bool reorganize, int x, int y = -1); + // getCard() finds a card by id. + CardItem *getCard(int cardId, const QString &cardName); + // takeCard() finds a card by position and removes it from the zone and from all of its views. + virtual CardItem *takeCard(int position, int cardId, bool canResize = true); + void removeCard(CardItem *card); + ZoneViewZone *getView() const { return view; } + void setView(ZoneViewZone *_view) { view = _view; } + virtual void reorganizeCards() = 0; + virtual QPointF closestGridPoint(const QPointF &point); + bool getIsView() const { return isView; } + bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } + void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } }; #endif diff --git a/cockatrice/src/chatview.cpp b/cockatrice/src/chatview.cpp index 376a6fd1..ae157647 100644 --- a/cockatrice/src/chatview.cpp +++ b/cockatrice/src/chatview.cpp @@ -10,256 +10,256 @@ #include "pixmapgenerator.h" ChatView::ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent) - : QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing) + : QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing) { - document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }"); - userContextMenu = new UserContextMenu(tabSupervisor, this, game); - connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - - viewport()->setCursor(Qt::IBeamCursor); - setReadOnly(true); - setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); - setOpenLinks(false); - connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &))); + document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }"); + userContextMenu = new UserContextMenu(tabSupervisor, this, game); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + + viewport()->setCursor(Qt::IBeamCursor); + setReadOnly(true); + setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); + setOpenLinks(false); + connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &))); } void ChatView::retranslateUi() { - userContextMenu->retranslateUi(); + userContextMenu->retranslateUi(); } QTextCursor ChatView::prepareBlock(bool same) { - lastSender.clear(); - - QTextCursor cursor(document()->lastBlock()); - cursor.movePosition(QTextCursor::End); - if (!same) { - QTextBlockFormat blockFormat; - if ((evenNumber = !evenNumber)) - blockFormat.setBackground(palette().alternateBase()); - blockFormat.setBottomMargin(2); - cursor.insertBlock(blockFormat); - } else - cursor.insertHtml("
"); - - return cursor; + lastSender.clear(); + + QTextCursor cursor(document()->lastBlock()); + cursor.movePosition(QTextCursor::End); + if (!same) { + QTextBlockFormat blockFormat; + if ((evenNumber = !evenNumber)) + blockFormat.setBackground(palette().alternateBase()); + blockFormat.setBottomMargin(2); + cursor.insertBlock(blockFormat); + } else + cursor.insertHtml("
"); + + return cursor; } void ChatView::appendHtml(const QString &html) { - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); - prepareBlock().insertHtml(html); - if (atBottom) - verticalScrollBar()->setValue(verticalScrollBar()->maximum()); + bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + prepareBlock().insertHtml(html); + if (atBottom) + verticalScrollBar()->setValue(verticalScrollBar()->maximum()); } void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName) { - QTextCharFormat oldFormat = cursor.charFormat(); - QTextCharFormat anchorFormat = oldFormat; - anchorFormat.setForeground(Qt::blue); - anchorFormat.setAnchor(true); - anchorFormat.setAnchorHref("card://" + cardName); - - cursor.setCharFormat(anchorFormat); - cursor.insertText(cardName); - cursor.setCharFormat(oldFormat); + QTextCharFormat oldFormat = cursor.charFormat(); + QTextCharFormat anchorFormat = oldFormat; + anchorFormat.setForeground(Qt::blue); + anchorFormat.setAnchor(true); + anchorFormat.setAnchorHref("card://" + cardName); + + cursor.setCharFormat(anchorFormat); + cursor.insertText(cardName); + cursor.setCharFormat(oldFormat); } void ChatView::appendUrlTag(QTextCursor &cursor, QString url) { - if (!url.contains("://")) - url.prepend("http://"); - - QTextCharFormat oldFormat = cursor.charFormat(); - QTextCharFormat anchorFormat = oldFormat; - anchorFormat.setForeground(Qt::blue); - anchorFormat.setAnchor(true); - anchorFormat.setAnchorHref(url); - - cursor.setCharFormat(anchorFormat); - cursor.insertText(url); - cursor.setCharFormat(oldFormat); + if (!url.contains("://")) + url.prepend("http://"); + + QTextCharFormat oldFormat = cursor.charFormat(); + QTextCharFormat anchorFormat = oldFormat; + anchorFormat.setForeground(Qt::blue); + anchorFormat.setAnchor(true); + anchorFormat.setAnchorHref(url); + + cursor.setCharFormat(anchorFormat); + cursor.insertText(url); + cursor.setCharFormat(oldFormat); } void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold) { - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); - bool sameSender = (sender == lastSender) && !lastSender.isEmpty(); - QTextCursor cursor = prepareBlock(sameSender); - lastSender = sender; - - if (showTimestamps && !sameSender) { - QTextCharFormat timeFormat; - timeFormat.setForeground(Qt::black); - cursor.setCharFormat(timeFormat); - cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] ")); - } - - QTextCharFormat senderFormat; - if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) { - senderFormat.setFontWeight(QFont::Bold); - senderFormat.setForeground(Qt::red); - } else { - senderFormat.setForeground(Qt::blue); - if (playerBold) - senderFormat.setFontWeight(QFont::Bold); - } - senderFormat.setAnchor(true); - senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender); - if (!sameSender) { - if (!sender.isEmpty()) { - const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); - cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel)); - cursor.insertText(" "); - } - cursor.setCharFormat(senderFormat); - if (!sender.isEmpty()) - sender.append(": "); - cursor.insertText(sender); - } else - cursor.insertText(" "); - - QTextCharFormat messageFormat; - if (sender.isEmpty()) - messageFormat.setForeground(Qt::darkGreen); - cursor.setCharFormat(messageFormat); - - int from = 0, index = 0; - while ((index = message.indexOf('[', from)) != -1) { - cursor.insertText(message.left(index)); - message = message.mid(index); - if (message.isEmpty()) - break; + bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + bool sameSender = (sender == lastSender) && !lastSender.isEmpty(); + QTextCursor cursor = prepareBlock(sameSender); + lastSender = sender; + + if (showTimestamps && !sameSender) { + QTextCharFormat timeFormat; + timeFormat.setForeground(Qt::black); + cursor.setCharFormat(timeFormat); + cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] ")); + } + + QTextCharFormat senderFormat; + if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) { + senderFormat.setFontWeight(QFont::Bold); + senderFormat.setForeground(Qt::red); + } else { + senderFormat.setForeground(Qt::blue); + if (playerBold) + senderFormat.setFontWeight(QFont::Bold); + } + senderFormat.setAnchor(true); + senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender); + if (!sameSender) { + if (!sender.isEmpty()) { + const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); + cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel)); + cursor.insertText(" "); + } + cursor.setCharFormat(senderFormat); + if (!sender.isEmpty()) + sender.append(": "); + cursor.insertText(sender); + } else + cursor.insertText(" "); + + QTextCharFormat messageFormat; + if (sender.isEmpty()) + messageFormat.setForeground(Qt::darkGreen); + cursor.setCharFormat(messageFormat); + + int from = 0, index = 0; + while ((index = message.indexOf('[', from)) != -1) { + cursor.insertText(message.left(index)); + message = message.mid(index); + if (message.isEmpty()) + break; - if (message.startsWith("[card]")) { - message = message.mid(6); - int closeTagIndex = message.indexOf("[/card]"); - QString cardName = message.left(closeTagIndex); - if (closeTagIndex == -1) - message.clear(); - else - message = message.mid(closeTagIndex + 7); - - appendCardTag(cursor, cardName); - } else if (message.startsWith("[[")) { - message = message.mid(2); - int closeTagIndex = message.indexOf("]]"); - QString cardName = message.left(closeTagIndex); - if (closeTagIndex == -1) - message.clear(); - else - message = message.mid(closeTagIndex + 2); - - appendCardTag(cursor, cardName); - } else if (message.startsWith("[url]")) { - message = message.mid(5); - int closeTagIndex = message.indexOf("[/url]"); - QString url = message.left(closeTagIndex); - if (closeTagIndex == -1) - message.clear(); - else - message = message.mid(closeTagIndex + 6); - - appendUrlTag(cursor, url); - } else - from = 1; - } - if (!message.isEmpty()) - cursor.insertText(message); - - if (atBottom) - verticalScrollBar()->setValue(verticalScrollBar()->maximum()); + if (message.startsWith("[card]")) { + message = message.mid(6); + int closeTagIndex = message.indexOf("[/card]"); + QString cardName = message.left(closeTagIndex); + if (closeTagIndex == -1) + message.clear(); + else + message = message.mid(closeTagIndex + 7); + + appendCardTag(cursor, cardName); + } else if (message.startsWith("[[")) { + message = message.mid(2); + int closeTagIndex = message.indexOf("]]"); + QString cardName = message.left(closeTagIndex); + if (closeTagIndex == -1) + message.clear(); + else + message = message.mid(closeTagIndex + 2); + + appendCardTag(cursor, cardName); + } else if (message.startsWith("[url]")) { + message = message.mid(5); + int closeTagIndex = message.indexOf("[/url]"); + QString url = message.left(closeTagIndex); + if (closeTagIndex == -1) + message.clear(); + else + message = message.mid(closeTagIndex + 6); + + appendUrlTag(cursor, url); + } else + from = 1; + } + if (!message.isEmpty()) + cursor.insertText(message); + + if (atBottom) + verticalScrollBar()->setValue(verticalScrollBar()->maximum()); } void ChatView::enterEvent(QEvent * /*event*/) { - setMouseTracking(true); + setMouseTracking(true); } void ChatView::leaveEvent(QEvent * /*event*/) { - setMouseTracking(false); + setMouseTracking(false); } QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const { - QTextCursor cursor(cursorForPosition(pos)); - QTextBlock block(cursor.block()); - QTextBlock::iterator it; - for (it = block.begin(); !(it.atEnd()); ++it) { - QTextFragment frag = it.fragment(); - if (frag.contains(cursor.position())) - return frag; - } - return QTextFragment(); + QTextCursor cursor(cursorForPosition(pos)); + QTextBlock block(cursor.block()); + QTextBlock::iterator it; + for (it = block.begin(); !(it.atEnd()); ++it) { + QTextFragment frag = it.fragment(); + if (frag.contains(cursor.position())) + return frag; + } + return QTextFragment(); } void ChatView::mouseMoveEvent(QMouseEvent *event) { - QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); - if (!anchorHref.isEmpty()) { - const int delimiterIndex = anchorHref.indexOf("://"); - if (delimiterIndex != -1) { - const QString scheme = anchorHref.left(delimiterIndex); - hoveredContent = anchorHref.mid(delimiterIndex + 3); - if (scheme == "card") { - hoveredItemType = HoveredCard; - emit cardNameHovered(hoveredContent); - } else if (scheme == "user") - hoveredItemType = HoveredUser; - else - hoveredItemType = HoveredUrl; - viewport()->setCursor(Qt::PointingHandCursor); - } else { - hoveredItemType = HoveredNothing; - viewport()->setCursor(Qt::IBeamCursor); - } - } else { - hoveredItemType = HoveredNothing; - viewport()->setCursor(Qt::IBeamCursor); - } - - QTextBrowser::mouseMoveEvent(event); + QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); + if (!anchorHref.isEmpty()) { + const int delimiterIndex = anchorHref.indexOf("://"); + if (delimiterIndex != -1) { + const QString scheme = anchorHref.left(delimiterIndex); + hoveredContent = anchorHref.mid(delimiterIndex + 3); + if (scheme == "card") { + hoveredItemType = HoveredCard; + emit cardNameHovered(hoveredContent); + } else if (scheme == "user") + hoveredItemType = HoveredUser; + else + hoveredItemType = HoveredUrl; + viewport()->setCursor(Qt::PointingHandCursor); + } else { + hoveredItemType = HoveredNothing; + viewport()->setCursor(Qt::IBeamCursor); + } + } else { + hoveredItemType = HoveredNothing; + viewport()->setCursor(Qt::IBeamCursor); + } + + QTextBrowser::mouseMoveEvent(event); } void ChatView::mousePressEvent(QMouseEvent *event) { - switch (hoveredItemType) { - case HoveredCard: { - if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) - emit showCardInfoPopup(event->globalPos(), hoveredContent); - break; - } - case HoveredUser: { - if (event->button() == Qt::RightButton) { - const int delimiterIndex = hoveredContent.indexOf("_"); - UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); - const QString userName = hoveredContent.mid(delimiterIndex + 1); - - userContextMenu->showContextMenu(event->globalPos(), userName, userLevel); - } - break; - } - default: { - QTextBrowser::mousePressEvent(event); - } - } + switch (hoveredItemType) { + case HoveredCard: { + if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) + emit showCardInfoPopup(event->globalPos(), hoveredContent); + break; + } + case HoveredUser: { + if (event->button() == Qt::RightButton) { + const int delimiterIndex = hoveredContent.indexOf("_"); + UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); + const QString userName = hoveredContent.mid(delimiterIndex + 1); + + userContextMenu->showContextMenu(event->globalPos(), userName, userLevel); + } + break; + } + default: { + QTextBrowser::mousePressEvent(event); + } + } } void ChatView::mouseReleaseEvent(QMouseEvent *event) { - if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) - emit deleteCardInfoPopup(QString("_")); - - QTextBrowser::mouseReleaseEvent(event); + if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) + emit deleteCardInfoPopup(QString("_")); + + QTextBrowser::mouseReleaseEvent(event); } void ChatView::openLink(const QUrl &link) { - if ((link.scheme() == "card") || (link.scheme() == "user")) - return; - - QDesktopServices::openUrl(link); + if ((link.scheme() == "card") || (link.scheme() == "user")) + return; + + QDesktopServices::openUrl(link); } diff --git a/cockatrice/src/chatview.h b/cockatrice/src/chatview.h index d5c35d38..1e8a2022 100644 --- a/cockatrice/src/chatview.h +++ b/cockatrice/src/chatview.h @@ -14,40 +14,40 @@ class TabSupervisor; class TabGame; class ChatView : public QTextBrowser { - Q_OBJECT + Q_OBJECT protected: - const TabSupervisor * const tabSupervisor; - TabGame * const game; + const TabSupervisor * const tabSupervisor; + TabGame * const game; private: - enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser }; - UserContextMenu *userContextMenu; - QString lastSender; - bool evenNumber; - bool showTimestamps; - HoveredItemType hoveredItemType; - QString hoveredContent; - QTextFragment getFragmentUnderMouse(const QPoint &pos) const; - QTextCursor prepareBlock(bool same = false); - void appendCardTag(QTextCursor &cursor, const QString &cardName); - void appendUrlTag(QTextCursor &cursor, QString url); + enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser }; + UserContextMenu *userContextMenu; + QString lastSender; + bool evenNumber; + bool showTimestamps; + HoveredItemType hoveredItemType; + QString hoveredContent; + QTextFragment getFragmentUnderMouse(const QPoint &pos) const; + QTextCursor prepareBlock(bool same = false); + void appendCardTag(QTextCursor &cursor, const QString &cardName); + void appendUrlTag(QTextCursor &cursor, QString url); private slots: - void openLink(const QUrl &link); + void openLink(const QUrl &link); public: - ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0); - void retranslateUi(); - void appendHtml(const QString &html); - void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false); + ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0); + void retranslateUi(); + void appendHtml(const QString &html); + void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false); protected: - void enterEvent(QEvent *event); - void leaveEvent(QEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); signals: - void openMessageDialog(const QString &userName, bool focus); - void cardNameHovered(QString cardName); - void showCardInfoPopup(QPoint pos, QString cardName); - void deleteCardInfoPopup(QString cardName); + void openMessageDialog(const QString &userName, bool focus); + void cardNameHovered(QString cardName); + void showCardInfoPopup(QPoint pos, QString cardName); + void deleteCardInfoPopup(QString cardName); }; #endif diff --git a/cockatrice/src/counter_general.cpp b/cockatrice/src/counter_general.cpp index 6ded4732..edc44519 100644 --- a/cockatrice/src/counter_general.cpp +++ b/cockatrice/src/counter_general.cpp @@ -3,34 +3,34 @@ #include GeneralCounter::GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent) - : AbstractCounter(_player, _id, _name, true, _value, parent), color(_color), radius(_radius) + : AbstractCounter(_player, _id, _name, true, _value, parent), color(_color), radius(_radius) { - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } QRectF GeneralCounter::boundingRect() const { - return QRectF(0, 0, radius * 2, radius * 2); + return QRectF(0, 0, radius * 2, radius * 2); } void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); - int translatedHeight = mapRect.size().height(); - qreal scaleFactor = translatedHeight / boundingRect().height(); - QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); - - painter->save(); - painter->resetTransform(); - painter->drawPixmap(QPoint(0, 0), pixmap); + QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); + int translatedHeight = mapRect.size().height(); + qreal scaleFactor = translatedHeight / boundingRect().height(); + QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); + + painter->save(); + painter->resetTransform(); + painter->drawPixmap(QPoint(0, 0), pixmap); - if (value) { - QFont f("Serif"); - f.setPixelSize(qMax((int) (radius * scaleFactor), 10)); - f.setWeight(QFont::Bold); - painter->setPen(Qt::black); - painter->setFont(f); - painter->drawText(mapRect, Qt::AlignCenter, QString::number(value)); - } - painter->restore(); + if (value) { + QFont f("Serif"); + f.setPixelSize(qMax((int) (radius * scaleFactor), 10)); + f.setWeight(QFont::Bold); + painter->setPen(Qt::black); + painter->setFont(f); + painter->drawText(mapRect, Qt::AlignCenter, QString::number(value)); + } + painter->restore(); } diff --git a/cockatrice/src/counter_general.h b/cockatrice/src/counter_general.h index d815f3c4..2808b654 100644 --- a/cockatrice/src/counter_general.h +++ b/cockatrice/src/counter_general.h @@ -4,14 +4,14 @@ #include "abstractcounter.h" class GeneralCounter : public AbstractCounter { - Q_OBJECT + Q_OBJECT private: - QColor color; - int radius; + QColor color; + int radius; public: - GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif diff --git a/cockatrice/src/deck_loader.cpp b/cockatrice/src/deck_loader.cpp index 5d8ff6e7..6a907ed7 100644 --- a/cockatrice/src/deck_loader.cpp +++ b/cockatrice/src/deck_loader.cpp @@ -4,96 +4,96 @@ #include "decklist.h" const QStringList DeckLoader::fileNameFilters = QStringList() - << QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)") - << QObject::tr("All files (*.*)"); + << QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)") + << QObject::tr("All files (*.*)"); DeckLoader::DeckLoader() - : DeckList(), - lastFileName(QString()), - lastFileFormat(CockatriceFormat), - lastRemoteDeckId(-1) + : DeckList(), + lastFileName(QString()), + lastFileFormat(CockatriceFormat), + lastRemoteDeckId(-1) { } DeckLoader::DeckLoader(const QString &nativeString) - : DeckList(nativeString), - lastFileName(QString()), - lastFileFormat(CockatriceFormat), - lastRemoteDeckId(-1) + : DeckList(nativeString), + lastFileName(QString()), + lastFileFormat(CockatriceFormat), + lastRemoteDeckId(-1) { } DeckLoader::DeckLoader(const DeckList &other) - : DeckList(other), - lastFileName(QString()), - lastFileFormat(CockatriceFormat), - lastRemoteDeckId(-1) + : DeckList(other), + lastFileName(QString()), + lastFileFormat(CockatriceFormat), + lastRemoteDeckId(-1) { } DeckLoader::DeckLoader(const DeckLoader &other) - : DeckList(other), - lastFileName(other.lastFileName), - lastFileFormat(other.lastFileFormat), - lastRemoteDeckId(other.lastRemoteDeckId) + : DeckList(other), + lastFileName(other.lastFileName), + lastFileFormat(other.lastFileFormat), + lastRemoteDeckId(other.lastRemoteDeckId) { } bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt) { - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return false; - - bool result = false; - switch (fmt) { - case PlainTextFormat: result = loadFromFile_Plain(&file); break; - case CockatriceFormat: result = loadFromFile_Native(&file); break; - } - if (result) { - lastFileName = fileName; - lastFileFormat = fmt; - - emit deckLoaded(); - } - return result; + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return false; + + bool result = false; + switch (fmt) { + case PlainTextFormat: result = loadFromFile_Plain(&file); break; + case CockatriceFormat: result = loadFromFile_Native(&file); break; + } + if (result) { + lastFileName = fileName; + lastFileFormat = fmt; + + emit deckLoaded(); + } + return result; } bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) { - bool result = loadFromString_Native(nativeString); - if (result) { - lastFileName = QString(); - lastFileFormat = CockatriceFormat; - lastRemoteDeckId = remoteDeckId; - - emit deckLoaded(); - } - return result; + bool result = loadFromString_Native(nativeString); + if (result) { + lastFileName = QString(); + lastFileFormat = CockatriceFormat; + lastRemoteDeckId = remoteDeckId; + + emit deckLoaded(); + } + return result; } bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) { - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) - return false; + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) + return false; - bool result = false; - switch (fmt) { - case PlainTextFormat: result = saveToFile_Plain(&file); break; - case CockatriceFormat: result = saveToFile_Native(&file); break; - } - if (result) { - lastFileName = fileName; - lastFileFormat = fmt; - } - return result; + bool result = false; + switch (fmt) { + case PlainTextFormat: result = saveToFile_Plain(&file); break; + case CockatriceFormat: result = saveToFile_Native(&file); break; + } + if (result) { + lastFileName = fileName; + lastFileFormat = fmt; + } + return result; } DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) { - if (fileName.endsWith(".cod", Qt::CaseInsensitive)) { - return CockatriceFormat; - } - return PlainTextFormat; + if (fileName.endsWith(".cod", Qt::CaseInsensitive)) { + return CockatriceFormat; + } + return PlainTextFormat; } diff --git a/cockatrice/src/deck_loader.h b/cockatrice/src/deck_loader.h index 892e4be4..70c481d1 100644 --- a/cockatrice/src/deck_loader.h +++ b/cockatrice/src/deck_loader.h @@ -4,30 +4,30 @@ #include "decklist.h" class DeckLoader : public DeckList { - Q_OBJECT + Q_OBJECT signals: - void deckLoaded(); + void deckLoaded(); public: - enum FileFormat { PlainTextFormat, CockatriceFormat }; - static const QStringList fileNameFilters; + enum FileFormat { PlainTextFormat, CockatriceFormat }; + static const QStringList fileNameFilters; private: - QString lastFileName; - FileFormat lastFileFormat; - int lastRemoteDeckId; + QString lastFileName; + FileFormat lastFileFormat; + int lastRemoteDeckId; public: - DeckLoader(); - DeckLoader(const QString &nativeString); - DeckLoader(const DeckList &other); - DeckLoader(const DeckLoader &other); - const QString &getLastFileName() const { return lastFileName; } - FileFormat getLastFileFormat() const { return lastFileFormat; } - int getLastRemoteDeckId() const { return lastRemoteDeckId; } - - static FileFormat getFormatFromName(const QString &fileName); - - bool loadFromFile(const QString &fileName, FileFormat fmt); - bool loadFromRemote(const QString &nativeString, int remoteDeckId); - bool saveToFile(const QString &fileName, FileFormat fmt); + DeckLoader(); + DeckLoader(const QString &nativeString); + DeckLoader(const DeckList &other); + DeckLoader(const DeckLoader &other); + const QString &getLastFileName() const { return lastFileName; } + FileFormat getLastFileFormat() const { return lastFileFormat; } + int getLastRemoteDeckId() const { return lastRemoteDeckId; } + + static FileFormat getFormatFromName(const QString &fileName); + + bool loadFromFile(const QString &fileName, FileFormat fmt); + bool loadFromRemote(const QString &nativeString, int remoteDeckId); + bool saveToFile(const QString &fileName, FileFormat fmt); }; #endif diff --git a/cockatrice/src/decklistmodel.cpp b/cockatrice/src/decklistmodel.cpp index 6abbba86..3e55ec15 100644 --- a/cockatrice/src/decklistmodel.cpp +++ b/cockatrice/src/decklistmodel.cpp @@ -14,423 +14,423 @@ #include "deck_loader.h" DeckListModel::DeckListModel(QObject *parent) - : QAbstractItemModel(parent) + : QAbstractItemModel(parent) { - deckList = new DeckLoader; - connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); - connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); - root = new InnerDecklistNode; + deckList = new DeckLoader; + connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); + connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); + root = new InnerDecklistNode; } DeckListModel::~DeckListModel() { - delete root; - delete deckList; + delete root; + delete deckList; } void DeckListModel::rebuildTree() { - root->clearTree(); - InnerDecklistNode *listRoot = deckList->getRoot(); - for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); - InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root); - for (int j = 0; j < currentZone->size(); j++) { - DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); - // XXX better sanity checking - if (!currentCard) - continue; + root->clearTree(); + InnerDecklistNode *listRoot = deckList->getRoot(); + for (int i = 0; i < listRoot->size(); i++) { + InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root); + for (int j = 0; j < currentZone->size(); j++) { + DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); + // XXX better sanity checking + if (!currentCard) + continue; - CardInfo *info = db->getCard(currentCard->getName()); - QString cardType; - if (!info) - cardType = "unknown"; - else - cardType = info->getMainCardType(); - InnerDecklistNode *cardTypeNode = dynamic_cast(node->findChild(cardType)); - if (!cardTypeNode) - cardTypeNode = new InnerDecklistNode(cardType, node); + CardInfo *info = db->getCard(currentCard->getName()); + QString cardType; + if (!info) + cardType = "unknown"; + else + cardType = info->getMainCardType(); + InnerDecklistNode *cardTypeNode = dynamic_cast(node->findChild(cardType)); + if (!cardTypeNode) + cardTypeNode = new InnerDecklistNode(cardType, node); - new DecklistModelCardNode(currentCard, cardTypeNode); - } - } + new DecklistModelCardNode(currentCard, cardTypeNode); + } + } - reset(); + reset(); } int DeckListModel::rowCount(const QModelIndex &parent) const { -// debugIndexInfo("rowCount", parent); - InnerDecklistNode *node = getNode(parent); - if (node) - return node->size(); - else - return 0; +// debugIndexInfo("rowCount", parent); + InnerDecklistNode *node = getNode(parent); + if (node) + return node->size(); + else + return 0; } int DeckListModel::columnCount(const QModelIndex &/*parent*/) const { - if (settingsCache->getPriceTagFeature()) - return 3; - else - return 2; + if (settingsCache->getPriceTagFeature()) + return 3; + else + return 2; } QVariant DeckListModel::data(const QModelIndex &index, int role) const { -// debugIndexInfo("data", index); - if (!index.isValid()) - return QVariant(); +// debugIndexInfo("data", index); + if (!index.isValid()) + return QVariant(); if (index.column() >= columnCount()) - return QVariant(); + return QVariant(); - AbstractDecklistNode *temp = static_cast(index.internalPointer()); - DecklistModelCardNode *card = dynamic_cast(temp); - if (!card) { - InnerDecklistNode *node = dynamic_cast(temp); - switch (role) { - case Qt::FontRole: { - QFont f; - f.setBold(true); - return f; - } - case Qt::DisplayRole: - case Qt::EditRole: - switch (index.column()) { + AbstractDecklistNode *temp = static_cast(index.internalPointer()); + DecklistModelCardNode *card = dynamic_cast(temp); + if (!card) { + InnerDecklistNode *node = dynamic_cast(temp); + switch (role) { + case Qt::FontRole: { + QFont f; + f.setBold(true); + return f; + } + case Qt::DisplayRole: + case Qt::EditRole: + switch (index.column()) { case 0: return node->recursiveCount(true); case 1: return node->getVisibleName(); case 2: return QString().sprintf("$%.2f", node->recursivePrice(true)); - default: return QVariant(); - } - case Qt::BackgroundRole: { - int color = 90 + 60 * node->depth(); - return QBrush(QColor(color, 255, color)); - } - default: return QVariant(); - } - } else { - switch (role) { - case Qt::DisplayRole: - case Qt::EditRole: { - switch (index.column()) { + default: return QVariant(); + } + case Qt::BackgroundRole: { + int color = 90 + 60 * node->depth(); + return QBrush(QColor(color, 255, color)); + } + default: return QVariant(); + } + } else { + switch (role) { + case Qt::DisplayRole: + case Qt::EditRole: { + switch (index.column()) { case 0: return card->getNumber(); case 1: return card->getName(); case 2: return QString().sprintf("$%.2f", card->getTotalPrice()); - default: return QVariant(); - } - } - case Qt::BackgroundRole: { - int color = 255 - (index.row() % 2) * 30; - return QBrush(QColor(color, color, color)); - } - default: return QVariant(); - } - } + default: return QVariant(); + } + } + case Qt::BackgroundRole: { + int color = 255 - (index.row() % 2) * 30; + return QBrush(QColor(color, color, color)); + } + default: return QVariant(); + } + } } QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - return QVariant(); + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) + return QVariant(); if (section >= columnCount()) - return QVariant(); - switch (section) { + return QVariant(); + switch (section) { case 0: return tr("Number"); case 1: return tr("Card"); case 2: return tr("Price"); - default: return QVariant(); - } + default: return QVariant(); + } } QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const { -// debugIndexInfo("index", parent); - if (!hasIndex(row, column, parent)) - return QModelIndex(); +// debugIndexInfo("index", parent); + if (!hasIndex(row, column, parent)) + return QModelIndex(); - InnerDecklistNode *parentNode = getNode(parent); - if (row >= parentNode->size()) - return QModelIndex(); + InnerDecklistNode *parentNode = getNode(parent); + if (row >= parentNode->size()) + return QModelIndex(); - return createIndex(row, column, parentNode->at(row)); + return createIndex(row, column, parentNode->at(row)); } QModelIndex DeckListModel::parent(const QModelIndex &ind) const { - if (!ind.isValid()) - return QModelIndex(); + if (!ind.isValid()) + return QModelIndex(); - return nodeToIndex(static_cast(ind.internalPointer())->getParent()); + return nodeToIndex(static_cast(ind.internalPointer())->getParent()); } Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - Qt::ItemFlags result = Qt::ItemIsEnabled; - if (getNode(index)) - result |= Qt::ItemIsSelectable; + Qt::ItemFlags result = Qt::ItemIsEnabled; + if (getNode(index)) + result |= Qt::ItemIsSelectable; - return result; + return result; } void DeckListModel::emitRecursiveUpdates(const QModelIndex &index) { - if (!index.isValid()) - return; - emit dataChanged(index, index); - emitRecursiveUpdates(index.parent()); + if (!index.isValid()) + return; + emit dataChanged(index, index); + emitRecursiveUpdates(index.parent()); } bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role) { - DecklistModelCardNode *node = getNode(index); - if (!node || (role != Qt::EditRole)) - return false; + DecklistModelCardNode *node = getNode(index); + if (!node || (role != Qt::EditRole)) + return false; - switch (index.column()) { + switch (index.column()) { case 0: node->setNumber(value.toInt()); break; case 1: node->setName(value.toString()); break; case 2: node->setPrice(value.toFloat()); break; - default: return false; - } - emitRecursiveUpdates(index); - deckList->updateDeckHash(); - return true; + default: return false; + } + emitRecursiveUpdates(index); + deckList->updateDeckHash(); + return true; } bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent) { - InnerDecklistNode *node = getNode(parent); - if (!node) - return false; - if (row + count > node->size()) - return false; + InnerDecklistNode *node = getNode(parent); + if (!node) + return false; + if (row + count > node->size()) + return false; - beginRemoveRows(parent, row, row + count - 1); - for (int i = 0; i < count; i++) { - AbstractDecklistNode *toDelete = node->takeAt(row); - if (DecklistModelCardNode *temp = dynamic_cast(toDelete)) - deckList->deleteNode(temp->getDataNode()); - delete toDelete; - } - endRemoveRows(); + beginRemoveRows(parent, row, row + count - 1); + for (int i = 0; i < count; i++) { + AbstractDecklistNode *toDelete = node->takeAt(row); + if (DecklistModelCardNode *temp = dynamic_cast(toDelete)) + deckList->deleteNode(temp->getDataNode()); + delete toDelete; + } + endRemoveRows(); - if (!node->size() && (node != root)) - removeRows(parent.row(), 1, parent.parent()); - else - emitRecursiveUpdates(parent); + if (!node->size() && (node != root)) + removeRows(parent.row(), 1, parent.parent()); + else + emitRecursiveUpdates(parent); - return true; + return true; } InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent) { - InnerDecklistNode *newNode = dynamic_cast(parent->findChild(name)); - if (!newNode) { - beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); - newNode = new InnerDecklistNode(name, parent); - endInsertRows(); - } - return newNode; + InnerDecklistNode *newNode = dynamic_cast(parent->findChild(name)); + if (!newNode) { + beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); + newNode = new InnerDecklistNode(name, parent); + endInsertRows(); + } + return newNode; } QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName) { - InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); + InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); - CardInfo *info = db->getCard(cardName); - QString cardType = info->getMainCardType(); - InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode); + CardInfo *info = db->getCard(cardName); + QString cardType = info->getMainCardType(); + InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode); - DecklistModelCardNode *cardNode = dynamic_cast(cardTypeNode->findChild(cardName)); - if (!cardNode) { - DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); - QModelIndex parentIndex = nodeToIndex(cardTypeNode); - beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); - cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); - endInsertRows(); - sort(1); - emitRecursiveUpdates(parentIndex); - return nodeToIndex(cardNode); - } else { - cardNode->setNumber(cardNode->getNumber() + 1); - QModelIndex ind = nodeToIndex(cardNode); - emitRecursiveUpdates(ind); - deckList->updateDeckHash(); - return ind; - } + DecklistModelCardNode *cardNode = dynamic_cast(cardTypeNode->findChild(cardName)); + if (!cardNode) { + DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); + QModelIndex parentIndex = nodeToIndex(cardTypeNode); + beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); + cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); + endInsertRows(); + sort(1); + emitRecursiveUpdates(parentIndex); + return nodeToIndex(cardNode); + } else { + cardNode->setNumber(cardNode->getNumber() + 1); + QModelIndex ind = nodeToIndex(cardNode); + emitRecursiveUpdates(ind); + deckList->updateDeckHash(); + return ind; + } } QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const { - if (node == root) - return QModelIndex(); - return createIndex(node->getParent()->indexOf(node), 0, node); + if (node == root) + return QModelIndex(); + return createIndex(node->getParent()->indexOf(node), 0, node); } void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order) { - // Sort children of node and save the information needed to - // update the list of persistent indexes. - QVector > sortResult = node->sort(order); - - QModelIndexList from, to; - for (int i = sortResult.size() - 1; i >= 0; --i) { - const int fromRow = sortResult[i].first; - const int toRow = sortResult[i].second; - AbstractDecklistNode *temp = node->at(toRow); - for (int j = columnCount(); j; --j) { - from << createIndex(fromRow, 0, temp); - to << createIndex(toRow, 0, temp); - } - } - changePersistentIndexList(from, to); - - // Recursion - for (int i = node->size() - 1; i >= 0; --i) { - InnerDecklistNode *subNode = dynamic_cast(node->at(i)); - if (subNode) - sortHelper(subNode, order); - } + // Sort children of node and save the information needed to + // update the list of persistent indexes. + QVector > sortResult = node->sort(order); + + QModelIndexList from, to; + for (int i = sortResult.size() - 1; i >= 0; --i) { + const int fromRow = sortResult[i].first; + const int toRow = sortResult[i].second; + AbstractDecklistNode *temp = node->at(toRow); + for (int j = columnCount(); j; --j) { + from << createIndex(fromRow, 0, temp); + to << createIndex(toRow, 0, temp); + } + } + changePersistentIndexList(from, to); + + // Recursion + for (int i = node->size() - 1; i >= 0; --i) { + InnerDecklistNode *subNode = dynamic_cast(node->at(i)); + if (subNode) + sortHelper(subNode, order); + } } void DeckListModel::sort(int /*column*/, Qt::SortOrder order) { - emit layoutAboutToBeChanged(); - sortHelper(root, order); - emit layoutChanged(); + emit layoutAboutToBeChanged(); + sortHelper(root, order); + emit layoutChanged(); } void DeckListModel::cleanList() { - setDeckList(new DeckLoader); + setDeckList(new DeckLoader); } void DeckListModel::setDeckList(DeckLoader *_deck) { - delete deckList; - deckList = _deck; - connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); - connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); - rebuildTree(); + delete deckList; + deckList = _deck; + connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); + connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); + rebuildTree(); } void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) { - const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2; + const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2; - if (node->height() == 1) { - QTextBlockFormat blockFormat; - QTextCharFormat charFormat; - charFormat.setFontPointSize(11); - charFormat.setFontWeight(QFont::Bold); - cursor->insertBlock(blockFormat, charFormat); - QString priceStr; - if (settingsCache->getPriceTagFeature()) - priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); + if (node->height() == 1) { + QTextBlockFormat blockFormat; + QTextCharFormat charFormat; + charFormat.setFontPointSize(11); + charFormat.setFontWeight(QFont::Bold); + cursor->insertBlock(blockFormat, charFormat); + QString priceStr; + if (settingsCache->getPriceTagFeature()) + priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr)); - QTextTableFormat tableFormat; - tableFormat.setCellPadding(0); - tableFormat.setCellSpacing(0); - tableFormat.setBorder(0); + QTextTableFormat tableFormat; + tableFormat.setCellPadding(0); + tableFormat.setCellSpacing(0); + tableFormat.setBorder(0); QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); - for (int i = 0; i < node->size(); i++) { - AbstractDecklistCardNode *card = dynamic_cast(node->at(i)); + for (int i = 0; i < node->size(); i++) { + AbstractDecklistCardNode *card = dynamic_cast(node->at(i)); - QTextCharFormat cellCharFormat; - cellCharFormat.setFontPointSize(9); + QTextCharFormat cellCharFormat; + cellCharFormat.setFontPointSize(9); - QTextTableCell cell = table->cellAt(i, 0); - cell.setFormat(cellCharFormat); - QTextCursor cellCursor = cell.firstCursorPosition(); - cellCursor.insertText(QString("%1 ").arg(card->getNumber())); + QTextTableCell cell = table->cellAt(i, 0); + cell.setFormat(cellCharFormat); + QTextCursor cellCursor = cell.firstCursorPosition(); + cellCursor.insertText(QString("%1 ").arg(card->getNumber())); - cell = table->cellAt(i, 1); - cell.setFormat(cellCharFormat); - cellCursor = cell.firstCursorPosition(); - cellCursor.insertText(card->getName()); + cell = table->cellAt(i, 1); + cell.setFormat(cellCharFormat); + cellCursor = cell.firstCursorPosition(); + cellCursor.insertText(card->getName()); - if (settingsCache->getPriceTagFeature()) { - cell = table->cellAt(i, 2); - cell.setFormat(cellCharFormat); - cellCursor = cell.firstCursorPosition(); - cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice())); - } - } - } else if (node->height() == 2) { - QTextBlockFormat blockFormat; - QTextCharFormat charFormat; - charFormat.setFontPointSize(14); - charFormat.setFontWeight(QFont::Bold); + if (settingsCache->getPriceTagFeature()) { + cell = table->cellAt(i, 2); + cell.setFormat(cellCharFormat); + cellCursor = cell.firstCursorPosition(); + cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice())); + } + } + } else if (node->height() == 2) { + QTextBlockFormat blockFormat; + QTextCharFormat charFormat; + charFormat.setFontPointSize(14); + charFormat.setFontWeight(QFont::Bold); - cursor->insertBlock(blockFormat, charFormat); - QString priceStr; - if (settingsCache->getPriceTagFeature()) - priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); + cursor->insertBlock(blockFormat, charFormat); + QString priceStr; + if (settingsCache->getPriceTagFeature()) + priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr)); - QTextTableFormat tableFormat; - tableFormat.setCellPadding(10); - tableFormat.setCellSpacing(0); - tableFormat.setBorder(0); - QVector constraints; - for (int i = 0; i < totalColumns; i++) - constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); - tableFormat.setColumnWidthConstraints(constraints); + QTextTableFormat tableFormat; + tableFormat.setCellPadding(10); + tableFormat.setCellSpacing(0); + tableFormat.setBorder(0); + QVector constraints; + for (int i = 0; i < totalColumns; i++) + constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); + tableFormat.setColumnWidthConstraints(constraints); - QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); - for (int i = 0; i < node->size(); i++) { - QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); - printDeckListNode(&cellCursor, dynamic_cast(node->at(i))); - } - } - cursor->movePosition(QTextCursor::End); + QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); + for (int i = 0; i < node->size(); i++) { + QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); + printDeckListNode(&cellCursor, dynamic_cast(node->at(i))); + } + } + cursor->movePosition(QTextCursor::End); } void DeckListModel::printDeckList(QPrinter *printer) { - QTextDocument doc; + QTextDocument doc; - QFont font("Serif"); - font.setStyleHint(QFont::Serif); - doc.setDefaultFont(font); + QFont font("Serif"); + font.setStyleHint(QFont::Serif); + doc.setDefaultFont(font); - QTextCursor cursor(&doc); + QTextCursor cursor(&doc); - QTextBlockFormat headerBlockFormat; - QTextCharFormat headerCharFormat; - headerCharFormat.setFontPointSize(16); - headerCharFormat.setFontWeight(QFont::Bold); + QTextBlockFormat headerBlockFormat; + QTextCharFormat headerCharFormat; + headerCharFormat.setFontPointSize(16); + headerCharFormat.setFontWeight(QFont::Bold); - cursor.insertBlock(headerBlockFormat, headerCharFormat); - cursor.insertText(deckList->getName()); + cursor.insertBlock(headerBlockFormat, headerCharFormat); + cursor.insertText(deckList->getName()); - headerCharFormat.setFontPointSize(12); - cursor.insertBlock(headerBlockFormat, headerCharFormat); - cursor.insertText(deckList->getComments()); - cursor.insertBlock(headerBlockFormat, headerCharFormat); + headerCharFormat.setFontPointSize(12); + cursor.insertBlock(headerBlockFormat, headerCharFormat); + cursor.insertText(deckList->getComments()); + cursor.insertBlock(headerBlockFormat, headerCharFormat); - for (int i = 0; i < root->size(); i++) { - cursor.insertHtml("
"); - //cursor.insertHtml("


"); - cursor.insertBlock(headerBlockFormat, headerCharFormat); + for (int i = 0; i < root->size(); i++) { + cursor.insertHtml("
"); + //cursor.insertHtml("
"); + cursor.insertBlock(headerBlockFormat, headerCharFormat); - printDeckListNode(&cursor, dynamic_cast(root->at(i))); - } + printDeckListNode(&cursor, dynamic_cast(root->at(i))); + } - doc.print(printer); + doc.print(printer); } void DeckListModel::pricesUpdated(InnerDecklistNode *node) { - if (!node) - node = root; - - if (node->isEmpty()) - return; - - emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last())); + if (!node) + node = root; + + if (node->isEmpty()) + return; + + emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last())); } diff --git a/cockatrice/src/decklistmodel.h b/cockatrice/src/decklistmodel.h index 4d81d007..2e2c570a 100644 --- a/cockatrice/src/decklistmodel.h +++ b/cockatrice/src/decklistmodel.h @@ -13,60 +13,60 @@ class QTextCursor; class DecklistModelCardNode : public AbstractDecklistCardNode { private: - DecklistCardNode *dataNode; + DecklistCardNode *dataNode; public: - DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } - int getNumber() const { return dataNode->getNumber(); } - void setNumber(int _number) { dataNode->setNumber(_number); } + DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } + int getNumber() const { return dataNode->getNumber(); } + void setNumber(int _number) { dataNode->setNumber(_number); } float getPrice() const { return dataNode->getPrice(); } void setPrice(float _price) { dataNode->setPrice(_price); } - QString getName() const { return dataNode->getName(); } - void setName(const QString &_name) { dataNode->setName(_name); } - DecklistCardNode *getDataNode() const { return dataNode; } + QString getName() const { return dataNode->getName(); } + void setName(const QString &_name) { dataNode->setName(_name); } + DecklistCardNode *getDataNode() const { return dataNode; } }; class DeckListModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT private slots: - void rebuildTree(); + void rebuildTree(); public slots: - void printDeckList(QPrinter *printer); + void printDeckList(QPrinter *printer); signals: - void deckHashChanged(); + void deckHashChanged(); public: - DeckListModel(QObject *parent = 0); - ~DeckListModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; + DeckListModel(QObject *parent = 0); + ~DeckListModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - QModelIndex addCard(const QString &cardName, const QString &zoneName); - void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); - void cleanList(); - DeckLoader *getDeckList() const { return deckList; } - void setDeckList(DeckLoader *_deck); - void pricesUpdated(InnerDecklistNode *node = 0); + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + bool setData(const QModelIndex &index, const QVariant &value, int role); + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); + QModelIndex addCard(const QString &cardName, const QString &zoneName); + void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); + void cleanList(); + DeckLoader *getDeckList() const { return deckList; } + void setDeckList(DeckLoader *_deck); + void pricesUpdated(InnerDecklistNode *node = 0); private: - DeckLoader *deckList; - InnerDecklistNode *root; - InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent); - QModelIndex nodeToIndex(AbstractDecklistNode *node) const; - void emitRecursiveUpdates(const QModelIndex &index); - void sortHelper(InnerDecklistNode *node, Qt::SortOrder order); + DeckLoader *deckList; + InnerDecklistNode *root; + InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent); + QModelIndex nodeToIndex(AbstractDecklistNode *node) const; + void emitRecursiveUpdates(const QModelIndex &index); + void sortHelper(InnerDecklistNode *node, Qt::SortOrder order); - void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node); + void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node); - template T getNode(const QModelIndex &index) const - { - if (!index.isValid()) - return dynamic_cast(root); - return dynamic_cast(static_cast(index.internalPointer())); - } + template T getNode(const QModelIndex &index) const + { + if (!index.isValid()) + return dynamic_cast(root); + return dynamic_cast(static_cast(index.internalPointer())); + } }; #endif diff --git a/cockatrice/src/deckstats_interface.cpp b/cockatrice/src/deckstats_interface.cpp index 65cb101c..eae4caae 100644 --- a/cockatrice/src/deckstats_interface.cpp +++ b/cockatrice/src/deckstats_interface.cpp @@ -8,46 +8,46 @@ #include DeckStatsInterface::DeckStatsInterface(QObject *parent) - : QObject(parent) + : QObject(parent) { - manager = new QNetworkAccessManager(this); - connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); + manager = new QNetworkAccessManager(this); + connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); } void DeckStatsInterface::queryFinished(QNetworkReply *reply) { - if (reply->error() != QNetworkReply::NoError) { - QMessageBox::critical(0, tr("Error"), reply->errorString()); - reply->deleteLater(); - deleteLater(); - return; - } - - QString data(reply->readAll()); - reply->deleteLater(); - - QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\""); - if (!rx.indexIn(data)) { - QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed.")); - deleteLater(); - return; - } - - QString deckUrl = rx.cap(1); - QDesktopServices::openUrl(deckUrl); - - deleteLater(); + if (reply->error() != QNetworkReply::NoError) { + QMessageBox::critical(0, tr("Error"), reply->errorString()); + reply->deleteLater(); + deleteLater(); + return; + } + + QString data(reply->readAll()); + reply->deleteLater(); + + QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\""); + if (!rx.indexIn(data)) { + QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed.")); + deleteLater(); + return; + } + + QString deckUrl = rx.cap(1); + QDesktopServices::openUrl(deckUrl); + + deleteLater(); } void DeckStatsInterface::analyzeDeck(DeckList *deck) { - QUrl params; - params.addQueryItem("deck", deck->writeToString_Plain()); - QByteArray data; - data.append(params.encodedQuery()); - - QNetworkRequest request(QUrl("http://deckstats.net/index.php")); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - - manager->post(request, data); + QUrl params; + params.addQueryItem("deck", deck->writeToString_Plain()); + QByteArray data; + data.append(params.encodedQuery()); + + QNetworkRequest request(QUrl("http://deckstats.net/index.php")); + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + manager->post(request, data); } diff --git a/cockatrice/src/deckstats_interface.h b/cockatrice/src/deckstats_interface.h index 89361b2d..e8454dd5 100644 --- a/cockatrice/src/deckstats_interface.h +++ b/cockatrice/src/deckstats_interface.h @@ -8,14 +8,14 @@ class QNetworkReply; class DeckList; class DeckStatsInterface : public QObject { - Q_OBJECT + Q_OBJECT private: - QNetworkAccessManager *manager; + QNetworkAccessManager *manager; private slots: - void queryFinished(QNetworkReply *reply); + void queryFinished(QNetworkReply *reply); public: - DeckStatsInterface(QObject *parent = 0); - void analyzeDeck(DeckList *deck); + DeckStatsInterface(QObject *parent = 0); + void analyzeDeck(DeckList *deck); }; #endif diff --git a/cockatrice/src/deckview.cpp b/cockatrice/src/deckview.cpp index a073cf2d..1746c58b 100644 --- a/cockatrice/src/deckview.cpp +++ b/cockatrice/src/deckview.cpp @@ -8,479 +8,479 @@ #include "main.h" DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag) - : AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0) + : AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0) { } void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos) { - QList colliding = scene()->items(cursorScenePos); + QList colliding = scene()->items(cursorScenePos); - DeckViewCardContainer *cursorZone = 0; - for (int i = colliding.size() - 1; i >= 0; i--) - if ((cursorZone = qgraphicsitem_cast(colliding.at(i)))) - break; - if (!cursorZone) - return; - currentZone = cursorZone; - - QPointF newPos = cursorScenePos; - if (newPos != pos()) { - for (int i = 0; i < childDrags.size(); i++) - childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); - setPos(newPos); - } + DeckViewCardContainer *cursorZone = 0; + for (int i = colliding.size() - 1; i >= 0; i--) + if ((cursorZone = qgraphicsitem_cast(colliding.at(i)))) + break; + if (!cursorZone) + return; + currentZone = cursorZone; + + QPointF newPos = cursorScenePos; + if (newPos != pos()) { + for (int i = 0; i < childDrags.size(); i++) + childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); + setPos(newPos); + } } void DeckViewCardDragItem::handleDrop(DeckViewCardContainer *target) { - DeckViewCard *card = static_cast(item); - DeckViewCardContainer *start = static_cast(item->parentItem()); - start->removeCard(card); - target->addCard(card); - card->setParentItem(target); + DeckViewCard *card = static_cast(item); + DeckViewCardContainer *start = static_cast(item->parentItem()); + start->removeCard(card); + target->addCard(card); + card->setParentItem(target); } void DeckViewCardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - setCursor(Qt::OpenHandCursor); - DeckViewScene *sc = static_cast(scene()); - sc->removeItem(this); + setCursor(Qt::OpenHandCursor); + DeckViewScene *sc = static_cast(scene()); + sc->removeItem(this); - if (currentZone) { - handleDrop(currentZone); - for (int i = 0; i < childDrags.size(); i++) { - DeckViewCardDragItem *c = static_cast(childDrags[i]); - c->handleDrop(currentZone); - sc->removeItem(c); - } - - sc->updateContents(); - } - - event->accept(); + if (currentZone) { + handleDrop(currentZone); + for (int i = 0; i < childDrags.size(); i++) { + DeckViewCardDragItem *c = static_cast(childDrags[i]); + c->handleDrop(currentZone); + sc->removeItem(c); + } + + sc->updateContents(); + } + + event->accept(); } DeckViewCard::DeckViewCard(const QString &_name, const QString &_originZone, QGraphicsItem *parent) - : AbstractCardItem(_name, 0, -1, parent), originZone(_originZone), dragItem(0) + : AbstractCardItem(_name, 0, -1, parent), originZone(_originZone), dragItem(0) { - setAcceptsHoverEvents(true); + setAcceptsHoverEvents(true); } DeckViewCard::~DeckViewCard() { - delete dragItem; + delete dragItem; } void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - AbstractCardItem::paint(painter, option, widget); - - painter->save(); - QPen pen;//(Qt::DotLine); - pen.setWidth(3); - if (originZone == "main") - pen.setColor(QColor(0, 255, 0)); - else - pen.setColor(QColor(255, 0, 0)); - painter->setPen(pen); - painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3)); - painter->restore(); + AbstractCardItem::paint(painter, option, widget); + + painter->save(); + QPen pen;//(Qt::DotLine); + pen.setWidth(3); + if (originZone == "main") + pen.setColor(QColor(0, 255, 0)); + else + pen.setColor(QColor(255, 0, 0)); + painter->setPen(pen); + painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3)); + painter->restore(); } void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) - return; - - if (static_cast(scene())->getLocked()) - return; - - delete dragItem; - dragItem = new DeckViewCardDragItem(this, event->pos()); - scene()->addItem(dragItem); - dragItem->updatePosition(event->scenePos()); - dragItem->grabMouse(); - - QList sel = scene()->selectedItems(); - int j = 0; - for (int i = 0; i < sel.size(); i++) { - DeckViewCard *c = static_cast(sel.at(i)); - if (c == this) - continue; - ++j; - QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0); - DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem); - drag->setPos(dragItem->pos() + childPos); - scene()->addItem(drag); - } - setCursor(Qt::OpenHandCursor); + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + return; + + if (static_cast(scene())->getLocked()) + return; + + delete dragItem; + dragItem = new DeckViewCardDragItem(this, event->pos()); + scene()->addItem(dragItem); + dragItem->updatePosition(event->scenePos()); + dragItem->grabMouse(); + + QList sel = scene()->selectedItems(); + int j = 0; + for (int i = 0; i < sel.size(); i++) { + DeckViewCard *c = static_cast(sel.at(i)); + if (c == this) + continue; + ++j; + QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0); + DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem); + drag->setPos(dragItem->pos() + childPos); + scene()->addItem(drag); + } + setCursor(Qt::OpenHandCursor); } void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - event->accept(); - processHoverEvent(); + event->accept(); + processHoverEvent(); } DeckViewCardContainer::DeckViewCardContainer(const QString &_name) - : QGraphicsItem(), name(_name), width(0), height(0) + : QGraphicsItem(), name(_name), width(0), height(0) { - QString bgPath = settingsCache->getTableBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); + QString bgPath = settingsCache->getTableBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } QRectF DeckViewCardContainer::boundingRect() const { - return QRectF(0, 0, width, height); + return QRectF(0, 0, width, height); } void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - qreal totalTextWidth = getCardTypeTextWidth(); - - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), QColor(0, 0, 100)); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); - painter->setPen(QColor(255, 255, 255, 100)); - painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); - - painter->setPen(QColor(Qt::white)); - QFont f("Serif"); - f.setStyleHint(QFont::Serif); - f.setPixelSize(24); - f.setWeight(QFont::Bold); - painter->setFont(f); - painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size())); - - f.setPixelSize(16); - painter->setFont(f); - QList cardTypeList = cardsByType.uniqueKeys(); - qreal yUntilNow = separatorY + paddingY; - for (int i = 0; i < cardTypeList.size(); ++i) { - if (i != 0) { - painter->setPen(QColor(255, 255, 255, 100)); - painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); - } - qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; - QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); - yUntilNow += thisRowHeight + paddingY; - - painter->setPen(Qt::white); - painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]); - } + qreal totalTextWidth = getCardTypeTextWidth(); + + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), QColor(0, 0, 100)); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); + painter->setPen(QColor(255, 255, 255, 100)); + painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); + + painter->setPen(QColor(Qt::white)); + QFont f("Serif"); + f.setStyleHint(QFont::Serif); + f.setPixelSize(24); + f.setWeight(QFont::Bold); + painter->setFont(f); + painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size())); + + f.setPixelSize(16); + painter->setFont(f); + QList cardTypeList = cardsByType.uniqueKeys(); + qreal yUntilNow = separatorY + paddingY; + for (int i = 0; i < cardTypeList.size(); ++i) { + if (i != 0) { + painter->setPen(QColor(255, 255, 255, 100)); + painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); + } + qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; + QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); + yUntilNow += thisRowHeight + paddingY; + + painter->setPen(Qt::white); + painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]); + } } void DeckViewCardContainer::addCard(DeckViewCard *card) { - cards.append(card); - cardsByType.insert(card->getInfo()->getMainCardType(), card); + cards.append(card); + cardsByType.insert(card->getInfo()->getMainCardType(), card); } void DeckViewCardContainer::removeCard(DeckViewCard *card) { - cards.removeAt(cards.indexOf(card)); - cardsByType.remove(card->getInfo()->getMainCardType(), card); + cards.removeAt(cards.indexOf(card)); + cardsByType.remove(card->getInfo()->getMainCardType(), card); } QList > DeckViewCardContainer::getRowsAndCols() const { - QList > result; - QList cardTypeList = cardsByType.uniqueKeys(); - for (int i = 0; i < cardTypeList.size(); ++i) - result.append(QPair(1, cardsByType.count(cardTypeList[i]))); - return result; + QList > result; + QList cardTypeList = cardsByType.uniqueKeys(); + for (int i = 0; i < cardTypeList.size(); ++i) + result.append(QPair(1, cardsByType.count(cardTypeList[i]))); + return result; } int DeckViewCardContainer::getCardTypeTextWidth() const { - QFont f("Serif"); - f.setStyleHint(QFont::Serif); - f.setPixelSize(16); - f.setWeight(QFont::Bold); - QFontMetrics fm(f); - - int maxCardTypeWidth = 0; - QMapIterator i(cardsByType); - while (i.hasNext()) { - int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width(); - if (cardTypeWidth > maxCardTypeWidth) - maxCardTypeWidth = cardTypeWidth; - } - - return maxCardTypeWidth + 15; + QFont f("Serif"); + f.setStyleHint(QFont::Serif); + f.setPixelSize(16); + f.setWeight(QFont::Bold); + QFontMetrics fm(f); + + int maxCardTypeWidth = 0; + QMapIterator i(cardsByType); + while (i.hasNext()) { + int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width(); + if (cardTypeWidth > maxCardTypeWidth) + maxCardTypeWidth = cardTypeWidth; + } + + return maxCardTypeWidth + 15; } QSizeF DeckViewCardContainer::calculateBoundingRect(const QList > &rowsAndCols) const { - qreal totalHeight = 0; - qreal totalWidth = 0; - - // Calculate space needed for cards - for (int i = 0; i < rowsAndCols.size(); ++i) { - totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY; - if (CARD_WIDTH * rowsAndCols[i].second > totalWidth) - totalWidth = CARD_WIDTH * rowsAndCols[i].second; - } - - return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY); + qreal totalHeight = 0; + qreal totalWidth = 0; + + // Calculate space needed for cards + for (int i = 0; i < rowsAndCols.size(); ++i) { + totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY; + if (CARD_WIDTH * rowsAndCols[i].second > totalWidth) + totalWidth = CARD_WIDTH * rowsAndCols[i].second; + } + + return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY); } void DeckViewCardContainer::rearrangeItems(const QList > &rowsAndCols) { - currentRowsAndCols = rowsAndCols; - - int totalCols = 0, totalRows = 0; - qreal yUntilNow = separatorY + paddingY; - qreal x = (qreal) getCardTypeTextWidth(); - for (int i = 0; i < rowsAndCols.size(); ++i) { - const int tempRows = rowsAndCols[i].first; - const int tempCols = rowsAndCols[i].second; - totalRows += tempRows; - if (tempCols > totalCols) - totalCols = tempCols; - - QList cardTypeList = cardsByType.uniqueKeys(); - QList row = cardsByType.values(cardTypeList[i]); - for (int j = 0; j < row.size(); ++j) { - DeckViewCard *card = row[j]; - card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT); - } - yUntilNow += tempRows * CARD_HEIGHT + paddingY; - } - - prepareGeometryChange(); - QSizeF bRect = calculateBoundingRect(rowsAndCols); - width = bRect.width(); - height = bRect.height(); + currentRowsAndCols = rowsAndCols; + + int totalCols = 0, totalRows = 0; + qreal yUntilNow = separatorY + paddingY; + qreal x = (qreal) getCardTypeTextWidth(); + for (int i = 0; i < rowsAndCols.size(); ++i) { + const int tempRows = rowsAndCols[i].first; + const int tempCols = rowsAndCols[i].second; + totalRows += tempRows; + if (tempCols > totalCols) + totalCols = tempCols; + + QList cardTypeList = cardsByType.uniqueKeys(); + QList row = cardsByType.values(cardTypeList[i]); + for (int j = 0; j < row.size(); ++j) { + DeckViewCard *card = row[j]; + card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT); + } + yUntilNow += tempRows * CARD_HEIGHT + paddingY; + } + + prepareGeometryChange(); + QSizeF bRect = calculateBoundingRect(rowsAndCols); + width = bRect.width(); + height = bRect.height(); } void DeckViewCardContainer::setWidth(qreal _width) { - prepareGeometryChange(); - width = _width; - update(); + prepareGeometryChange(); + width = _width; + update(); } DeckViewScene::DeckViewScene(QObject *parent) - : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) + : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) { } DeckViewScene::~DeckViewScene() { - clearContents(); - delete deck; + clearContents(); + delete deck; } void DeckViewScene::clearContents() { - QMapIterator i(cardContainers); - while (i.hasNext()) - delete i.next().value(); - cardContainers.clear(); + QMapIterator i(cardContainers); + while (i.hasNext()) + delete i.next().value(); + cardContainers.clear(); } void DeckViewScene::setDeck(const DeckList &_deck) { - if (deck) - delete deck; - - deck = new DeckList(_deck); - rebuildTree(); - applySideboardPlan(deck->getCurrentSideboardPlan()); - rearrangeItems(); + if (deck) + delete deck; + + deck = new DeckList(_deck); + rebuildTree(); + applySideboardPlan(deck->getCurrentSideboardPlan()); + rearrangeItems(); } void DeckViewScene::rebuildTree() { - clearContents(); - - if (!deck) - return; - - InnerDecklistNode *listRoot = deck->getRoot(); - for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); - - DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); - if (!container) { - container = new DeckViewCardContainer(currentZone->getName()); - cardContainers.insert(currentZone->getName(), container); - addItem(container); - } - - for (int j = 0; j < currentZone->size(); j++) { - DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); - if (!currentCard) - continue; + clearContents(); + + if (!deck) + return; + + InnerDecklistNode *listRoot = deck->getRoot(); + for (int i = 0; i < listRoot->size(); i++) { + InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + + DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); + if (!container) { + container = new DeckViewCardContainer(currentZone->getName()); + cardContainers.insert(currentZone->getName(), container); + addItem(container); + } + + for (int j = 0; j < currentZone->size(); j++) { + DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); + if (!currentCard) + continue; - for (int k = 0; k < currentCard->getNumber(); ++k) { - DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container); - container->addCard(newCard); - emit newCardAdded(newCard); - } - } - } + for (int k = 0; k < currentCard->getNumber(); ++k) { + DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container); + container->addCard(newCard); + emit newCardAdded(newCard); + } + } + } } void DeckViewScene::applySideboardPlan(const QList &plan) { - for (int i = 0; i < plan.size(); ++i) { - const MoveCard_ToZone &m = plan[i]; - DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone())); - DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone())); - if (!start || !target) - continue; - - DeckViewCard *card = 0; - const QList &cardList = start->getCards(); - for (int j = 0; j < cardList.size(); ++j) - if (cardList[j]->getName() == QString::fromStdString(m.card_name())) { - card = cardList[j]; - break; - } - if (!card) - continue; - - start->removeCard(card); - target->addCard(card); - card->setParentItem(target); - } + for (int i = 0; i < plan.size(); ++i) { + const MoveCard_ToZone &m = plan[i]; + DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone())); + DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone())); + if (!start || !target) + continue; + + DeckViewCard *card = 0; + const QList &cardList = start->getCards(); + for (int j = 0; j < cardList.size(); ++j) + if (cardList[j]->getName() == QString::fromStdString(m.card_name())) { + card = cardList[j]; + break; + } + if (!card) + continue; + + start->removeCard(card); + target->addCard(card); + card->setParentItem(target); + } } void DeckViewScene::rearrangeItems() { - const int spacing = CARD_HEIGHT / 3; - QList contList = cardContainers.values(); - - // Initialize space requirements - QList > > rowsAndColsList; - QList > cardCountList; - for (int i = 0; i < contList.size(); ++i) { - QList > rowsAndCols = contList[i]->getRowsAndCols(); - rowsAndColsList.append(rowsAndCols); - - cardCountList.append(QList()); - for (int j = 0; j < rowsAndCols.size(); ++j) - cardCountList[i].append(rowsAndCols[j].second); - } - - qreal totalHeight, totalWidth; - for (;;) { - // Calculate total size before this iteration - totalHeight = -spacing; - totalWidth = 0; - for (int i = 0; i < contList.size(); ++i) { - QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]); - totalHeight += contSize.height() + spacing; - if (contSize.width() > totalWidth) - totalWidth = contSize.width(); - } - - // We're done when the aspect ratio shifts from too high to too low. - if (totalWidth / totalHeight <= optimalAspectRatio) - break; - - // Find category with highest column count - int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0; - for (int i = 0; i < rowsAndColsList.size(); ++i) - for (int j = 0; j < rowsAndColsList[i].size(); ++j) - if (rowsAndColsList[i][j].second > maxCols) { - maxIndex1 = i; - maxIndex2 = j; - maxCols = rowsAndColsList[i][j].second; - } - - // Add row to category - const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; - const int maxCardCount = cardCountList[maxIndex1][maxIndex2]; - rowsAndColsList[maxIndex1][maxIndex2] = QPair(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1))); - } - - totalHeight = -spacing; - for (int i = 0; i < contList.size(); ++i) { - DeckViewCardContainer *c = contList[i]; - c->rearrangeItems(rowsAndColsList[i]); - c->setPos(0, totalHeight + spacing); - totalHeight += c->boundingRect().height() + spacing; - } - - totalWidth = totalHeight * optimalAspectRatio; - for (int i = 0; i < contList.size(); ++i) - contList[i]->setWidth(totalWidth); - - setSceneRect(QRectF(0, 0, totalWidth, totalHeight)); + const int spacing = CARD_HEIGHT / 3; + QList contList = cardContainers.values(); + + // Initialize space requirements + QList > > rowsAndColsList; + QList > cardCountList; + for (int i = 0; i < contList.size(); ++i) { + QList > rowsAndCols = contList[i]->getRowsAndCols(); + rowsAndColsList.append(rowsAndCols); + + cardCountList.append(QList()); + for (int j = 0; j < rowsAndCols.size(); ++j) + cardCountList[i].append(rowsAndCols[j].second); + } + + qreal totalHeight, totalWidth; + for (;;) { + // Calculate total size before this iteration + totalHeight = -spacing; + totalWidth = 0; + for (int i = 0; i < contList.size(); ++i) { + QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]); + totalHeight += contSize.height() + spacing; + if (contSize.width() > totalWidth) + totalWidth = contSize.width(); + } + + // We're done when the aspect ratio shifts from too high to too low. + if (totalWidth / totalHeight <= optimalAspectRatio) + break; + + // Find category with highest column count + int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0; + for (int i = 0; i < rowsAndColsList.size(); ++i) + for (int j = 0; j < rowsAndColsList[i].size(); ++j) + if (rowsAndColsList[i][j].second > maxCols) { + maxIndex1 = i; + maxIndex2 = j; + maxCols = rowsAndColsList[i][j].second; + } + + // Add row to category + const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; + const int maxCardCount = cardCountList[maxIndex1][maxIndex2]; + rowsAndColsList[maxIndex1][maxIndex2] = QPair(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1))); + } + + totalHeight = -spacing; + for (int i = 0; i < contList.size(); ++i) { + DeckViewCardContainer *c = contList[i]; + c->rearrangeItems(rowsAndColsList[i]); + c->setPos(0, totalHeight + spacing); + totalHeight += c->boundingRect().height() + spacing; + } + + totalWidth = totalHeight * optimalAspectRatio; + for (int i = 0; i < contList.size(); ++i) + contList[i]->setWidth(totalWidth); + + setSceneRect(QRectF(0, 0, totalWidth, totalHeight)); } void DeckViewScene::updateContents() { - rearrangeItems(); - emit sideboardPlanChanged(); + rearrangeItems(); + emit sideboardPlanChanged(); } QList DeckViewScene::getSideboardPlan() const { - QList result; - QMapIterator containerIterator(cardContainers); - while (containerIterator.hasNext()) { - DeckViewCardContainer *cont = containerIterator.next().value(); - const QList cardList = cont->getCards(); - for (int i = 0; i < cardList.size(); ++i) - if (cardList[i]->getOriginZone() != cont->getName()) { - MoveCard_ToZone m; - m.set_card_name(cardList[i]->getName().toStdString()); - m.set_start_zone(cardList[i]->getOriginZone().toStdString()); - m.set_target_zone(cont->getName().toStdString()); - result.append(m); - } - } - return result; + QList result; + QMapIterator containerIterator(cardContainers); + while (containerIterator.hasNext()) { + DeckViewCardContainer *cont = containerIterator.next().value(); + const QList cardList = cont->getCards(); + for (int i = 0; i < cardList.size(); ++i) + if (cardList[i]->getOriginZone() != cont->getName()) { + MoveCard_ToZone m; + m.set_card_name(cardList[i]->getName().toStdString()); + m.set_start_zone(cardList[i]->getOriginZone().toStdString()); + m.set_target_zone(cont->getName().toStdString()); + result.append(m); + } + } + return result; } void DeckViewScene::resetSideboardPlan() { - rebuildTree(); - rearrangeItems(); + rebuildTree(); + rearrangeItems(); } DeckView::DeckView(QWidget *parent) - : QGraphicsView(parent) + : QGraphicsView(parent) { - deckViewScene = new DeckViewScene(this); - - setBackgroundBrush(QBrush(QColor(0, 0, 0))); - setDragMode(RubberBandDrag); - setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/); - setScene(deckViewScene); + deckViewScene = new DeckViewScene(this); + + setBackgroundBrush(QBrush(QColor(0, 0, 0))); + setDragMode(RubberBandDrag); + setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/); + setScene(deckViewScene); - connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); - connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); - connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged())); + connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); + connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); + connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged())); } void DeckView::resizeEvent(QResizeEvent *event) { - QGraphicsView::resizeEvent(event); - deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height()); - deckViewScene->rearrangeItems(); + QGraphicsView::resizeEvent(event); + deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height()); + deckViewScene->rearrangeItems(); } void DeckView::updateSceneRect(const QRectF &rect) { - fitInView(rect, Qt::KeepAspectRatio); + fitInView(rect, Qt::KeepAspectRatio); } void DeckView::setDeck(const DeckList &_deck) { - deckViewScene->setDeck(_deck); + deckViewScene->setDeck(_deck); } void DeckView::resetSideboardPlan() { - deckViewScene->resetSideboardPlan(); + deckViewScene->resetSideboardPlan(); } diff --git a/cockatrice/src/deckview.h b/cockatrice/src/deckview.h index a7aeb2f1..059afa2a 100644 --- a/cockatrice/src/deckview.h +++ b/cockatrice/src/deckview.h @@ -19,101 +19,101 @@ class MoveCardToZone; class DeckViewCard : public AbstractCardItem { private: - QString originZone; - DeckViewCardDragItem *dragItem; + QString originZone; + DeckViewCardDragItem *dragItem; public: - DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0); - ~DeckViewCard(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - const QString &getOriginZone() const { return originZone; } + DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0); + ~DeckViewCard(); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + const QString &getOriginZone() const { return originZone; } protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); }; class DeckViewCardDragItem : public AbstractCardDragItem { private: - DeckViewCardContainer *currentZone; - void handleDrop(DeckViewCardContainer *target); + DeckViewCardContainer *currentZone; + void handleDrop(DeckViewCardContainer *target); public: - DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); - void updatePosition(const QPointF &cursorScenePos); + DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); + void updatePosition(const QPointF &cursorScenePos); protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; class DeckViewCardContainer : public QGraphicsItem { private: - static const int separatorY = 20; - static const int paddingY = 10; - - QString name; - QList cards; - QMultiMap cardsByType; - QList > currentRowsAndCols; - qreal width, height; - QPixmap bgPixmap; - int getCardTypeTextWidth() const; + static const int separatorY = 20; + static const int paddingY = 10; + + QString name; + QList cards; + QMultiMap cardsByType; + QList > currentRowsAndCols; + qreal width, height; + QPixmap bgPixmap; + int getCardTypeTextWidth() const; public: - enum { Type = typeDeckViewCardContainer }; - int type() const { return Type; } - DeckViewCardContainer(const QString &_name); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void addCard(DeckViewCard *card); - void removeCard(DeckViewCard *card); - const QList &getCards() const { return cards; } - const QString &getName() const { return name; } - void setWidth(qreal _width); + enum { Type = typeDeckViewCardContainer }; + int type() const { return Type; } + DeckViewCardContainer(const QString &_name); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void addCard(DeckViewCard *card); + void removeCard(DeckViewCard *card); + const QList &getCards() const { return cards; } + const QString &getName() const { return name; } + void setWidth(qreal _width); - QList > getRowsAndCols() const; - QSizeF calculateBoundingRect(const QList > &rowsAndCols) const; - void rearrangeItems(const QList > &rowsAndCols); + QList > getRowsAndCols() const; + QSizeF calculateBoundingRect(const QList > &rowsAndCols) const; + void rearrangeItems(const QList > &rowsAndCols); }; class DeckViewScene : public QGraphicsScene { - Q_OBJECT + Q_OBJECT signals: - void newCardAdded(AbstractCardItem *card); - void sideboardPlanChanged(); + void newCardAdded(AbstractCardItem *card); + void sideboardPlanChanged(); private: - bool locked; - DeckList *deck; - QMap cardContainers; - qreal optimalAspectRatio; - void clearContents(); - void rebuildTree(); - void applySideboardPlan(const QList &plan); + bool locked; + DeckList *deck; + QMap cardContainers; + qreal optimalAspectRatio; + void clearContents(); + void rebuildTree(); + void applySideboardPlan(const QList &plan); public: - DeckViewScene(QObject *parent = 0); - ~DeckViewScene(); - void setLocked(bool _locked) { locked = _locked; } - bool getLocked() const { return locked; } - void setDeck(const DeckList &_deck); - void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } - void rearrangeItems(); - void updateContents(); - QList getSideboardPlan() const; - void resetSideboardPlan(); + DeckViewScene(QObject *parent = 0); + ~DeckViewScene(); + void setLocked(bool _locked) { locked = _locked; } + bool getLocked() const { return locked; } + void setDeck(const DeckList &_deck); + void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } + void rearrangeItems(); + void updateContents(); + QList getSideboardPlan() const; + void resetSideboardPlan(); }; class DeckView : public QGraphicsView { - Q_OBJECT + Q_OBJECT private: - DeckViewScene *deckViewScene; + DeckViewScene *deckViewScene; protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); public slots: - void updateSceneRect(const QRectF &rect); + void updateSceneRect(const QRectF &rect); signals: - void newCardAdded(AbstractCardItem *card); - void sideboardPlanChanged(); + void newCardAdded(AbstractCardItem *card); + void sideboardPlanChanged(); public: - DeckView(QWidget *parent = 0); - void setDeck(const DeckList &_deck); - void setLocked(bool _locked) { deckViewScene->setLocked(_locked); } - QList getSideboardPlan() const { return deckViewScene->getSideboardPlan(); } - void resetSideboardPlan(); + DeckView(QWidget *parent = 0); + void setDeck(const DeckList &_deck); + void setLocked(bool _locked) { deckViewScene->setLocked(_locked); } + QList getSideboardPlan() const { return deckViewScene->getSideboardPlan(); } + void resetSideboardPlan(); }; #endif diff --git a/cockatrice/src/dlg_cardsearch.cpp b/cockatrice/src/dlg_cardsearch.cpp index 55d9419c..e73e11a2 100644 --- a/cockatrice/src/dlg_cardsearch.cpp +++ b/cockatrice/src/dlg_cardsearch.cpp @@ -10,86 +10,86 @@ #include "main.h" DlgCardSearch::DlgCardSearch(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - QLabel *cardNameLabel = new QLabel(tr("Card name:")); - cardNameEdit = new QLineEdit; - - QLabel *cardTextLabel = new QLabel(tr("Card text:")); - cardTextEdit = new QLineEdit; - - QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):")); - const QStringList &cardTypes = db->getAllMainCardTypes(); - QVBoxLayout *cardTypesLayout = new QVBoxLayout; - for (int i = 0; i < cardTypes.size(); ++i) { - QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]); - cardTypeCheckBox->setChecked(true); - cardTypeCheckBoxes.append(cardTypeCheckBox); - cardTypesLayout->addWidget(cardTypeCheckBox); - } - - QLabel *cardColorsLabel = new QLabel(tr("Color (OR):")); - const QStringList &cardColors = db->getAllColors(); - QHBoxLayout *cardColorsLayout = new QHBoxLayout; - for (int i = 0; i < cardColors.size(); ++i) { - QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]); - cardColorCheckBox->setChecked(true); - cardColorCheckBoxes.append(cardColorCheckBox); - cardColorsLayout->addWidget(cardColorCheckBox); - } - - QPushButton *okButton = new QPushButton(tr("O&K")); - okButton->setDefault(true); - okButton->setAutoDefault(true); - QPushButton *cancelButton = new QPushButton(tr("&Cancel")); - connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); - QHBoxLayout *buttonHBox = new QHBoxLayout; - buttonHBox->addStretch(); - buttonHBox->addWidget(okButton); - buttonHBox->addWidget(cancelButton); - - QGridLayout *optionsLayout = new QGridLayout; - optionsLayout->addWidget(cardNameLabel, 0, 0); - optionsLayout->addWidget(cardNameEdit, 0, 1); - optionsLayout->addWidget(cardTextLabel, 1, 0); - optionsLayout->addWidget(cardTextEdit, 1, 1); - optionsLayout->addWidget(cardTypesLabel, 2, 0); - optionsLayout->addLayout(cardTypesLayout, 2, 1); - optionsLayout->addWidget(cardColorsLabel, 3, 0); - optionsLayout->addLayout(cardColorsLayout, 3, 1); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(optionsLayout); - mainLayout->addLayout(buttonHBox); - setLayout(mainLayout); - setWindowTitle(tr("Card search")); + QLabel *cardNameLabel = new QLabel(tr("Card name:")); + cardNameEdit = new QLineEdit; + + QLabel *cardTextLabel = new QLabel(tr("Card text:")); + cardTextEdit = new QLineEdit; + + QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):")); + const QStringList &cardTypes = db->getAllMainCardTypes(); + QVBoxLayout *cardTypesLayout = new QVBoxLayout; + for (int i = 0; i < cardTypes.size(); ++i) { + QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]); + cardTypeCheckBox->setChecked(true); + cardTypeCheckBoxes.append(cardTypeCheckBox); + cardTypesLayout->addWidget(cardTypeCheckBox); + } + + QLabel *cardColorsLabel = new QLabel(tr("Color (OR):")); + const QStringList &cardColors = db->getAllColors(); + QHBoxLayout *cardColorsLayout = new QHBoxLayout; + for (int i = 0; i < cardColors.size(); ++i) { + QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]); + cardColorCheckBox->setChecked(true); + cardColorCheckBoxes.append(cardColorCheckBox); + cardColorsLayout->addWidget(cardColorCheckBox); + } + + QPushButton *okButton = new QPushButton(tr("O&K")); + okButton->setDefault(true); + okButton->setAutoDefault(true); + QPushButton *cancelButton = new QPushButton(tr("&Cancel")); + connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + QHBoxLayout *buttonHBox = new QHBoxLayout; + buttonHBox->addStretch(); + buttonHBox->addWidget(okButton); + buttonHBox->addWidget(cancelButton); + + QGridLayout *optionsLayout = new QGridLayout; + optionsLayout->addWidget(cardNameLabel, 0, 0); + optionsLayout->addWidget(cardNameEdit, 0, 1); + optionsLayout->addWidget(cardTextLabel, 1, 0); + optionsLayout->addWidget(cardTextEdit, 1, 1); + optionsLayout->addWidget(cardTypesLabel, 2, 0); + optionsLayout->addLayout(cardTypesLayout, 2, 1); + optionsLayout->addWidget(cardColorsLabel, 3, 0); + optionsLayout->addLayout(cardColorsLayout, 3, 1); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(optionsLayout); + mainLayout->addLayout(buttonHBox); + setLayout(mainLayout); + setWindowTitle(tr("Card search")); } QString DlgCardSearch::getCardName() const { - return cardNameEdit->text(); + return cardNameEdit->text(); } QString DlgCardSearch::getCardText() const { - return cardTextEdit->text(); + return cardTextEdit->text(); } QSet DlgCardSearch::getCardTypes() const { - QStringList result; - for (int i = 0; i < cardTypeCheckBoxes.size(); ++i) - if (cardTypeCheckBoxes[i]->isChecked()) - result.append(cardTypeCheckBoxes[i]->text()); - return QSet::fromList(result); + QStringList result; + for (int i = 0; i < cardTypeCheckBoxes.size(); ++i) + if (cardTypeCheckBoxes[i]->isChecked()) + result.append(cardTypeCheckBoxes[i]->text()); + return QSet::fromList(result); } QSet DlgCardSearch::getCardColors() const { - QStringList result; - for (int i = 0; i < cardColorCheckBoxes.size(); ++i) - if (cardColorCheckBoxes[i]->isChecked()) - result.append(cardColorCheckBoxes[i]->text()); - return QSet::fromList(result); + QStringList result; + for (int i = 0; i < cardColorCheckBoxes.size(); ++i) + if (cardColorCheckBoxes[i]->isChecked()) + result.append(cardColorCheckBoxes[i]->text()); + return QSet::fromList(result); } diff --git a/cockatrice/src/dlg_cardsearch.h b/cockatrice/src/dlg_cardsearch.h index 4c2ccccf..0736085f 100644 --- a/cockatrice/src/dlg_cardsearch.h +++ b/cockatrice/src/dlg_cardsearch.h @@ -9,16 +9,16 @@ class QLineEdit; class QCheckBox; class DlgCardSearch : public QDialog { - Q_OBJECT + Q_OBJECT private: - QLineEdit *cardNameEdit, *cardTextEdit; - QList cardTypeCheckBoxes, cardColorCheckBoxes; + QLineEdit *cardNameEdit, *cardTextEdit; + QList cardTypeCheckBoxes, cardColorCheckBoxes; public: - DlgCardSearch(QWidget *parent = 0); - QString getCardName() const; - QString getCardText() const; - QSet getCardTypes() const; - QSet getCardColors() const; + DlgCardSearch(QWidget *parent = 0); + QString getCardName() const; + QString getCardText() const; + QSet getCardTypes() const; + QSet getCardColors() const; }; #endif diff --git a/cockatrice/src/dlg_connect.cpp b/cockatrice/src/dlg_connect.cpp index b645b1eb..d1955d14 100644 --- a/cockatrice/src/dlg_connect.cpp +++ b/cockatrice/src/dlg_connect.cpp @@ -7,66 +7,66 @@ #include "dlg_connect.h" DlgConnect::DlgConnect(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - QSettings settings; - settings.beginGroup("server"); + QSettings settings; + settings.beginGroup("server"); - hostLabel = new QLabel(tr("&Host:")); - hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString()); - hostLabel->setBuddy(hostEdit); + hostLabel = new QLabel(tr("&Host:")); + hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString()); + hostLabel->setBuddy(hostEdit); - portLabel = new QLabel(tr("&Port:")); - portEdit = new QLineEdit(settings.value("port", "4747").toString()); - portLabel->setBuddy(portEdit); + portLabel = new QLabel(tr("&Port:")); + portEdit = new QLineEdit(settings.value("port", "4747").toString()); + portLabel->setBuddy(portEdit); - playernameLabel = new QLabel(tr("Player &name:")); - playernameEdit = new QLineEdit(settings.value("playername", "Player").toString()); - playernameLabel->setBuddy(playernameEdit); + playernameLabel = new QLabel(tr("Player &name:")); + playernameEdit = new QLineEdit(settings.value("playername", "Player").toString()); + playernameLabel->setBuddy(playernameEdit); - passwordLabel = new QLabel(tr("P&assword:")); - passwordEdit = new QLineEdit(settings.value("password").toString()); - passwordLabel->setBuddy(passwordEdit); - passwordEdit->setEchoMode(QLineEdit::Password); - - savePasswordCheckBox = new QCheckBox(tr("&Save password")); - savePasswordCheckBox->setChecked(settings.value("save_password", 1).toInt()); + passwordLabel = new QLabel(tr("P&assword:")); + passwordEdit = new QLineEdit(settings.value("password").toString()); + passwordLabel->setBuddy(passwordEdit); + passwordEdit->setEchoMode(QLineEdit::Password); + + savePasswordCheckBox = new QCheckBox(tr("&Save password")); + savePasswordCheckBox->setChecked(settings.value("save_password", 1).toInt()); - QGridLayout *grid = new QGridLayout; - grid->addWidget(hostLabel, 0, 0); - grid->addWidget(hostEdit, 0, 1); - grid->addWidget(portLabel, 1, 0); - grid->addWidget(portEdit, 1, 1); - grid->addWidget(playernameLabel, 2, 0); - grid->addWidget(playernameEdit, 2, 1); - grid->addWidget(passwordLabel, 3, 0); - grid->addWidget(passwordEdit, 3, 1); - grid->addWidget(savePasswordCheckBox, 4, 0, 1, 2); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(grid); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + QGridLayout *grid = new QGridLayout; + grid->addWidget(hostLabel, 0, 0); + grid->addWidget(hostEdit, 0, 1); + grid->addWidget(portLabel, 1, 0); + grid->addWidget(portEdit, 1, 1); + grid->addWidget(playernameLabel, 2, 0); + grid->addWidget(playernameEdit, 2, 1); + grid->addWidget(passwordLabel, 3, 0); + grid->addWidget(passwordEdit, 3, 1); + grid->addWidget(savePasswordCheckBox, 4, 0, 1, 2); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(grid); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); - setWindowTitle(tr("Connect to server")); - setFixedHeight(sizeHint().height()); - setMinimumWidth(300); + setWindowTitle(tr("Connect to server")); + setFixedHeight(sizeHint().height()); + setMinimumWidth(300); } void DlgConnect::actOk() { - QSettings settings; - settings.beginGroup("server"); - settings.setValue("hostname", hostEdit->text()); - settings.setValue("port", portEdit->text()); - settings.setValue("playername", playernameEdit->text()); - settings.setValue("password", savePasswordCheckBox->isChecked() ? passwordEdit->text() : QString()); - settings.setValue("save_password", savePasswordCheckBox->isChecked() ? 1 : 0); - settings.endGroup(); + QSettings settings; + settings.beginGroup("server"); + settings.setValue("hostname", hostEdit->text()); + settings.setValue("port", portEdit->text()); + settings.setValue("playername", playernameEdit->text()); + settings.setValue("password", savePasswordCheckBox->isChecked() ? passwordEdit->text() : QString()); + settings.setValue("save_password", savePasswordCheckBox->isChecked() ? 1 : 0); + settings.endGroup(); - accept(); + accept(); } diff --git a/cockatrice/src/dlg_connect.h b/cockatrice/src/dlg_connect.h index 9a292c34..87fe4ed9 100644 --- a/cockatrice/src/dlg_connect.h +++ b/cockatrice/src/dlg_connect.h @@ -9,19 +9,19 @@ class QPushButton; class QCheckBox; class DlgConnect : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgConnect(QWidget *parent = 0); - QString getHost() const { return hostEdit->text(); } - int getPort() const { return portEdit->text().toInt(); } - QString getPlayerName() const { return playernameEdit->text(); } - QString getPassword() const { return passwordEdit->text(); } + DlgConnect(QWidget *parent = 0); + QString getHost() const { return hostEdit->text(); } + int getPort() const { return portEdit->text().toInt(); } + QString getPlayerName() const { return playernameEdit->text(); } + QString getPassword() const { return passwordEdit->text(); } private slots: - void actOk(); + void actOk(); private: - QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel; - QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit; - QCheckBox *savePasswordCheckBox; + QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel; + QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit; + QCheckBox *savePasswordCheckBox; }; #endif diff --git a/cockatrice/src/dlg_create_token.cpp b/cockatrice/src/dlg_create_token.cpp index 21d2eeac..942fdda6 100644 --- a/cockatrice/src/dlg_create_token.cpp +++ b/cockatrice/src/dlg_create_token.cpp @@ -16,160 +16,160 @@ #include "main.h" DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent) - : QDialog(parent), predefinedTokens(_predefinedTokens) + : QDialog(parent), predefinedTokens(_predefinedTokens) { - nameLabel = new QLabel(tr("&Name:")); - nameEdit = new QLineEdit(tr("Token")); - nameEdit->selectAll(); - nameLabel->setBuddy(nameEdit); + nameLabel = new QLabel(tr("&Name:")); + nameEdit = new QLineEdit(tr("Token")); + nameEdit->selectAll(); + nameLabel->setBuddy(nameEdit); - colorLabel = new QLabel(tr("C&olor:")); - colorEdit = new QComboBox; - colorEdit->addItem(tr("white"), "w"); - colorEdit->addItem(tr("blue"), "u"); - colorEdit->addItem(tr("black"), "b"); - colorEdit->addItem(tr("red"), "r"); - colorEdit->addItem(tr("green"), "g"); - colorEdit->addItem(tr("multicolor"), "m"); - colorEdit->addItem(tr("colorless"), QString()); - colorLabel->setBuddy(colorEdit); + colorLabel = new QLabel(tr("C&olor:")); + colorEdit = new QComboBox; + colorEdit->addItem(tr("white"), "w"); + colorEdit->addItem(tr("blue"), "u"); + colorEdit->addItem(tr("black"), "b"); + colorEdit->addItem(tr("red"), "r"); + colorEdit->addItem(tr("green"), "g"); + colorEdit->addItem(tr("multicolor"), "m"); + colorEdit->addItem(tr("colorless"), QString()); + colorLabel->setBuddy(colorEdit); - ptLabel = new QLabel(tr("&P/T:")); - ptEdit = new QLineEdit; - ptLabel->setBuddy(ptEdit); + ptLabel = new QLabel(tr("&P/T:")); + ptEdit = new QLineEdit; + ptLabel->setBuddy(ptEdit); - annotationLabel = new QLabel(tr("&Annotation:")); - annotationEdit = new QLineEdit; - annotationLabel->setBuddy(annotationEdit); - - destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table")); - destroyCheckBox->setChecked(true); + annotationLabel = new QLabel(tr("&Annotation:")); + annotationEdit = new QLineEdit; + annotationLabel->setBuddy(annotationEdit); + + destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table")); + destroyCheckBox->setChecked(true); - QGridLayout *grid = new QGridLayout; - grid->addWidget(nameLabel, 0, 0); - grid->addWidget(nameEdit, 0, 1); - grid->addWidget(colorLabel, 1, 0); - grid->addWidget(colorEdit, 1, 1); - grid->addWidget(ptLabel, 2, 0); - grid->addWidget(ptEdit, 2, 1); - grid->addWidget(annotationLabel, 3, 0); - grid->addWidget(annotationEdit, 3, 1); - grid->addWidget(destroyCheckBox, 4, 0, 1, 2); - - QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); - tokenDataGroupBox->setLayout(grid); - - cardDatabaseModel = new CardDatabaseModel(db, this); - cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); - cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); - cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); - - chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens")); - connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool))); - chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck")); - connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool))); - QTreeView *chooseTokenView = new QTreeView; - chooseTokenView->setModel(cardDatabaseDisplayModel); - chooseTokenView->setUniformRowHeights(true); - chooseTokenView->setRootIsDecorated(false); - chooseTokenView->setAlternatingRowColors(true); - chooseTokenView->setSortingEnabled(true); - chooseTokenView->sortByColumn(0, Qt::AscendingOrder); - chooseTokenView->resizeColumnToContents(0); - chooseTokenView->header()->setStretchLastSection(false); - chooseTokenView->header()->hideSection(1); - chooseTokenView->header()->hideSection(2); - chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); - chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); - connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); - - if (predefinedTokens.isEmpty()) - chooseTokenFromAllRadioButton->setChecked(true); - else { - chooseTokenFromDeckRadioButton->setChecked(true); - cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); - } - - QVBoxLayout *tokenChooseLayout = new QVBoxLayout; - tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton); - tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton); - tokenChooseLayout->addWidget(chooseTokenView); - - QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list")); - tokenChooseGroupBox->setLayout(tokenChooseLayout); - - QVBoxLayout *leftVBox = new QVBoxLayout; - leftVBox->addWidget(tokenDataGroupBox); - leftVBox->addStretch(); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addLayout(leftVBox); - hbox->addWidget(tokenChooseGroupBox); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hbox); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + QGridLayout *grid = new QGridLayout; + grid->addWidget(nameLabel, 0, 0); + grid->addWidget(nameEdit, 0, 1); + grid->addWidget(colorLabel, 1, 0); + grid->addWidget(colorEdit, 1, 1); + grid->addWidget(ptLabel, 2, 0); + grid->addWidget(ptEdit, 2, 1); + grid->addWidget(annotationLabel, 3, 0); + grid->addWidget(annotationEdit, 3, 1); + grid->addWidget(destroyCheckBox, 4, 0, 1, 2); + + QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); + tokenDataGroupBox->setLayout(grid); + + cardDatabaseModel = new CardDatabaseModel(db, this); + cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); + cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); + cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); + + chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens")); + connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool))); + chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck")); + connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool))); + QTreeView *chooseTokenView = new QTreeView; + chooseTokenView->setModel(cardDatabaseDisplayModel); + chooseTokenView->setUniformRowHeights(true); + chooseTokenView->setRootIsDecorated(false); + chooseTokenView->setAlternatingRowColors(true); + chooseTokenView->setSortingEnabled(true); + chooseTokenView->sortByColumn(0, Qt::AscendingOrder); + chooseTokenView->resizeColumnToContents(0); + chooseTokenView->header()->setStretchLastSection(false); + chooseTokenView->header()->hideSection(1); + chooseTokenView->header()->hideSection(2); + chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); + chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); + connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); + + if (predefinedTokens.isEmpty()) + chooseTokenFromAllRadioButton->setChecked(true); + else { + chooseTokenFromDeckRadioButton->setChecked(true); + cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); + } + + QVBoxLayout *tokenChooseLayout = new QVBoxLayout; + tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton); + tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton); + tokenChooseLayout->addWidget(chooseTokenView); + + QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list")); + tokenChooseGroupBox->setLayout(tokenChooseLayout); + + QVBoxLayout *leftVBox = new QVBoxLayout; + leftVBox->addWidget(tokenDataGroupBox); + leftVBox->addStretch(); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addLayout(leftVBox); + hbox->addWidget(tokenChooseGroupBox); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hbox); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); - setWindowTitle(tr("Create token")); - setFixedHeight(sizeHint().height()); - setMinimumWidth(300); + setWindowTitle(tr("Create token")); + setFixedHeight(sizeHint().height()); + setMinimumWidth(300); } void DlgCreateToken::tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/) { - const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); - const CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : db->getCard(); - - nameEdit->setText(cardInfo->getName()); - const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); - colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); - ptEdit->setText(cardInfo->getPowTough()); - annotationEdit->setText(cardInfo->getText()); + const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); + const CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : db->getCard(); + + nameEdit->setText(cardInfo->getName()); + const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); + colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); + ptEdit->setText(cardInfo->getPowTough()); + annotationEdit->setText(cardInfo->getText()); } void DlgCreateToken::actChooseTokenFromAll(bool checked) { - if (checked) - cardDatabaseDisplayModel->setCardNameSet(QSet()); + if (checked) + cardDatabaseDisplayModel->setCardNameSet(QSet()); } void DlgCreateToken::actChooseTokenFromDeck(bool checked) { - if (checked) - cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); + if (checked) + cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); } void DlgCreateToken::actOk() { - accept(); + accept(); } QString DlgCreateToken::getName() const { - return nameEdit->text(); + return nameEdit->text(); } QString DlgCreateToken::getColor() const { - return colorEdit->itemData(colorEdit->currentIndex()).toString(); + return colorEdit->itemData(colorEdit->currentIndex()).toString(); } QString DlgCreateToken::getPT() const { - return ptEdit->text(); + return ptEdit->text(); } QString DlgCreateToken::getAnnotation() const { - return annotationEdit->text(); + return annotationEdit->text(); } bool DlgCreateToken::getDestroy() const { - return destroyCheckBox->isChecked(); + return destroyCheckBox->isChecked(); } diff --git a/cockatrice/src/dlg_create_token.h b/cockatrice/src/dlg_create_token.h index 2bc371fe..45d7c2c5 100644 --- a/cockatrice/src/dlg_create_token.h +++ b/cockatrice/src/dlg_create_token.h @@ -15,28 +15,28 @@ class CardDatabaseModel; class CardDatabaseDisplayModel; class DlgCreateToken : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0); - QString getName() const; - QString getColor() const; - QString getPT() const; - QString getAnnotation() const; - bool getDestroy() const; + DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0); + QString getName() const; + QString getColor() const; + QString getPT() const; + QString getAnnotation() const; + bool getDestroy() const; private slots: - void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); - void actChooseTokenFromAll(bool checked); - void actChooseTokenFromDeck(bool checked); - void actOk(); + void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); + void actChooseTokenFromAll(bool checked); + void actChooseTokenFromDeck(bool checked); + void actOk(); private: - CardDatabaseModel *cardDatabaseModel; - CardDatabaseDisplayModel *cardDatabaseDisplayModel; - QStringList predefinedTokens; - QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; - QComboBox *colorEdit; - QLineEdit *nameEdit, *ptEdit, *annotationEdit; - QCheckBox *destroyCheckBox; - QRadioButton *chooseTokenFromAllRadioButton, *chooseTokenFromDeckRadioButton; + CardDatabaseModel *cardDatabaseModel; + CardDatabaseDisplayModel *cardDatabaseDisplayModel; + QStringList predefinedTokens; + QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; + QComboBox *colorEdit; + QLineEdit *nameEdit, *ptEdit, *annotationEdit; + QCheckBox *destroyCheckBox; + QRadioButton *chooseTokenFromAllRadioButton, *chooseTokenFromDeckRadioButton; }; #endif diff --git a/cockatrice/src/dlg_creategame.cpp b/cockatrice/src/dlg_creategame.cpp index 6dd88901..fc62df7d 100644 --- a/cockatrice/src/dlg_creategame.cpp +++ b/cockatrice/src/dlg_creategame.cpp @@ -20,180 +20,180 @@ void DlgCreateGame::sharedCtor() { - descriptionLabel = new QLabel(tr("&Description:")); - descriptionEdit = new QLineEdit; - descriptionLabel->setBuddy(descriptionEdit); - descriptionEdit->setMaxLength(60); + descriptionLabel = new QLabel(tr("&Description:")); + descriptionEdit = new QLineEdit; + descriptionLabel->setBuddy(descriptionEdit); + descriptionEdit->setMaxLength(60); - maxPlayersLabel = new QLabel(tr("P&layers:")); - maxPlayersEdit = new QSpinBox(); - maxPlayersEdit->setMinimum(1); - maxPlayersEdit->setMaximum(100); - maxPlayersEdit->setValue(2); - maxPlayersLabel->setBuddy(maxPlayersEdit); - - QGridLayout *generalGrid = new QGridLayout; - generalGrid->addWidget(descriptionLabel, 0, 0); - generalGrid->addWidget(descriptionEdit, 0, 1); - generalGrid->addWidget(maxPlayersLabel, 1, 0); - generalGrid->addWidget(maxPlayersEdit, 1, 1); - - QVBoxLayout *gameTypeLayout = new QVBoxLayout; - QMapIterator gameTypeIterator(gameTypes); - while (gameTypeIterator.hasNext()) { - gameTypeIterator.next(); - QCheckBox *gameTypeCheckBox = new QCheckBox(gameTypeIterator.value()); - gameTypeLayout->addWidget(gameTypeCheckBox); - gameTypeCheckBoxes.insert(gameTypeIterator.key(), gameTypeCheckBox); - } - QGroupBox *gameTypeGroupBox = new QGroupBox(tr("Game type")); - gameTypeGroupBox->setLayout(gameTypeLayout); - - passwordLabel = new QLabel(tr("&Password:")); - passwordEdit = new QLineEdit; - passwordLabel->setBuddy(passwordEdit); + maxPlayersLabel = new QLabel(tr("P&layers:")); + maxPlayersEdit = new QSpinBox(); + maxPlayersEdit->setMinimum(1); + maxPlayersEdit->setMaximum(100); + maxPlayersEdit->setValue(2); + maxPlayersLabel->setBuddy(maxPlayersEdit); + + QGridLayout *generalGrid = new QGridLayout; + generalGrid->addWidget(descriptionLabel, 0, 0); + generalGrid->addWidget(descriptionEdit, 0, 1); + generalGrid->addWidget(maxPlayersLabel, 1, 0); + generalGrid->addWidget(maxPlayersEdit, 1, 1); + + QVBoxLayout *gameTypeLayout = new QVBoxLayout; + QMapIterator gameTypeIterator(gameTypes); + while (gameTypeIterator.hasNext()) { + gameTypeIterator.next(); + QCheckBox *gameTypeCheckBox = new QCheckBox(gameTypeIterator.value()); + gameTypeLayout->addWidget(gameTypeCheckBox); + gameTypeCheckBoxes.insert(gameTypeIterator.key(), gameTypeCheckBox); + } + QGroupBox *gameTypeGroupBox = new QGroupBox(tr("Game type")); + gameTypeGroupBox->setLayout(gameTypeLayout); + + passwordLabel = new QLabel(tr("&Password:")); + passwordEdit = new QLineEdit; + passwordLabel->setBuddy(passwordEdit); - onlyBuddiesCheckBox = new QCheckBox(tr("Only &buddies can join")); - onlyRegisteredCheckBox = new QCheckBox(tr("Only ®istered users can join")); - if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) - onlyRegisteredCheckBox->setChecked(true); - - QGridLayout *joinRestrictionsLayout = new QGridLayout; - joinRestrictionsLayout->addWidget(passwordLabel, 0, 0); - joinRestrictionsLayout->addWidget(passwordEdit, 0, 1); - joinRestrictionsLayout->addWidget(onlyBuddiesCheckBox, 1, 0, 1, 2); - joinRestrictionsLayout->addWidget(onlyRegisteredCheckBox, 2, 0, 1, 2); - - QGroupBox *joinRestrictionsGroupBox = new QGroupBox(tr("Joining restrictions")); - joinRestrictionsGroupBox->setLayout(joinRestrictionsLayout); - - spectatorsAllowedCheckBox = new QCheckBox(tr("&Spectators allowed")); - spectatorsAllowedCheckBox->setChecked(true); - connect(spectatorsAllowedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(spectatorsAllowedChanged(int))); - spectatorsNeedPasswordCheckBox = new QCheckBox(tr("Spectators &need a password to join")); - spectatorsCanTalkCheckBox = new QCheckBox(tr("Spectators can &chat")); - spectatorsSeeEverythingCheckBox = new QCheckBox(tr("Spectators see &everything")); - QVBoxLayout *spectatorsLayout = new QVBoxLayout; - spectatorsLayout->addWidget(spectatorsAllowedCheckBox); - spectatorsLayout->addWidget(spectatorsNeedPasswordCheckBox); - spectatorsLayout->addWidget(spectatorsCanTalkCheckBox); - spectatorsLayout->addWidget(spectatorsSeeEverythingCheckBox); - spectatorsGroupBox = new QGroupBox(tr("Spectators")); - spectatorsGroupBox->setLayout(spectatorsLayout); + onlyBuddiesCheckBox = new QCheckBox(tr("Only &buddies can join")); + onlyRegisteredCheckBox = new QCheckBox(tr("Only ®istered users can join")); + if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) + onlyRegisteredCheckBox->setChecked(true); + + QGridLayout *joinRestrictionsLayout = new QGridLayout; + joinRestrictionsLayout->addWidget(passwordLabel, 0, 0); + joinRestrictionsLayout->addWidget(passwordEdit, 0, 1); + joinRestrictionsLayout->addWidget(onlyBuddiesCheckBox, 1, 0, 1, 2); + joinRestrictionsLayout->addWidget(onlyRegisteredCheckBox, 2, 0, 1, 2); + + QGroupBox *joinRestrictionsGroupBox = new QGroupBox(tr("Joining restrictions")); + joinRestrictionsGroupBox->setLayout(joinRestrictionsLayout); + + spectatorsAllowedCheckBox = new QCheckBox(tr("&Spectators allowed")); + spectatorsAllowedCheckBox->setChecked(true); + connect(spectatorsAllowedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(spectatorsAllowedChanged(int))); + spectatorsNeedPasswordCheckBox = new QCheckBox(tr("Spectators &need a password to join")); + spectatorsCanTalkCheckBox = new QCheckBox(tr("Spectators can &chat")); + spectatorsSeeEverythingCheckBox = new QCheckBox(tr("Spectators see &everything")); + QVBoxLayout *spectatorsLayout = new QVBoxLayout; + spectatorsLayout->addWidget(spectatorsAllowedCheckBox); + spectatorsLayout->addWidget(spectatorsNeedPasswordCheckBox); + spectatorsLayout->addWidget(spectatorsCanTalkCheckBox); + spectatorsLayout->addWidget(spectatorsSeeEverythingCheckBox); + spectatorsGroupBox = new QGroupBox(tr("Spectators")); + spectatorsGroupBox->setLayout(spectatorsLayout); - QGridLayout *grid = new QGridLayout; - grid->addLayout(generalGrid, 0, 0); - grid->addWidget(spectatorsGroupBox, 1, 0); - grid->addWidget(joinRestrictionsGroupBox, 0, 1); - grid->addWidget(gameTypeGroupBox, 1, 1); + QGridLayout *grid = new QGridLayout; + grid->addLayout(generalGrid, 0, 0); + grid->addWidget(spectatorsGroupBox, 1, 0); + grid->addWidget(joinRestrictionsGroupBox, 0, 1); + grid->addWidget(gameTypeGroupBox, 1, 1); - buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(grid); - mainLayout->addWidget(buttonBox); + buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(grid); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + setLayout(mainLayout); - setFixedHeight(sizeHint().height()); + setFixedHeight(sizeHint().height()); } DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent) - : QDialog(parent), room(_room), gameTypes(_gameTypes) + : QDialog(parent), room(_room), gameTypes(_gameTypes) { - sharedCtor(); - - buttonBox->addButton(QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); - - setWindowTitle(tr("Create game")); + sharedCtor(); + + buttonBox->addButton(QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); + + setWindowTitle(tr("Create game")); } DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap &_gameTypes, QWidget *parent) - : QDialog(parent), room(0), gameTypes(_gameTypes) + : QDialog(parent), room(0), gameTypes(_gameTypes) { - sharedCtor(); - - descriptionEdit->setEnabled(false); - maxPlayersEdit->setEnabled(false); - passwordEdit->setEnabled(false); - onlyBuddiesCheckBox->setEnabled(false); - onlyRegisteredCheckBox->setEnabled(false); - spectatorsAllowedCheckBox->setEnabled(false); - spectatorsNeedPasswordCheckBox->setEnabled(false); - spectatorsCanTalkCheckBox->setEnabled(false); - spectatorsSeeEverythingCheckBox->setEnabled(false); - - descriptionEdit->setText(QString::fromStdString(gameInfo.description())); - maxPlayersEdit->setValue(gameInfo.max_players()); - onlyBuddiesCheckBox->setChecked(gameInfo.only_buddies()); - onlyRegisteredCheckBox->setChecked(gameInfo.only_registered()); - spectatorsAllowedCheckBox->setChecked(gameInfo.spectators_allowed()); - spectatorsNeedPasswordCheckBox->setChecked(gameInfo.spectators_need_password()); - spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat()); - spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient()); - - QSet types; - for (int i = 0; i < gameInfo.game_types_size(); ++i) - types.insert(gameInfo.game_types(i)); - - QMapIterator gameTypeIterator(gameTypes); - while (gameTypeIterator.hasNext()) { - gameTypeIterator.next(); - - QCheckBox *gameTypeCheckBox = gameTypeCheckBoxes.value(gameTypeIterator.key()); - gameTypeCheckBox->setEnabled(false); - gameTypeCheckBox->setChecked(types.contains(gameTypeIterator.key())); - } - - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - - setWindowTitle(tr("Game information")); + sharedCtor(); + + descriptionEdit->setEnabled(false); + maxPlayersEdit->setEnabled(false); + passwordEdit->setEnabled(false); + onlyBuddiesCheckBox->setEnabled(false); + onlyRegisteredCheckBox->setEnabled(false); + spectatorsAllowedCheckBox->setEnabled(false); + spectatorsNeedPasswordCheckBox->setEnabled(false); + spectatorsCanTalkCheckBox->setEnabled(false); + spectatorsSeeEverythingCheckBox->setEnabled(false); + + descriptionEdit->setText(QString::fromStdString(gameInfo.description())); + maxPlayersEdit->setValue(gameInfo.max_players()); + onlyBuddiesCheckBox->setChecked(gameInfo.only_buddies()); + onlyRegisteredCheckBox->setChecked(gameInfo.only_registered()); + spectatorsAllowedCheckBox->setChecked(gameInfo.spectators_allowed()); + spectatorsNeedPasswordCheckBox->setChecked(gameInfo.spectators_need_password()); + spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat()); + spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient()); + + QSet types; + for (int i = 0; i < gameInfo.game_types_size(); ++i) + types.insert(gameInfo.game_types(i)); + + QMapIterator gameTypeIterator(gameTypes); + while (gameTypeIterator.hasNext()) { + gameTypeIterator.next(); + + QCheckBox *gameTypeCheckBox = gameTypeCheckBoxes.value(gameTypeIterator.key()); + gameTypeCheckBox->setEnabled(false); + gameTypeCheckBox->setChecked(types.contains(gameTypeIterator.key())); + } + + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + + setWindowTitle(tr("Game information")); } void DlgCreateGame::actOK() { - Command_CreateGame cmd; - cmd.set_description(descriptionEdit->text().toStdString()); - cmd.set_password(passwordEdit->text().toStdString()); - cmd.set_max_players(maxPlayersEdit->value()); - cmd.set_only_buddies(onlyBuddiesCheckBox->isChecked()); - cmd.set_only_registered(onlyRegisteredCheckBox->isChecked()); - cmd.set_spectators_allowed(spectatorsAllowedCheckBox->isChecked()); - cmd.set_spectators_need_password(spectatorsNeedPasswordCheckBox->isChecked()); - cmd.set_spectators_can_talk(spectatorsCanTalkCheckBox->isChecked()); - cmd.set_spectators_see_everything(spectatorsSeeEverythingCheckBox->isChecked()); - - QMapIterator gameTypeCheckBoxIterator(gameTypeCheckBoxes); - while (gameTypeCheckBoxIterator.hasNext()) { - gameTypeCheckBoxIterator.next(); - if (gameTypeCheckBoxIterator.value()->isChecked()) - cmd.add_game_type_ids(gameTypeCheckBoxIterator.key()); - } - - PendingCommand *pend = room->prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); - room->sendRoomCommand(pend); - - buttonBox->setEnabled(false); + Command_CreateGame cmd; + cmd.set_description(descriptionEdit->text().toStdString()); + cmd.set_password(passwordEdit->text().toStdString()); + cmd.set_max_players(maxPlayersEdit->value()); + cmd.set_only_buddies(onlyBuddiesCheckBox->isChecked()); + cmd.set_only_registered(onlyRegisteredCheckBox->isChecked()); + cmd.set_spectators_allowed(spectatorsAllowedCheckBox->isChecked()); + cmd.set_spectators_need_password(spectatorsNeedPasswordCheckBox->isChecked()); + cmd.set_spectators_can_talk(spectatorsCanTalkCheckBox->isChecked()); + cmd.set_spectators_see_everything(spectatorsSeeEverythingCheckBox->isChecked()); + + QMapIterator gameTypeCheckBoxIterator(gameTypeCheckBoxes); + while (gameTypeCheckBoxIterator.hasNext()) { + gameTypeCheckBoxIterator.next(); + if (gameTypeCheckBoxIterator.value()->isChecked()) + cmd.add_game_type_ids(gameTypeCheckBoxIterator.key()); + } + + PendingCommand *pend = room->prepareRoomCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); + room->sendRoomCommand(pend); + + buttonBox->setEnabled(false); } void DlgCreateGame::checkResponse(const Response &response) { - buttonBox->setEnabled(true); + buttonBox->setEnabled(true); - if (response.response_code() == Response::RespOk) - accept(); - else { - QMessageBox::critical(this, tr("Error"), tr("Server error.")); - return; - } + if (response.response_code() == Response::RespOk) + accept(); + else { + QMessageBox::critical(this, tr("Error"), tr("Server error.")); + return; + } } void DlgCreateGame::spectatorsAllowedChanged(int state) { - spectatorsNeedPasswordCheckBox->setEnabled(state); - spectatorsCanTalkCheckBox->setEnabled(state); - spectatorsSeeEverythingCheckBox->setEnabled(state); + spectatorsNeedPasswordCheckBox->setEnabled(state); + spectatorsCanTalkCheckBox->setEnabled(state); + spectatorsSeeEverythingCheckBox->setEnabled(state); } diff --git a/cockatrice/src/dlg_creategame.h b/cockatrice/src/dlg_creategame.h index b6ee2046..032bfc6f 100644 --- a/cockatrice/src/dlg_creategame.h +++ b/cockatrice/src/dlg_creategame.h @@ -17,28 +17,28 @@ class Response; class ServerInfo_Game; class DlgCreateGame : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent = 0); - DlgCreateGame(const ServerInfo_Game &game, const QMap &_gameTypes, QWidget *parent = 0); + DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent = 0); + DlgCreateGame(const ServerInfo_Game &game, const QMap &_gameTypes, QWidget *parent = 0); private slots: - void actOK(); - void checkResponse(const Response &response); - void spectatorsAllowedChanged(int state); + void actOK(); + void checkResponse(const Response &response); + void spectatorsAllowedChanged(int state); private: - TabRoom *room; - QMap gameTypes; - QMap gameTypeCheckBoxes; + TabRoom *room; + QMap gameTypes; + QMap gameTypeCheckBoxes; - QGroupBox *spectatorsGroupBox; - QLabel *descriptionLabel, *passwordLabel, *maxPlayersLabel; - QLineEdit *descriptionEdit, *passwordEdit; - QSpinBox *maxPlayersEdit; - QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox; - QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox; - QDialogButtonBox *buttonBox; - - void sharedCtor(); + QGroupBox *spectatorsGroupBox; + QLabel *descriptionLabel, *passwordLabel, *maxPlayersLabel; + QLineEdit *descriptionEdit, *passwordEdit; + QSpinBox *maxPlayersEdit; + QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox; + QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox; + QDialogButtonBox *buttonBox; + + void sharedCtor(); }; #endif diff --git a/cockatrice/src/dlg_edit_tokens.cpp b/cockatrice/src/dlg_edit_tokens.cpp index 4e41d578..038b1a4a 100644 --- a/cockatrice/src/dlg_edit_tokens.cpp +++ b/cockatrice/src/dlg_edit_tokens.cpp @@ -16,160 +16,160 @@ #include DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent) - : QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel) + : QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel) { - nameLabel = new QLabel(tr("&Name:")); - nameEdit = new QLineEdit; - nameEdit->setEnabled(false); - nameLabel->setBuddy(nameEdit); - - colorLabel = new QLabel(tr("C&olor:")); - colorEdit = new QComboBox; - colorEdit->addItem(tr("white"), "w"); - colorEdit->addItem(tr("blue"), "u"); - colorEdit->addItem(tr("black"), "b"); - colorEdit->addItem(tr("red"), "r"); - colorEdit->addItem(tr("green"), "g"); - colorEdit->addItem(tr("multicolor"), "m"); - colorEdit->addItem(tr("colorless"), QString()); - colorLabel->setBuddy(colorEdit); - connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int))); - - ptLabel = new QLabel(tr("&P/T:")); - ptEdit = new QLineEdit; - ptLabel->setBuddy(ptEdit); - connect(ptEdit, SIGNAL(textChanged(QString)), this, SLOT(ptChanged(QString))); - - annotationLabel = new QLabel(tr("&Annotation:")); - annotationEdit = new QLineEdit; - annotationLabel->setBuddy(annotationEdit); - connect(annotationEdit, SIGNAL(textChanged(QString)), this, SLOT(annotationChanged(QString))); - - QGridLayout *grid = new QGridLayout; - grid->addWidget(nameLabel, 0, 0); - grid->addWidget(nameEdit, 0, 1); - grid->addWidget(colorLabel, 1, 0); - grid->addWidget(colorEdit, 1, 1); - grid->addWidget(ptLabel, 2, 0); - grid->addWidget(ptEdit, 2, 1); - grid->addWidget(annotationLabel, 3, 0); - grid->addWidget(annotationEdit, 3, 1); - - QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); - tokenDataGroupBox->setLayout(grid); - - cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); - cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); - cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); - - chooseTokenView = new QTreeView; - chooseTokenView->setModel(cardDatabaseDisplayModel); - chooseTokenView->setUniformRowHeights(true); - chooseTokenView->setRootIsDecorated(false); - chooseTokenView->setAlternatingRowColors(true); - chooseTokenView->setSortingEnabled(true); - chooseTokenView->sortByColumn(0, Qt::AscendingOrder); - chooseTokenView->resizeColumnToContents(0); - chooseTokenView->header()->setStretchLastSection(false); - chooseTokenView->header()->hideSection(1); - chooseTokenView->header()->hideSection(2); - chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); - chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); - connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); - - QAction *aAddToken = new QAction(tr("Add token"), this); - aAddToken->setIcon(QIcon(":/resources/increment.svg")); - connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken())); - QAction *aRemoveToken = new QAction(tr("Remove token"), this); - aRemoveToken->setIcon(QIcon(":/resources/decrement.svg")); - connect(aRemoveToken, SIGNAL(triggered()), this, SLOT(actRemoveToken())); - - QToolBar *databaseToolBar = new QToolBar; - databaseToolBar->addAction(aAddToken); - databaseToolBar->addAction(aRemoveToken); - - QVBoxLayout *leftVBox = new QVBoxLayout; - leftVBox->addWidget(chooseTokenView); - leftVBox->addWidget(databaseToolBar); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addLayout(leftVBox); - hbox->addWidget(tokenDataGroupBox); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hbox); - mainLayout->addWidget(buttonBox); + nameLabel = new QLabel(tr("&Name:")); + nameEdit = new QLineEdit; + nameEdit->setEnabled(false); + nameLabel->setBuddy(nameEdit); + + colorLabel = new QLabel(tr("C&olor:")); + colorEdit = new QComboBox; + colorEdit->addItem(tr("white"), "w"); + colorEdit->addItem(tr("blue"), "u"); + colorEdit->addItem(tr("black"), "b"); + colorEdit->addItem(tr("red"), "r"); + colorEdit->addItem(tr("green"), "g"); + colorEdit->addItem(tr("multicolor"), "m"); + colorEdit->addItem(tr("colorless"), QString()); + colorLabel->setBuddy(colorEdit); + connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int))); + + ptLabel = new QLabel(tr("&P/T:")); + ptEdit = new QLineEdit; + ptLabel->setBuddy(ptEdit); + connect(ptEdit, SIGNAL(textChanged(QString)), this, SLOT(ptChanged(QString))); + + annotationLabel = new QLabel(tr("&Annotation:")); + annotationEdit = new QLineEdit; + annotationLabel->setBuddy(annotationEdit); + connect(annotationEdit, SIGNAL(textChanged(QString)), this, SLOT(annotationChanged(QString))); + + QGridLayout *grid = new QGridLayout; + grid->addWidget(nameLabel, 0, 0); + grid->addWidget(nameEdit, 0, 1); + grid->addWidget(colorLabel, 1, 0); + grid->addWidget(colorEdit, 1, 1); + grid->addWidget(ptLabel, 2, 0); + grid->addWidget(ptEdit, 2, 1); + grid->addWidget(annotationLabel, 3, 0); + grid->addWidget(annotationEdit, 3, 1); + + QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); + tokenDataGroupBox->setLayout(grid); + + cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); + cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); + cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); + + chooseTokenView = new QTreeView; + chooseTokenView->setModel(cardDatabaseDisplayModel); + chooseTokenView->setUniformRowHeights(true); + chooseTokenView->setRootIsDecorated(false); + chooseTokenView->setAlternatingRowColors(true); + chooseTokenView->setSortingEnabled(true); + chooseTokenView->sortByColumn(0, Qt::AscendingOrder); + chooseTokenView->resizeColumnToContents(0); + chooseTokenView->header()->setStretchLastSection(false); + chooseTokenView->header()->hideSection(1); + chooseTokenView->header()->hideSection(2); + chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); + chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); + connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); + + QAction *aAddToken = new QAction(tr("Add token"), this); + aAddToken->setIcon(QIcon(":/resources/increment.svg")); + connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken())); + QAction *aRemoveToken = new QAction(tr("Remove token"), this); + aRemoveToken->setIcon(QIcon(":/resources/decrement.svg")); + connect(aRemoveToken, SIGNAL(triggered()), this, SLOT(actRemoveToken())); + + QToolBar *databaseToolBar = new QToolBar; + databaseToolBar->addAction(aAddToken); + databaseToolBar->addAction(aRemoveToken); + + QVBoxLayout *leftVBox = new QVBoxLayout; + leftVBox->addWidget(chooseTokenView); + leftVBox->addWidget(databaseToolBar); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addLayout(leftVBox); + hbox->addWidget(tokenDataGroupBox); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hbox); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); - setWindowTitle(tr("Edit tokens")); + setLayout(mainLayout); + setWindowTitle(tr("Edit tokens")); } void DlgEditTokens::tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous) { - const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); - CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard(); - if (!cardInfo->getName().isEmpty()) - currentCard = cardInfo; - else - currentCard = 0; - - nameEdit->setText(cardInfo->getName()); - const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); - colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); - ptEdit->setText(cardInfo->getPowTough()); - annotationEdit->setText(cardInfo->getText()); + const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); + CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard(); + if (!cardInfo->getName().isEmpty()) + currentCard = cardInfo; + else + currentCard = 0; + + nameEdit->setText(cardInfo->getName()); + const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); + colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); + ptEdit->setText(cardInfo->getPowTough()); + annotationEdit->setText(cardInfo->getText()); } void DlgEditTokens::actAddToken() { - QString name; - bool askAgain; - do { - name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:")); - if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) { - QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.")); - askAgain = true; - } else - askAgain = false; - } while (askAgain); - - if (name.isEmpty()) - return; - - CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true); - card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK")); - card->setCardType("Token"); - cardDatabaseModel->getDatabase()->addCard(card); + QString name; + bool askAgain; + do { + name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:")); + if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) { + QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.")); + askAgain = true; + } else + askAgain = false; + } while (askAgain); + + if (name.isEmpty()) + return; + + CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true); + card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK")); + card->setCardType("Token"); + cardDatabaseModel->getDatabase()->addCard(card); } void DlgEditTokens::actRemoveToken() { - if (currentCard) { - CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() - currentCard = 0; - cardDatabaseModel->getDatabase()->removeCard(cardToRemove); - delete cardToRemove; - } + if (currentCard) { + CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() + currentCard = 0; + cardDatabaseModel->getDatabase()->removeCard(cardToRemove); + delete cardToRemove; + } } void DlgEditTokens::colorChanged(int colorIndex) { - if (currentCard) - currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString()); + if (currentCard) + currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString()); } void DlgEditTokens::ptChanged(const QString &_pt) { - if (currentCard) - currentCard->setPowTough(_pt); + if (currentCard) + currentCard->setPowTough(_pt); } void DlgEditTokens::annotationChanged(const QString &_annotation) { - if (currentCard) - currentCard->setText(_annotation); + if (currentCard) + currentCard->setText(_annotation); } diff --git a/cockatrice/src/dlg_edit_tokens.h b/cockatrice/src/dlg_edit_tokens.h index ac36512e..61d941ff 100644 --- a/cockatrice/src/dlg_edit_tokens.h +++ b/cockatrice/src/dlg_edit_tokens.h @@ -13,26 +13,26 @@ class QTreeView; class CardInfo; class DlgEditTokens : public QDialog { - Q_OBJECT + Q_OBJECT private slots: - void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); - void colorChanged(int _colorIndex); - void ptChanged(const QString &_pt); - void annotationChanged(const QString &_annotation); - - void actAddToken(); - void actRemoveToken(); + void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); + void colorChanged(int _colorIndex); + void ptChanged(const QString &_pt); + void annotationChanged(const QString &_annotation); + + void actAddToken(); + void actRemoveToken(); private: - CardInfo *currentCard; - CardDatabaseModel *cardDatabaseModel; - CardDatabaseDisplayModel *cardDatabaseDisplayModel; - QStringList predefinedTokens; - QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; - QComboBox *colorEdit; - QLineEdit *nameEdit, *ptEdit, *annotationEdit; - QTreeView *chooseTokenView; + CardInfo *currentCard; + CardDatabaseModel *cardDatabaseModel; + CardDatabaseDisplayModel *cardDatabaseDisplayModel; + QStringList predefinedTokens; + QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; + QComboBox *colorEdit; + QLineEdit *nameEdit, *ptEdit, *annotationEdit; + QTreeView *chooseTokenView; public: - DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0); + DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/dlg_filter_games.cpp b/cockatrice/src/dlg_filter_games.cpp index 721a3d20..5e402294 100644 --- a/cockatrice/src/dlg_filter_games.cpp +++ b/cockatrice/src/dlg_filter_games.cpp @@ -11,162 +11,162 @@ #include DlgFilterGames::DlgFilterGames(const QMap &allGameTypes, QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - unavailableGamesVisibleCheckBox = new QCheckBox(tr("Show &unavailable games")); - passwordProtectedGamesVisibleCheckBox = new QCheckBox(tr("Show &password protected games")); - - QLabel *gameNameFilterLabel = new QLabel(tr("Game &description:")); - gameNameFilterEdit = new QLineEdit; - gameNameFilterLabel->setBuddy(gameNameFilterEdit); - - QLabel *creatorNameFilterLabel = new QLabel(tr("&Creator name:")); - creatorNameFilterEdit = new QLineEdit; - creatorNameFilterLabel->setBuddy(creatorNameFilterEdit); - - QVBoxLayout *gameTypeFilterLayout = new QVBoxLayout; - QMapIterator gameTypesIterator(allGameTypes); - while (gameTypesIterator.hasNext()) { - gameTypesIterator.next(); - QCheckBox *temp = new QCheckBox(gameTypesIterator.value()); - gameTypeFilterCheckBoxes.insert(gameTypesIterator.key(), temp); - gameTypeFilterLayout->addWidget(temp); - } - QGroupBox *gameTypeFilterGroupBox; - if (!allGameTypes.isEmpty()) { - gameTypeFilterGroupBox = new QGroupBox(tr("&Game types")); - gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout); - } else - gameTypeFilterGroupBox = 0; - - QLabel *maxPlayersFilterMinLabel = new QLabel(tr("at &least:")); - maxPlayersFilterMinSpinBox = new QSpinBox; - maxPlayersFilterMinSpinBox->setMinimum(1); - maxPlayersFilterMinSpinBox->setMaximum(99); - maxPlayersFilterMinSpinBox->setValue(1); - maxPlayersFilterMinLabel->setBuddy(maxPlayersFilterMinSpinBox); - - QLabel *maxPlayersFilterMaxLabel = new QLabel(tr("at &most:")); - maxPlayersFilterMaxSpinBox = new QSpinBox; - maxPlayersFilterMaxSpinBox->setMinimum(1); - maxPlayersFilterMaxSpinBox->setMaximum(99); - maxPlayersFilterMaxSpinBox->setValue(99); - maxPlayersFilterMaxLabel->setBuddy(maxPlayersFilterMaxSpinBox); - - QGridLayout *maxPlayersFilterLayout = new QGridLayout; - maxPlayersFilterLayout->addWidget(maxPlayersFilterMinLabel, 0, 0); - maxPlayersFilterLayout->addWidget(maxPlayersFilterMinSpinBox, 0, 1); - maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxLabel, 1, 0); - maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxSpinBox, 1, 1); - - QGroupBox *maxPlayersGroupBox = new QGroupBox(tr("Maximum player count")); - maxPlayersGroupBox->setLayout(maxPlayersFilterLayout); - - QGridLayout *leftGrid = new QGridLayout; - leftGrid->addWidget(gameNameFilterLabel, 0, 0); - leftGrid->addWidget(gameNameFilterEdit, 0, 1); - leftGrid->addWidget(creatorNameFilterLabel, 1, 0); - leftGrid->addWidget(creatorNameFilterEdit, 1, 1); - leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2); - leftGrid->addWidget(unavailableGamesVisibleCheckBox, 3, 0, 1, 2); - leftGrid->addWidget(passwordProtectedGamesVisibleCheckBox, 4, 0, 1, 2); - - QVBoxLayout *leftColumn = new QVBoxLayout; - leftColumn->addLayout(leftGrid); - leftColumn->addStretch(); - - QVBoxLayout *rightColumn = new QVBoxLayout; - rightColumn->addWidget(gameTypeFilterGroupBox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addLayout(leftColumn); - hbox->addLayout(rightColumn); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hbox); - mainLayout->addWidget(buttonBox); - - setLayout(mainLayout); - setWindowTitle(tr("Filter games")); + unavailableGamesVisibleCheckBox = new QCheckBox(tr("Show &unavailable games")); + passwordProtectedGamesVisibleCheckBox = new QCheckBox(tr("Show &password protected games")); + + QLabel *gameNameFilterLabel = new QLabel(tr("Game &description:")); + gameNameFilterEdit = new QLineEdit; + gameNameFilterLabel->setBuddy(gameNameFilterEdit); + + QLabel *creatorNameFilterLabel = new QLabel(tr("&Creator name:")); + creatorNameFilterEdit = new QLineEdit; + creatorNameFilterLabel->setBuddy(creatorNameFilterEdit); + + QVBoxLayout *gameTypeFilterLayout = new QVBoxLayout; + QMapIterator gameTypesIterator(allGameTypes); + while (gameTypesIterator.hasNext()) { + gameTypesIterator.next(); + QCheckBox *temp = new QCheckBox(gameTypesIterator.value()); + gameTypeFilterCheckBoxes.insert(gameTypesIterator.key(), temp); + gameTypeFilterLayout->addWidget(temp); + } + QGroupBox *gameTypeFilterGroupBox; + if (!allGameTypes.isEmpty()) { + gameTypeFilterGroupBox = new QGroupBox(tr("&Game types")); + gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout); + } else + gameTypeFilterGroupBox = 0; + + QLabel *maxPlayersFilterMinLabel = new QLabel(tr("at &least:")); + maxPlayersFilterMinSpinBox = new QSpinBox; + maxPlayersFilterMinSpinBox->setMinimum(1); + maxPlayersFilterMinSpinBox->setMaximum(99); + maxPlayersFilterMinSpinBox->setValue(1); + maxPlayersFilterMinLabel->setBuddy(maxPlayersFilterMinSpinBox); + + QLabel *maxPlayersFilterMaxLabel = new QLabel(tr("at &most:")); + maxPlayersFilterMaxSpinBox = new QSpinBox; + maxPlayersFilterMaxSpinBox->setMinimum(1); + maxPlayersFilterMaxSpinBox->setMaximum(99); + maxPlayersFilterMaxSpinBox->setValue(99); + maxPlayersFilterMaxLabel->setBuddy(maxPlayersFilterMaxSpinBox); + + QGridLayout *maxPlayersFilterLayout = new QGridLayout; + maxPlayersFilterLayout->addWidget(maxPlayersFilterMinLabel, 0, 0); + maxPlayersFilterLayout->addWidget(maxPlayersFilterMinSpinBox, 0, 1); + maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxLabel, 1, 0); + maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxSpinBox, 1, 1); + + QGroupBox *maxPlayersGroupBox = new QGroupBox(tr("Maximum player count")); + maxPlayersGroupBox->setLayout(maxPlayersFilterLayout); + + QGridLayout *leftGrid = new QGridLayout; + leftGrid->addWidget(gameNameFilterLabel, 0, 0); + leftGrid->addWidget(gameNameFilterEdit, 0, 1); + leftGrid->addWidget(creatorNameFilterLabel, 1, 0); + leftGrid->addWidget(creatorNameFilterEdit, 1, 1); + leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2); + leftGrid->addWidget(unavailableGamesVisibleCheckBox, 3, 0, 1, 2); + leftGrid->addWidget(passwordProtectedGamesVisibleCheckBox, 4, 0, 1, 2); + + QVBoxLayout *leftColumn = new QVBoxLayout; + leftColumn->addLayout(leftGrid); + leftColumn->addStretch(); + + QVBoxLayout *rightColumn = new QVBoxLayout; + rightColumn->addWidget(gameTypeFilterGroupBox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addLayout(leftColumn); + hbox->addLayout(rightColumn); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hbox); + mainLayout->addWidget(buttonBox); + + setLayout(mainLayout); + setWindowTitle(tr("Filter games")); } bool DlgFilterGames::getUnavailableGamesVisible() const { - return unavailableGamesVisibleCheckBox->isChecked(); + return unavailableGamesVisibleCheckBox->isChecked(); } void DlgFilterGames::setUnavailableGamesVisible(bool _unavailableGamesVisible) { - unavailableGamesVisibleCheckBox->setChecked(_unavailableGamesVisible); + unavailableGamesVisibleCheckBox->setChecked(_unavailableGamesVisible); } bool DlgFilterGames::getPasswordProtectedGamesVisible() const { - return passwordProtectedGamesVisibleCheckBox->isChecked(); + return passwordProtectedGamesVisibleCheckBox->isChecked(); } void DlgFilterGames::setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible) { - passwordProtectedGamesVisibleCheckBox->setChecked(_passwordProtectedGamesVisible); + passwordProtectedGamesVisibleCheckBox->setChecked(_passwordProtectedGamesVisible); } QString DlgFilterGames::getGameNameFilter() const { - return gameNameFilterEdit->text(); + return gameNameFilterEdit->text(); } void DlgFilterGames::setGameNameFilter(const QString &_gameNameFilter) { - gameNameFilterEdit->setText(_gameNameFilter); + gameNameFilterEdit->setText(_gameNameFilter); } QString DlgFilterGames::getCreatorNameFilter() const { - return creatorNameFilterEdit->text(); + return creatorNameFilterEdit->text(); } void DlgFilterGames::setCreatorNameFilter(const QString &_creatorNameFilter) { - creatorNameFilterEdit->setText(_creatorNameFilter); + creatorNameFilterEdit->setText(_creatorNameFilter); } QSet DlgFilterGames::getGameTypeFilter() const { - QSet result; - QMapIterator i(gameTypeFilterCheckBoxes); - while (i.hasNext()) { - i.next(); - if (i.value()->isChecked()) - result.insert(i.key()); - } - return result; + QSet result; + QMapIterator i(gameTypeFilterCheckBoxes); + while (i.hasNext()) { + i.next(); + if (i.value()->isChecked()) + result.insert(i.key()); + } + return result; } void DlgFilterGames::setGameTypeFilter(const QSet &_gameTypeFilter) { - QMapIterator i(gameTypeFilterCheckBoxes); - while (i.hasNext()) { - i.next(); - i.value()->setChecked(_gameTypeFilter.contains(i.key())); - } + QMapIterator i(gameTypeFilterCheckBoxes); + while (i.hasNext()) { + i.next(); + i.value()->setChecked(_gameTypeFilter.contains(i.key())); + } } int DlgFilterGames::getMaxPlayersFilterMin() const { - return maxPlayersFilterMinSpinBox->value(); + return maxPlayersFilterMinSpinBox->value(); } int DlgFilterGames::getMaxPlayersFilterMax() const { - return maxPlayersFilterMaxSpinBox->value(); + return maxPlayersFilterMaxSpinBox->value(); } void DlgFilterGames::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax) { - maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin); - maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax); + maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin); + maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax); } diff --git a/cockatrice/src/dlg_filter_games.h b/cockatrice/src/dlg_filter_games.h index 5c768bc1..8059da45 100644 --- a/cockatrice/src/dlg_filter_games.h +++ b/cockatrice/src/dlg_filter_games.h @@ -10,31 +10,31 @@ class QLineEdit; class QSpinBox; class DlgFilterGames : public QDialog { - Q_OBJECT + Q_OBJECT private: - QCheckBox *unavailableGamesVisibleCheckBox; - QCheckBox *passwordProtectedGamesVisibleCheckBox; - QLineEdit *gameNameFilterEdit; - QLineEdit *creatorNameFilterEdit; - QMap gameTypeFilterCheckBoxes; - QSpinBox *maxPlayersFilterMinSpinBox; - QSpinBox *maxPlayersFilterMaxSpinBox; + QCheckBox *unavailableGamesVisibleCheckBox; + QCheckBox *passwordProtectedGamesVisibleCheckBox; + QLineEdit *gameNameFilterEdit; + QLineEdit *creatorNameFilterEdit; + QMap gameTypeFilterCheckBoxes; + QSpinBox *maxPlayersFilterMinSpinBox; + QSpinBox *maxPlayersFilterMaxSpinBox; public: - DlgFilterGames(const QMap &allGameTypes, QWidget *parent = 0); - - bool getUnavailableGamesVisible() const; - void setUnavailableGamesVisible(bool _unavailableGamesVisible); - bool getPasswordProtectedGamesVisible() const; - void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); - QString getGameNameFilter() const; - void setGameNameFilter(const QString &_gameNameFilter); - QString getCreatorNameFilter() const; - void setCreatorNameFilter(const QString &_creatorNameFilter); - QSet getGameTypeFilter() const; - void setGameTypeFilter(const QSet &_gameTypeFilter); - int getMaxPlayersFilterMin() const; - int getMaxPlayersFilterMax() const; - void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); + DlgFilterGames(const QMap &allGameTypes, QWidget *parent = 0); + + bool getUnavailableGamesVisible() const; + void setUnavailableGamesVisible(bool _unavailableGamesVisible); + bool getPasswordProtectedGamesVisible() const; + void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); + QString getGameNameFilter() const; + void setGameNameFilter(const QString &_gameNameFilter); + QString getCreatorNameFilter() const; + void setCreatorNameFilter(const QString &_creatorNameFilter); + QSet getGameTypeFilter() const; + void setGameTypeFilter(const QSet &_gameTypeFilter); + int getMaxPlayersFilterMin() const; + int getMaxPlayersFilterMax() const; + void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); }; #endif diff --git a/cockatrice/src/dlg_load_deck_from_clipboard.cpp b/cockatrice/src/dlg_load_deck_from_clipboard.cpp index 0744ff7e..3eb3428f 100644 --- a/cockatrice/src/dlg_load_deck_from_clipboard.cpp +++ b/cockatrice/src/dlg_load_deck_from_clipboard.cpp @@ -12,47 +12,47 @@ #include "deck_loader.h" DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) - : QDialog(parent), deckList(0) + : QDialog(parent), deckList(0) { - contentsEdit = new QPlainTextEdit; - - refreshButton = new QPushButton(tr("&Refresh")); - refreshButton->setShortcut(QKeySequence("F5")); - connect(refreshButton, SIGNAL(clicked()), this, SLOT(actRefresh())); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(contentsEdit); - mainLayout->addWidget(buttonBox); + contentsEdit = new QPlainTextEdit; + + refreshButton = new QPushButton(tr("&Refresh")); + refreshButton->setShortcut(QKeySequence("F5")); + connect(refreshButton, SIGNAL(clicked()), this, SLOT(actRefresh())); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(contentsEdit); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + setLayout(mainLayout); - setWindowTitle(tr("Load deck from clipboard")); - resize(500, 500); - - actRefresh(); + setWindowTitle(tr("Load deck from clipboard")); + resize(500, 500); + + actRefresh(); } void DlgLoadDeckFromClipboard::actRefresh() { - contentsEdit->setPlainText(QApplication::clipboard()->text()); + contentsEdit->setPlainText(QApplication::clipboard()->text()); } void DlgLoadDeckFromClipboard::actOK() { - QString buffer = contentsEdit->toPlainText(); - QTextStream stream(&buffer); - - DeckLoader *l = new DeckLoader; - if (l->loadFromStream_Plain(stream)) { - deckList = l; - accept(); - } else { - QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); - delete l; - } + QString buffer = contentsEdit->toPlainText(); + QTextStream stream(&buffer); + + DeckLoader *l = new DeckLoader; + if (l->loadFromStream_Plain(stream)) { + deckList = l; + accept(); + } else { + QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); + delete l; + } } diff --git a/cockatrice/src/dlg_load_deck_from_clipboard.h b/cockatrice/src/dlg_load_deck_from_clipboard.h index 5fcd759e..375c713d 100644 --- a/cockatrice/src/dlg_load_deck_from_clipboard.h +++ b/cockatrice/src/dlg_load_deck_from_clipboard.h @@ -8,18 +8,18 @@ class QPlainTextEdit; class QPushButton; class DlgLoadDeckFromClipboard : public QDialog { - Q_OBJECT + Q_OBJECT private slots: - void actOK(); - void actRefresh(); + void actOK(); + void actRefresh(); private: - DeckLoader *deckList; + DeckLoader *deckList; public: - DlgLoadDeckFromClipboard(QWidget *parent = 0); - DeckLoader *getDeckList() const { return deckList; } + DlgLoadDeckFromClipboard(QWidget *parent = 0); + DeckLoader *getDeckList() const { return deckList; } private: - QPlainTextEdit *contentsEdit; - QPushButton *refreshButton; + QPlainTextEdit *contentsEdit; + QPushButton *refreshButton; }; #endif diff --git a/cockatrice/src/dlg_load_remote_deck.cpp b/cockatrice/src/dlg_load_remote_deck.cpp index 1ebcf056..09b820ac 100644 --- a/cockatrice/src/dlg_load_remote_deck.cpp +++ b/cockatrice/src/dlg_load_remote_deck.cpp @@ -7,34 +7,34 @@ #include "main.h" DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) - : QDialog(parent), client(_client) + : QDialog(parent), client(_client) { - dirView = new RemoteDeckList_TreeWidget(client); - - buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + dirView = new RemoteDeckList_TreeWidget(client); + + buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(dirView); - mainLayout->addWidget(buttonBox); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(dirView); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + setLayout(mainLayout); - setWindowTitle(tr("Load deck")); - setMinimumWidth(sizeHint().width()); - resize(400, 600); + setWindowTitle(tr("Load deck")); + setMinimumWidth(sizeHint().width()); + resize(400, 600); - connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &))); + connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &))); } void DlgLoadRemoteDeck::currentItemChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/) { - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(dynamic_cast(dirView->getNode(current))); + buttonBox->button(QDialogButtonBox::Ok)->setEnabled(dynamic_cast(dirView->getNode(current))); } int DlgLoadRemoteDeck::getDeckId() const { - return dynamic_cast(dirView->getNode(dirView->selectionModel()->currentIndex()))->getId(); + return dynamic_cast(dirView->getNode(dirView->selectionModel()->currentIndex()))->getId(); } diff --git a/cockatrice/src/dlg_load_remote_deck.h b/cockatrice/src/dlg_load_remote_deck.h index 304934a5..5fd78258 100644 --- a/cockatrice/src/dlg_load_remote_deck.h +++ b/cockatrice/src/dlg_load_remote_deck.h @@ -10,16 +10,16 @@ class QPushButton; class QDialogButtonBox; class DlgLoadRemoteDeck: public QDialog { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - RemoteDeckList_TreeWidget *dirView; - QDialogButtonBox *buttonBox; + AbstractClient *client; + RemoteDeckList_TreeWidget *dirView; + QDialogButtonBox *buttonBox; private slots: - void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous); + void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous); public: - DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0); - int getDeckId() const; + DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0); + int getDeckId() const; }; #endif diff --git a/cockatrice/src/dlg_settings.cpp b/cockatrice/src/dlg_settings.cpp index 112efad4..32d4f1fb 100644 --- a/cockatrice/src/dlg_settings.cpp +++ b/cockatrice/src/dlg_settings.cpp @@ -25,707 +25,707 @@ GeneralSettingsPage::GeneralSettingsPage() { - languageLabel = new QLabel; - languageBox = new QComboBox; - - QString setLanguage = settingsCache->getLang(); - QStringList qmFiles = findQmFiles(); - for (int i = 0; i < qmFiles.size(); i++) { - QString langName = languageName(qmFiles[i]); - languageBox->addItem(langName, qmFiles[i]); - if ((qmFiles[i] == setLanguage) || (setLanguage.isEmpty() && langName == tr("English"))) - languageBox->setCurrentIndex(i); - } - - picDownloadCheckBox = new QCheckBox; - picDownloadCheckBox->setChecked(settingsCache->getPicDownload()); - - connect(languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int))); - connect(picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int))); - - QGridLayout *personalGrid = new QGridLayout; - personalGrid->addWidget(languageLabel, 0, 0); - personalGrid->addWidget(languageBox, 0, 1); - personalGrid->addWidget(picDownloadCheckBox, 1, 0, 1, 2); - - personalGroupBox = new QGroupBox; - personalGroupBox->setLayout(personalGrid); - - deckPathLabel = new QLabel; - deckPathEdit = new QLineEdit(settingsCache->getDeckPath()); - deckPathEdit->setReadOnly(true); - QPushButton *deckPathButton = new QPushButton("..."); - connect(deckPathButton, SIGNAL(clicked()), this, SLOT(deckPathButtonClicked())); - - replaysPathLabel = new QLabel; - replaysPathEdit = new QLineEdit(settingsCache->getReplaysPath()); - replaysPathEdit->setReadOnly(true); - QPushButton *replaysPathButton = new QPushButton("..."); - connect(replaysPathButton, SIGNAL(clicked()), this, SLOT(replaysPathButtonClicked())); - - picsPathLabel = new QLabel; - picsPathEdit = new QLineEdit(settingsCache->getPicsPath()); - picsPathEdit->setReadOnly(true); - QPushButton *picsPathButton = new QPushButton("..."); - connect(picsPathButton, SIGNAL(clicked()), this, SLOT(picsPathButtonClicked())); - - cardDatabasePathLabel = new QLabel; - cardDatabasePathEdit = new QLineEdit(settingsCache->getCardDatabasePath()); - cardDatabasePathEdit->setReadOnly(true); - QPushButton *cardDatabasePathButton = new QPushButton("..."); - connect(cardDatabasePathButton, SIGNAL(clicked()), this, SLOT(cardDatabasePathButtonClicked())); - - tokenDatabasePathLabel = new QLabel; - tokenDatabasePathEdit = new QLineEdit(settingsCache->getTokenDatabasePath()); - tokenDatabasePathEdit->setReadOnly(true); - QPushButton *tokenDatabasePathButton = new QPushButton("..."); - connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked())); - - QGridLayout *pathsGrid = new QGridLayout; - pathsGrid->addWidget(deckPathLabel, 0, 0); - pathsGrid->addWidget(deckPathEdit, 0, 1); - pathsGrid->addWidget(deckPathButton, 0, 2); - pathsGrid->addWidget(replaysPathLabel, 1, 0); - pathsGrid->addWidget(replaysPathEdit, 1, 1); - pathsGrid->addWidget(replaysPathButton, 1, 2); - pathsGrid->addWidget(picsPathLabel, 2, 0); - pathsGrid->addWidget(picsPathEdit, 2, 1); - pathsGrid->addWidget(picsPathButton, 2, 2); - pathsGrid->addWidget(cardDatabasePathLabel, 3, 0); - pathsGrid->addWidget(cardDatabasePathEdit, 3, 1); - pathsGrid->addWidget(cardDatabasePathButton, 3, 2); - pathsGrid->addWidget(tokenDatabasePathLabel, 4, 0); - pathsGrid->addWidget(tokenDatabasePathEdit, 4, 1); - pathsGrid->addWidget(tokenDatabasePathButton, 4, 2); - pathsGroupBox = new QGroupBox; - pathsGroupBox->setLayout(pathsGrid); + languageLabel = new QLabel; + languageBox = new QComboBox; + + QString setLanguage = settingsCache->getLang(); + QStringList qmFiles = findQmFiles(); + for (int i = 0; i < qmFiles.size(); i++) { + QString langName = languageName(qmFiles[i]); + languageBox->addItem(langName, qmFiles[i]); + if ((qmFiles[i] == setLanguage) || (setLanguage.isEmpty() && langName == tr("English"))) + languageBox->setCurrentIndex(i); + } + + picDownloadCheckBox = new QCheckBox; + picDownloadCheckBox->setChecked(settingsCache->getPicDownload()); + + connect(languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int))); + connect(picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int))); + + QGridLayout *personalGrid = new QGridLayout; + personalGrid->addWidget(languageLabel, 0, 0); + personalGrid->addWidget(languageBox, 0, 1); + personalGrid->addWidget(picDownloadCheckBox, 1, 0, 1, 2); + + personalGroupBox = new QGroupBox; + personalGroupBox->setLayout(personalGrid); + + deckPathLabel = new QLabel; + deckPathEdit = new QLineEdit(settingsCache->getDeckPath()); + deckPathEdit->setReadOnly(true); + QPushButton *deckPathButton = new QPushButton("..."); + connect(deckPathButton, SIGNAL(clicked()), this, SLOT(deckPathButtonClicked())); + + replaysPathLabel = new QLabel; + replaysPathEdit = new QLineEdit(settingsCache->getReplaysPath()); + replaysPathEdit->setReadOnly(true); + QPushButton *replaysPathButton = new QPushButton("..."); + connect(replaysPathButton, SIGNAL(clicked()), this, SLOT(replaysPathButtonClicked())); + + picsPathLabel = new QLabel; + picsPathEdit = new QLineEdit(settingsCache->getPicsPath()); + picsPathEdit->setReadOnly(true); + QPushButton *picsPathButton = new QPushButton("..."); + connect(picsPathButton, SIGNAL(clicked()), this, SLOT(picsPathButtonClicked())); + + cardDatabasePathLabel = new QLabel; + cardDatabasePathEdit = new QLineEdit(settingsCache->getCardDatabasePath()); + cardDatabasePathEdit->setReadOnly(true); + QPushButton *cardDatabasePathButton = new QPushButton("..."); + connect(cardDatabasePathButton, SIGNAL(clicked()), this, SLOT(cardDatabasePathButtonClicked())); + + tokenDatabasePathLabel = new QLabel; + tokenDatabasePathEdit = new QLineEdit(settingsCache->getTokenDatabasePath()); + tokenDatabasePathEdit->setReadOnly(true); + QPushButton *tokenDatabasePathButton = new QPushButton("..."); + connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked())); + + QGridLayout *pathsGrid = new QGridLayout; + pathsGrid->addWidget(deckPathLabel, 0, 0); + pathsGrid->addWidget(deckPathEdit, 0, 1); + pathsGrid->addWidget(deckPathButton, 0, 2); + pathsGrid->addWidget(replaysPathLabel, 1, 0); + pathsGrid->addWidget(replaysPathEdit, 1, 1); + pathsGrid->addWidget(replaysPathButton, 1, 2); + pathsGrid->addWidget(picsPathLabel, 2, 0); + pathsGrid->addWidget(picsPathEdit, 2, 1); + pathsGrid->addWidget(picsPathButton, 2, 2); + pathsGrid->addWidget(cardDatabasePathLabel, 3, 0); + pathsGrid->addWidget(cardDatabasePathEdit, 3, 1); + pathsGrid->addWidget(cardDatabasePathButton, 3, 2); + pathsGrid->addWidget(tokenDatabasePathLabel, 4, 0); + pathsGrid->addWidget(tokenDatabasePathEdit, 4, 1); + pathsGrid->addWidget(tokenDatabasePathButton, 4, 2); + pathsGroupBox = new QGroupBox; + pathsGroupBox->setLayout(pathsGrid); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(personalGroupBox); - mainLayout->addWidget(pathsGroupBox); - - setLayout(mainLayout); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(personalGroupBox); + mainLayout->addWidget(pathsGroupBox); + + setLayout(mainLayout); } QStringList GeneralSettingsPage::findQmFiles() { - QDir dir(translationPath); - QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name); - fileNames.replaceInStrings(QRegExp(translationPrefix + "_(.*)\\.qm"), "\\1"); - return fileNames; + QDir dir(translationPath); + QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name); + fileNames.replaceInStrings(QRegExp(translationPrefix + "_(.*)\\.qm"), "\\1"); + return fileNames; } QString GeneralSettingsPage::languageName(const QString &qmFile) { - QTranslator translator; - translator.load(translationPrefix + "_" + qmFile + ".qm", translationPath); - - return translator.translate("GeneralSettingsPage", "English"); + QTranslator translator; + translator.load(translationPrefix + "_" + qmFile + ".qm", translationPath); + + return translator.translate("GeneralSettingsPage", "English"); } void GeneralSettingsPage::deckPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - deckPathEdit->setText(path); - settingsCache->setDeckPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + deckPathEdit->setText(path); + settingsCache->setDeckPath(path); } void GeneralSettingsPage::replaysPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - replaysPathEdit->setText(path); - settingsCache->setReplaysPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + replaysPathEdit->setText(path); + settingsCache->setReplaysPath(path); } void GeneralSettingsPage::picsPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - picsPathEdit->setText(path); - settingsCache->setPicsPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + picsPathEdit->setText(path); + settingsCache->setPicsPath(path); } void GeneralSettingsPage::cardDatabasePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - cardDatabasePathEdit->setText(path); - settingsCache->setCardDatabasePath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + cardDatabasePathEdit->setText(path); + settingsCache->setCardDatabasePath(path); } void GeneralSettingsPage::tokenDatabasePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - tokenDatabasePathEdit->setText(path); - settingsCache->setTokenDatabasePath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + tokenDatabasePathEdit->setText(path); + settingsCache->setTokenDatabasePath(path); } void GeneralSettingsPage::languageBoxChanged(int index) { - settingsCache->setLang(languageBox->itemData(index).toString()); + settingsCache->setLang(languageBox->itemData(index).toString()); } void GeneralSettingsPage::retranslateUi() { - personalGroupBox->setTitle(tr("Personal settings")); - languageLabel->setText(tr("Language:")); - picDownloadCheckBox->setText(tr("Download card pictures on the fly")); - pathsGroupBox->setTitle(tr("Paths")); - deckPathLabel->setText(tr("Decks directory:")); - replaysPathLabel->setText(tr("Replays directory:")); - picsPathLabel->setText(tr("Pictures directory:")); - cardDatabasePathLabel->setText(tr("Path to card database:")); - tokenDatabasePathLabel->setText(tr("Path to token database:")); + personalGroupBox->setTitle(tr("Personal settings")); + languageLabel->setText(tr("Language:")); + picDownloadCheckBox->setText(tr("Download card pictures on the fly")); + pathsGroupBox->setTitle(tr("Paths")); + deckPathLabel->setText(tr("Decks directory:")); + replaysPathLabel->setText(tr("Replays directory:")); + picsPathLabel->setText(tr("Pictures directory:")); + cardDatabasePathLabel->setText(tr("Path to card database:")); + tokenDatabasePathLabel->setText(tr("Path to token database:")); } AppearanceSettingsPage::AppearanceSettingsPage() { - QIcon deleteIcon(":/resources/icon_delete.svg"); - - handBgLabel = new QLabel; - handBgEdit = new QLineEdit(settingsCache->getHandBgPath()); - handBgEdit->setReadOnly(true); - QPushButton *handBgClearButton = new QPushButton(deleteIcon, QString()); - connect(handBgClearButton, SIGNAL(clicked()), this, SLOT(handBgClearButtonClicked())); - QPushButton *handBgButton = new QPushButton("..."); - connect(handBgButton, SIGNAL(clicked()), this, SLOT(handBgButtonClicked())); - - stackBgLabel = new QLabel; - stackBgEdit = new QLineEdit(settingsCache->getStackBgPath()); - stackBgEdit->setReadOnly(true); - QPushButton *stackBgClearButton = new QPushButton(deleteIcon, QString()); - connect(stackBgClearButton, SIGNAL(clicked()), this, SLOT(stackBgClearButtonClicked())); - QPushButton *stackBgButton = new QPushButton("..."); - connect(stackBgButton, SIGNAL(clicked()), this, SLOT(stackBgButtonClicked())); + QIcon deleteIcon(":/resources/icon_delete.svg"); + + handBgLabel = new QLabel; + handBgEdit = new QLineEdit(settingsCache->getHandBgPath()); + handBgEdit->setReadOnly(true); + QPushButton *handBgClearButton = new QPushButton(deleteIcon, QString()); + connect(handBgClearButton, SIGNAL(clicked()), this, SLOT(handBgClearButtonClicked())); + QPushButton *handBgButton = new QPushButton("..."); + connect(handBgButton, SIGNAL(clicked()), this, SLOT(handBgButtonClicked())); + + stackBgLabel = new QLabel; + stackBgEdit = new QLineEdit(settingsCache->getStackBgPath()); + stackBgEdit->setReadOnly(true); + QPushButton *stackBgClearButton = new QPushButton(deleteIcon, QString()); + connect(stackBgClearButton, SIGNAL(clicked()), this, SLOT(stackBgClearButtonClicked())); + QPushButton *stackBgButton = new QPushButton("..."); + connect(stackBgButton, SIGNAL(clicked()), this, SLOT(stackBgButtonClicked())); - tableBgLabel = new QLabel; - tableBgEdit = new QLineEdit(settingsCache->getTableBgPath()); - tableBgEdit->setReadOnly(true); - QPushButton *tableBgClearButton = new QPushButton(deleteIcon, QString()); - connect(tableBgClearButton, SIGNAL(clicked()), this, SLOT(tableBgClearButtonClicked())); - QPushButton *tableBgButton = new QPushButton("..."); - connect(tableBgButton, SIGNAL(clicked()), this, SLOT(tableBgButtonClicked())); - - playerAreaBgLabel = new QLabel; - playerAreaBgEdit = new QLineEdit(settingsCache->getPlayerBgPath()); - playerAreaBgEdit->setReadOnly(true); - QPushButton *playerAreaBgClearButton = new QPushButton(deleteIcon, QString()); - connect(playerAreaBgClearButton, SIGNAL(clicked()), this, SLOT(playerAreaBgClearButtonClicked())); - QPushButton *playerAreaBgButton = new QPushButton("..."); - connect(playerAreaBgButton, SIGNAL(clicked()), this, SLOT(playerAreaBgButtonClicked())); - - cardBackPicturePathLabel = new QLabel; - cardBackPicturePathEdit = new QLineEdit(settingsCache->getCardBackPicturePath()); - cardBackPicturePathEdit->setReadOnly(true); - QPushButton *cardBackPicturePathClearButton = new QPushButton(deleteIcon, QString()); - connect(cardBackPicturePathClearButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathClearButtonClicked())); - QPushButton *cardBackPicturePathButton = new QPushButton("..."); - connect(cardBackPicturePathButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathButtonClicked())); - - QGridLayout *zoneBgGrid = new QGridLayout; - zoneBgGrid->addWidget(handBgLabel, 0, 0); - zoneBgGrid->addWidget(handBgEdit, 0, 1); - zoneBgGrid->addWidget(handBgClearButton, 0, 2); - zoneBgGrid->addWidget(handBgButton, 0, 3); - zoneBgGrid->addWidget(stackBgLabel, 1, 0); - zoneBgGrid->addWidget(stackBgEdit, 1, 1); - zoneBgGrid->addWidget(stackBgClearButton, 1, 2); - zoneBgGrid->addWidget(stackBgButton, 1, 3); - zoneBgGrid->addWidget(tableBgLabel, 2, 0); - zoneBgGrid->addWidget(tableBgEdit, 2, 1); - zoneBgGrid->addWidget(tableBgClearButton, 2, 2); - zoneBgGrid->addWidget(tableBgButton, 2, 3); - zoneBgGrid->addWidget(playerAreaBgLabel, 3, 0); - zoneBgGrid->addWidget(playerAreaBgEdit, 3, 1); - zoneBgGrid->addWidget(playerAreaBgClearButton, 3, 2); - zoneBgGrid->addWidget(playerAreaBgButton, 3, 3); - zoneBgGrid->addWidget(cardBackPicturePathLabel, 4, 0); - zoneBgGrid->addWidget(cardBackPicturePathEdit, 4, 1); - zoneBgGrid->addWidget(cardBackPicturePathClearButton, 4, 2); - zoneBgGrid->addWidget(cardBackPicturePathButton, 4, 3); + tableBgLabel = new QLabel; + tableBgEdit = new QLineEdit(settingsCache->getTableBgPath()); + tableBgEdit->setReadOnly(true); + QPushButton *tableBgClearButton = new QPushButton(deleteIcon, QString()); + connect(tableBgClearButton, SIGNAL(clicked()), this, SLOT(tableBgClearButtonClicked())); + QPushButton *tableBgButton = new QPushButton("..."); + connect(tableBgButton, SIGNAL(clicked()), this, SLOT(tableBgButtonClicked())); + + playerAreaBgLabel = new QLabel; + playerAreaBgEdit = new QLineEdit(settingsCache->getPlayerBgPath()); + playerAreaBgEdit->setReadOnly(true); + QPushButton *playerAreaBgClearButton = new QPushButton(deleteIcon, QString()); + connect(playerAreaBgClearButton, SIGNAL(clicked()), this, SLOT(playerAreaBgClearButtonClicked())); + QPushButton *playerAreaBgButton = new QPushButton("..."); + connect(playerAreaBgButton, SIGNAL(clicked()), this, SLOT(playerAreaBgButtonClicked())); + + cardBackPicturePathLabel = new QLabel; + cardBackPicturePathEdit = new QLineEdit(settingsCache->getCardBackPicturePath()); + cardBackPicturePathEdit->setReadOnly(true); + QPushButton *cardBackPicturePathClearButton = new QPushButton(deleteIcon, QString()); + connect(cardBackPicturePathClearButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathClearButtonClicked())); + QPushButton *cardBackPicturePathButton = new QPushButton("..."); + connect(cardBackPicturePathButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathButtonClicked())); + + QGridLayout *zoneBgGrid = new QGridLayout; + zoneBgGrid->addWidget(handBgLabel, 0, 0); + zoneBgGrid->addWidget(handBgEdit, 0, 1); + zoneBgGrid->addWidget(handBgClearButton, 0, 2); + zoneBgGrid->addWidget(handBgButton, 0, 3); + zoneBgGrid->addWidget(stackBgLabel, 1, 0); + zoneBgGrid->addWidget(stackBgEdit, 1, 1); + zoneBgGrid->addWidget(stackBgClearButton, 1, 2); + zoneBgGrid->addWidget(stackBgButton, 1, 3); + zoneBgGrid->addWidget(tableBgLabel, 2, 0); + zoneBgGrid->addWidget(tableBgEdit, 2, 1); + zoneBgGrid->addWidget(tableBgClearButton, 2, 2); + zoneBgGrid->addWidget(tableBgButton, 2, 3); + zoneBgGrid->addWidget(playerAreaBgLabel, 3, 0); + zoneBgGrid->addWidget(playerAreaBgEdit, 3, 1); + zoneBgGrid->addWidget(playerAreaBgClearButton, 3, 2); + zoneBgGrid->addWidget(playerAreaBgButton, 3, 3); + zoneBgGrid->addWidget(cardBackPicturePathLabel, 4, 0); + zoneBgGrid->addWidget(cardBackPicturePathEdit, 4, 1); + zoneBgGrid->addWidget(cardBackPicturePathClearButton, 4, 2); + zoneBgGrid->addWidget(cardBackPicturePathButton, 4, 3); - zoneBgGroupBox = new QGroupBox; - zoneBgGroupBox->setLayout(zoneBgGrid); + zoneBgGroupBox = new QGroupBox; + zoneBgGroupBox->setLayout(zoneBgGrid); - displayCardNamesCheckBox = new QCheckBox; - displayCardNamesCheckBox->setChecked(settingsCache->getDisplayCardNames()); - connect(displayCardNamesCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDisplayCardNames(int))); - - QGridLayout *cardsGrid = new QGridLayout; - cardsGrid->addWidget(displayCardNamesCheckBox, 0, 0, 1, 2); - - cardsGroupBox = new QGroupBox; - cardsGroupBox->setLayout(cardsGrid); - - horizontalHandCheckBox = new QCheckBox; - horizontalHandCheckBox->setChecked(settingsCache->getHorizontalHand()); - connect(horizontalHandCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setHorizontalHand(int))); - - QGridLayout *handGrid = new QGridLayout; - handGrid->addWidget(horizontalHandCheckBox, 0, 0, 1, 2); - - handGroupBox = new QGroupBox; - handGroupBox->setLayout(handGrid); - - invertVerticalCoordinateCheckBox = new QCheckBox; - invertVerticalCoordinateCheckBox->setChecked(settingsCache->getInvertVerticalCoordinate()); - connect(invertVerticalCoordinateCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setInvertVerticalCoordinate(int))); - - minPlayersForMultiColumnLayoutLabel = new QLabel; - minPlayersForMultiColumnLayoutEdit = new QSpinBox; - minPlayersForMultiColumnLayoutEdit->setMinimum(2); - minPlayersForMultiColumnLayoutEdit->setValue(settingsCache->getMinPlayersForMultiColumnLayout()); - connect(minPlayersForMultiColumnLayoutEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMinPlayersForMultiColumnLayout(int))); - minPlayersForMultiColumnLayoutLabel->setBuddy(minPlayersForMultiColumnLayoutEdit); - - QGridLayout *tableGrid = new QGridLayout; - tableGrid->addWidget(invertVerticalCoordinateCheckBox, 0, 0, 1, 2); - tableGrid->addWidget(minPlayersForMultiColumnLayoutLabel, 1, 0, 1, 1); - tableGrid->addWidget(minPlayersForMultiColumnLayoutEdit, 1, 1, 1, 1); - - tableGroupBox = new QGroupBox; - tableGroupBox->setLayout(tableGrid); - - zoneViewSortByNameCheckBox = new QCheckBox; - zoneViewSortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); - connect(zoneViewSortByNameCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByName(int))); - zoneViewSortByTypeCheckBox = new QCheckBox; - zoneViewSortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); - connect(zoneViewSortByTypeCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByType(int))); + displayCardNamesCheckBox = new QCheckBox; + displayCardNamesCheckBox->setChecked(settingsCache->getDisplayCardNames()); + connect(displayCardNamesCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDisplayCardNames(int))); + + QGridLayout *cardsGrid = new QGridLayout; + cardsGrid->addWidget(displayCardNamesCheckBox, 0, 0, 1, 2); + + cardsGroupBox = new QGroupBox; + cardsGroupBox->setLayout(cardsGrid); + + horizontalHandCheckBox = new QCheckBox; + horizontalHandCheckBox->setChecked(settingsCache->getHorizontalHand()); + connect(horizontalHandCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setHorizontalHand(int))); + + QGridLayout *handGrid = new QGridLayout; + handGrid->addWidget(horizontalHandCheckBox, 0, 0, 1, 2); + + handGroupBox = new QGroupBox; + handGroupBox->setLayout(handGrid); + + invertVerticalCoordinateCheckBox = new QCheckBox; + invertVerticalCoordinateCheckBox->setChecked(settingsCache->getInvertVerticalCoordinate()); + connect(invertVerticalCoordinateCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setInvertVerticalCoordinate(int))); + + minPlayersForMultiColumnLayoutLabel = new QLabel; + minPlayersForMultiColumnLayoutEdit = new QSpinBox; + minPlayersForMultiColumnLayoutEdit->setMinimum(2); + minPlayersForMultiColumnLayoutEdit->setValue(settingsCache->getMinPlayersForMultiColumnLayout()); + connect(minPlayersForMultiColumnLayoutEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMinPlayersForMultiColumnLayout(int))); + minPlayersForMultiColumnLayoutLabel->setBuddy(minPlayersForMultiColumnLayoutEdit); + + QGridLayout *tableGrid = new QGridLayout; + tableGrid->addWidget(invertVerticalCoordinateCheckBox, 0, 0, 1, 2); + tableGrid->addWidget(minPlayersForMultiColumnLayoutLabel, 1, 0, 1, 1); + tableGrid->addWidget(minPlayersForMultiColumnLayoutEdit, 1, 1, 1, 1); + + tableGroupBox = new QGroupBox; + tableGroupBox->setLayout(tableGrid); + + zoneViewSortByNameCheckBox = new QCheckBox; + zoneViewSortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); + connect(zoneViewSortByNameCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByName(int))); + zoneViewSortByTypeCheckBox = new QCheckBox; + zoneViewSortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); + connect(zoneViewSortByTypeCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByType(int))); - QGridLayout *zoneViewGrid = new QGridLayout; - zoneViewGrid->addWidget(zoneViewSortByNameCheckBox, 0, 0, 1, 2); - zoneViewGrid->addWidget(zoneViewSortByTypeCheckBox, 1, 0, 1, 2); + QGridLayout *zoneViewGrid = new QGridLayout; + zoneViewGrid->addWidget(zoneViewSortByNameCheckBox, 0, 0, 1, 2); + zoneViewGrid->addWidget(zoneViewSortByTypeCheckBox, 1, 0, 1, 2); - zoneViewGroupBox = new QGroupBox; - zoneViewGroupBox->setLayout(zoneViewGrid); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(zoneBgGroupBox); - mainLayout->addWidget(cardsGroupBox); - mainLayout->addWidget(handGroupBox); - mainLayout->addWidget(tableGroupBox); - mainLayout->addWidget(zoneViewGroupBox); - - setLayout(mainLayout); + zoneViewGroupBox = new QGroupBox; + zoneViewGroupBox->setLayout(zoneViewGrid); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(zoneBgGroupBox); + mainLayout->addWidget(cardsGroupBox); + mainLayout->addWidget(handGroupBox); + mainLayout->addWidget(tableGroupBox); + mainLayout->addWidget(zoneViewGroupBox); + + setLayout(mainLayout); } void AppearanceSettingsPage::retranslateUi() { - zoneBgGroupBox->setTitle(tr("Zone background pictures")); - handBgLabel->setText(tr("Path to hand background:")); - stackBgLabel->setText(tr("Path to stack background:")); - tableBgLabel->setText(tr("Path to table background:")); - playerAreaBgLabel->setText(tr("Path to player info background:")); - cardBackPicturePathLabel->setText(tr("Path to picture of card back:")); - - cardsGroupBox->setTitle(tr("Card rendering")); - displayCardNamesCheckBox->setText(tr("Display card names on cards having a picture")); - - handGroupBox->setTitle(tr("Hand layout")); - horizontalHandCheckBox->setText(tr("Display hand horizontally (wastes space)")); - - tableGroupBox->setTitle(tr("Table grid layout")); - invertVerticalCoordinateCheckBox->setText(tr("Invert vertical coordinate")); - minPlayersForMultiColumnLayoutLabel->setText(tr("Minimum player count for multi-column layout:")); - - zoneViewGroupBox->setTitle(tr("Zone view layout")); - zoneViewSortByNameCheckBox->setText(tr("Sort by name")); - zoneViewSortByTypeCheckBox->setText(tr("Sort by type")); + zoneBgGroupBox->setTitle(tr("Zone background pictures")); + handBgLabel->setText(tr("Path to hand background:")); + stackBgLabel->setText(tr("Path to stack background:")); + tableBgLabel->setText(tr("Path to table background:")); + playerAreaBgLabel->setText(tr("Path to player info background:")); + cardBackPicturePathLabel->setText(tr("Path to picture of card back:")); + + cardsGroupBox->setTitle(tr("Card rendering")); + displayCardNamesCheckBox->setText(tr("Display card names on cards having a picture")); + + handGroupBox->setTitle(tr("Hand layout")); + horizontalHandCheckBox->setText(tr("Display hand horizontally (wastes space)")); + + tableGroupBox->setTitle(tr("Table grid layout")); + invertVerticalCoordinateCheckBox->setText(tr("Invert vertical coordinate")); + minPlayersForMultiColumnLayoutLabel->setText(tr("Minimum player count for multi-column layout:")); + + zoneViewGroupBox->setTitle(tr("Zone view layout")); + zoneViewSortByNameCheckBox->setText(tr("Sort by name")); + zoneViewSortByTypeCheckBox->setText(tr("Sort by type")); } void AppearanceSettingsPage::handBgClearButtonClicked() { - handBgEdit->setText(QString()); - settingsCache->setHandBgPath(QString()); + handBgEdit->setText(QString()); + settingsCache->setHandBgPath(QString()); } void AppearanceSettingsPage::handBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - handBgEdit->setText(path); - settingsCache->setHandBgPath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + handBgEdit->setText(path); + settingsCache->setHandBgPath(path); } void AppearanceSettingsPage::stackBgClearButtonClicked() { - stackBgEdit->setText(QString()); - settingsCache->setStackBgPath(QString()); + stackBgEdit->setText(QString()); + settingsCache->setStackBgPath(QString()); } void AppearanceSettingsPage::stackBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - stackBgEdit->setText(path); - settingsCache->setStackBgPath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + stackBgEdit->setText(path); + settingsCache->setStackBgPath(path); } void AppearanceSettingsPage::tableBgClearButtonClicked() { - tableBgEdit->setText(QString()); - settingsCache->setTableBgPath(QString()); + tableBgEdit->setText(QString()); + settingsCache->setTableBgPath(QString()); } void AppearanceSettingsPage::tableBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; - tableBgEdit->setText(path); - settingsCache->setTableBgPath(path); + tableBgEdit->setText(path); + settingsCache->setTableBgPath(path); } void AppearanceSettingsPage::playerAreaBgClearButtonClicked() { - playerAreaBgEdit->setText(QString()); - settingsCache->setPlayerBgPath(QString()); + playerAreaBgEdit->setText(QString()); + settingsCache->setPlayerBgPath(QString()); } void AppearanceSettingsPage::playerAreaBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - playerAreaBgEdit->setText(path); - settingsCache->setPlayerBgPath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + playerAreaBgEdit->setText(path); + settingsCache->setPlayerBgPath(path); } void AppearanceSettingsPage::cardBackPicturePathClearButtonClicked() { - cardBackPicturePathEdit->setText(QString()); - settingsCache->setCardBackPicturePath(QString()); + cardBackPicturePathEdit->setText(QString()); + settingsCache->setCardBackPicturePath(QString()); } void AppearanceSettingsPage::cardBackPicturePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - cardBackPicturePathEdit->setText(path); - settingsCache->setCardBackPicturePath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + cardBackPicturePathEdit->setText(path); + settingsCache->setCardBackPicturePath(path); } UserInterfaceSettingsPage::UserInterfaceSettingsPage() { - QIcon deleteIcon(":/resources/icon_delete.svg"); + QIcon deleteIcon(":/resources/icon_delete.svg"); - notificationsEnabledCheckBox = new QCheckBox; - notificationsEnabledCheckBox->setChecked(settingsCache->getNotificationsEnabled()); - connect(notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotificationsEnabled(int))); + notificationsEnabledCheckBox = new QCheckBox; + notificationsEnabledCheckBox->setChecked(settingsCache->getNotificationsEnabled()); + connect(notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotificationsEnabled(int))); - doubleClickToPlayCheckBox = new QCheckBox; - doubleClickToPlayCheckBox->setChecked(settingsCache->getDoubleClickToPlay()); - connect(doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int))); - - playToStackCheckBox = new QCheckBox; - playToStackCheckBox->setChecked(settingsCache->getPlayToStack()); - connect(playToStackCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPlayToStack(int))); - - QGridLayout *generalGrid = new QGridLayout; - generalGrid->addWidget(notificationsEnabledCheckBox, 0, 0); - generalGrid->addWidget(doubleClickToPlayCheckBox, 1, 0); - generalGrid->addWidget(playToStackCheckBox, 2, 0); - - generalGroupBox = new QGroupBox; - generalGroupBox->setLayout(generalGrid); - - tapAnimationCheckBox = new QCheckBox; - tapAnimationCheckBox->setChecked(settingsCache->getTapAnimation()); - connect(tapAnimationCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setTapAnimation(int))); - - soundEnabledCheckBox = new QCheckBox; - soundEnabledCheckBox->setChecked(settingsCache->getSoundEnabled()); - connect(soundEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setSoundEnabled(int))); - - soundPathLabel = new QLabel; - soundPathEdit = new QLineEdit(settingsCache->getSoundPath()); - soundPathEdit->setReadOnly(true); - QPushButton *soundPathClearButton = new QPushButton(deleteIcon, QString()); - connect(soundPathClearButton, SIGNAL(clicked()), this, SLOT(soundPathClearButtonClicked())); - QPushButton *soundPathButton = new QPushButton("..."); - connect(soundPathButton, SIGNAL(clicked()), this, SLOT(soundPathButtonClicked())); - - QGridLayout *soundGrid = new QGridLayout; - soundGrid->addWidget(soundEnabledCheckBox, 0, 0, 1, 4); - soundGrid->addWidget(soundPathLabel, 1, 0); - soundGrid->addWidget(soundPathEdit, 1, 1); - soundGrid->addWidget(soundPathClearButton, 1, 2); - soundGrid->addWidget(soundPathButton, 1, 3); - - soundGroupBox = new QGroupBox; - soundGroupBox->setLayout(soundGrid); - - QGridLayout *animationGrid = new QGridLayout; - animationGrid->addWidget(tapAnimationCheckBox, 0, 0); - - animationGroupBox = new QGroupBox; - animationGroupBox->setLayout(animationGrid); + doubleClickToPlayCheckBox = new QCheckBox; + doubleClickToPlayCheckBox->setChecked(settingsCache->getDoubleClickToPlay()); + connect(doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int))); + + playToStackCheckBox = new QCheckBox; + playToStackCheckBox->setChecked(settingsCache->getPlayToStack()); + connect(playToStackCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPlayToStack(int))); + + QGridLayout *generalGrid = new QGridLayout; + generalGrid->addWidget(notificationsEnabledCheckBox, 0, 0); + generalGrid->addWidget(doubleClickToPlayCheckBox, 1, 0); + generalGrid->addWidget(playToStackCheckBox, 2, 0); + + generalGroupBox = new QGroupBox; + generalGroupBox->setLayout(generalGrid); + + tapAnimationCheckBox = new QCheckBox; + tapAnimationCheckBox->setChecked(settingsCache->getTapAnimation()); + connect(tapAnimationCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setTapAnimation(int))); + + soundEnabledCheckBox = new QCheckBox; + soundEnabledCheckBox->setChecked(settingsCache->getSoundEnabled()); + connect(soundEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setSoundEnabled(int))); + + soundPathLabel = new QLabel; + soundPathEdit = new QLineEdit(settingsCache->getSoundPath()); + soundPathEdit->setReadOnly(true); + QPushButton *soundPathClearButton = new QPushButton(deleteIcon, QString()); + connect(soundPathClearButton, SIGNAL(clicked()), this, SLOT(soundPathClearButtonClicked())); + QPushButton *soundPathButton = new QPushButton("..."); + connect(soundPathButton, SIGNAL(clicked()), this, SLOT(soundPathButtonClicked())); + + QGridLayout *soundGrid = new QGridLayout; + soundGrid->addWidget(soundEnabledCheckBox, 0, 0, 1, 4); + soundGrid->addWidget(soundPathLabel, 1, 0); + soundGrid->addWidget(soundPathEdit, 1, 1); + soundGrid->addWidget(soundPathClearButton, 1, 2); + soundGrid->addWidget(soundPathButton, 1, 3); + + soundGroupBox = new QGroupBox; + soundGroupBox->setLayout(soundGrid); + + QGridLayout *animationGrid = new QGridLayout; + animationGrid->addWidget(tapAnimationCheckBox, 0, 0); + + animationGroupBox = new QGroupBox; + animationGroupBox->setLayout(animationGrid); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(generalGroupBox); - mainLayout->addWidget(animationGroupBox); - mainLayout->addWidget(soundGroupBox); - - setLayout(mainLayout); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(generalGroupBox); + mainLayout->addWidget(animationGroupBox); + mainLayout->addWidget(soundGroupBox); + + setLayout(mainLayout); } void UserInterfaceSettingsPage::retranslateUi() { - generalGroupBox->setTitle(tr("General interface settings")); - notificationsEnabledCheckBox->setText(tr("Enable notifications in taskbar")); - doubleClickToPlayCheckBox->setText(tr("&Double-click cards to play them (instead of single-click)")); - playToStackCheckBox->setText(tr("&Play all nonlands onto the stack (not the battlefield) by default")); - animationGroupBox->setTitle(tr("Animation settings")); - tapAnimationCheckBox->setText(tr("&Tap/untap animation")); - soundEnabledCheckBox->setText(tr("Enable &sounds")); - soundPathLabel->setText(tr("Path to sounds directory:")); + generalGroupBox->setTitle(tr("General interface settings")); + notificationsEnabledCheckBox->setText(tr("Enable notifications in taskbar")); + doubleClickToPlayCheckBox->setText(tr("&Double-click cards to play them (instead of single-click)")); + playToStackCheckBox->setText(tr("&Play all nonlands onto the stack (not the battlefield) by default")); + animationGroupBox->setTitle(tr("Animation settings")); + tapAnimationCheckBox->setText(tr("&Tap/untap animation")); + soundEnabledCheckBox->setText(tr("Enable &sounds")); + soundPathLabel->setText(tr("Path to sounds directory:")); } void UserInterfaceSettingsPage::soundPathClearButtonClicked() { - soundPathEdit->setText(QString()); - settingsCache->setSoundPath(QString()); + soundPathEdit->setText(QString()); + settingsCache->setSoundPath(QString()); } void UserInterfaceSettingsPage::soundPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - soundPathEdit->setText(path); - settingsCache->setSoundPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + soundPathEdit->setText(path); + settingsCache->setSoundPath(path); } DeckEditorSettingsPage::DeckEditorSettingsPage() { - priceTagsCheckBox = new QCheckBox; - priceTagsCheckBox->setChecked(settingsCache->getPriceTagFeature()); - connect(priceTagsCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPriceTagFeature(int))); - - QGridLayout *generalGrid = new QGridLayout; - generalGrid->addWidget(priceTagsCheckBox, 0, 0); - - generalGroupBox = new QGroupBox; - generalGroupBox->setLayout(generalGrid); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(generalGroupBox); - - setLayout(mainLayout); + priceTagsCheckBox = new QCheckBox; + priceTagsCheckBox->setChecked(settingsCache->getPriceTagFeature()); + connect(priceTagsCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPriceTagFeature(int))); + + QGridLayout *generalGrid = new QGridLayout; + generalGrid->addWidget(priceTagsCheckBox, 0, 0); + + generalGroupBox = new QGroupBox; + generalGroupBox->setLayout(generalGrid); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(generalGroupBox); + + setLayout(mainLayout); } void DeckEditorSettingsPage::retranslateUi() { - priceTagsCheckBox->setText(tr("Enable &price tag feature (using data from blacklotusproject.com)")); - generalGroupBox->setTitle(tr("General")); + priceTagsCheckBox->setText(tr("Enable &price tag feature (using data from blacklotusproject.com)")); + generalGroupBox->setTitle(tr("General")); } MessagesSettingsPage::MessagesSettingsPage() { - aAdd = new QAction(this); - connect(aAdd, SIGNAL(triggered()), this, SLOT(actAdd())); - aRemove = new QAction(this); - connect(aRemove, SIGNAL(triggered()), this, SLOT(actRemove())); - - messageList = new QListWidget; - QToolBar *messageToolBar = new QToolBar; - messageToolBar->setOrientation(Qt::Vertical); - messageToolBar->addAction(aAdd); - messageToolBar->addAction(aRemove); + aAdd = new QAction(this); + connect(aAdd, SIGNAL(triggered()), this, SLOT(actAdd())); + aRemove = new QAction(this); + connect(aRemove, SIGNAL(triggered()), this, SLOT(actRemove())); + + messageList = new QListWidget; + QToolBar *messageToolBar = new QToolBar; + messageToolBar->setOrientation(Qt::Vertical); + messageToolBar->addAction(aAdd); + messageToolBar->addAction(aRemove); - QSettings settings; - settings.beginGroup("messages"); - int count = settings.value("count", 0).toInt(); - for (int i = 0; i < count; i++) - messageList->addItem(settings.value(QString("msg%1").arg(i)).toString()); - - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addWidget(messageList); - mainLayout->addWidget(messageToolBar); + QSettings settings; + settings.beginGroup("messages"); + int count = settings.value("count", 0).toInt(); + for (int i = 0; i < count; i++) + messageList->addItem(settings.value(QString("msg%1").arg(i)).toString()); + + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addWidget(messageList); + mainLayout->addWidget(messageToolBar); - setLayout(mainLayout); - - retranslateUi(); + setLayout(mainLayout); + + retranslateUi(); } void MessagesSettingsPage::storeSettings() { - QSettings settings; - settings.beginGroup("messages"); - settings.setValue("count", messageList->count()); - for (int i = 0; i < messageList->count(); i++) - settings.setValue(QString("msg%1").arg(i), messageList->item(i)->text()); + QSettings settings; + settings.beginGroup("messages"); + settings.setValue("count", messageList->count()); + for (int i = 0; i < messageList->count(); i++) + settings.setValue(QString("msg%1").arg(i), messageList->item(i)->text()); } void MessagesSettingsPage::actAdd() { - bool ok; - QString msg = QInputDialog::getText(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok); - if (ok) { - messageList->addItem(msg); - storeSettings(); - } + bool ok; + QString msg = QInputDialog::getText(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok); + if (ok) { + messageList->addItem(msg); + storeSettings(); + } } void MessagesSettingsPage::actRemove() { - if (messageList->currentItem()) { - delete messageList->takeItem(messageList->currentRow()); - storeSettings(); - } + if (messageList->currentItem()) { + delete messageList->takeItem(messageList->currentRow()); + storeSettings(); + } } void MessagesSettingsPage::retranslateUi() { - aAdd->setText(tr("&Add")); - aRemove->setText(tr("&Remove")); + aAdd->setText(tr("&Add")); + aRemove->setText(tr("&Remove")); } DlgSettings::DlgSettings(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage())); - - contentsWidget = new QListWidget; - contentsWidget->setViewMode(QListView::IconMode); - contentsWidget->setIconSize(QSize(96, 84)); - contentsWidget->setMovement(QListView::Static); - contentsWidget->setMinimumWidth(130); - contentsWidget->setMaximumWidth(150); - contentsWidget->setSpacing(12); - - pagesWidget = new QStackedWidget; - pagesWidget->addWidget(new GeneralSettingsPage); - pagesWidget->addWidget(new AppearanceSettingsPage); - pagesWidget->addWidget(new UserInterfaceSettingsPage); - pagesWidget->addWidget(new DeckEditorSettingsPage); - pagesWidget->addWidget(new MessagesSettingsPage); - - createIcons(); - contentsWidget->setCurrentRow(0); - - QHBoxLayout *hboxLayout = new QHBoxLayout; - hboxLayout->addWidget(contentsWidget); - hboxLayout->addWidget(pagesWidget); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(close())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hboxLayout); - mainLayout->addSpacing(12); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); - - retranslateUi(); - - resize(800, 450); + connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage())); + + contentsWidget = new QListWidget; + contentsWidget->setViewMode(QListView::IconMode); + contentsWidget->setIconSize(QSize(96, 84)); + contentsWidget->setMovement(QListView::Static); + contentsWidget->setMinimumWidth(130); + contentsWidget->setMaximumWidth(150); + contentsWidget->setSpacing(12); + + pagesWidget = new QStackedWidget; + pagesWidget->addWidget(new GeneralSettingsPage); + pagesWidget->addWidget(new AppearanceSettingsPage); + pagesWidget->addWidget(new UserInterfaceSettingsPage); + pagesWidget->addWidget(new DeckEditorSettingsPage); + pagesWidget->addWidget(new MessagesSettingsPage); + + createIcons(); + contentsWidget->setCurrentRow(0); + + QHBoxLayout *hboxLayout = new QHBoxLayout; + hboxLayout->addWidget(contentsWidget); + hboxLayout->addWidget(pagesWidget); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(close())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hboxLayout); + mainLayout->addSpacing(12); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); + + retranslateUi(); + + resize(800, 450); } void DlgSettings::createIcons() { - generalButton = new QListWidgetItem(contentsWidget); - generalButton->setTextAlignment(Qt::AlignHCenter); - generalButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - generalButton->setIcon(QIcon(":/resources/icon_config_general.svg")); - - appearanceButton = new QListWidgetItem(contentsWidget); - appearanceButton->setTextAlignment(Qt::AlignHCenter); - appearanceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - appearanceButton->setIcon(QIcon(":/resources/icon_config_appearance.svg")); - - userInterfaceButton = new QListWidgetItem(contentsWidget); - userInterfaceButton->setTextAlignment(Qt::AlignHCenter); - userInterfaceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - userInterfaceButton->setIcon(QIcon(":/resources/icon_config_interface.svg")); - - deckEditorButton = new QListWidgetItem(contentsWidget); - deckEditorButton->setTextAlignment(Qt::AlignHCenter); - deckEditorButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - deckEditorButton->setIcon(QIcon(":/resources/icon_config_deckeditor.svg")); - - messagesButton = new QListWidgetItem(contentsWidget); - messagesButton->setTextAlignment(Qt::AlignHCenter); - messagesButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - messagesButton->setIcon(QIcon(":/resources/icon_config_messages.svg")); - - connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(changePage(QListWidgetItem *, QListWidgetItem *))); + generalButton = new QListWidgetItem(contentsWidget); + generalButton->setTextAlignment(Qt::AlignHCenter); + generalButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + generalButton->setIcon(QIcon(":/resources/icon_config_general.svg")); + + appearanceButton = new QListWidgetItem(contentsWidget); + appearanceButton->setTextAlignment(Qt::AlignHCenter); + appearanceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + appearanceButton->setIcon(QIcon(":/resources/icon_config_appearance.svg")); + + userInterfaceButton = new QListWidgetItem(contentsWidget); + userInterfaceButton->setTextAlignment(Qt::AlignHCenter); + userInterfaceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + userInterfaceButton->setIcon(QIcon(":/resources/icon_config_interface.svg")); + + deckEditorButton = new QListWidgetItem(contentsWidget); + deckEditorButton->setTextAlignment(Qt::AlignHCenter); + deckEditorButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + deckEditorButton->setIcon(QIcon(":/resources/icon_config_deckeditor.svg")); + + messagesButton = new QListWidgetItem(contentsWidget); + messagesButton->setTextAlignment(Qt::AlignHCenter); + messagesButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + messagesButton->setIcon(QIcon(":/resources/icon_config_messages.svg")); + + connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(changePage(QListWidgetItem *, QListWidgetItem *))); } void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous) { - if (!current) - current = previous; - - pagesWidget->setCurrentIndex(contentsWidget->row(current)); + if (!current) + current = previous; + + pagesWidget->setCurrentIndex(contentsWidget->row(current)); } void DlgSettings::updateLanguage() { - qApp->removeTranslator(translator); - installNewTranslator(); + qApp->removeTranslator(translator); + installNewTranslator(); } void DlgSettings::changeEvent(QEvent *event) { - if (event->type() == QEvent::LanguageChange) - retranslateUi(); - QDialog::changeEvent(event); + if (event->type() == QEvent::LanguageChange) + retranslateUi(); + QDialog::changeEvent(event); } void DlgSettings::closeEvent(QCloseEvent *event) { - if (!db->getLoadSuccess()) - if (QMessageBox::critical(this, tr("Error"), tr("Your card database is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - event->ignore(); - return; - } - if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) - if (QMessageBox::critical(this, tr("Error"), tr("The path to your deck directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - event->ignore(); - return; - } - if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) - if (QMessageBox::critical(this, tr("Error"), tr("The path to your card pictures directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - event->ignore(); - return; - } - event->accept(); + if (!db->getLoadSuccess()) + if (QMessageBox::critical(this, tr("Error"), tr("Your card database is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + event->ignore(); + return; + } + if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) + if (QMessageBox::critical(this, tr("Error"), tr("The path to your deck directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + event->ignore(); + return; + } + if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) + if (QMessageBox::critical(this, tr("Error"), tr("The path to your card pictures directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + event->ignore(); + return; + } + event->accept(); } void DlgSettings::retranslateUi() { - setWindowTitle(tr("Settings")); - - generalButton->setText(tr("General")); - appearanceButton->setText(tr("Appearance")); - userInterfaceButton->setText(tr("User interface")); - deckEditorButton->setText(tr("Deck editor")); - messagesButton->setText(tr("Messages")); - - for (int i = 0; i < pagesWidget->count(); i++) - dynamic_cast(pagesWidget->widget(i))->retranslateUi(); + setWindowTitle(tr("Settings")); + + generalButton->setText(tr("General")); + appearanceButton->setText(tr("Appearance")); + userInterfaceButton->setText(tr("User interface")); + deckEditorButton->setText(tr("Deck editor")); + messagesButton->setText(tr("Messages")); + + for (int i = 0; i < pagesWidget->count(); i++) + dynamic_cast(pagesWidget->widget(i))->retranslateUi(); } diff --git a/cockatrice/src/dlg_settings.h b/cockatrice/src/dlg_settings.h index 7911ccd9..5f87887c 100644 --- a/cockatrice/src/dlg_settings.h +++ b/cockatrice/src/dlg_settings.h @@ -18,123 +18,123 @@ class QSpinBox; class AbstractSettingsPage : public QWidget { public: - virtual void retranslateUi() = 0; + virtual void retranslateUi() = 0; }; class GeneralSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT public: - GeneralSettingsPage(); - void retranslateUi(); + GeneralSettingsPage(); + void retranslateUi(); private slots: - void deckPathButtonClicked(); - void replaysPathButtonClicked(); - void picsPathButtonClicked(); - void cardDatabasePathButtonClicked(); - void tokenDatabasePathButtonClicked(); - void languageBoxChanged(int index); + void deckPathButtonClicked(); + void replaysPathButtonClicked(); + void picsPathButtonClicked(); + void cardDatabasePathButtonClicked(); + void tokenDatabasePathButtonClicked(); + void languageBoxChanged(int index); private: - QStringList findQmFiles(); - QString languageName(const QString &qmFile); - QLineEdit *deckPathEdit, *replaysPathEdit, *picsPathEdit, *cardDatabasePathEdit, *tokenDatabasePathEdit; - QGroupBox *personalGroupBox, *pathsGroupBox; - QComboBox *languageBox; - QCheckBox *picDownloadCheckBox; - QLabel *languageLabel, *deckPathLabel, *replaysPathLabel, *picsPathLabel, *cardDatabasePathLabel, *tokenDatabasePathLabel; + QStringList findQmFiles(); + QString languageName(const QString &qmFile); + QLineEdit *deckPathEdit, *replaysPathEdit, *picsPathEdit, *cardDatabasePathEdit, *tokenDatabasePathEdit; + QGroupBox *personalGroupBox, *pathsGroupBox; + QComboBox *languageBox; + QCheckBox *picDownloadCheckBox; + QLabel *languageLabel, *deckPathLabel, *replaysPathLabel, *picsPathLabel, *cardDatabasePathLabel, *tokenDatabasePathLabel; }; class AppearanceSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT private slots: - void handBgClearButtonClicked(); - void handBgButtonClicked(); - void stackBgClearButtonClicked(); - void stackBgButtonClicked(); - void tableBgClearButtonClicked(); - void tableBgButtonClicked(); - void playerAreaBgClearButtonClicked(); - void playerAreaBgButtonClicked(); - void cardBackPicturePathClearButtonClicked(); - void cardBackPicturePathButtonClicked(); + void handBgClearButtonClicked(); + void handBgButtonClicked(); + void stackBgClearButtonClicked(); + void stackBgButtonClicked(); + void tableBgClearButtonClicked(); + void tableBgButtonClicked(); + void playerAreaBgClearButtonClicked(); + void playerAreaBgButtonClicked(); + void cardBackPicturePathClearButtonClicked(); + void cardBackPicturePathButtonClicked(); signals: - void handBgChanged(const QString &path); - void stackBgChanged(const QString &path); - void tableBgChanged(const QString &path); - void playerAreaBgChanged(const QString &path); - void cardBackPicturePathChanged(const QString &path); + void handBgChanged(const QString &path); + void stackBgChanged(const QString &path); + void tableBgChanged(const QString &path); + void playerAreaBgChanged(const QString &path); + void cardBackPicturePathChanged(const QString &path); private: - QLabel *handBgLabel, *stackBgLabel, *tableBgLabel, *playerAreaBgLabel, *cardBackPicturePathLabel, *minPlayersForMultiColumnLayoutLabel; - QLineEdit *handBgEdit, *stackBgEdit, *tableBgEdit, *playerAreaBgEdit, *cardBackPicturePathEdit; - QCheckBox *displayCardNamesCheckBox, *horizontalHandCheckBox, *invertVerticalCoordinateCheckBox, *zoneViewSortByNameCheckBox, *zoneViewSortByTypeCheckBox; - QGroupBox *zoneBgGroupBox, *cardsGroupBox, *handGroupBox, *tableGroupBox, *zoneViewGroupBox; - QSpinBox *minPlayersForMultiColumnLayoutEdit; + QLabel *handBgLabel, *stackBgLabel, *tableBgLabel, *playerAreaBgLabel, *cardBackPicturePathLabel, *minPlayersForMultiColumnLayoutLabel; + QLineEdit *handBgEdit, *stackBgEdit, *tableBgEdit, *playerAreaBgEdit, *cardBackPicturePathEdit; + QCheckBox *displayCardNamesCheckBox, *horizontalHandCheckBox, *invertVerticalCoordinateCheckBox, *zoneViewSortByNameCheckBox, *zoneViewSortByTypeCheckBox; + QGroupBox *zoneBgGroupBox, *cardsGroupBox, *handGroupBox, *tableGroupBox, *zoneViewGroupBox; + QSpinBox *minPlayersForMultiColumnLayoutEdit; public: - AppearanceSettingsPage(); - void retranslateUi(); + AppearanceSettingsPage(); + void retranslateUi(); }; class UserInterfaceSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT private slots: - void soundPathClearButtonClicked(); - void soundPathButtonClicked(); + void soundPathClearButtonClicked(); + void soundPathButtonClicked(); signals: - void soundPathChanged(); + void soundPathChanged(); private: - QCheckBox *notificationsEnabledCheckBox; - QCheckBox *doubleClickToPlayCheckBox; - QCheckBox *playToStackCheckBox; - QCheckBox *tapAnimationCheckBox; - QCheckBox *soundEnabledCheckBox; - QLabel *soundPathLabel; - QLineEdit *soundPathEdit; - QGroupBox *generalGroupBox, *animationGroupBox, *soundGroupBox; + QCheckBox *notificationsEnabledCheckBox; + QCheckBox *doubleClickToPlayCheckBox; + QCheckBox *playToStackCheckBox; + QCheckBox *tapAnimationCheckBox; + QCheckBox *soundEnabledCheckBox; + QLabel *soundPathLabel; + QLineEdit *soundPathEdit; + QGroupBox *generalGroupBox, *animationGroupBox, *soundGroupBox; public: - UserInterfaceSettingsPage(); - void retranslateUi(); + UserInterfaceSettingsPage(); + void retranslateUi(); }; class DeckEditorSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT public: - DeckEditorSettingsPage(); - void retranslateUi(); + DeckEditorSettingsPage(); + void retranslateUi(); private: - QCheckBox *priceTagsCheckBox; - QGroupBox *generalGroupBox; + QCheckBox *priceTagsCheckBox; + QGroupBox *generalGroupBox; }; class MessagesSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT public: - MessagesSettingsPage(); - void retranslateUi(); + MessagesSettingsPage(); + void retranslateUi(); private slots: - void actAdd(); - void actRemove(); + void actAdd(); + void actRemove(); private: - QListWidget *messageList; - QAction *aAdd, *aRemove; - - void storeSettings(); + QListWidget *messageList; + QAction *aAdd, *aRemove; + + void storeSettings(); }; class DlgSettings : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgSettings(QWidget *parent = 0); + DlgSettings(QWidget *parent = 0); private slots: - void changePage(QListWidgetItem *current, QListWidgetItem *previous); - void updateLanguage(); + void changePage(QListWidgetItem *current, QListWidgetItem *previous); + void updateLanguage(); private: - QListWidget *contentsWidget; - QStackedWidget *pagesWidget; - QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton; - void createIcons(); - void retranslateUi(); + QListWidget *contentsWidget; + QStackedWidget *pagesWidget; + QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton; + void createIcons(); + void retranslateUi(); protected: - void changeEvent(QEvent *event); - void closeEvent(QCloseEvent *event); + void changeEvent(QEvent *event); + void closeEvent(QCloseEvent *event); }; #endif diff --git a/cockatrice/src/gamescene.cpp b/cockatrice/src/gamescene.cpp index ce083c76..8e777168 100644 --- a/cockatrice/src/gamescene.cpp +++ b/cockatrice/src/gamescene.cpp @@ -13,103 +13,103 @@ #include GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent) - : QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()) + : QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()) { - animationTimer = new QBasicTimer; - addItem(phasesToolbar); - connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange())); - - rearrange(); + animationTimer = new QBasicTimer; + addItem(phasesToolbar); + connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange())); + + rearrange(); } GameScene::~GameScene() { - delete animationTimer; + delete animationTimer; } void GameScene::retranslateUi() { - for (int i = 0; i < zoneViews.size(); ++i) - zoneViews[i]->retranslateUi(); + for (int i = 0; i < zoneViews.size(); ++i) + zoneViews[i]->retranslateUi(); } void GameScene::addPlayer(Player *player) { - qDebug("GameScene::addPlayer"); - players << player; - addItem(player); - connect(player, SIGNAL(sizeChanged()), this, SLOT(rearrange())); - connect(player, SIGNAL(gameConceded()), this, SLOT(rearrange())); + qDebug("GameScene::addPlayer"); + players << player; + addItem(player); + connect(player, SIGNAL(sizeChanged()), this, SLOT(rearrange())); + connect(player, SIGNAL(gameConceded()), this, SLOT(rearrange())); } void GameScene::removePlayer(Player *player) { - qDebug("GameScene::removePlayer"); - players.removeAt(players.indexOf(player)); - removeItem(player); - rearrange(); + qDebug("GameScene::removePlayer"); + players.removeAt(players.indexOf(player)); + removeItem(player); + rearrange(); } void GameScene::rearrange() { - playersByColumn.clear(); + playersByColumn.clear(); - QList playersPlaying; - int firstPlayer = -1; - for (int i = 0; i < players.size(); ++i) - if (!players[i]->getConceded()) { - playersPlaying.append(players[i]); - if ((firstPlayer == -1) && (players[i]->getLocal())) - firstPlayer = playersPlaying.size() - 1; - } - if (firstPlayer == -1) - firstPlayer = 0; - const int playersCount = playersPlaying.size(); - const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2; - const int rows = ceil((qreal) playersCount / columns); - qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; - QList columnWidth; - int firstPlayerOfColumn = firstPlayer; - for (int col = 0; col < columns; ++col) { - playersByColumn.append(QList()); - columnWidth.append(0); - qreal thisColumnHeight = -playerAreaSpacing; - const int rowsInColumn = rows - (playersCount % columns) * col; // only correct for max. 2 cols - for (int j = 0; j < rowsInColumn; ++j) { - Player *player = playersPlaying[(firstPlayerOfColumn + j) % playersCount]; - if (col == 0) - playersByColumn[col].prepend(player); - else - playersByColumn[col].append(player); - thisColumnHeight += player->boundingRect().height() + playerAreaSpacing; - if (player->boundingRect().width() > columnWidth[col]) - columnWidth[col] = player->boundingRect().width(); - } - if (thisColumnHeight > sceneHeight) - sceneHeight = thisColumnHeight; - sceneWidth += columnWidth[col] + playerAreaSpacing; + QList playersPlaying; + int firstPlayer = -1; + for (int i = 0; i < players.size(); ++i) + if (!players[i]->getConceded()) { + playersPlaying.append(players[i]); + if ((firstPlayer == -1) && (players[i]->getLocal())) + firstPlayer = playersPlaying.size() - 1; + } + if (firstPlayer == -1) + firstPlayer = 0; + const int playersCount = playersPlaying.size(); + const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2; + const int rows = ceil((qreal) playersCount / columns); + qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; + QList columnWidth; + int firstPlayerOfColumn = firstPlayer; + for (int col = 0; col < columns; ++col) { + playersByColumn.append(QList()); + columnWidth.append(0); + qreal thisColumnHeight = -playerAreaSpacing; + const int rowsInColumn = rows - (playersCount % columns) * col; // only correct for max. 2 cols + for (int j = 0; j < rowsInColumn; ++j) { + Player *player = playersPlaying[(firstPlayerOfColumn + j) % playersCount]; + if (col == 0) + playersByColumn[col].prepend(player); + else + playersByColumn[col].append(player); + thisColumnHeight += player->boundingRect().height() + playerAreaSpacing; + if (player->boundingRect().width() > columnWidth[col]) + columnWidth[col] = player->boundingRect().width(); + } + if (thisColumnHeight > sceneHeight) + sceneHeight = thisColumnHeight; + sceneWidth += columnWidth[col] + playerAreaSpacing; - firstPlayerOfColumn += rowsInColumn; - } + firstPlayerOfColumn += rowsInColumn; + } - phasesToolbar->setHeight(sceneHeight); - qreal phasesWidth = phasesToolbar->getWidth(); - sceneWidth += phasesWidth; + phasesToolbar->setHeight(sceneHeight); + qreal phasesWidth = phasesToolbar->getWidth(); + sceneWidth += phasesWidth; - qreal x = phasesWidth; - for (int col = 0; col < columns; ++col) { - qreal y = 0; - for (int row = 0; row < playersByColumn[col].size(); ++row) { - Player *player = playersByColumn[col][row]; - player->setPos(x, y); - player->setMirrored(row != rows - 1); - y += player->boundingRect().height() + playerAreaSpacing; - } - x += columnWidth[col] + playerAreaSpacing; - } + qreal x = phasesWidth; + for (int col = 0; col < columns; ++col) { + qreal y = 0; + for (int row = 0; row < playersByColumn[col].size(); ++row) { + Player *player = playersByColumn[col][row]; + player->setPos(x, y); + player->setMirrored(row != rows - 1); + y += player->boundingRect().height() + playerAreaSpacing; + } + x += columnWidth[col] + playerAreaSpacing; + } - setSceneRect(sceneRect().x(), sceneRect().y(), sceneWidth, sceneHeight); - processViewSizeChange(viewSize); + setSceneRect(sceneRect().x(), sceneRect().y(), sceneWidth, sceneHeight); + processViewSizeChange(viewSize); } void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numberCards) @@ -123,166 +123,166 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb } } - ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false); + ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false); zoneViews.append(item); connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); - addItem(item); - item->setPos(50, 50); + addItem(item); + item->setPos(50, 50); } void GameScene::addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission) { - ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList); - zoneViews.append(item); + ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList); + zoneViews.append(item); connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); - addItem(item); - item->setPos(50, 50); + addItem(item); + item->setPos(50, 50); } void GameScene::removeZoneView(ZoneViewWidget *item) { zoneViews.removeAt(zoneViews.indexOf(item)); - removeItem(item); + removeItem(item); } void GameScene::clearViews() { - while (!zoneViews.isEmpty()) - zoneViews.first()->close(); + while (!zoneViews.isEmpty()) + zoneViews.first()->close(); } void GameScene::closeMostRecentZoneView() { - if (!zoneViews.isEmpty()) - zoneViews.last()->close(); + if (!zoneViews.isEmpty()) + zoneViews.last()->close(); } QTransform GameScene::getViewTransform() const { - return views().at(0)->transform(); + return views().at(0)->transform(); } QTransform GameScene::getViewportTransform() const { - return views().at(0)->viewportTransform(); + return views().at(0)->viewportTransform(); } void GameScene::processViewSizeChange(const QSize &newSize) { - viewSize = newSize; - - qreal newRatio = ((qreal) newSize.width()) / newSize.height(); - qreal minWidth = 0; - QList minWidthByColumn; - for (int col = 0; col < playersByColumn.size(); ++col) { - minWidthByColumn.append(0); - for (int row = 0; row < playersByColumn[col].size(); ++row) { - qreal w = playersByColumn[col][row]->getMinimumWidth(); - if (w > minWidthByColumn[col]) - minWidthByColumn[col] = w; - } - minWidth += minWidthByColumn[col]; - } - minWidth += phasesToolbar->getWidth(); - - qreal minRatio = minWidth / sceneRect().height(); - qreal newWidth; - if (minRatio > newRatio) { - // Aspect ratio is dominated by table width. - newWidth = minWidth; - } else { - // Aspect ratio is dominated by window dimensions. - newWidth = newRatio * sceneRect().height(); - } - setSceneRect(0, 0, newWidth, sceneRect().height()); + viewSize = newSize; + + qreal newRatio = ((qreal) newSize.width()) / newSize.height(); + qreal minWidth = 0; + QList minWidthByColumn; + for (int col = 0; col < playersByColumn.size(); ++col) { + minWidthByColumn.append(0); + for (int row = 0; row < playersByColumn[col].size(); ++row) { + qreal w = playersByColumn[col][row]->getMinimumWidth(); + if (w > minWidthByColumn[col]) + minWidthByColumn[col] = w; + } + minWidth += minWidthByColumn[col]; + } + minWidth += phasesToolbar->getWidth(); + + qreal minRatio = minWidth / sceneRect().height(); + qreal newWidth; + if (minRatio > newRatio) { + // Aspect ratio is dominated by table width. + newWidth = minWidth; + } else { + // Aspect ratio is dominated by window dimensions. + newWidth = newRatio * sceneRect().height(); + } + setSceneRect(0, 0, newWidth, sceneRect().height()); - qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); - for (int col = 0; col < playersByColumn.size(); ++col) - for (int row = 0; row < playersByColumn[col].size(); ++row) - playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn); + qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); + for (int col = 0; col < playersByColumn.size(); ++col) + for (int row = 0; row < playersByColumn[col].size(); ++row) + playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn); } void GameScene::updateHover(const QPointF &scenePos) { - QList itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); - - // Search for the topmost zone and ignore all cards not belonging to that zone. - CardZone *zone = 0; - for (int i = 0; i < itemList.size(); ++i) - if ((zone = qgraphicsitem_cast(itemList[i]))) - break; - - CardItem *maxZCard = 0; - if (zone) { - qreal maxZ = -1; - for (int i = 0; i < itemList.size(); ++i) { - CardItem *card = qgraphicsitem_cast(itemList[i]); - if (!card) - continue; - if (card->getAttachedTo()) { - if (card->getAttachedTo()->getZone() != zone) - continue; - } else if (card->getZone() != zone) - continue; - - if (card->getRealZValue() > maxZ) { - maxZ = card->getRealZValue(); - maxZCard = card; - } - } - } - if (hoveredCard && (maxZCard != hoveredCard)) - hoveredCard->setHovered(false); - if (maxZCard && (maxZCard != hoveredCard)) - maxZCard->setHovered(true); - hoveredCard = maxZCard; + QList itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); + + // Search for the topmost zone and ignore all cards not belonging to that zone. + CardZone *zone = 0; + for (int i = 0; i < itemList.size(); ++i) + if ((zone = qgraphicsitem_cast(itemList[i]))) + break; + + CardItem *maxZCard = 0; + if (zone) { + qreal maxZ = -1; + for (int i = 0; i < itemList.size(); ++i) { + CardItem *card = qgraphicsitem_cast(itemList[i]); + if (!card) + continue; + if (card->getAttachedTo()) { + if (card->getAttachedTo()->getZone() != zone) + continue; + } else if (card->getZone() != zone) + continue; + + if (card->getRealZValue() > maxZ) { + maxZ = card->getRealZValue(); + maxZCard = card; + } + } + } + if (hoveredCard && (maxZCard != hoveredCard)) + hoveredCard->setHovered(false); + if (maxZCard && (maxZCard != hoveredCard)) + maxZCard->setHovered(true); + hoveredCard = maxZCard; } bool GameScene::event(QEvent *event) { - if (event->type() == QEvent::GraphicsSceneMouseMove) - updateHover(static_cast(event)->scenePos()); - - return QGraphicsScene::event(event); + if (event->type() == QEvent::GraphicsSceneMouseMove) + updateHover(static_cast(event)->scenePos()); + + return QGraphicsScene::event(event); } void GameScene::timerEvent(QTimerEvent * /*event*/) { - QMutableSetIterator i(cardsToAnimate); - while (i.hasNext()) { - i.next(); - if (!i.value()->animationEvent()) - i.remove(); - } - if (cardsToAnimate.isEmpty()) - animationTimer->stop(); + QMutableSetIterator i(cardsToAnimate); + while (i.hasNext()) { + i.next(); + if (!i.value()->animationEvent()) + i.remove(); + } + if (cardsToAnimate.isEmpty()) + animationTimer->stop(); } void GameScene::registerAnimationItem(AbstractCardItem *card) { - cardsToAnimate.insert(static_cast(card)); - if (!animationTimer->isActive()) - animationTimer->start(50, this); + cardsToAnimate.insert(static_cast(card)); + if (!animationTimer->isActive()) + animationTimer->start(50, this); } void GameScene::unregisterAnimationItem(AbstractCardItem *card) { - cardsToAnimate.remove(static_cast(card)); - if (cardsToAnimate.isEmpty()) - animationTimer->stop(); + cardsToAnimate.remove(static_cast(card)); + if (cardsToAnimate.isEmpty()) + animationTimer->stop(); } void GameScene::startRubberBand(const QPointF &selectionOrigin) { - emit sigStartRubberBand(selectionOrigin); + emit sigStartRubberBand(selectionOrigin); } void GameScene::resizeRubberBand(const QPointF &cursorPoint) { - emit sigResizeRubberBand(cursorPoint); + emit sigResizeRubberBand(cursorPoint); } void GameScene::stopRubberBand() { - emit sigStopRubberBand(); + emit sigStopRubberBand(); } diff --git a/cockatrice/src/gamescene.h b/cockatrice/src/gamescene.h index 7deb78c8..b542f0ec 100644 --- a/cockatrice/src/gamescene.h +++ b/cockatrice/src/gamescene.h @@ -16,49 +16,49 @@ class PhasesToolbar; class QBasicTimer; class GameScene : public QGraphicsScene { - Q_OBJECT + Q_OBJECT private: - static const int playerAreaSpacing = 5; - - PhasesToolbar *phasesToolbar; - QList players; - QList > playersByColumn; - QList zoneViews; - QSize viewSize; - QPointer hoveredCard; - QBasicTimer *animationTimer; - QSet cardsToAnimate; - void updateHover(const QPointF &scenePos); + static const int playerAreaSpacing = 5; + + PhasesToolbar *phasesToolbar; + QList players; + QList > playersByColumn; + QList zoneViews; + QSize viewSize; + QPointer hoveredCard; + QBasicTimer *animationTimer; + QSet cardsToAnimate; + void updateHover(const QPointF &scenePos); public: - GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0); - ~GameScene(); - void retranslateUi(); - void processViewSizeChange(const QSize &newSize); - QTransform getViewTransform() const; - QTransform getViewportTransform() const; - - void startRubberBand(const QPointF &selectionOrigin); - void resizeRubberBand(const QPointF &cursorPoint); - void stopRubberBand(); - - void registerAnimationItem(AbstractCardItem *item); - void unregisterAnimationItem(AbstractCardItem *card); + GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0); + ~GameScene(); + void retranslateUi(); + void processViewSizeChange(const QSize &newSize); + QTransform getViewTransform() const; + QTransform getViewportTransform() const; + + void startRubberBand(const QPointF &selectionOrigin); + void resizeRubberBand(const QPointF &cursorPoint); + void stopRubberBand(); + + void registerAnimationItem(AbstractCardItem *item); + void unregisterAnimationItem(AbstractCardItem *card); public slots: - void toggleZoneView(Player *player, const QString &zoneName, int numberCards); - void addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission); - void removeZoneView(ZoneViewWidget *item); - void addPlayer(Player *player); - void removePlayer(Player *player); - void clearViews(); - void closeMostRecentZoneView(); - void rearrange(); + void toggleZoneView(Player *player, const QString &zoneName, int numberCards); + void addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission); + void removeZoneView(ZoneViewWidget *item); + void addPlayer(Player *player); + void removePlayer(Player *player); + void clearViews(); + void closeMostRecentZoneView(); + void rearrange(); protected: - bool event(QEvent *event); - void timerEvent(QTimerEvent *event); + bool event(QEvent *event); + void timerEvent(QTimerEvent *event); signals: - void sigStartRubberBand(const QPointF &selectionOrigin); - void sigResizeRubberBand(const QPointF &cursorPoint); - void sigStopRubberBand(); + void sigStartRubberBand(const QPointF &selectionOrigin); + void sigResizeRubberBand(const QPointF &cursorPoint); + void sigStopRubberBand(); }; #endif diff --git a/cockatrice/src/gameselector.cpp b/cockatrice/src/gameselector.cpp index 86f86df9..6a05d905 100644 --- a/cockatrice/src/gameselector.cpp +++ b/cockatrice/src/gameselector.cpp @@ -18,173 +18,173 @@ #include "pb/response.pb.h" GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, QWidget *parent) - : QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room) + : QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room) { - gameListView = new QTreeView; - gameListModel = new GamesModel(_rooms, _gameTypes, this); - gameListProxyModel = new GamesProxyModel(this, tabSupervisor->getUserInfo()); - gameListProxyModel->setSourceModel(gameListModel); - gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); - gameListView->setModel(gameListProxyModel); - gameListView->setSortingEnabled(true); - gameListView->setAlternatingRowColors(true); - gameListView->setRootIsDecorated(true); - if (_room) - gameListView->header()->hideSection(1); - else - gameListProxyModel->setUnavailableGamesVisible(true); - gameListView->header()->setResizeMode(1, QHeaderView::ResizeToContents); + gameListView = new QTreeView; + gameListModel = new GamesModel(_rooms, _gameTypes, this); + gameListProxyModel = new GamesProxyModel(this, tabSupervisor->getUserInfo()); + gameListProxyModel->setSourceModel(gameListModel); + gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + gameListView->setModel(gameListProxyModel); + gameListView->setSortingEnabled(true); + gameListView->setAlternatingRowColors(true); + gameListView->setRootIsDecorated(true); + if (_room) + gameListView->header()->hideSection(1); + else + gameListProxyModel->setUnavailableGamesVisible(true); + gameListView->header()->setResizeMode(1, QHeaderView::ResizeToContents); - filterButton = new QPushButton; - filterButton->setIcon(QIcon(":/resources/icon_search.svg")); - connect(filterButton, SIGNAL(clicked()), this, SLOT(actSetFilter())); - clearFilterButton = new QPushButton; - clearFilterButton->setIcon(QIcon(":/resources/icon_clearsearch.svg")); - clearFilterButton->setEnabled(false); - connect(clearFilterButton, SIGNAL(clicked()), this, SLOT(actClearFilter())); + filterButton = new QPushButton; + filterButton->setIcon(QIcon(":/resources/icon_search.svg")); + connect(filterButton, SIGNAL(clicked()), this, SLOT(actSetFilter())); + clearFilterButton = new QPushButton; + clearFilterButton->setIcon(QIcon(":/resources/icon_clearsearch.svg")); + clearFilterButton->setEnabled(false); + connect(clearFilterButton, SIGNAL(clicked()), this, SLOT(actClearFilter())); - if (room) { - createButton = new QPushButton; - connect(createButton, SIGNAL(clicked()), this, SLOT(actCreate())); - } else - createButton = 0; - joinButton = new QPushButton; - spectateButton = new QPushButton; - - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addWidget(filterButton); - buttonLayout->addWidget(clearFilterButton); - buttonLayout->addStretch(); - if (room) - buttonLayout->addWidget(createButton); - buttonLayout->addWidget(joinButton); - buttonLayout->addWidget(spectateButton); - buttonLayout->setAlignment(Qt::AlignTop); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(gameListView); - mainLayout->addLayout(buttonLayout); + if (room) { + createButton = new QPushButton; + connect(createButton, SIGNAL(clicked()), this, SLOT(actCreate())); + } else + createButton = 0; + joinButton = new QPushButton; + spectateButton = new QPushButton; + + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addWidget(filterButton); + buttonLayout->addWidget(clearFilterButton); + buttonLayout->addStretch(); + if (room) + buttonLayout->addWidget(createButton); + buttonLayout->addWidget(joinButton); + buttonLayout->addWidget(spectateButton); + buttonLayout->setAlignment(Qt::AlignTop); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(gameListView); + mainLayout->addLayout(buttonLayout); - retranslateUi(); - setLayout(mainLayout); + retranslateUi(); + setLayout(mainLayout); - setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5); - setMinimumHeight(200); + setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5); + setMinimumHeight(200); - connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin())); - connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin())); + connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin())); + connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin())); } void GameSelector::actSetFilter() { - GameTypeMap gameTypeMap; - if (room) - gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId()); - DlgFilterGames dlg(gameTypeMap, this); - dlg.setUnavailableGamesVisible(gameListProxyModel->getUnavailableGamesVisible()); - dlg.setPasswordProtectedGamesVisible(gameListProxyModel->getPasswordProtectedGamesVisible()); - dlg.setGameNameFilter(gameListProxyModel->getGameNameFilter()); - dlg.setCreatorNameFilter(gameListProxyModel->getCreatorNameFilter()); - dlg.setGameTypeFilter(gameListProxyModel->getGameTypeFilter()); - dlg.setMaxPlayersFilter(gameListProxyModel->getMaxPlayersFilterMin(), gameListProxyModel->getMaxPlayersFilterMax()); - - if (!dlg.exec()) - return; - - clearFilterButton->setEnabled(true); - - gameListProxyModel->setUnavailableGamesVisible(dlg.getUnavailableGamesVisible()); - gameListProxyModel->setPasswordProtectedGamesVisible(dlg.getPasswordProtectedGamesVisible()); - gameListProxyModel->setGameNameFilter(dlg.getGameNameFilter()); - gameListProxyModel->setCreatorNameFilter(dlg.getCreatorNameFilter()); - gameListProxyModel->setGameTypeFilter(dlg.getGameTypeFilter()); - gameListProxyModel->setMaxPlayersFilter(dlg.getMaxPlayersFilterMin(), dlg.getMaxPlayersFilterMax()); + GameTypeMap gameTypeMap; + if (room) + gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId()); + DlgFilterGames dlg(gameTypeMap, this); + dlg.setUnavailableGamesVisible(gameListProxyModel->getUnavailableGamesVisible()); + dlg.setPasswordProtectedGamesVisible(gameListProxyModel->getPasswordProtectedGamesVisible()); + dlg.setGameNameFilter(gameListProxyModel->getGameNameFilter()); + dlg.setCreatorNameFilter(gameListProxyModel->getCreatorNameFilter()); + dlg.setGameTypeFilter(gameListProxyModel->getGameTypeFilter()); + dlg.setMaxPlayersFilter(gameListProxyModel->getMaxPlayersFilterMin(), gameListProxyModel->getMaxPlayersFilterMax()); + + if (!dlg.exec()) + return; + + clearFilterButton->setEnabled(true); + + gameListProxyModel->setUnavailableGamesVisible(dlg.getUnavailableGamesVisible()); + gameListProxyModel->setPasswordProtectedGamesVisible(dlg.getPasswordProtectedGamesVisible()); + gameListProxyModel->setGameNameFilter(dlg.getGameNameFilter()); + gameListProxyModel->setCreatorNameFilter(dlg.getCreatorNameFilter()); + gameListProxyModel->setGameTypeFilter(dlg.getGameTypeFilter()); + gameListProxyModel->setMaxPlayersFilter(dlg.getMaxPlayersFilterMin(), dlg.getMaxPlayersFilterMax()); } void GameSelector::actClearFilter() { - clearFilterButton->setEnabled(false); - - gameListProxyModel->resetFilterParameters(); + clearFilterButton->setEnabled(false); + + gameListProxyModel->resetFilterParameters(); } void GameSelector::actCreate() { - DlgCreateGame dlg(room, room->getGameTypes(), this); - dlg.exec(); + DlgCreateGame dlg(room, room->getGameTypes(), this); + dlg.exec(); } void GameSelector::checkResponse(const Response &response) { - if (createButton) - createButton->setEnabled(true); - joinButton->setEnabled(true); - spectateButton->setEnabled(true); + if (createButton) + createButton->setEnabled(true); + joinButton->setEnabled(true); + spectateButton->setEnabled(true); - switch (response.response_code()) { - case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break; - case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break; - case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break; - case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break; - case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break; - case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break; - case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break; - case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break; - default: ; - } + switch (response.response_code()) { + case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break; + case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break; + case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break; + case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break; + case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break; + case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break; + case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break; + case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break; + default: ; + } } void GameSelector::actJoin() { - bool spectator = sender() == spectateButton; - - QModelIndex ind = gameListView->currentIndex(); - if (!ind.isValid()) - return; - const ServerInfo_Game &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt()); - bool overrideRestrictions = !tabSupervisor->getAdminLocked(); - QString password; - if (game.with_password() && !(spectator && !game.spectators_need_password()) && !overrideRestrictions) { - bool ok; - password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok); - if (!ok) - return; - } - - Command_JoinGame cmd; - cmd.set_game_id(game.game_id()); - cmd.set_password(password.toStdString()); - cmd.set_spectator(spectator); - cmd.set_override_restrictions(overrideRestrictions); - - TabRoom *r = tabSupervisor->getRoomTabs().value(game.room_id()); - if (!r) { - QMessageBox::critical(this, tr("Error"), tr("Please join the respective room first.")); - return; - } - - PendingCommand *pend = r->prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); - r->sendRoomCommand(pend); + bool spectator = sender() == spectateButton; + + QModelIndex ind = gameListView->currentIndex(); + if (!ind.isValid()) + return; + const ServerInfo_Game &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt()); + bool overrideRestrictions = !tabSupervisor->getAdminLocked(); + QString password; + if (game.with_password() && !(spectator && !game.spectators_need_password()) && !overrideRestrictions) { + bool ok; + password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok); + if (!ok) + return; + } + + Command_JoinGame cmd; + cmd.set_game_id(game.game_id()); + cmd.set_password(password.toStdString()); + cmd.set_spectator(spectator); + cmd.set_override_restrictions(overrideRestrictions); + + TabRoom *r = tabSupervisor->getRoomTabs().value(game.room_id()); + if (!r) { + QMessageBox::critical(this, tr("Error"), tr("Please join the respective room first.")); + return; + } + + PendingCommand *pend = r->prepareRoomCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); + r->sendRoomCommand(pend); - if (createButton) - createButton->setEnabled(false); - joinButton->setEnabled(false); - spectateButton->setEnabled(false); + if (createButton) + createButton->setEnabled(false); + joinButton->setEnabled(false); + spectateButton->setEnabled(false); } void GameSelector::retranslateUi() { - setTitle(tr("Games")); - filterButton->setText(tr("&Filter games")); - clearFilterButton->setText(tr("C&lear filter")); - if (createButton) - createButton->setText(tr("C&reate")); - joinButton->setText(tr("&Join")); - spectateButton->setText(tr("J&oin as spectator")); + setTitle(tr("Games")); + filterButton->setText(tr("&Filter games")); + clearFilterButton->setText(tr("C&lear filter")); + if (createButton) + createButton->setText(tr("C&reate")); + joinButton->setText(tr("&Join")); + spectateButton->setText(tr("J&oin as spectator")); } void GameSelector::processGameInfo(const ServerInfo_Game &info) { - gameListModel->updateGameList(info); + gameListModel->updateGameList(info); } diff --git a/cockatrice/src/gameselector.h b/cockatrice/src/gameselector.h index 4712e3a8..47a9c395 100644 --- a/cockatrice/src/gameselector.h +++ b/cockatrice/src/gameselector.h @@ -16,28 +16,28 @@ class ServerInfo_Game; class Response; class GameSelector : public QGroupBox { - Q_OBJECT + Q_OBJECT private slots: - void actSetFilter(); - void actClearFilter(); - void actCreate(); - void actJoin(); - void checkResponse(const Response &response); + void actSetFilter(); + void actClearFilter(); + void actCreate(); + void actJoin(); + void checkResponse(const Response &response); signals: - void gameJoined(int gameId); + void gameJoined(int gameId); private: - AbstractClient *client; - const TabSupervisor *tabSupervisor; - TabRoom *room; + AbstractClient *client; + const TabSupervisor *tabSupervisor; + TabRoom *room; - QTreeView *gameListView; - GamesModel *gameListModel; - GamesProxyModel *gameListProxyModel; - QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton; + QTreeView *gameListView; + GamesModel *gameListModel; + GamesProxyModel *gameListProxyModel; + QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton; public: - GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, QWidget *parent = 0); - void retranslateUi(); - void processGameInfo(const ServerInfo_Game &info); + GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, QWidget *parent = 0); + void retranslateUi(); + void processGameInfo(const ServerInfo_Game &info); }; #endif diff --git a/cockatrice/src/gamesmodel.cpp b/cockatrice/src/gamesmodel.cpp index cbffc86d..0ee41f35 100644 --- a/cockatrice/src/gamesmodel.cpp +++ b/cockatrice/src/gamesmodel.cpp @@ -3,187 +3,187 @@ #include GamesModel::GamesModel(const QMap &_rooms, const QMap &_gameTypes, QObject *parent) - : QAbstractTableModel(parent), rooms(_rooms), gameTypes(_gameTypes) + : QAbstractTableModel(parent), rooms(_rooms), gameTypes(_gameTypes) { } QVariant GamesModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if (role == Qt::UserRole) - return index.row(); - if (role != Qt::DisplayRole) - return QVariant(); - if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) - return QVariant(); - - const ServerInfo_Game &g = gameList[index.row()]; - switch (index.column()) { - case 0: return QString::fromStdString(g.description()); - case 1: return rooms.value(g.room_id()); - case 2: return QString::fromStdString(g.creator_info().name()); - case 3: { - QStringList result; - GameTypeMap gameTypeMap = gameTypes.value(g.room_id()); - for (int i = g.game_types_size() - 1; i >= 0; --i) - result.append(gameTypeMap.value(g.game_types(i))); - return result.join(", "); - } - case 4: return g.with_password() ? ((g.spectators_need_password() || !g.spectators_allowed()) ? tr("yes") : tr("yes, free for spectators")) : tr("no"); - case 5: { - QStringList result; - if (g.only_buddies()) - result.append(tr("buddies only")); - if (g.only_registered()) - result.append(tr("reg. users only")); - return result.join(", "); - } - case 6: return QString("%1/%2").arg(g.player_count()).arg(g.max_players()); - case 7: return g.spectators_allowed() ? QVariant(g.spectators_count()) : QVariant(tr("not allowed")); - default: return QVariant(); - } + if (!index.isValid()) + return QVariant(); + if (role == Qt::UserRole) + return index.row(); + if (role != Qt::DisplayRole) + return QVariant(); + if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) + return QVariant(); + + const ServerInfo_Game &g = gameList[index.row()]; + switch (index.column()) { + case 0: return QString::fromStdString(g.description()); + case 1: return rooms.value(g.room_id()); + case 2: return QString::fromStdString(g.creator_info().name()); + case 3: { + QStringList result; + GameTypeMap gameTypeMap = gameTypes.value(g.room_id()); + for (int i = g.game_types_size() - 1; i >= 0; --i) + result.append(gameTypeMap.value(g.game_types(i))); + return result.join(", "); + } + case 4: return g.with_password() ? ((g.spectators_need_password() || !g.spectators_allowed()) ? tr("yes") : tr("yes, free for spectators")) : tr("no"); + case 5: { + QStringList result; + if (g.only_buddies()) + result.append(tr("buddies only")); + if (g.only_registered()) + result.append(tr("reg. users only")); + return result.join(", "); + } + case 6: return QString("%1/%2").arg(g.player_count()).arg(g.max_players()); + case 7: return g.spectators_allowed() ? QVariant(g.spectators_count()) : QVariant(tr("not allowed")); + default: return QVariant(); + } } QVariant GamesModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - return QVariant(); - switch (section) { - case 0: return tr("Description"); - case 1: return tr("Room"); - case 2: return tr("Creator"); - case 3: return tr("Game type"); - case 4: return tr("Password"); - case 5: return tr("Restrictions"); - case 6: return tr("Players"); - case 7: return tr("Spectators"); - default: return QVariant(); - } + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) + return QVariant(); + switch (section) { + case 0: return tr("Description"); + case 1: return tr("Room"); + case 2: return tr("Creator"); + case 3: return tr("Game type"); + case 4: return tr("Password"); + case 5: return tr("Restrictions"); + case 6: return tr("Players"); + case 7: return tr("Spectators"); + default: return QVariant(); + } } const ServerInfo_Game &GamesModel::getGame(int row) { - Q_ASSERT(row < gameList.size()); - return gameList[row]; + Q_ASSERT(row < gameList.size()); + return gameList[row]; } void GamesModel::updateGameList(const ServerInfo_Game &game) { - for (int i = 0; i < gameList.size(); i++) - if (gameList[i].game_id() == game.game_id()) { - if (game.closed()) { - beginRemoveRows(QModelIndex(), i, i); - gameList.removeAt(i); - endRemoveRows(); - } else { - gameList[i].MergeFrom(game); - emit dataChanged(index(i, 0), index(i, 7)); - } - return; - } - if (game.player_count() <= 0) - return; - beginInsertRows(QModelIndex(), gameList.size(), gameList.size()); - gameList.append(game); - endInsertRows(); + for (int i = 0; i < gameList.size(); i++) + if (gameList[i].game_id() == game.game_id()) { + if (game.closed()) { + beginRemoveRows(QModelIndex(), i, i); + gameList.removeAt(i); + endRemoveRows(); + } else { + gameList[i].MergeFrom(game); + emit dataChanged(index(i, 0), index(i, 7)); + } + return; + } + if (game.player_count() <= 0) + return; + beginInsertRows(QModelIndex(), gameList.size(), gameList.size()); + gameList.append(game); + endInsertRows(); } GamesProxyModel::GamesProxyModel(QObject *parent, ServerInfo_User *_ownUser) - : QSortFilterProxyModel(parent), + : QSortFilterProxyModel(parent), ownUser(_ownUser), unavailableGamesVisible(false), maxPlayersFilterMin(-1), maxPlayersFilterMax(-1) { - setDynamicSortFilter(true); + setDynamicSortFilter(true); } void GamesProxyModel::setUnavailableGamesVisible(bool _unavailableGamesVisible) { - unavailableGamesVisible = _unavailableGamesVisible; - invalidateFilter(); + unavailableGamesVisible = _unavailableGamesVisible; + invalidateFilter(); } void GamesProxyModel::setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible) { - passwordProtectedGamesVisible = _passwordProtectedGamesVisible; - invalidateFilter(); + passwordProtectedGamesVisible = _passwordProtectedGamesVisible; + invalidateFilter(); } void GamesProxyModel::setGameNameFilter(const QString &_gameNameFilter) { - gameNameFilter = _gameNameFilter; - invalidateFilter(); + gameNameFilter = _gameNameFilter; + invalidateFilter(); } void GamesProxyModel::setCreatorNameFilter(const QString &_creatorNameFilter) { - creatorNameFilter = _creatorNameFilter; - invalidateFilter(); + creatorNameFilter = _creatorNameFilter; + invalidateFilter(); } void GamesProxyModel::setGameTypeFilter(const QSet &_gameTypeFilter) { - gameTypeFilter = _gameTypeFilter; - invalidateFilter(); + gameTypeFilter = _gameTypeFilter; + invalidateFilter(); } void GamesProxyModel::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax) { - maxPlayersFilterMin = _maxPlayersFilterMin; - maxPlayersFilterMax = _maxPlayersFilterMax; - invalidateFilter(); + maxPlayersFilterMin = _maxPlayersFilterMin; + maxPlayersFilterMax = _maxPlayersFilterMax; + invalidateFilter(); } void GamesProxyModel::resetFilterParameters() { - unavailableGamesVisible = false; - passwordProtectedGamesVisible = false; - gameNameFilter = QString(); - creatorNameFilter = QString(); - gameTypeFilter.clear(); - maxPlayersFilterMin = -1; - maxPlayersFilterMax = -1; - - invalidateFilter(); + unavailableGamesVisible = false; + passwordProtectedGamesVisible = false; + gameNameFilter = QString(); + creatorNameFilter = QString(); + gameTypeFilter.clear(); + maxPlayersFilterMin = -1; + maxPlayersFilterMax = -1; + + invalidateFilter(); } bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourceParent*/) const { - GamesModel *model = qobject_cast(sourceModel()); - if (!model) - return false; - - const ServerInfo_Game &game = model->getGame(sourceRow); - if (!unavailableGamesVisible) { - if (game.player_count() == game.max_players()) - return false; - if (game.started()) - return false; - if (!(ownUser->user_level() & ServerInfo_User::IsRegistered)) - if (game.only_registered()) - return false; - } - if (!passwordProtectedGamesVisible && game.with_password()) - return false; - if (!gameNameFilter.isEmpty()) - if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive)) - return false; - if (!creatorNameFilter.isEmpty()) - if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive)) - return false; - - QSet gameTypes; - for (int i = 0; i < game.game_types_size(); ++i) - gameTypes.insert(game.game_types(i)); - if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty()) - return false; - - if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin)) - return false; - if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax)) - return false; - - return true; + GamesModel *model = qobject_cast(sourceModel()); + if (!model) + return false; + + const ServerInfo_Game &game = model->getGame(sourceRow); + if (!unavailableGamesVisible) { + if (game.player_count() == game.max_players()) + return false; + if (game.started()) + return false; + if (!(ownUser->user_level() & ServerInfo_User::IsRegistered)) + if (game.only_registered()) + return false; + } + if (!passwordProtectedGamesVisible && game.with_password()) + return false; + if (!gameNameFilter.isEmpty()) + if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive)) + return false; + if (!creatorNameFilter.isEmpty()) + if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive)) + return false; + + QSet gameTypes; + for (int i = 0; i < game.game_types_size(); ++i) + gameTypes.insert(game.game_types(i)); + if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty()) + return false; + + if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin)) + return false; + if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax)) + return false; + + return true; } diff --git a/cockatrice/src/gamesmodel.h b/cockatrice/src/gamesmodel.h index 843fb043..aeb37e95 100644 --- a/cockatrice/src/gamesmodel.h +++ b/cockatrice/src/gamesmodel.h @@ -11,51 +11,51 @@ class ServerInfo_User; class GamesModel : public QAbstractTableModel { - Q_OBJECT + Q_OBJECT private: - QList gameList; - QMap rooms; - QMap gameTypes; + QList gameList; + QMap rooms; + QMap gameTypes; public: - GamesModel(const QMap &_rooms, const QMap &_gameTypes, QObject *parent = 0); - int rowCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : gameList.size(); } - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return 8; } - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - - const ServerInfo_Game &getGame(int row); - void updateGameList(const ServerInfo_Game &game); - const QMap &getGameTypes() { return gameTypes; } + GamesModel(const QMap &_rooms, const QMap &_gameTypes, QObject *parent = 0); + int rowCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : gameList.size(); } + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return 8; } + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + + const ServerInfo_Game &getGame(int row); + void updateGameList(const ServerInfo_Game &game); + const QMap &getGameTypes() { return gameTypes; } }; class GamesProxyModel : public QSortFilterProxyModel { - Q_OBJECT + Q_OBJECT private: - ServerInfo_User *ownUser; - bool unavailableGamesVisible; - bool passwordProtectedGamesVisible; - QString gameNameFilter, creatorNameFilter; - QSet gameTypeFilter; - int maxPlayersFilterMin, maxPlayersFilterMax; + ServerInfo_User *ownUser; + bool unavailableGamesVisible; + bool passwordProtectedGamesVisible; + QString gameNameFilter, creatorNameFilter; + QSet gameTypeFilter; + int maxPlayersFilterMin, maxPlayersFilterMax; public: - GamesProxyModel(QObject *parent = 0, ServerInfo_User *_ownUser = 0); - - bool getUnavailableGamesVisible() const { return unavailableGamesVisible; } - void setUnavailableGamesVisible(bool _unavailableGamesVisible); - bool getPasswordProtectedGamesVisible() const { return passwordProtectedGamesVisible; } - void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); - QString getGameNameFilter() const { return gameNameFilter; } - void setGameNameFilter(const QString &_gameNameFilter); - QString getCreatorNameFilter() const { return creatorNameFilter; } - void setCreatorNameFilter(const QString &_creatorNameFilter); - QSet getGameTypeFilter() const { return gameTypeFilter; } - void setGameTypeFilter(const QSet &_gameTypeFilter); - int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; } - int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; } - void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); - void resetFilterParameters(); + GamesProxyModel(QObject *parent = 0, ServerInfo_User *_ownUser = 0); + + bool getUnavailableGamesVisible() const { return unavailableGamesVisible; } + void setUnavailableGamesVisible(bool _unavailableGamesVisible); + bool getPasswordProtectedGamesVisible() const { return passwordProtectedGamesVisible; } + void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); + QString getGameNameFilter() const { return gameNameFilter; } + void setGameNameFilter(const QString &_gameNameFilter); + QString getCreatorNameFilter() const { return creatorNameFilter; } + void setCreatorNameFilter(const QString &_creatorNameFilter); + QSet getGameTypeFilter() const { return gameTypeFilter; } + void setGameTypeFilter(const QSet &_gameTypeFilter); + int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; } + int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; } + void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); + void resetFilterParameters(); protected: - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; #endif diff --git a/cockatrice/src/gameview.cpp b/cockatrice/src/gameview.cpp index 75a4024b..7a28b492 100644 --- a/cockatrice/src/gameview.cpp +++ b/cockatrice/src/gameview.cpp @@ -5,57 +5,57 @@ #include GameView::GameView(QGraphicsScene *scene, QWidget *parent) - : QGraphicsView(scene, parent), rubberBand(0) + : QGraphicsView(scene, parent), rubberBand(0) { - setBackgroundBrush(QBrush(QColor(0, 0, 0))); - setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing); - setFocusPolicy(Qt::NoFocus); - setViewportUpdateMode(BoundingRectViewportUpdate); + setBackgroundBrush(QBrush(QColor(0, 0, 0))); + setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing); + setFocusPolicy(Qt::NoFocus); + setViewportUpdateMode(BoundingRectViewportUpdate); - connect(scene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); - - connect(scene, SIGNAL(sigStartRubberBand(const QPointF &)), this, SLOT(startRubberBand(const QPointF &))); - connect(scene, SIGNAL(sigResizeRubberBand(const QPointF &)), this, SLOT(resizeRubberBand(const QPointF &))); - connect(scene, SIGNAL(sigStopRubberBand()), this, SLOT(stopRubberBand())); + connect(scene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); + + connect(scene, SIGNAL(sigStartRubberBand(const QPointF &)), this, SLOT(startRubberBand(const QPointF &))); + connect(scene, SIGNAL(sigResizeRubberBand(const QPointF &)), this, SLOT(resizeRubberBand(const QPointF &))); + connect(scene, SIGNAL(sigStopRubberBand()), this, SLOT(stopRubberBand())); - aCloseMostRecentZoneView = new QAction(this); - aCloseMostRecentZoneView->setShortcut(tr("Esc")); - connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView())); - addAction(aCloseMostRecentZoneView); + aCloseMostRecentZoneView = new QAction(this); + aCloseMostRecentZoneView->setShortcut(tr("Esc")); + connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView())); + addAction(aCloseMostRecentZoneView); - rubberBand = new QRubberBand(QRubberBand::Rectangle, this); + rubberBand = new QRubberBand(QRubberBand::Rectangle, this); } void GameView::resizeEvent(QResizeEvent *event) { - QGraphicsView::resizeEvent(event); + QGraphicsView::resizeEvent(event); - GameScene *s = dynamic_cast(scene()); - if (s) - s->processViewSizeChange(event->size()); - - updateSceneRect(scene()->sceneRect()); + GameScene *s = dynamic_cast(scene()); + if (s) + s->processViewSizeChange(event->size()); + + updateSceneRect(scene()->sceneRect()); } void GameView::updateSceneRect(const QRectF &rect) { - fitInView(rect, Qt::KeepAspectRatio); + fitInView(rect, Qt::KeepAspectRatio); } void GameView::startRubberBand(const QPointF &_selectionOrigin) { - selectionOrigin = _selectionOrigin; - rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0))); - rubberBand->show(); + selectionOrigin = _selectionOrigin; + rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0))); + rubberBand->show(); } void GameView::resizeRubberBand(const QPointF &cursorPoint) { - if (rubberBand) - rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized()); + if (rubberBand) + rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized()); } void GameView::stopRubberBand() { - rubberBand->hide(); + rubberBand->hide(); } diff --git a/cockatrice/src/gameview.h b/cockatrice/src/gameview.h index 84acf45e..e678f293 100644 --- a/cockatrice/src/gameview.h +++ b/cockatrice/src/gameview.h @@ -6,21 +6,21 @@ class QRubberBand; class GameView : public QGraphicsView { - Q_OBJECT + Q_OBJECT private: - QAction *aCloseMostRecentZoneView; - QRubberBand *rubberBand; - QPointF selectionOrigin; + QAction *aCloseMostRecentZoneView; + QRubberBand *rubberBand; + QPointF selectionOrigin; protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); private slots: - void startRubberBand(const QPointF &selectionOrigin); - void resizeRubberBand(const QPointF &cursorPoint); - void stopRubberBand(); + void startRubberBand(const QPointF &selectionOrigin); + void resizeRubberBand(const QPointF &cursorPoint); + void stopRubberBand(); public slots: - void updateSceneRect(const QRectF &rect); + void updateSceneRect(const QRectF &rect); public: - GameView(QGraphicsScene *scene, QWidget *parent = 0); + GameView(QGraphicsScene *scene, QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/handcounter.cpp b/cockatrice/src/handcounter.cpp index f5210dd1..4aa33d69 100644 --- a/cockatrice/src/handcounter.cpp +++ b/cockatrice/src/handcounter.cpp @@ -6,9 +6,9 @@ #include "cardzone.h" HandCounter::HandCounter(QGraphicsItem *parent) - : AbstractGraphicsItem(parent), number(0) + : AbstractGraphicsItem(parent), number(0) { - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } HandCounter::~HandCounter() @@ -17,43 +17,43 @@ HandCounter::~HandCounter() void HandCounter::updateNumber() { - number = static_cast(sender())->getCards().size(); - update(); + number = static_cast(sender())->getCards().size(); + update(); } QRectF HandCounter::boundingRect() const { - return QRectF(0, 0, 72, 72); + return QRectF(0, 0, 72, 72); } void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - painter->save(); - QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); - QPixmap cachedPixmap; + painter->save(); + QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); + QPixmap cachedPixmap; #if QT_VERSION >= 0x040600 - if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) { + if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) { #else - if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), cachedPixmap)) { + if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), cachedPixmap)) { #endif - QSvgRenderer svg(QString(":/resources/hand.svg")); - cachedPixmap = QPixmap(translatedSize); - cachedPixmap.fill(Qt::transparent); - QPainter painter(&cachedPixmap); - svg.render(&painter, QRectF(0, 0, translatedSize.width(), translatedSize.height())); - QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap); - } - painter->resetTransform(); - painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect()); - painter->restore(); - - paintNumberEllipse(number, 24, Qt::white, -1, -1, painter); + QSvgRenderer svg(QString(":/resources/hand.svg")); + cachedPixmap = QPixmap(translatedSize); + cachedPixmap.fill(Qt::transparent); + QPainter painter(&cachedPixmap); + svg.render(&painter, QRectF(0, 0, translatedSize.width(), translatedSize.height())); + QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap); + } + painter->resetTransform(); + painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect()); + painter->restore(); + + paintNumberEllipse(number, 24, Qt::white, -1, -1, painter); } void HandCounter::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::RightButton) { - emit showContextMenu(event->screenPos()); - event->accept(); - } + if (event->button() == Qt::RightButton) { + emit showContextMenu(event->screenPos()); + event->accept(); + } } diff --git a/cockatrice/src/handcounter.h b/cockatrice/src/handcounter.h index 7e3b7346..af1cf3e4 100644 --- a/cockatrice/src/handcounter.h +++ b/cockatrice/src/handcounter.h @@ -8,22 +8,22 @@ class QPainter; class QPixmap; class HandCounter : public AbstractGraphicsItem { - Q_OBJECT + Q_OBJECT private: - int number; + int number; protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); public slots: - void updateNumber(); + void updateNumber(); signals: - void showContextMenu(const QPoint &screenPos); + void showContextMenu(const QPoint &screenPos); public: - enum { Type = typeOther }; - int type() const { return Type; } - HandCounter(QGraphicsItem *parent = 0); - ~HandCounter(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + enum { Type = typeOther }; + int type() const { return Type; } + HandCounter(QGraphicsItem *parent = 0); + ~HandCounter(); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif diff --git a/cockatrice/src/handzone.cpp b/cockatrice/src/handzone.cpp index 2827f41f..1799b65f 100644 --- a/cockatrice/src/handzone.cpp +++ b/cockatrice/src/handzone.cpp @@ -8,137 +8,137 @@ #include "pb/command_move_card.pb.h" HandZone::HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent) - : SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight) + : SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight) { - connect(settingsCache, SIGNAL(handBgPathChanged()), this, SLOT(updateBgPixmap())); - updateBgPixmap(); - setCacheMode(DeviceCoordinateCache); + connect(settingsCache, SIGNAL(handBgPathChanged()), this, SLOT(updateBgPixmap())); + updateBgPixmap(); + setCacheMode(DeviceCoordinateCache); } void HandZone::updateBgPixmap() { - QString bgPath = settingsCache->getHandBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); - update(); + QString bgPath = settingsCache->getHandBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); + update(); } void HandZone::addCardImpl(CardItem *card, int x, int /*y*/) { - if (x == -1) - x = cards.size(); - cards.insert(x, card); + if (x == -1) + x = cards.size(); + cards.insert(x, card); - if (!cards.getContentsKnown()) { - card->setId(-1); - card->setName(); - } - card->setParentItem(this); - card->resetState(); - card->setVisible(true); - card->update(); + if (!cards.getContentsKnown()) { + card->setId(-1); + card->setName(); + } + card->setParentItem(this); + card->resetState(); + card->setVisible(true); + card->update(); } void HandZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint & dropPoint) { - QPoint point = dropPoint + scenePos().toPoint(); - int x = -1; - if (settingsCache->getHorizontalHand()) { - for (x = 0; x < cards.size(); x++) - if (point.x() < ((CardItem *) cards.at(x))->scenePos().x()) - break; - } else { - for (x = 0; x < cards.size(); x++) - if (point.y() < ((CardItem *) cards.at(x))->scenePos().y()) - break; - } - - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(x); - cmd.set_y(-1); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - - player->sendGameCommand(cmd); + QPoint point = dropPoint + scenePos().toPoint(); + int x = -1; + if (settingsCache->getHorizontalHand()) { + for (x = 0; x < cards.size(); x++) + if (point.x() < ((CardItem *) cards.at(x))->scenePos().x()) + break; + } else { + for (x = 0; x < cards.size(); x++) + if (point.y() < ((CardItem *) cards.at(x))->scenePos().y()) + break; + } + + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(x); + cmd.set_y(-1); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + + player->sendGameCommand(cmd); } QRectF HandZone::boundingRect() const { - if (settingsCache->getHorizontalHand()) - return QRectF(0, 0, width, CARD_HEIGHT + 10); - else - return QRectF(0, 0, 100, zoneHeight); + if (settingsCache->getHorizontalHand()) + return QRectF(0, 0, width, CARD_HEIGHT + 10); + else + return QRectF(0, 0, 100, zoneHeight); } void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), Qt::darkGreen); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), Qt::darkGreen); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); } void HandZone::reorganizeCards() { - if (!cards.isEmpty()) { - const int cardCount = cards.size(); - if (settingsCache->getHorizontalHand()) { - const int xPadding = 5; - qreal totalWidth = boundingRect().width() - 2 * xPadding; - qreal cardWidth = cards.at(0)->boundingRect().width(); - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cards.at(i); - - // If the total width of the cards is smaller than the available width, - // the cards do not need to overlap and are displayed in the center of the area. - if (cardWidth * cardCount > totalWidth) - c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5); - else - c->setPos(xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2, 5); - c->setRealZValue(i); - } - } else { - qreal totalWidth = boundingRect().width(); - qreal totalHeight = boundingRect().height(); - qreal cardWidth = cards.at(0)->boundingRect().width(); - qreal cardHeight = cards.at(0)->boundingRect().height(); - qreal xspace = 5; - qreal x1 = xspace; - qreal x2 = totalWidth - xspace - cardWidth; - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cards.at(i); - qreal x = i % 2 ? x2 : x1; - // If the total height of the cards is smaller than the available height, - // the cards do not need to overlap and are displayed in the center of the area. - if (cardHeight * cardCount > totalHeight) - c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); - else - c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); - c->setRealZValue(i); - } - } - } - update(); + if (!cards.isEmpty()) { + const int cardCount = cards.size(); + if (settingsCache->getHorizontalHand()) { + const int xPadding = 5; + qreal totalWidth = boundingRect().width() - 2 * xPadding; + qreal cardWidth = cards.at(0)->boundingRect().width(); + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + + // If the total width of the cards is smaller than the available width, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardWidth * cardCount > totalWidth) + c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5); + else + c->setPos(xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2, 5); + c->setRealZValue(i); + } + } else { + qreal totalWidth = boundingRect().width(); + qreal totalHeight = boundingRect().height(); + qreal cardWidth = cards.at(0)->boundingRect().width(); + qreal cardHeight = cards.at(0)->boundingRect().height(); + qreal xspace = 5; + qreal x1 = xspace; + qreal x2 = totalWidth - xspace - cardWidth; + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + qreal x = i % 2 ? x2 : x1; + // If the total height of the cards is smaller than the available height, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardHeight * cardCount > totalHeight) + c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); + else + c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setRealZValue(i); + } + } + } + update(); } void HandZone::setWidth(qreal _width) { - if (settingsCache->getHorizontalHand()) { - prepareGeometryChange(); - width = _width; - reorganizeCards(); - } + if (settingsCache->getHorizontalHand()) { + prepareGeometryChange(); + width = _width; + reorganizeCards(); + } } void HandZone::updateOrientation() { - prepareGeometryChange(); - reorganizeCards(); + prepareGeometryChange(); + reorganizeCards(); } diff --git a/cockatrice/src/handzone.h b/cockatrice/src/handzone.h index fb51cecb..66245c50 100644 --- a/cockatrice/src/handzone.h +++ b/cockatrice/src/handzone.h @@ -4,23 +4,23 @@ #include "selectzone.h" class HandZone : public SelectZone { - Q_OBJECT + Q_OBJECT private: - qreal width, zoneHeight; - QPixmap bgPixmap; + qreal width, zoneHeight; + QPixmap bgPixmap; private slots: - void updateBgPixmap(); + void updateBgPixmap(); public slots: - void updateOrientation(); + void updateOrientation(); public: - HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); - void setWidth(qreal _width); + HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); + void setWidth(qreal _width); protected: - void addCardImpl(CardItem *card, int x, int y); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/localclient.cpp b/cockatrice/src/localclient.cpp index f9ee06ec..3ad7c809 100644 --- a/cockatrice/src/localclient.cpp +++ b/cockatrice/src/localclient.cpp @@ -4,17 +4,17 @@ #include "pb/session_commands.pb.h" LocalClient::LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent) - : AbstractClient(parent), lsi(_lsi) + : AbstractClient(parent), lsi(_lsi) { - connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &))); - - Command_Login loginCmd; - loginCmd.set_user_name(_playerName.toStdString()); - sendCommand(prepareSessionCommand(loginCmd)); - - Command_JoinRoom joinCmd; - joinCmd.set_room_id(0); - sendCommand(prepareSessionCommand(joinCmd)); + connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &))); + + Command_Login loginCmd; + loginCmd.set_user_name(_playerName.toStdString()); + sendCommand(prepareSessionCommand(loginCmd)); + + Command_JoinRoom joinCmd; + joinCmd.set_room_id(0); + sendCommand(prepareSessionCommand(joinCmd)); } LocalClient::~LocalClient() @@ -23,10 +23,10 @@ LocalClient::~LocalClient() void LocalClient::sendCommandContainer(const CommandContainer &cont) { - lsi->itemFromClient(cont); + lsi->itemFromClient(cont); } void LocalClient::itemFromServer(const ServerMessage &item) { - processProtocolItem(item); + processProtocolItem(item); } diff --git a/cockatrice/src/localclient.h b/cockatrice/src/localclient.h index 6cf5382e..febacada 100644 --- a/cockatrice/src/localclient.h +++ b/cockatrice/src/localclient.h @@ -6,16 +6,16 @@ class LocalServerInterface; class LocalClient : public AbstractClient { - Q_OBJECT + Q_OBJECT private: - LocalServerInterface *lsi; + LocalServerInterface *lsi; public: - LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent = 0); - ~LocalClient(); - - void sendCommandContainer(const CommandContainer &cont); + LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent = 0); + ~LocalClient(); + + void sendCommandContainer(const CommandContainer &cont); private slots: - void itemFromServer(const ServerMessage &item); + void itemFromServer(const ServerMessage &item); }; #endif diff --git a/cockatrice/src/localserver.cpp b/cockatrice/src/localserver.cpp index 833b4446..dc49078a 100644 --- a/cockatrice/src/localserver.cpp +++ b/cockatrice/src/localserver.cpp @@ -3,37 +3,37 @@ #include "server_room.h" LocalServer::LocalServer(QObject *parent) - : Server(false, parent) + : Server(false, parent) { - setDatabaseInterface(new LocalServer_DatabaseInterface(this)); - addRoom(new Server_Room(0, QString(), QString(), false, QString(), QStringList(), this)); + setDatabaseInterface(new LocalServer_DatabaseInterface(this)); + addRoom(new Server_Room(0, QString(), QString(), false, QString(), QStringList(), this)); } LocalServer::~LocalServer() { - prepareDestroy(); + prepareDestroy(); } LocalServerInterface *LocalServer::newConnection() { - LocalServerInterface *lsi = new LocalServerInterface(this, getDatabaseInterface()); - addClient(lsi); - return lsi; + LocalServerInterface *lsi = new LocalServerInterface(this, getDatabaseInterface()); + addClient(lsi); + return lsi; } LocalServer_DatabaseInterface::LocalServer_DatabaseInterface(LocalServer *_localServer) - : Server_DatabaseInterface(_localServer), localServer(_localServer) + : Server_DatabaseInterface(_localServer), localServer(_localServer) { } ServerInfo_User LocalServer_DatabaseInterface::getUserData(const QString &name, bool /*withId*/) { - ServerInfo_User result; - result.set_name(name.toStdString()); - return result; + ServerInfo_User result; + result.set_name(name.toStdString()); + return result; } AuthenticationResult LocalServer_DatabaseInterface::checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft) { - return UnknownUser; + return UnknownUser; } diff --git a/cockatrice/src/localserver.h b/cockatrice/src/localserver.h index c77e6e7c..f47187f2 100644 --- a/cockatrice/src/localserver.h +++ b/cockatrice/src/localserver.h @@ -8,25 +8,25 @@ class LocalServerInterface; class LocalServer : public Server { - Q_OBJECT + Q_OBJECT public: - LocalServer(QObject *parent = 0); - ~LocalServer(); - - LocalServerInterface *newConnection(); + LocalServer(QObject *parent = 0); + ~LocalServer(); + + LocalServerInterface *newConnection(); }; class LocalServer_DatabaseInterface : public Server_DatabaseInterface { - Q_OBJECT + Q_OBJECT private: - LocalServer *localServer; + LocalServer *localServer; protected: - ServerInfo_User getUserData(const QString &name, bool withId = false); + ServerInfo_User getUserData(const QString &name, bool withId = false); public: - LocalServer_DatabaseInterface(LocalServer *_localServer); - AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft); - int getNextGameId() { return localServer->getNextLocalGameId(); } - int getNextReplayId() { return -1; } + LocalServer_DatabaseInterface(LocalServer *_localServer); + AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft); + int getNextGameId() { return localServer->getNextLocalGameId(); } + int getNextReplayId() { return -1; } }; #endif diff --git a/cockatrice/src/localserverinterface.cpp b/cockatrice/src/localserverinterface.cpp index ebf873b8..291da146 100644 --- a/cockatrice/src/localserverinterface.cpp +++ b/cockatrice/src/localserverinterface.cpp @@ -3,7 +3,7 @@ #include LocalServerInterface::LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface) - : Server_ProtocolHandler(_server, _databaseInterface, _server) + : Server_ProtocolHandler(_server, _databaseInterface, _server) { } @@ -13,10 +13,10 @@ LocalServerInterface::~LocalServerInterface() void LocalServerInterface::transmitProtocolItem(const ServerMessage &item) { - emit itemToClient(item); + emit itemToClient(item); } void LocalServerInterface::itemFromClient(const CommandContainer &item) { - processCommandContainer(item); + processCommandContainer(item); } diff --git a/cockatrice/src/localserverinterface.h b/cockatrice/src/localserverinterface.h index d9c9d8c6..1ad895e7 100644 --- a/cockatrice/src/localserverinterface.h +++ b/cockatrice/src/localserverinterface.h @@ -7,17 +7,17 @@ class LocalServer; class LocalServerInterface : public Server_ProtocolHandler { - Q_OBJECT + Q_OBJECT public: - LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface); - ~LocalServerInterface(); - - QString getAddress() const { return QString(); } - void transmitProtocolItem(const ServerMessage &item); + LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface); + ~LocalServerInterface(); + + QString getAddress() const { return QString(); } + void transmitProtocolItem(const ServerMessage &item); signals: - void itemToClient(const ServerMessage &item); + void itemToClient(const ServerMessage &item); public slots: - void itemFromClient(const CommandContainer &item); + void itemFromClient(const CommandContainer &item); }; #endif diff --git a/cockatrice/src/main.cpp b/cockatrice/src/main.cpp index 90c743d5..595a6534 100644 --- a/cockatrice/src/main.cpp +++ b/cockatrice/src/main.cpp @@ -56,118 +56,118 @@ QString translationPath = QString(); void myMessageOutput(QtMsgType /*type*/, const char *msg) { - static FILE *f = NULL; - if (!f) - f = fopen("qdebug.txt", "w"); - fprintf(f, "%s\n", msg); - fflush(f); + static FILE *f = NULL; + if (!f) + f = fopen("qdebug.txt", "w"); + fprintf(f, "%s\n", msg); + fflush(f); } void installNewTranslator() { - QString lang = settingsCache->getLang(); + QString lang = settingsCache->getLang(); - qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); - qApp->installTranslator(qtTranslator); - translator->load(translationPrefix + "_" + lang, translationPath); - qApp->installTranslator(translator); + qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + qApp->installTranslator(qtTranslator); + translator->load(translationPrefix + "_" + lang, translationPath); + qApp->installTranslator(translator); } int main(int argc, char *argv[]) { - QApplication app(argc, argv); - - if (app.arguments().contains("--debug-output")) - qInstallMsgHandler(myMessageOutput); + QApplication app(argc, argv); + + if (app.arguments().contains("--debug-output")) + qInstallMsgHandler(myMessageOutput); #ifdef Q_OS_MAC - QDir baseDir(app.applicationDirPath()); - baseDir.cdUp(); - baseDir.cdUp(); - baseDir.cdUp(); - QDir pluginsDir = baseDir; - pluginsDir.cd("PlugIns"); - app.addLibraryPath(pluginsDir.absolutePath()); + QDir baseDir(app.applicationDirPath()); + baseDir.cdUp(); + baseDir.cdUp(); + baseDir.cdUp(); + QDir pluginsDir = baseDir; + pluginsDir.cd("PlugIns"); + app.addLibraryPath(pluginsDir.absolutePath()); #endif #ifdef Q_OS_WIN - app.addLibraryPath(app.applicationDirPath() + "/plugins"); + app.addLibraryPath(app.applicationDirPath() + "/plugins"); #endif - QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); - QCoreApplication::setOrganizationName("Cockatrice"); - QCoreApplication::setOrganizationDomain("cockatrice.de"); - QCoreApplication::setApplicationName("Cockatrice"); - - if (translationPath.isEmpty()) { + QCoreApplication::setOrganizationName("Cockatrice"); + QCoreApplication::setOrganizationDomain("cockatrice.de"); + QCoreApplication::setApplicationName("Cockatrice"); + + if (translationPath.isEmpty()) { #ifdef Q_OS_MAC - QDir translationsDir = baseDir; - translationsDir.cd("translations"); - translationPath = translationsDir.absolutePath(); + QDir translationsDir = baseDir; + translationsDir.cd("translations"); + translationPath = translationsDir.absolutePath(); #endif #ifdef Q_OS_WIN - translationPath = app.applicationDirPath() + "/translations"; + translationPath = app.applicationDirPath() + "/translations"; #endif - } - - rng = new RNG_SFMT; - settingsCache = new SettingsCache; - db = new CardDatabase; + } + + rng = new RNG_SFMT; + settingsCache = new SettingsCache; + db = new CardDatabase; - qtTranslator = new QTranslator; - translator = new QTranslator; - installNewTranslator(); - - qsrand(QDateTime::currentDateTime().toTime_t()); - - bool startMainProgram = true; - const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); - if (!db->getLoadSuccess()) - if (db->loadCardDatabase(dataDir + "/cards.xml")) - settingsCache->setCardDatabasePath(dataDir + "/cards.xml"); - if (settingsCache->getTokenDatabasePath().isEmpty()) - settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml"); - if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) { - QDir().mkpath(dataDir + "/decks"); - settingsCache->setDeckPath(dataDir + "/decks"); - } - if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) { - QDir().mkpath(dataDir + "/replays"); - settingsCache->setReplaysPath(dataDir + "/replays"); - } - if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) { - QDir().mkpath(dataDir + "/pics"); - settingsCache->setPicsPath(dataDir + "/pics"); - } - if (!db->getLoadSuccess() || !QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty() || settingsCache->getPicsPath().isEmpty() || !QDir(settingsCache->getPicsPath()).exists()) { - DlgSettings dlgSettings; - dlgSettings.show(); - app.exec(); - startMainProgram = (db->getLoadSuccess() && QDir(settingsCache->getDeckPath()).exists() && !settingsCache->getDeckPath().isEmpty() && QDir(settingsCache->getPicsPath()).exists() && !settingsCache->getPicsPath().isEmpty()); - } - - if (startMainProgram) { - qDebug("main(): starting main program"); - soundEngine = new SoundEngine; - qDebug("main(): SoundEngine constructor finished"); + qtTranslator = new QTranslator; + translator = new QTranslator; + installNewTranslator(); + + qsrand(QDateTime::currentDateTime().toTime_t()); + + bool startMainProgram = true; + const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); + if (!db->getLoadSuccess()) + if (db->loadCardDatabase(dataDir + "/cards.xml")) + settingsCache->setCardDatabasePath(dataDir + "/cards.xml"); + if (settingsCache->getTokenDatabasePath().isEmpty()) + settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml"); + if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) { + QDir().mkpath(dataDir + "/decks"); + settingsCache->setDeckPath(dataDir + "/decks"); + } + if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) { + QDir().mkpath(dataDir + "/replays"); + settingsCache->setReplaysPath(dataDir + "/replays"); + } + if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) { + QDir().mkpath(dataDir + "/pics"); + settingsCache->setPicsPath(dataDir + "/pics"); + } + if (!db->getLoadSuccess() || !QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty() || settingsCache->getPicsPath().isEmpty() || !QDir(settingsCache->getPicsPath()).exists()) { + DlgSettings dlgSettings; + dlgSettings.show(); + app.exec(); + startMainProgram = (db->getLoadSuccess() && QDir(settingsCache->getDeckPath()).exists() && !settingsCache->getDeckPath().isEmpty() && QDir(settingsCache->getPicsPath()).exists() && !settingsCache->getPicsPath().isEmpty()); + } + + if (startMainProgram) { + qDebug("main(): starting main program"); + soundEngine = new SoundEngine; + qDebug("main(): SoundEngine constructor finished"); - MainWindow ui; - qDebug("main(): MainWindow constructor finished"); - - QIcon icon(":/resources/appicon.svg"); - ui.setWindowIcon(icon); - - ui.show(); - qDebug("main(): ui.show() finished"); - - app.exec(); - } - - qDebug("Event loop finished, terminating..."); - delete db; - delete settingsCache; - delete rng; - PingPixmapGenerator::clear(); - CountryPixmapGenerator::clear(); - UserLevelPixmapGenerator::clear(); - - return 0; + MainWindow ui; + qDebug("main(): MainWindow constructor finished"); + + QIcon icon(":/resources/appicon.svg"); + ui.setWindowIcon(icon); + + ui.show(); + qDebug("main(): ui.show() finished"); + + app.exec(); + } + + qDebug("Event loop finished, terminating..."); + delete db; + delete settingsCache; + delete rng; + PingPixmapGenerator::clear(); + CountryPixmapGenerator::clear(); + UserLevelPixmapGenerator::clear(); + + return 0; } diff --git a/cockatrice/src/messagelogwidget.cpp b/cockatrice/src/messagelogwidget.cpp index a5f59a3f..ec9b90cb 100644 --- a/cockatrice/src/messagelogwidget.cpp +++ b/cockatrice/src/messagelogwidget.cpp @@ -11,867 +11,867 @@ QString MessageLogWidget::sanitizeHtml(QString dirty) const { - return dirty - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - .replace("\"", """); + return dirty + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """); } QString MessageLogWidget::cardLink(const QString &cardName) const { - return QString("%2").arg(cardName).arg(cardName); + return QString("%2").arg(cardName).arg(cardName); } bool MessageLogWidget::isFemale(Player *player) const { - return player->getUserInfo()->gender() == ServerInfo_User::Female; + return player->getUserInfo()->gender() == ServerInfo_User::Female; } bool MessageLogWidget::userIsFemale() const { - return (tabSupervisor && tabSupervisor->getUserInfo() && (tabSupervisor->getUserInfo()->gender() & ServerInfo_User::Female)); + return (tabSupervisor && tabSupervisor->getUserInfo() && (tabSupervisor->getUserInfo()->gender() & ServerInfo_User::Female)); } void MessageLogWidget::logGameJoined(int gameId) { - if (userIsFemale()) - appendHtml(tr("You have joined game #%1.", "female").arg(gameId)); - else - appendHtml(tr("You have joined game #%1.", "male").arg(gameId)); + if (userIsFemale()) + appendHtml(tr("You have joined game #%1.", "female").arg(gameId)); + else + appendHtml(tr("You have joined game #%1.", "male").arg(gameId)); } void MessageLogWidget::logReplayStarted(int gameId) { - if (userIsFemale()) - appendHtml(tr("You are watching a replay of game #%1.", "female").arg(gameId)); - else - appendHtml(tr("You are watching a replay of game #%1.", "male").arg(gameId)); + if (userIsFemale()) + appendHtml(tr("You are watching a replay of game #%1.", "female").arg(gameId)); + else + appendHtml(tr("You are watching a replay of game #%1.", "male").arg(gameId)); } void MessageLogWidget::logJoin(Player *player) { - soundEngine->cuckoo(); - if (isFemale(player)) - appendHtml(tr("%1 has joined the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has joined the game.", "male").arg(sanitizeHtml(player->getName()))); + soundEngine->cuckoo(); + if (isFemale(player)) + appendHtml(tr("%1 has joined the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has joined the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logLeave(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 has left the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has left the game.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 has left the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has left the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logGameClosed() { - appendHtml(tr("The game has been closed.")); + appendHtml(tr("The game has been closed.")); } void MessageLogWidget::logKicked() { - appendHtml(tr("You have been kicked out of the game.")); + appendHtml(tr("You have been kicked out of the game.")); } void MessageLogWidget::logJoinSpectator(QString name) { - appendHtml(tr("%1 is now watching the game.").arg(sanitizeHtml(name))); + appendHtml(tr("%1 is now watching the game.").arg(sanitizeHtml(name))); } void MessageLogWidget::logLeaveSpectator(QString name) { - appendHtml(tr("%1 is not watching the game any more.").arg(sanitizeHtml(name))); + appendHtml(tr("%1 is not watching the game any more.").arg(sanitizeHtml(name))); } void MessageLogWidget::logDeckSelect(Player *player, QString deckHash) { - if (isFemale(player)) - appendHtml(tr("%1 has loaded a deck (%2).", "female").arg(sanitizeHtml(player->getName())).arg(deckHash)); - else - appendHtml(tr("%1 has loaded a deck (%2).", "male").arg(sanitizeHtml(player->getName())).arg(deckHash)); + if (isFemale(player)) + appendHtml(tr("%1 has loaded a deck (%2).", "female").arg(sanitizeHtml(player->getName())).arg(deckHash)); + else + appendHtml(tr("%1 has loaded a deck (%2).", "male").arg(sanitizeHtml(player->getName())).arg(deckHash)); } void MessageLogWidget::logReadyStart(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 is ready to start the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 is ready to start the game.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 is ready to start the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 is ready to start the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logNotReadyStart(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 is not ready to start the game any more.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 is not ready to start the game any more.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 is not ready to start the game any more.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 is not ready to start the game any more.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logSetSideboardLock(Player *player, bool locked) { - if (locked) { - if (isFemale(player)) - appendHtml(tr("%1 has locked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has locked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 has unlocked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has unlocked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); - } + if (locked) { + if (isFemale(player)) + appendHtml(tr("%1 has locked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has locked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 has unlocked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has unlocked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); + } } void MessageLogWidget::logConcede(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 has conceded the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has conceded the game.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 has conceded the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has conceded the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logGameStart() { - appendHtml(tr("The game has started.")); + appendHtml(tr("The game has started.")); } void MessageLogWidget::logConnectionStateChanged(Player *player, bool connectionState) { - if (connectionState) { - if (isFemale(player)) - appendHtml(tr("%1 has restored connection to the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has restored connection to the game.", "male").arg(sanitizeHtml(player->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 has lost connection to the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has lost connection to the game.", "male").arg(sanitizeHtml(player->getName()))); - } + if (connectionState) { + if (isFemale(player)) + appendHtml(tr("%1 has restored connection to the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has restored connection to the game.", "male").arg(sanitizeHtml(player->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 has lost connection to the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has lost connection to the game.", "male").arg(sanitizeHtml(player->getName()))); + } } void MessageLogWidget::logSay(Player *player, QString message) { - appendMessage(message, player->getName(), UserLevelFlags(player->getUserInfo()->user_level()), true); + appendMessage(message, player->getName(), UserLevelFlags(player->getUserInfo()->user_level()), true); } void MessageLogWidget::logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message) { - appendMessage(message, spectatorName, spectatorUserLevel, false); + appendMessage(message, spectatorName, spectatorUserLevel, false); } void MessageLogWidget::logShuffle(Player *player, CardZone *zone) { - soundEngine->shuffle(); - if (currentContext != MessageContext_Mulligan) { - appendHtml((isFemale(player) - ? tr("%1 shuffles %2.", "female") - : tr("%1 shuffles %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseShuffleZone))); - } + soundEngine->shuffle(); + if (currentContext != MessageContext_Mulligan) { + appendHtml((isFemale(player) + ? tr("%1 shuffles %2.", "female") + : tr("%1 shuffles %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseShuffleZone))); + } } void MessageLogWidget::logRollDie(Player *player, int sides, int roll) { - if (isFemale(player)) - appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "female").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); - else - appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "male").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); + if (isFemale(player)) + appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "female").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); + else + appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "male").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); } void MessageLogWidget::logDrawCards(Player *player, int number) { - if (currentContext == MessageContext_Mulligan) - mulliganPlayer = player; - else { - soundEngine->draw(); - if (isFemale(player)) - appendHtml(tr("%1 draws %n card(s).", "female", number).arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 draws %n card(s).", "male", number).arg(sanitizeHtml(player->getName()))); - } + if (currentContext == MessageContext_Mulligan) + mulliganPlayer = player; + else { + soundEngine->draw(); + if (isFemale(player)) + appendHtml(tr("%1 draws %n card(s).", "female", number).arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 draws %n card(s).", "male", number).arg(sanitizeHtml(player->getName()))); + } } void MessageLogWidget::logUndoDraw(Player *player, QString cardName) { - if (cardName.isEmpty()) - appendHtml((isFemale(player) ? tr("%1 undoes her last draw.") : tr("%1 undoes his last draw.")).arg(sanitizeHtml(player->getName()))); - else - appendHtml((isFemale(player) ? tr("%1 undoes her last draw (%2).") : tr("%1 undoes his last draw (%2).")).arg(sanitizeHtml(player->getName())).arg(QString("%2").arg(sanitizeHtml(cardName)).arg(sanitizeHtml(cardName)))); + if (cardName.isEmpty()) + appendHtml((isFemale(player) ? tr("%1 undoes her last draw.") : tr("%1 undoes his last draw.")).arg(sanitizeHtml(player->getName()))); + else + appendHtml((isFemale(player) ? tr("%1 undoes her last draw (%2).") : tr("%1 undoes his last draw (%2).")).arg(sanitizeHtml(player->getName())).arg(QString("%2").arg(sanitizeHtml(cardName)).arg(sanitizeHtml(cardName)))); } QPair MessageLogWidget::getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const { - bool cardNameContainsStartZone = false; - QString fromStr; - QString startName = zone->getName(); - - if (startName == "table") - fromStr = tr(" from table"); - else if (startName == "grave") - fromStr = tr(" from graveyard"); - else if (startName == "rfg") - fromStr = tr(" from exile"); - else if (startName == "hand") - fromStr = tr(" from hand"); - else if (startName == "deck") { - if (position >= zone->getCards().size() - 1) { - if (cardName.isEmpty()) { - if (ownerChange) - cardName = tr("the bottom card of %1's library").arg(zone->getPlayer()->getName()); - else - cardName = isFemale(zone->getPlayer()) ? tr("the bottom card of her library") : tr("the bottom card of his library"); - cardNameContainsStartZone = true; - } else { - if (ownerChange) - fromStr = tr(" from the bottom of %1's library").arg(zone->getPlayer()->getName()); - else - fromStr = isFemale(zone->getPlayer()) ? tr(" from the bottom of her library") : tr(" from the bottom of his library"); - } - } else if (position == 0) { - if (cardName.isEmpty()) { - if (ownerChange) - cardName = tr("the top card of %1's library").arg(zone->getPlayer()->getName()); - else - cardName = isFemale(zone->getPlayer()) ? tr("the top card of her library") : tr("the top card of his library"); - cardNameContainsStartZone = true; - } else { - if (ownerChange) - fromStr = tr(" from the top of %1's library").arg(zone->getPlayer()->getName()); - else - fromStr = isFemale(zone->getPlayer()) ? tr(" from the top of her library") : tr(" from the top of his library"); - } - } else { - if (ownerChange) - fromStr = tr(" from %1's library").arg(zone->getPlayer()->getName()); - else - fromStr = tr(" from library"); - } - } else if (startName == "sb") - fromStr = tr(" from sideboard"); - else if (startName == "stack") - fromStr = tr(" from the stack"); + bool cardNameContainsStartZone = false; + QString fromStr; + QString startName = zone->getName(); + + if (startName == "table") + fromStr = tr(" from table"); + else if (startName == "grave") + fromStr = tr(" from graveyard"); + else if (startName == "rfg") + fromStr = tr(" from exile"); + else if (startName == "hand") + fromStr = tr(" from hand"); + else if (startName == "deck") { + if (position >= zone->getCards().size() - 1) { + if (cardName.isEmpty()) { + if (ownerChange) + cardName = tr("the bottom card of %1's library").arg(zone->getPlayer()->getName()); + else + cardName = isFemale(zone->getPlayer()) ? tr("the bottom card of her library") : tr("the bottom card of his library"); + cardNameContainsStartZone = true; + } else { + if (ownerChange) + fromStr = tr(" from the bottom of %1's library").arg(zone->getPlayer()->getName()); + else + fromStr = isFemale(zone->getPlayer()) ? tr(" from the bottom of her library") : tr(" from the bottom of his library"); + } + } else if (position == 0) { + if (cardName.isEmpty()) { + if (ownerChange) + cardName = tr("the top card of %1's library").arg(zone->getPlayer()->getName()); + else + cardName = isFemale(zone->getPlayer()) ? tr("the top card of her library") : tr("the top card of his library"); + cardNameContainsStartZone = true; + } else { + if (ownerChange) + fromStr = tr(" from the top of %1's library").arg(zone->getPlayer()->getName()); + else + fromStr = isFemale(zone->getPlayer()) ? tr(" from the top of her library") : tr(" from the top of his library"); + } + } else { + if (ownerChange) + fromStr = tr(" from %1's library").arg(zone->getPlayer()->getName()); + else + fromStr = tr(" from library"); + } + } else if (startName == "sb") + fromStr = tr(" from sideboard"); + else if (startName == "stack") + fromStr = tr(" from the stack"); - if (!cardNameContainsStartZone) - cardName.clear(); - return QPair(cardName, fromStr); + if (!cardNameContainsStartZone) + cardName.clear(); + return QPair(cardName, fromStr); } void MessageLogWidget::doMoveCard(LogMoveCard &attributes) { - bool ownerChange = attributes.startZone->getPlayer() != attributes.targetZone->getPlayer(); - QString startName = attributes.startZone->getName(); - QString targetName = attributes.targetZone->getName(); - if (((startName == "table") && (targetName == "table") && (attributes.startZone == attributes.targetZone)) || ((startName == "hand") && (targetName == "hand"))) - return; - QString cardName = attributes.cardName; - QPair temp = getFromStr(attributes.startZone, cardName, attributes.oldX, ownerChange); - bool cardNameContainsStartZone = false; - if (!temp.first.isEmpty()) { - cardNameContainsStartZone = true; - cardName = temp.first; - } - QString fromStr = temp.second; - QString cardStr; - if (cardNameContainsStartZone) - cardStr = cardName; - else if (cardName.isEmpty()) - cardStr = tr("a card"); - else - cardStr = cardLink(cardName); - - if (ownerChange && (attributes.startZone->getPlayer() == attributes.player)) { - appendHtml(tr("%1 gives %2 control over %3.").arg(sanitizeHtml(attributes.player->getName())).arg(sanitizeHtml(attributes.targetZone->getPlayer()->getName())).arg(cardStr)); - return; - } - - QString finalStr; - if (targetName == "table") { - soundEngine->playCard(); - if (moveCardTapped.value(attributes.card)) - finalStr = tr("%1 puts %2 into play tapped%3."); - else - finalStr = tr("%1 puts %2 into play%3."); - } else if (targetName == "grave") - finalStr = tr("%1 puts %2%3 into graveyard."); - else if (targetName == "rfg") - finalStr = tr("%1 exiles %2%3."); - else if (targetName == "hand") - finalStr = tr("%1 moves %2%3 to hand."); - else if (targetName == "deck") { - if (attributes.newX == -1) - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library.") : tr("%1 puts %2%3 into his library."); - else if (attributes.newX == attributes.targetZone->getCards().size() - 1) - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on bottom of her library.") : tr("%1 puts %2%3 on bottom of his library."); - else if (attributes.newX == 0) - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on top of her library.") : tr("%1 puts %2%3 on top of his library."); - else - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library at position %4.") : tr("%1 puts %2%3 into his library at position %4."); - } else if (targetName == "sb") - finalStr = tr("%1 moves %2%3 to sideboard."); - else if (targetName == "stack") { - soundEngine->playCard(); - finalStr = tr("%1 plays %2%3."); - } - - appendHtml(finalStr.arg(sanitizeHtml(attributes.player->getName())).arg(cardStr).arg(fromStr).arg(attributes.newX)); + bool ownerChange = attributes.startZone->getPlayer() != attributes.targetZone->getPlayer(); + QString startName = attributes.startZone->getName(); + QString targetName = attributes.targetZone->getName(); + if (((startName == "table") && (targetName == "table") && (attributes.startZone == attributes.targetZone)) || ((startName == "hand") && (targetName == "hand"))) + return; + QString cardName = attributes.cardName; + QPair temp = getFromStr(attributes.startZone, cardName, attributes.oldX, ownerChange); + bool cardNameContainsStartZone = false; + if (!temp.first.isEmpty()) { + cardNameContainsStartZone = true; + cardName = temp.first; + } + QString fromStr = temp.second; + QString cardStr; + if (cardNameContainsStartZone) + cardStr = cardName; + else if (cardName.isEmpty()) + cardStr = tr("a card"); + else + cardStr = cardLink(cardName); + + if (ownerChange && (attributes.startZone->getPlayer() == attributes.player)) { + appendHtml(tr("%1 gives %2 control over %3.").arg(sanitizeHtml(attributes.player->getName())).arg(sanitizeHtml(attributes.targetZone->getPlayer()->getName())).arg(cardStr)); + return; + } + + QString finalStr; + if (targetName == "table") { + soundEngine->playCard(); + if (moveCardTapped.value(attributes.card)) + finalStr = tr("%1 puts %2 into play tapped%3."); + else + finalStr = tr("%1 puts %2 into play%3."); + } else if (targetName == "grave") + finalStr = tr("%1 puts %2%3 into graveyard."); + else if (targetName == "rfg") + finalStr = tr("%1 exiles %2%3."); + else if (targetName == "hand") + finalStr = tr("%1 moves %2%3 to hand."); + else if (targetName == "deck") { + if (attributes.newX == -1) + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library.") : tr("%1 puts %2%3 into his library."); + else if (attributes.newX == attributes.targetZone->getCards().size() - 1) + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on bottom of her library.") : tr("%1 puts %2%3 on bottom of his library."); + else if (attributes.newX == 0) + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on top of her library.") : tr("%1 puts %2%3 on top of his library."); + else + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library at position %4.") : tr("%1 puts %2%3 into his library at position %4."); + } else if (targetName == "sb") + finalStr = tr("%1 moves %2%3 to sideboard."); + else if (targetName == "stack") { + soundEngine->playCard(); + finalStr = tr("%1 plays %2%3."); + } + + appendHtml(finalStr.arg(sanitizeHtml(attributes.player->getName())).arg(cardStr).arg(fromStr).arg(attributes.newX)); } void MessageLogWidget::logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX) { - LogMoveCard attributes = {player, card, card->getName(), startZone, oldX, targetZone, newX}; - if (currentContext == MessageContext_MoveCard) - moveCardQueue.append(attributes); - else if (currentContext == MessageContext_Mulligan) - mulliganPlayer = player; - else - doMoveCard(attributes); + LogMoveCard attributes = {player, card, card->getName(), startZone, oldX, targetZone, newX}; + if (currentContext == MessageContext_MoveCard) + moveCardQueue.append(attributes); + else if (currentContext == MessageContext_Mulligan) + mulliganPlayer = player; + else + doMoveCard(attributes); } void MessageLogWidget::logMulligan(Player *player, int number) { - if (!player) - return; + if (!player) + return; - if (number > -1) { - if (isFemale(player)) - appendHtml(tr("%1 takes a mulligan to %n.", "female", number).arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 takes a mulligan to %n.", "male", number).arg(sanitizeHtml(player->getName()))); - } else - appendHtml((isFemale(player) ? tr("%1 draws her initial hand.") : tr("%1 draws his initial hand.")).arg(sanitizeHtml(player->getName()))); + if (number > -1) { + if (isFemale(player)) + appendHtml(tr("%1 takes a mulligan to %n.", "female", number).arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 takes a mulligan to %n.", "male", number).arg(sanitizeHtml(player->getName()))); + } else + appendHtml((isFemale(player) ? tr("%1 draws her initial hand.") : tr("%1 draws his initial hand.")).arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logFlipCard(Player *player, QString cardName, bool faceDown) { - if (faceDown) { - if (isFemale(player)) - appendHtml(tr("%1 flips %2 face-down.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); - else - appendHtml(tr("%1 flips %2 face-down.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); - } else { - if (isFemale(player)) - appendHtml(tr("%1 flips %2 face-up.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); - else - appendHtml(tr("%1 flips %2 face-up.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); - } + if (faceDown) { + if (isFemale(player)) + appendHtml(tr("%1 flips %2 face-down.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); + else + appendHtml(tr("%1 flips %2 face-down.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); + } else { + if (isFemale(player)) + appendHtml(tr("%1 flips %2 face-up.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); + else + appendHtml(tr("%1 flips %2 face-up.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); + } } void MessageLogWidget::logDestroyCard(Player *player, QString cardName) { - if (isFemale(player)) - appendHtml(tr("%1 destroys %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); - else - appendHtml(tr("%1 destroys %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + if (isFemale(player)) + appendHtml(tr("%1 destroys %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + else + appendHtml(tr("%1 destroys %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); } void MessageLogWidget::logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName) { - QString str; - if (isFemale(player)) { - if (isFemale(targetPlayer)) - str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 female"); - else - str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 female"); - else - str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 male"); - } - - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(sanitizeHtml(targetPlayer->getName())).arg(cardLink(targetCardName))); + QString str; + if (isFemale(player)) { + if (isFemale(targetPlayer)) + str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 female"); + else + str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 female"); + else + str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 male"); + } + + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(sanitizeHtml(targetPlayer->getName())).arg(cardLink(targetCardName))); } void MessageLogWidget::logUnattachCard(Player *player, QString cardName) { - if (isFemale(player)) - appendHtml(tr("%1 unattaches %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); - else - appendHtml(tr("%1 unattaches %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + if (isFemale(player)) + appendHtml(tr("%1 unattaches %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + else + appendHtml(tr("%1 unattaches %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); } void MessageLogWidget::logCreateToken(Player *player, QString cardName, QString pt) { - if (isFemale(player)) - appendHtml(tr("%1 creates token: %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); - else - appendHtml(tr("%1 creates token: %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); + if (isFemale(player)) + appendHtml(tr("%1 creates token: %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); + else + appendHtml(tr("%1 creates token: %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); } void MessageLogWidget::logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget) { - startCard = cardLink(startCard); - targetCard = cardLink(targetCard); - QString str; - if (playerTarget) { - if ((player == startPlayer) && (player == targetPlayer)) { - if (isFemale(player)) - str = tr("%1 points from her %2 to herself.", "female"); - else - str = tr("%1 points from his %2 to himself.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard)); - } else if (player == startPlayer) { - if (isFemale(player)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from her %2 to %3.", "p1 female, p2 female"); - else - str = tr("%1 points from her %2 to %3.", "p1 female, p2 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from his %2 to %3.", "p1 male, p2 female"); - else - str = tr("%1 points from his %2 to %3.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); - } else if (player == targetPlayer) { - if (isFemale(player)) { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to herself.", "card owner female, target female"); - else - str = tr("%1 points from %2's %3 to herself.", "card owner male, target female"); - } else { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to himself.", "card owner female, target male"); - else - str = tr("%1 points from %2's %3 to himself.", "card owner male, target male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard)); - } else { - if (isFemale(player)) { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 male"); - } - } else { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 male"); - } - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); - } - } else { - if ((player == startPlayer) && (player == targetPlayer)) { - if (isFemale(player)) - str = tr("%1 points from her %2 to her %3.", "female"); - else - str = tr("%1 points from his %2 to his %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(targetCard)); - } else if (player == startPlayer) { - if (isFemale(player)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 female"); - else - str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 female"); - else - str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); - } else if (player == targetPlayer) { - if (isFemale(player)) { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to her own %4.", "card owner female, target female"); - else - str = tr("%1 points from %2's %3 to her own %4.", "card owner male, target female"); - } else { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to his own %4.", "card owner female, target male"); - else - str = tr("%1 points from %2's %3 to his own %4.", "card owner male, target male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(targetCard)); - } else { - if (isFemale(player)) { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 male"); - } - } else { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 male"); - } - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); - } - } + startCard = cardLink(startCard); + targetCard = cardLink(targetCard); + QString str; + if (playerTarget) { + if ((player == startPlayer) && (player == targetPlayer)) { + if (isFemale(player)) + str = tr("%1 points from her %2 to herself.", "female"); + else + str = tr("%1 points from his %2 to himself.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard)); + } else if (player == startPlayer) { + if (isFemale(player)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from her %2 to %3.", "p1 female, p2 female"); + else + str = tr("%1 points from her %2 to %3.", "p1 female, p2 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from his %2 to %3.", "p1 male, p2 female"); + else + str = tr("%1 points from his %2 to %3.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); + } else if (player == targetPlayer) { + if (isFemale(player)) { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to herself.", "card owner female, target female"); + else + str = tr("%1 points from %2's %3 to herself.", "card owner male, target female"); + } else { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to himself.", "card owner female, target male"); + else + str = tr("%1 points from %2's %3 to himself.", "card owner male, target male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard)); + } else { + if (isFemale(player)) { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 male"); + } + } else { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 male"); + } + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); + } + } else { + if ((player == startPlayer) && (player == targetPlayer)) { + if (isFemale(player)) + str = tr("%1 points from her %2 to her %3.", "female"); + else + str = tr("%1 points from his %2 to his %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(targetCard)); + } else if (player == startPlayer) { + if (isFemale(player)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 female"); + else + str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 female"); + else + str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); + } else if (player == targetPlayer) { + if (isFemale(player)) { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to her own %4.", "card owner female, target female"); + else + str = tr("%1 points from %2's %3 to her own %4.", "card owner male, target female"); + } else { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to his own %4.", "card owner female, target male"); + else + str = tr("%1 points from %2's %3 to his own %4.", "card owner male, target male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(targetCard)); + } else { + if (isFemale(player)) { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 male"); + } + } else { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 male"); + } + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); + } + } } void MessageLogWidget::logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue) { - QString finalStr, colorStr; - - int delta = abs(oldValue - value); - if (value > oldValue) { - if (isFemale(player)) - finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "female", delta); - else - finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "male", delta); - } else { - if (isFemale(player)) - finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "female", delta); - else - finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "male", delta); - } - - switch (counterId) { - case 0: colorStr = tr("red", "", delta); break; - case 1: colorStr = tr("yellow", "", delta); break; - case 2: colorStr = tr("green", "", delta); break; - default: ; - } - - appendHtml(finalStr.arg(sanitizeHtml(player->getName())).arg(colorStr).arg(cardLink(cardName)).arg(value)); + QString finalStr, colorStr; + + int delta = abs(oldValue - value); + if (value > oldValue) { + if (isFemale(player)) + finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "female", delta); + else + finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "male", delta); + } else { + if (isFemale(player)) + finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "female", delta); + else + finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "male", delta); + } + + switch (counterId) { + case 0: colorStr = tr("red", "", delta); break; + case 1: colorStr = tr("yellow", "", delta); break; + case 2: colorStr = tr("green", "", delta); break; + default: ; + } + + appendHtml(finalStr.arg(sanitizeHtml(player->getName())).arg(colorStr).arg(cardLink(cardName)).arg(value)); } void MessageLogWidget::logSetTapped(Player *player, CardItem *card, bool tapped) { - if (tapped) - soundEngine->tap(); - else - soundEngine->untap(); - - if (currentContext == MessageContext_MoveCard) - moveCardTapped.insert(card, tapped); - else { - QString str; - if (!card) { - if (isFemale(player)) { - if (tapped) - str = tr("%1 taps her permanents.", "female"); - else - str = tr("%1 untaps her permanents.", "female"); - } else { - if (tapped) - str = tr("%1 taps his permanents.", "male"); - else - str = tr("%1 untaps his permanents.", "male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName()))); - } else { - if (isFemale(player)) { - if (tapped) - str = tr("%1 taps %2.", "female"); - else - str = tr("%1 untaps %2.", "female"); - } else { - if (tapped) - str = tr("%1 taps %2.", "male"); - else - str = tr("%1 untaps %2.", "male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); - } - } + if (tapped) + soundEngine->tap(); + else + soundEngine->untap(); + + if (currentContext == MessageContext_MoveCard) + moveCardTapped.insert(card, tapped); + else { + QString str; + if (!card) { + if (isFemale(player)) { + if (tapped) + str = tr("%1 taps her permanents.", "female"); + else + str = tr("%1 untaps her permanents.", "female"); + } else { + if (tapped) + str = tr("%1 taps his permanents.", "male"); + else + str = tr("%1 untaps his permanents.", "male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName()))); + } else { + if (isFemale(player)) { + if (tapped) + str = tr("%1 taps %2.", "female"); + else + str = tr("%1 untaps %2.", "female"); + } else { + if (tapped) + str = tr("%1 taps %2.", "male"); + else + str = tr("%1 untaps %2.", "male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); + } + } } void MessageLogWidget::logSetCounter(Player *player, QString counterName, int value, int oldValue) { - QString str; - if (isFemale(player)) - str = tr("%1 sets counter %2 to %3 (%4%5).", "female"); - else - str = tr("%1 sets counter %2 to %3 (%4%5).", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(QString("%1").arg(sanitizeHtml(counterName))).arg(QString("%1").arg(value)).arg(value > oldValue ? "+" : "").arg(value - oldValue)); + QString str; + if (isFemale(player)) + str = tr("%1 sets counter %2 to %3 (%4%5).", "female"); + else + str = tr("%1 sets counter %2 to %3 (%4%5).", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(QString("%1").arg(sanitizeHtml(counterName))).arg(QString("%1").arg(value)).arg(value > oldValue ? "+" : "").arg(value - oldValue)); } void MessageLogWidget::logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap) { - QString str; - if (doesntUntap) { - if (isFemale(player)) - str = tr("%1 sets %2 to not untap normally.", "female"); - else - str = tr("%1 sets %2 to not untap normally.", "male"); - } else { - if (isFemale(player)) - str = tr("%1 sets %2 to untap normally.", "female"); - else - str = tr("%1 sets %2 to untap normally.", "male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); + QString str; + if (doesntUntap) { + if (isFemale(player)) + str = tr("%1 sets %2 to not untap normally.", "female"); + else + str = tr("%1 sets %2 to not untap normally.", "male"); + } else { + if (isFemale(player)) + str = tr("%1 sets %2 to untap normally.", "female"); + else + str = tr("%1 sets %2 to untap normally.", "male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); } void MessageLogWidget::logSetPT(Player *player, CardItem *card, QString newPT) { - if (currentContext == MessageContext_MoveCard) - moveCardPT.insert(card, newPT); - else { - QString str; - if (isFemale(player)) - str = tr("%1 sets PT of %2 to %3.", "female"); - else - str = tr("%1 sets PT of %2 to %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString("%1").arg(sanitizeHtml(newPT)))); - } + if (currentContext == MessageContext_MoveCard) + moveCardPT.insert(card, newPT); + else { + QString str; + if (isFemale(player)) + str = tr("%1 sets PT of %2 to %3.", "female"); + else + str = tr("%1 sets PT of %2 to %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString("%1").arg(sanitizeHtml(newPT)))); + } } void MessageLogWidget::logSetAnnotation(Player *player, CardItem *card, QString newAnnotation) { - QString str; - if (isFemale(player)) - str = tr("%1 sets annotation of %2 to %3.", "female"); - else - str = tr("%1 sets annotation of %2 to %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString(""%1"").arg(sanitizeHtml(newAnnotation)))); + QString str; + if (isFemale(player)) + str = tr("%1 sets annotation of %2 to %3.", "female"); + else + str = tr("%1 sets annotation of %2 to %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString(""%1"").arg(sanitizeHtml(newAnnotation)))); } void MessageLogWidget::logDumpZone(Player *player, CardZone *zone, int numberCards) { - if (numberCards == -1) - appendHtml((isFemale(player) - ? tr("%1 is looking at %2.", "female") - : tr("%1 is looking at %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); - else - appendHtml((isFemale(player) - ? tr("%1 is looking at the top %n card(s) %2.", "female", numberCards) - : tr("%1 is looking at the top %n card(s) %2.", "male", numberCards) - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseTopCardsOfZone))); + if (numberCards == -1) + appendHtml((isFemale(player) + ? tr("%1 is looking at %2.", "female") + : tr("%1 is looking at %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); + else + appendHtml((isFemale(player) + ? tr("%1 is looking at the top %n card(s) %2.", "female", numberCards) + : tr("%1 is looking at the top %n card(s) %2.", "male", numberCards) + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseTopCardsOfZone))); } void MessageLogWidget::logStopDumpZone(Player *player, CardZone *zone) { - appendHtml((isFemale(player) - ? tr("%1 stops looking at %2.", "female") - : tr("%1 stops looking at %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); + appendHtml((isFemale(player) + ? tr("%1 stops looking at %2.", "female") + : tr("%1 stops looking at %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); } void MessageLogWidget::logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown) { - QPair temp = getFromStr(zone, cardName, cardId, false); - bool cardNameContainsStartZone = false; - if (!temp.first.isEmpty()) { - cardNameContainsStartZone = true; - cardName = temp.first; - } - QString fromStr = temp.second; + QPair temp = getFromStr(zone, cardName, cardId, false); + bool cardNameContainsStartZone = false; + if (!temp.first.isEmpty()) { + cardNameContainsStartZone = true; + cardName = temp.first; + } + QString fromStr = temp.second; - QString cardStr; - if (cardNameContainsStartZone) - cardStr = cardName; - else if (cardName.isEmpty()) - cardStr = tr("a card"); - else - cardStr = cardLink(cardName); + QString cardStr; + if (cardNameContainsStartZone) + cardStr = cardName; + else if (cardName.isEmpty()) + cardStr = tr("a card"); + else + cardStr = cardLink(cardName); - QString str; - if (cardId == -1) { - if (otherPlayer) { - if (isFemale(player)) { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2 to %3.", "p1 female, p2 female"); - else - str = tr("%1 reveals %2 to %3.", "p1 female, p2 male"); - } else { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2 to %3.", "p1 male, p2 female"); - else - str = tr("%1 reveals %2 to %3.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(zone->getTranslatedName(true, CaseRevealZone)).arg(sanitizeHtml(otherPlayer->getName()))); - } else { - appendHtml((isFemale(player) - ? tr("%1 reveals %2.", "female") - : tr("%1 reveals %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseRevealZone))); - } - } else if (cardId == -2) { - if (otherPlayer) { - if (isFemale(player)) { - if (isFemale(otherPlayer)) - str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 female"); - else - str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 male"); - } else { - if (isFemale(otherPlayer)) - str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 female"); - else - str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 randomly reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - else - appendHtml(tr("%1 randomly reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - } - } else { - if (faceDown && (player == otherPlayer)) { - if (cardName.isEmpty()) { - if (isFemale(player)) - str = tr("%1 peeks at face down card #%2.", "female"); - else - str = tr("%1 peeks at face down card #%2.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId)); - } else { - if (isFemale(player)) - str = tr("%1 peeks at face down card #%2: %3.", "female"); - else - str = tr("%1 peeks at face down card #%2: %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId).arg(cardStr)); - } - } else if (otherPlayer) { - if (isFemale(player)) { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 female"); - else - str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 male"); - } else { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 female"); - else - str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - else - appendHtml(tr("%1 reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - } - } + QString str; + if (cardId == -1) { + if (otherPlayer) { + if (isFemale(player)) { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2 to %3.", "p1 female, p2 female"); + else + str = tr("%1 reveals %2 to %3.", "p1 female, p2 male"); + } else { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2 to %3.", "p1 male, p2 female"); + else + str = tr("%1 reveals %2 to %3.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(zone->getTranslatedName(true, CaseRevealZone)).arg(sanitizeHtml(otherPlayer->getName()))); + } else { + appendHtml((isFemale(player) + ? tr("%1 reveals %2.", "female") + : tr("%1 reveals %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseRevealZone))); + } + } else if (cardId == -2) { + if (otherPlayer) { + if (isFemale(player)) { + if (isFemale(otherPlayer)) + str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 female"); + else + str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 male"); + } else { + if (isFemale(otherPlayer)) + str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 female"); + else + str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 randomly reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + else + appendHtml(tr("%1 randomly reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + } + } else { + if (faceDown && (player == otherPlayer)) { + if (cardName.isEmpty()) { + if (isFemale(player)) + str = tr("%1 peeks at face down card #%2.", "female"); + else + str = tr("%1 peeks at face down card #%2.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId)); + } else { + if (isFemale(player)) + str = tr("%1 peeks at face down card #%2: %3.", "female"); + else + str = tr("%1 peeks at face down card #%2: %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId).arg(cardStr)); + } + } else if (otherPlayer) { + if (isFemale(player)) { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 female"); + else + str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 male"); + } else { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 female"); + else + str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + else + appendHtml(tr("%1 reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + } + } } void MessageLogWidget::logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal) { - appendHtml((reveal - ? tr("%1 is now keeping the top card %2 revealed.") - : tr("%1 is not revealing the top card %2 any longer.") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseTopCardsOfZone)) - ); + appendHtml((reveal + ? tr("%1 is now keeping the top card %2 revealed.") + : tr("%1 is not revealing the top card %2 any longer.") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseTopCardsOfZone)) + ); } void MessageLogWidget::logSetActivePlayer(Player *player) { - soundEngine->notification(); - - QString str; - if (isFemale(player)) - str = tr("It is now %1's turn.", "female"); - else - str = tr("It is now %1's turn.", "male"); - appendHtml("
" + str.arg(player->getName()) + "
"); + soundEngine->notification(); + + QString str; + if (isFemale(player)) + str = tr("It is now %1's turn.", "female"); + else + str = tr("It is now %1's turn.", "male"); + appendHtml("
" + str.arg(player->getName()) + "
"); } void MessageLogWidget::logSetActivePhase(int phase) { - soundEngine->notification(); - QString phaseName; - switch (phase) { - case 0: phaseName = tr("untap step"); break; - case 1: phaseName = tr("upkeep step"); break; - case 2: phaseName = tr("draw step"); break; - case 3: phaseName = tr("first main phase"); break; - case 4: phaseName = tr("beginning of combat step"); break; - case 5: phaseName = tr("declare attackers step"); break; - case 6: phaseName = tr("declare blockers step"); break; - case 7: phaseName = tr("combat damage step"); break; - case 8: phaseName = tr("end of combat step"); break; - case 9: phaseName = tr("second main phase"); break; - case 10: phaseName = tr("ending phase"); break; - } - appendHtml("" + tr("It is now the %1.").arg(phaseName) + ""); + soundEngine->notification(); + QString phaseName; + switch (phase) { + case 0: phaseName = tr("untap step"); break; + case 1: phaseName = tr("upkeep step"); break; + case 2: phaseName = tr("draw step"); break; + case 3: phaseName = tr("first main phase"); break; + case 4: phaseName = tr("beginning of combat step"); break; + case 5: phaseName = tr("declare attackers step"); break; + case 6: phaseName = tr("declare blockers step"); break; + case 7: phaseName = tr("combat damage step"); break; + case 8: phaseName = tr("end of combat step"); break; + case 9: phaseName = tr("second main phase"); break; + case 10: phaseName = tr("ending phase"); break; + } + appendHtml("" + tr("It is now the %1.").arg(phaseName) + ""); } void MessageLogWidget::containerProcessingStarted(const GameEventContext &_context) { - if (_context.HasExtension(Context_MoveCard::ext)) - currentContext = MessageContext_MoveCard; - else if (_context.HasExtension(Context_Mulligan::ext)) { - const Context_Mulligan &contextMulligan = _context.GetExtension(Context_Mulligan::ext); - currentContext = MessageContext_Mulligan; - mulliganPlayer = 0; - mulliganNumber = contextMulligan.number(); - } + if (_context.HasExtension(Context_MoveCard::ext)) + currentContext = MessageContext_MoveCard; + else if (_context.HasExtension(Context_Mulligan::ext)) { + const Context_Mulligan &contextMulligan = _context.GetExtension(Context_Mulligan::ext); + currentContext = MessageContext_Mulligan; + mulliganPlayer = 0; + mulliganNumber = contextMulligan.number(); + } } void MessageLogWidget::containerProcessingDone() { - if (currentContext == MessageContext_MoveCard) { - for (int i = 0; i < moveCardQueue.size(); ++i) - doMoveCard(moveCardQueue[i]); - moveCardQueue.clear(); - moveCardPT.clear(); - moveCardTapped.clear(); - } else if (currentContext == MessageContext_Mulligan) { - logMulligan(mulliganPlayer, mulliganNumber); - mulliganPlayer = 0; - mulliganNumber = 0; - } - - currentContext = MessageContext_None; + if (currentContext == MessageContext_MoveCard) { + for (int i = 0; i < moveCardQueue.size(); ++i) + doMoveCard(moveCardQueue[i]); + moveCardQueue.clear(); + moveCardPT.clear(); + moveCardTapped.clear(); + } else if (currentContext == MessageContext_Mulligan) { + logMulligan(mulliganPlayer, mulliganNumber); + mulliganPlayer = 0; + mulliganNumber = 0; + } + + currentContext = MessageContext_None; } void MessageLogWidget::connectToPlayer(Player *player) { - connect(player, SIGNAL(logSay(Player *, QString)), this, SLOT(logSay(Player *, QString))); - connect(player, SIGNAL(logShuffle(Player *, CardZone *)), this, SLOT(logShuffle(Player *, CardZone *))); - connect(player, SIGNAL(logRollDie(Player *, int, int)), this, SLOT(logRollDie(Player *, int, int))); - connect(player, SIGNAL(logCreateArrow(Player *, Player *, QString, Player *, QString, bool)), this, SLOT(logCreateArrow(Player *, Player *, QString, Player *, QString, bool))); - connect(player, SIGNAL(logCreateToken(Player *, QString, QString)), this, SLOT(logCreateToken(Player *, QString, QString))); - connect(player, SIGNAL(logSetCounter(Player *, QString, int, int)), this, SLOT(logSetCounter(Player *, QString, int, int))); - connect(player, SIGNAL(logSetCardCounter(Player *, QString, int, int, int)), this, SLOT(logSetCardCounter(Player *, QString, int, int, int))); - connect(player, SIGNAL(logSetTapped(Player *, CardItem *, bool)), this, SLOT(logSetTapped(Player *, CardItem *, bool))); - connect(player, SIGNAL(logSetDoesntUntap(Player *, CardItem *, bool)), this, SLOT(logSetDoesntUntap(Player *, CardItem *, bool))); - connect(player, SIGNAL(logSetPT(Player *, CardItem *, QString)), this, SLOT(logSetPT(Player *, CardItem *, QString))); - connect(player, SIGNAL(logSetAnnotation(Player *, CardItem *, QString)), this, SLOT(logSetAnnotation(Player *, CardItem *, QString))); - connect(player, SIGNAL(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int)), this, SLOT(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int))); - connect(player, SIGNAL(logFlipCard(Player *, QString, bool)), this, SLOT(logFlipCard(Player *, QString, bool))); - connect(player, SIGNAL(logDestroyCard(Player *, QString)), this, SLOT(logDestroyCard(Player *, QString))); - connect(player, SIGNAL(logAttachCard(Player *, QString, Player *, QString)), this, SLOT(logAttachCard(Player *, QString, Player *, QString))); - connect(player, SIGNAL(logUnattachCard(Player *, QString)), this, SLOT(logUnattachCard(Player *, QString))); - connect(player, SIGNAL(logDumpZone(Player *, CardZone *, int)), this, SLOT(logDumpZone(Player *, CardZone *, int))); - connect(player, SIGNAL(logStopDumpZone(Player *, CardZone *)), this, SLOT(logStopDumpZone(Player *, CardZone *))); - connect(player, SIGNAL(logDrawCards(Player *, int)), this, SLOT(logDrawCards(Player *, int))); - connect(player, SIGNAL(logUndoDraw(Player *, QString)), this, SLOT(logUndoDraw(Player *, QString))); - connect(player, SIGNAL(logRevealCards(Player *, CardZone *, int, QString, Player *, bool)), this, SLOT(logRevealCards(Player *, CardZone *, int, QString, Player *, bool))); - connect(player, SIGNAL(logAlwaysRevealTopCard(Player *, CardZone *, bool)), this, SLOT(logAlwaysRevealTopCard(Player *, CardZone *, bool))); + connect(player, SIGNAL(logSay(Player *, QString)), this, SLOT(logSay(Player *, QString))); + connect(player, SIGNAL(logShuffle(Player *, CardZone *)), this, SLOT(logShuffle(Player *, CardZone *))); + connect(player, SIGNAL(logRollDie(Player *, int, int)), this, SLOT(logRollDie(Player *, int, int))); + connect(player, SIGNAL(logCreateArrow(Player *, Player *, QString, Player *, QString, bool)), this, SLOT(logCreateArrow(Player *, Player *, QString, Player *, QString, bool))); + connect(player, SIGNAL(logCreateToken(Player *, QString, QString)), this, SLOT(logCreateToken(Player *, QString, QString))); + connect(player, SIGNAL(logSetCounter(Player *, QString, int, int)), this, SLOT(logSetCounter(Player *, QString, int, int))); + connect(player, SIGNAL(logSetCardCounter(Player *, QString, int, int, int)), this, SLOT(logSetCardCounter(Player *, QString, int, int, int))); + connect(player, SIGNAL(logSetTapped(Player *, CardItem *, bool)), this, SLOT(logSetTapped(Player *, CardItem *, bool))); + connect(player, SIGNAL(logSetDoesntUntap(Player *, CardItem *, bool)), this, SLOT(logSetDoesntUntap(Player *, CardItem *, bool))); + connect(player, SIGNAL(logSetPT(Player *, CardItem *, QString)), this, SLOT(logSetPT(Player *, CardItem *, QString))); + connect(player, SIGNAL(logSetAnnotation(Player *, CardItem *, QString)), this, SLOT(logSetAnnotation(Player *, CardItem *, QString))); + connect(player, SIGNAL(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int)), this, SLOT(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int))); + connect(player, SIGNAL(logFlipCard(Player *, QString, bool)), this, SLOT(logFlipCard(Player *, QString, bool))); + connect(player, SIGNAL(logDestroyCard(Player *, QString)), this, SLOT(logDestroyCard(Player *, QString))); + connect(player, SIGNAL(logAttachCard(Player *, QString, Player *, QString)), this, SLOT(logAttachCard(Player *, QString, Player *, QString))); + connect(player, SIGNAL(logUnattachCard(Player *, QString)), this, SLOT(logUnattachCard(Player *, QString))); + connect(player, SIGNAL(logDumpZone(Player *, CardZone *, int)), this, SLOT(logDumpZone(Player *, CardZone *, int))); + connect(player, SIGNAL(logStopDumpZone(Player *, CardZone *)), this, SLOT(logStopDumpZone(Player *, CardZone *))); + connect(player, SIGNAL(logDrawCards(Player *, int)), this, SLOT(logDrawCards(Player *, int))); + connect(player, SIGNAL(logUndoDraw(Player *, QString)), this, SLOT(logUndoDraw(Player *, QString))); + connect(player, SIGNAL(logRevealCards(Player *, CardZone *, int, QString, Player *, bool)), this, SLOT(logRevealCards(Player *, CardZone *, int, QString, Player *, bool))); + connect(player, SIGNAL(logAlwaysRevealTopCard(Player *, CardZone *, bool)), this, SLOT(logAlwaysRevealTopCard(Player *, CardZone *, bool))); } MessageLogWidget::MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent) - : ChatView(_tabSupervisor, _game, false, parent) + : ChatView(_tabSupervisor, _game, false, parent) { } diff --git a/cockatrice/src/messagelogwidget.h b/cockatrice/src/messagelogwidget.h index d1c1d6f7..1747a338 100644 --- a/cockatrice/src/messagelogwidget.h +++ b/cockatrice/src/messagelogwidget.h @@ -12,81 +12,81 @@ class GameEventContext; class CardItem; struct LogMoveCard { - Player *player; - CardItem *card; - QString cardName; - CardZone *startZone; - int oldX; - CardZone *targetZone; - int newX; + Player *player; + CardItem *card; + QString cardName; + CardZone *startZone; + int oldX; + CardZone *targetZone; + int newX; }; class MessageLogWidget : public ChatView { - Q_OBJECT + Q_OBJECT private: - enum MessageContext { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan }; - - QString sanitizeHtml(QString dirty) const; - QString cardLink(const QString &cardName) const; - bool isFemale(Player *player) const; - bool userIsFemale() const; - QPair getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const; - MessageContext currentContext; - - QList moveCardQueue; - QMap moveCardPT; - QMap moveCardTapped; - - Player *mulliganPlayer; - int mulliganNumber; + enum MessageContext { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan }; + + QString sanitizeHtml(QString dirty) const; + QString cardLink(const QString &cardName) const; + bool isFemale(Player *player) const; + bool userIsFemale() const; + QPair getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const; + MessageContext currentContext; + + QList moveCardQueue; + QMap moveCardPT; + QMap moveCardTapped; + + Player *mulliganPlayer; + int mulliganNumber; public slots: - void logGameJoined(int gameId); - void logReplayStarted(int gameId); - void logJoin(Player *player); - void logLeave(Player *player); - void logGameClosed(); - void logKicked(); - void logJoinSpectator(QString name); - void logLeaveSpectator(QString name); - void logDeckSelect(Player *player, QString deckHash); - void logReadyStart(Player *player); - void logNotReadyStart(Player *player); - void logSetSideboardLock(Player *player, bool locked); - void logConcede(Player *player); - void logGameStart(); - void logConnectionStateChanged(Player *player, bool connectionState); - void logSay(Player *player, QString message); - void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message); - void logShuffle(Player *player, CardZone *zone); - void logRollDie(Player *player, int sides, int roll); - void logDrawCards(Player *player, int number); - void logUndoDraw(Player *player, QString cardName); - void doMoveCard(LogMoveCard &attributes); - void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); - void logMulligan(Player *player, int number); - void logFlipCard(Player *player, QString cardName, bool faceDown); - void logDestroyCard(Player *player, QString cardName); - void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); - void logUnattachCard(Player *player, QString cardName); - void logCreateToken(Player *player, QString cardName, QString pt); - void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget); - void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); - void logSetTapped(Player *player, CardItem *card, bool tapped); - void logSetCounter(Player *player, QString counterName, int value, int oldValue); - void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); - void logSetPT(Player *player, CardItem *card, QString newPT); - void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); - void logDumpZone(Player *player, CardZone *zone, int numberCards); - void logStopDumpZone(Player *player, CardZone *zone); - void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); - void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); - void logSetActivePlayer(Player *player); - void logSetActivePhase(int phase); - void containerProcessingStarted(const GameEventContext &context); - void containerProcessingDone(); + void logGameJoined(int gameId); + void logReplayStarted(int gameId); + void logJoin(Player *player); + void logLeave(Player *player); + void logGameClosed(); + void logKicked(); + void logJoinSpectator(QString name); + void logLeaveSpectator(QString name); + void logDeckSelect(Player *player, QString deckHash); + void logReadyStart(Player *player); + void logNotReadyStart(Player *player); + void logSetSideboardLock(Player *player, bool locked); + void logConcede(Player *player); + void logGameStart(); + void logConnectionStateChanged(Player *player, bool connectionState); + void logSay(Player *player, QString message); + void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message); + void logShuffle(Player *player, CardZone *zone); + void logRollDie(Player *player, int sides, int roll); + void logDrawCards(Player *player, int number); + void logUndoDraw(Player *player, QString cardName); + void doMoveCard(LogMoveCard &attributes); + void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); + void logMulligan(Player *player, int number); + void logFlipCard(Player *player, QString cardName, bool faceDown); + void logDestroyCard(Player *player, QString cardName); + void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); + void logUnattachCard(Player *player, QString cardName); + void logCreateToken(Player *player, QString cardName, QString pt); + void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget); + void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); + void logSetTapped(Player *player, CardItem *card, bool tapped); + void logSetCounter(Player *player, QString counterName, int value, int oldValue); + void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); + void logSetPT(Player *player, CardItem *card, QString newPT); + void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); + void logDumpZone(Player *player, CardZone *zone, int numberCards); + void logStopDumpZone(Player *player, CardZone *zone); + void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); + void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); + void logSetActivePlayer(Player *player); + void logSetActivePhase(int phase); + void containerProcessingStarted(const GameEventContext &context); + void containerProcessingDone(); public: - void connectToPlayer(Player *player); - MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent = 0); + void connectToPlayer(Player *player); + MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/pending_command.h b/cockatrice/src/pending_command.h index 2e2a2bf2..9b092dcd 100644 --- a/cockatrice/src/pending_command.h +++ b/cockatrice/src/pending_command.h @@ -6,26 +6,26 @@ #include class PendingCommand : public QObject { - Q_OBJECT + Q_OBJECT signals: - void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData); - void finished(Response::ResponseCode respCode); + void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData); + void finished(Response::ResponseCode respCode); private: - CommandContainer commandContainer; - QVariant extraData; - int ticks; + CommandContainer commandContainer; + QVariant extraData; + int ticks; public: - PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()) - : commandContainer(_commandContainer), extraData(_extraData), ticks(0) { } - CommandContainer &getCommandContainer() { return commandContainer; } - void setExtraData(const QVariant &_extraData) { extraData = _extraData; } - QVariant getExtraData() const { return extraData; } - void processResponse(const Response &response) - { - emit finished(response, commandContainer, extraData); - emit finished(response.response_code()); - } - int tick() { return ++ticks; } + PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()) + : commandContainer(_commandContainer), extraData(_extraData), ticks(0) { } + CommandContainer &getCommandContainer() { return commandContainer; } + void setExtraData(const QVariant &_extraData) { extraData = _extraData; } + QVariant getExtraData() const { return extraData; } + void processResponse(const Response &response) + { + emit finished(response, commandContainer, extraData); + emit finished(response.response_code()); + } + int tick() { return ++ticks; } }; #endif diff --git a/cockatrice/src/phasestoolbar.cpp b/cockatrice/src/phasestoolbar.cpp index 3ea9ad91..98f27404 100644 --- a/cockatrice/src/phasestoolbar.cpp +++ b/cockatrice/src/phasestoolbar.cpp @@ -13,239 +13,239 @@ #include "pb/command_draw_cards.pb.h" PhaseButton::PhaseButton(const QString &_name, QGraphicsItem *parent, QAction *_doubleClickAction, bool _highlightable) - : QObject(), QGraphicsItem(parent), name(_name), active(false), highlightable(_highlightable), activeAnimationCounter(0), doubleClickAction(_doubleClickAction), width(50) + : QObject(), QGraphicsItem(parent), name(_name), active(false), highlightable(_highlightable), activeAnimationCounter(0), doubleClickAction(_doubleClickAction), width(50) { - if (highlightable) { - activeAnimationTimer = new QTimer(this); - connect(activeAnimationTimer, SIGNAL(timeout()), this, SLOT(updateAnimation())); - activeAnimationTimer->setSingleShot(false); - } else - activeAnimationCounter = 9.0; - - setCacheMode(DeviceCoordinateCache); + if (highlightable) { + activeAnimationTimer = new QTimer(this); + connect(activeAnimationTimer, SIGNAL(timeout()), this, SLOT(updateAnimation())); + activeAnimationTimer->setSingleShot(false); + } else + activeAnimationCounter = 9.0; + + setCacheMode(DeviceCoordinateCache); } QRectF PhaseButton::boundingRect() const { - return QRectF(0, 0, width, width); + return QRectF(0, 0, width, width); } void PhaseButton::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QRectF iconRect = boundingRect().adjusted(3, 3, -3, -3); - QRectF translatedIconRect = painter->combinedTransform().mapRect(iconRect); - qreal scaleFactor = translatedIconRect.width() / iconRect.width(); - QPixmap iconPixmap = PhasePixmapGenerator::generatePixmap(round(translatedIconRect.height()), name); - - painter->setBrush(QColor(220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0))); - painter->setPen(Qt::gray); - painter->drawRect(0, 0, width - 1, width - 1); - painter->save(); - painter->resetTransform(); - painter->drawPixmap(iconPixmap.rect().translated(round(3 * scaleFactor), round(3 * scaleFactor)), iconPixmap, iconPixmap.rect()); - painter->restore(); - - painter->setBrush(QColor(0, 0, 0, 255 * ((10 - activeAnimationCounter) / 15.0))); - painter->setPen(Qt::gray); - painter->drawRect(0, 0, width - 1, width - 1); + QRectF iconRect = boundingRect().adjusted(3, 3, -3, -3); + QRectF translatedIconRect = painter->combinedTransform().mapRect(iconRect); + qreal scaleFactor = translatedIconRect.width() / iconRect.width(); + QPixmap iconPixmap = PhasePixmapGenerator::generatePixmap(round(translatedIconRect.height()), name); + + painter->setBrush(QColor(220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0))); + painter->setPen(Qt::gray); + painter->drawRect(0, 0, width - 1, width - 1); + painter->save(); + painter->resetTransform(); + painter->drawPixmap(iconPixmap.rect().translated(round(3 * scaleFactor), round(3 * scaleFactor)), iconPixmap, iconPixmap.rect()); + painter->restore(); + + painter->setBrush(QColor(0, 0, 0, 255 * ((10 - activeAnimationCounter) / 15.0))); + painter->setPen(Qt::gray); + painter->drawRect(0, 0, width - 1, width - 1); } void PhaseButton::setWidth(double _width) { - prepareGeometryChange(); - width = _width; + prepareGeometryChange(); + width = _width; } void PhaseButton::setActive(bool _active) { - if ((active == _active) || !highlightable) - return; - - active = _active; - activeAnimationTimer->start(50); + if ((active == _active) || !highlightable) + return; + + active = _active; + activeAnimationTimer->start(50); } void PhaseButton::updateAnimation() { - if (!highlightable) - return; - - if (active) { - if (++activeAnimationCounter >= 10) - activeAnimationTimer->stop(); - } else { - if (--activeAnimationCounter <= 0) - activeAnimationTimer->stop(); - } - update(); + if (!highlightable) + return; + + if (active) { + if (++activeAnimationCounter >= 10) + activeAnimationTimer->stop(); + } else { + if (--activeAnimationCounter <= 0) + activeAnimationTimer->stop(); + } + update(); } void PhaseButton::mousePressEvent(QGraphicsSceneMouseEvent * /*event*/) { - emit clicked(); + emit clicked(); } void PhaseButton::mouseDoubleClickEvent(QGraphicsSceneMouseEvent */*event*/) { - triggerDoubleClickAction(); + triggerDoubleClickAction(); } void PhaseButton::triggerDoubleClickAction() { - if (doubleClickAction) - doubleClickAction->trigger(); + if (doubleClickAction) + doubleClickAction->trigger(); } PhasesToolbar::PhasesToolbar(QGraphicsItem *parent) - : QGraphicsItem(parent), width(100), height(100) + : QGraphicsItem(parent), width(100), height(100) { - QAction *aUntapAll = new QAction(this); - connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); - QAction *aDrawCard = new QAction(this); - connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); - - PhaseButton *untapButton = new PhaseButton("untap", this, aUntapAll); - PhaseButton *upkeepButton = new PhaseButton("upkeep", this); - PhaseButton *drawButton = new PhaseButton("draw", this, aDrawCard); - PhaseButton *main1Button = new PhaseButton("main1", this); - PhaseButton *combatStartButton = new PhaseButton("combat_start", this); - PhaseButton *combatAttackersButton = new PhaseButton("combat_attackers", this); - PhaseButton *combatBlockersButton = new PhaseButton("combat_blockers", this); - PhaseButton *combatDamageButton = new PhaseButton("combat_damage", this); - PhaseButton *combatEndButton = new PhaseButton("combat_end", this); - PhaseButton *main2Button = new PhaseButton("main2", this); - PhaseButton *cleanupButton = new PhaseButton("cleanup", this); - - buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton - << combatAttackersButton << combatBlockersButton << combatDamageButton << combatEndButton - << main2Button << cleanupButton; - - for (int i = 0; i < buttonList.size(); ++i) - connect(buttonList[i], SIGNAL(clicked()), this, SLOT(phaseButtonClicked())); - - nextTurnButton = new PhaseButton("nextturn", this, 0, false); - connect(nextTurnButton, SIGNAL(clicked()), this, SLOT(actNextTurn())); - - rearrangeButtons(); - - retranslateUi(); + QAction *aUntapAll = new QAction(this); + connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); + QAction *aDrawCard = new QAction(this); + connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); + + PhaseButton *untapButton = new PhaseButton("untap", this, aUntapAll); + PhaseButton *upkeepButton = new PhaseButton("upkeep", this); + PhaseButton *drawButton = new PhaseButton("draw", this, aDrawCard); + PhaseButton *main1Button = new PhaseButton("main1", this); + PhaseButton *combatStartButton = new PhaseButton("combat_start", this); + PhaseButton *combatAttackersButton = new PhaseButton("combat_attackers", this); + PhaseButton *combatBlockersButton = new PhaseButton("combat_blockers", this); + PhaseButton *combatDamageButton = new PhaseButton("combat_damage", this); + PhaseButton *combatEndButton = new PhaseButton("combat_end", this); + PhaseButton *main2Button = new PhaseButton("main2", this); + PhaseButton *cleanupButton = new PhaseButton("cleanup", this); + + buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton + << combatAttackersButton << combatBlockersButton << combatDamageButton << combatEndButton + << main2Button << cleanupButton; + + for (int i = 0; i < buttonList.size(); ++i) + connect(buttonList[i], SIGNAL(clicked()), this, SLOT(phaseButtonClicked())); + + nextTurnButton = new PhaseButton("nextturn", this, 0, false); + connect(nextTurnButton, SIGNAL(clicked()), this, SLOT(actNextTurn())); + + rearrangeButtons(); + + retranslateUi(); } QRectF PhasesToolbar::boundingRect() const { - return QRectF(0, 0, width, height); + return QRectF(0, 0, width, height); } void PhasesToolbar::retranslateUi() { - for (int i = 0; i < buttonList.size(); ++i) - buttonList[i]->setToolTip(getLongPhaseName(i)); + for (int i = 0; i < buttonList.size(); ++i) + buttonList[i]->setToolTip(getLongPhaseName(i)); } QString PhasesToolbar::getLongPhaseName(int phase) const { - switch (phase) { - case 0: return tr("Untap step"); - case 1: return tr("Upkeep step"); - case 2: return tr("Draw step"); - case 3: return tr("First main phase"); - case 4: return tr("Beginning of combat step"); - case 5: return tr("Declare attackers step"); - case 6: return tr("Declare blockers step"); - case 7: return tr("Combat damage step"); - case 8: return tr("End of combat step"); - case 9: return tr("Second main phase"); - case 10: return tr("End of turn step"); - default: return QString(); - } + switch (phase) { + case 0: return tr("Untap step"); + case 1: return tr("Upkeep step"); + case 2: return tr("Draw step"); + case 3: return tr("First main phase"); + case 4: return tr("Beginning of combat step"); + case 5: return tr("Declare attackers step"); + case 6: return tr("Declare blockers step"); + case 7: return tr("Combat damage step"); + case 8: return tr("End of combat step"); + case 9: return tr("Second main phase"); + case 10: return tr("End of turn step"); + default: return QString(); + } } void PhasesToolbar::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - painter->fillRect(boundingRect(), QColor(50, 50, 50)); + painter->fillRect(boundingRect(), QColor(50, 50, 50)); } const double PhasesToolbar::marginSize = 3; void PhasesToolbar::rearrangeButtons() { - for (int i = 0; i < buttonList.size(); ++i) - buttonList[i]->setWidth(symbolSize); - nextTurnButton->setWidth(symbolSize); - - double y = marginSize; - buttonList[0]->setPos(marginSize, y); - buttonList[1]->setPos(marginSize, y += symbolSize); - buttonList[2]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[3]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[4]->setPos(marginSize, y += symbolSize); - buttonList[5]->setPos(marginSize, y += symbolSize); - buttonList[6]->setPos(marginSize, y += symbolSize); - buttonList[7]->setPos(marginSize, y += symbolSize); - buttonList[8]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[9]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[10]->setPos(marginSize, y += symbolSize); - y += ySpacing; - y += ySpacing; - nextTurnButton->setPos(marginSize, y += symbolSize); + for (int i = 0; i < buttonList.size(); ++i) + buttonList[i]->setWidth(symbolSize); + nextTurnButton->setWidth(symbolSize); + + double y = marginSize; + buttonList[0]->setPos(marginSize, y); + buttonList[1]->setPos(marginSize, y += symbolSize); + buttonList[2]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[3]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[4]->setPos(marginSize, y += symbolSize); + buttonList[5]->setPos(marginSize, y += symbolSize); + buttonList[6]->setPos(marginSize, y += symbolSize); + buttonList[7]->setPos(marginSize, y += symbolSize); + buttonList[8]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[9]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[10]->setPos(marginSize, y += symbolSize); + y += ySpacing; + y += ySpacing; + nextTurnButton->setPos(marginSize, y += symbolSize); } void PhasesToolbar::setHeight(double _height) { - prepareGeometryChange(); - - height = _height; - ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount); - symbolSize = ySpacing * 5; - width = symbolSize + 2 * marginSize; - - rearrangeButtons(); + prepareGeometryChange(); + + height = _height; + ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount); + symbolSize = ySpacing * 5; + width = symbolSize + 2 * marginSize; + + rearrangeButtons(); } void PhasesToolbar::setActivePhase(int phase) { - if (phase >= buttonList.size()) - return; - - for (int i = 0; i < buttonList.size(); ++i) - buttonList[i]->setActive(i == phase); + if (phase >= buttonList.size()) + return; + + for (int i = 0; i < buttonList.size(); ++i) + buttonList[i]->setActive(i == phase); } void PhasesToolbar::phaseButtonClicked() { - PhaseButton *button = qobject_cast(sender()); - if (button->getActive()) - button->triggerDoubleClickAction(); - - Command_SetActivePhase cmd; - cmd.set_phase(buttonList.indexOf(button)); - - emit sendGameCommand(cmd, -1); + PhaseButton *button = qobject_cast(sender()); + if (button->getActive()) + button->triggerDoubleClickAction(); + + Command_SetActivePhase cmd; + cmd.set_phase(buttonList.indexOf(button)); + + emit sendGameCommand(cmd, -1); } void PhasesToolbar::actNextTurn() { - emit sendGameCommand(Command_NextTurn(), -1); + emit sendGameCommand(Command_NextTurn(), -1); } void PhasesToolbar::actUntapAll() { - Command_SetCardAttr cmd; - cmd.set_zone("table"); - cmd.set_attribute(AttrTapped); - cmd.set_attr_value("0"); - - emit sendGameCommand(cmd, -1); + Command_SetCardAttr cmd; + cmd.set_zone("table"); + cmd.set_attribute(AttrTapped); + cmd.set_attr_value("0"); + + emit sendGameCommand(cmd, -1); } void PhasesToolbar::actDrawCard() { - Command_DrawCards cmd; - cmd.set_number(1); - - emit sendGameCommand(cmd, -1); + Command_DrawCards cmd; + cmd.set_number(1); + + emit sendGameCommand(cmd, -1); } diff --git a/cockatrice/src/phasestoolbar.h b/cockatrice/src/phasestoolbar.h index 3a39a950..852f4f58 100644 --- a/cockatrice/src/phasestoolbar.h +++ b/cockatrice/src/phasestoolbar.h @@ -10,62 +10,62 @@ class Player; class GameCommand; class PhaseButton : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT private: - QString name; - bool active, highlightable; - int activeAnimationCounter; - QTimer *activeAnimationTimer; - QAction *doubleClickAction; - double width; - - void updatePixmap(QPixmap &pixmap); + QString name; + bool active, highlightable; + int activeAnimationCounter; + QTimer *activeAnimationTimer; + QAction *doubleClickAction; + double width; + + void updatePixmap(QPixmap &pixmap); private slots: - void updateAnimation(); + void updateAnimation(); public: - PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true); - QRectF boundingRect() const; - void setWidth(double _width); - void setActive(bool _active); - bool getActive() const { return active; } - void triggerDoubleClickAction(); + PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true); + QRectF boundingRect() const; + void setWidth(double _width); + void setActive(bool _active); + bool getActive() const { return active; } + void triggerDoubleClickAction(); signals: - void clicked(); + void clicked(); protected: - void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); }; class PhasesToolbar : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT private: - QList buttonList; - PhaseButton *nextTurnButton; - double width, height, ySpacing, symbolSize; - static const int buttonCount = 12; - static const int spaceCount = 6; - static const double marginSize; - void rearrangeButtons(); + QList buttonList; + PhaseButton *nextTurnButton; + double width, height, ySpacing, symbolSize; + static const int buttonCount = 12; + static const int spaceCount = 6; + static const double marginSize; + void rearrangeButtons(); public: - PhasesToolbar(QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void retranslateUi(); - void setHeight(double _height); - double getWidth() const { return width; } - int phaseCount() const { return buttonList.size(); } - QString getLongPhaseName(int phase) const; + PhasesToolbar(QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void retranslateUi(); + void setHeight(double _height); + double getWidth() const { return width; } + int phaseCount() const { return buttonList.size(); } + QString getLongPhaseName(int phase) const; public slots: - void setActivePhase(int phase); + void setActivePhase(int phase); private slots: - void phaseButtonClicked(); - void actNextTurn(); - void actUntapAll(); - void actDrawCard(); + void phaseButtonClicked(); + void actNextTurn(); + void actUntapAll(); + void actDrawCard(); signals: - void sendGameCommand(const ::google::protobuf::Message &command, int playerId); + void sendGameCommand(const ::google::protobuf::Message &command, int playerId); protected: - void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); + void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); }; #endif diff --git a/cockatrice/src/pilezone.cpp b/cockatrice/src/pilezone.cpp index 97d32902..d34d4c06 100644 --- a/cockatrice/src/pilezone.cpp +++ b/cockatrice/src/pilezone.cpp @@ -10,109 +10,109 @@ #include "pb/command_move_card.pb.h" PileZone::PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent) - : CardZone(_p, _name, false, _isShufflable, _contentsKnown, parent) + : CardZone(_p, _name, false, _isShufflable, _contentsKnown, parent) { - setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor! - setAcceptsHoverEvents(true); - setCursor(Qt::OpenHandCursor); - - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor! + setAcceptsHoverEvents(true); + setCursor(Qt::OpenHandCursor); + + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); } QRectF PileZone::boundingRect() const { - return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); + return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - if (!cards.isEmpty()) - cards.at(0)->paintPicture(painter, cards.at(0)->getTranslatedSize(painter), 90); + if (!cards.isEmpty()) + cards.at(0)->paintPicture(painter, cards.at(0)->getTranslatedSize(painter), 90); - painter->drawRect(QRectF(0.5, 0.5, CARD_WIDTH - 1, CARD_HEIGHT - 1)); - - painter->translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2); - painter->rotate(-90); - painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2); - paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter); + painter->drawRect(QRectF(0.5, 0.5, CARD_WIDTH - 1, CARD_HEIGHT - 1)); + + painter->translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2); + painter->rotate(-90); + painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2); + paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter); } void PileZone::addCardImpl(CardItem *card, int x, int /*y*/) { - connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate())); - cards.insert(x, card); - card->setPos(0, 0); - if (!contentsKnown()) { - card->setName(QString()); - card->setId(-1); - // If we obscure a previously revealed card, its name has to be forgotten - if (cards.size() > x + 1) - cards.at(x + 1)->setName(QString()); - } - card->setVisible(false); - card->resetState(); - card->setParentItem(this); + connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate())); + cards.insert(x, card); + card->setPos(0, 0); + if (!contentsKnown()) { + card->setName(QString()); + card->setId(-1); + // If we obscure a previously revealed card, its name has to be forgotten + if (cards.size() > x + 1) + cards.at(x + 1)->setName(QString()); + } + card->setVisible(false); + card->resetState(); + card->setParentItem(this); } void PileZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) { - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(0); - cmd.set_y(0); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(0); + cmd.set_y(0); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - player->sendGameCommand(cmd); + player->sendGameCommand(cmd); } void PileZone::reorganizeCards() { - update(); + update(); } void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { - CardZone::mousePressEvent(event); - if (event->isAccepted()) - return; + CardZone::mousePressEvent(event); + if (event->isAccepted()) + return; - if (event->button() == Qt::LeftButton) { - setCursor(Qt::ClosedHandCursor); - event->accept(); - } else - event->ignore(); + if (event->button() == Qt::LeftButton) { + setCursor(Qt::ClosedHandCursor); + event->accept(); + } else + event->ignore(); } void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance()) - return; + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance()) + return; - if (cards.isEmpty()) - return; + if (cards.isEmpty()) + return; - bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); - bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); - CardItem *card = bottomCard ? cards.last() : cards.first(); - const int cardid = contentsKnown() ? card->getId() : (bottomCard ? cards.size() - 1 : 0); - CardDragItem *drag = card->createDragItem(cardid, event->pos(), event->scenePos(), faceDown); - drag->grabMouse(); - setCursor(Qt::OpenHandCursor); + bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); + bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); + CardItem *card = bottomCard ? cards.last() : cards.first(); + const int cardid = contentsKnown() ? card->getId() : (bottomCard ? cards.size() - 1 : 0); + CardDragItem *drag = card->createDragItem(cardid, event->pos(), event->scenePos(), faceDown); + drag->grabMouse(); + setCursor(Qt::OpenHandCursor); } void PileZone::mouseReleaseEvent(QGraphicsSceneMouseEvent */*event*/) { - setCursor(Qt::OpenHandCursor); + setCursor(Qt::OpenHandCursor); } void PileZone::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - if (!cards.isEmpty()) - cards[0]->processHoverEvent(); - QGraphicsItem::hoverEnterEvent(event); + if (!cards.isEmpty()) + cards[0]->processHoverEvent(); + QGraphicsItem::hoverEnterEvent(event); } diff --git a/cockatrice/src/pilezone.h b/cockatrice/src/pilezone.h index 8675c99b..2469eb1e 100644 --- a/cockatrice/src/pilezone.h +++ b/cockatrice/src/pilezone.h @@ -4,21 +4,21 @@ #include "cardzone.h" class PileZone : public CardZone { - Q_OBJECT + Q_OBJECT private slots: - void callUpdate() { update(); } + void callUpdate() { update(); } public: - PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); - void addCardImpl(CardItem *card, int x, int y); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/pixmapgenerator.cpp b/cockatrice/src/pixmapgenerator.cpp index e5b4a7dc..7ff7ca98 100644 --- a/cockatrice/src/pixmapgenerator.cpp +++ b/cockatrice/src/pixmapgenerator.cpp @@ -9,152 +9,152 @@ QMap PhasePixmapGenerator::pmCache; QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name) { - QString key = name + QString::number(height); - if (pmCache.contains(key)) - return pmCache.value(key); - - QSvgRenderer svg(QString(":/resources/phases/icon_phase_" + name + ".svg")); - - QPixmap pixmap(height, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, height, height)); - pmCache.insert(key, pixmap); - return pixmap; + QString key = name + QString::number(height); + if (pmCache.contains(key)) + return pmCache.value(key); + + QSvgRenderer svg(QString(":/resources/phases/icon_phase_" + name + ".svg")); + + QPixmap pixmap(height, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, height, height)); + pmCache.insert(key, pixmap); + return pixmap; } QMap CounterPixmapGenerator::pmCache; QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool highlight) { - if (highlight) - name.append("_highlight"); - QString key = name + QString::number(height); - if (pmCache.contains(key)) - return pmCache.value(key); - - QSvgRenderer svg(QString(":/resources/counters/" + name + ".svg")); - - if (!svg.isValid()) { - name = "general"; - if (highlight) - name.append("_highlight"); - svg.load(QString(":/resources/counters/" + name + ".svg")); - } - - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - pmCache.insert(key, pixmap); - return pixmap; + if (highlight) + name.append("_highlight"); + QString key = name + QString::number(height); + if (pmCache.contains(key)) + return pmCache.value(key); + + QSvgRenderer svg(QString(":/resources/counters/" + name + ".svg")); + + if (!svg.isValid()) { + name = "general"; + if (highlight) + name.append("_highlight"); + svg.load(QString(":/resources/counters/" + name + ".svg")); + } + + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + pmCache.insert(key, pixmap); + return pixmap; } QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max) { - int key = size * 1000000 + max * 1000 + value; - if (pmCache.contains(key)) - return pmCache.value(key); - - QPixmap pixmap(size, size); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - QColor color; - if ((max == -1) || (value == -1)) - color = Qt::black; - else - color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255); - - QRadialGradient g(QPointF((double) pixmap.width() / 2, (double) pixmap.height() / 2), qMin(pixmap.width(), pixmap.height()) / 2.0); - g.setColorAt(0, color); - g.setColorAt(1, Qt::transparent); - painter.fillRect(0, 0, pixmap.width(), pixmap.height(), QBrush(g)); - - pmCache.insert(key, pixmap); + int key = size * 1000000 + max * 1000 + value; + if (pmCache.contains(key)) + return pmCache.value(key); + + QPixmap pixmap(size, size); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + QColor color; + if ((max == -1) || (value == -1)) + color = Qt::black; + else + color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255); + + QRadialGradient g(QPointF((double) pixmap.width() / 2, (double) pixmap.height() / 2), qMin(pixmap.width(), pixmap.height()) / 2.0); + g.setColorAt(0, color); + g.setColorAt(1, Qt::transparent); + painter.fillRect(0, 0, pixmap.width(), pixmap.height(), QBrush(g)); + + pmCache.insert(key, pixmap); - return pixmap; + return pixmap; } QMap PingPixmapGenerator::pmCache; QPixmap GenderPixmapGenerator::generatePixmap(int height, int _gender) { - ServerInfo_User::Gender gender = static_cast(_gender); - if ((gender != ServerInfo_User::Male) && (gender != ServerInfo_User::Female)) - gender = ServerInfo_User::GenderUnknown; - - int key = gender * 100000 + height; - if (pmCache.contains(key)) - return pmCache.value(key); - - QString genderStr; - switch (gender) { - case ServerInfo_User::Male: genderStr = "male"; break; - case ServerInfo_User::Female: genderStr = "female"; break; - default: genderStr = "unknown"; - }; - - QSvgRenderer svg(QString(":/resources/genders/" + genderStr + ".svg")); - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - - pmCache.insert(key, pixmap); - return pixmap; + ServerInfo_User::Gender gender = static_cast(_gender); + if ((gender != ServerInfo_User::Male) && (gender != ServerInfo_User::Female)) + gender = ServerInfo_User::GenderUnknown; + + int key = gender * 100000 + height; + if (pmCache.contains(key)) + return pmCache.value(key); + + QString genderStr; + switch (gender) { + case ServerInfo_User::Male: genderStr = "male"; break; + case ServerInfo_User::Female: genderStr = "female"; break; + default: genderStr = "unknown"; + }; + + QSvgRenderer svg(QString(":/resources/genders/" + genderStr + ".svg")); + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + + pmCache.insert(key, pixmap); + return pixmap; } QMap GenderPixmapGenerator::pmCache; QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode) { - if (countryCode.size() != 2) - return QPixmap(); - QString key = countryCode + QString::number(height); - if (pmCache.contains(key)) - return pmCache.value(key); - - QSvgRenderer svg(QString(":/resources/countries/" + countryCode + ".svg")); - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - painter.setPen(Qt::black); - painter.drawRect(0, 0, width - 1, height - 1); - - pmCache.insert(key, pixmap); - return pixmap; + if (countryCode.size() != 2) + return QPixmap(); + QString key = countryCode + QString::number(height); + if (pmCache.contains(key)) + return pmCache.value(key); + + QSvgRenderer svg(QString(":/resources/countries/" + countryCode + ".svg")); + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + painter.setPen(Qt::black); + painter.drawRect(0, 0, width - 1, height - 1); + + pmCache.insert(key, pixmap); + return pixmap; } QMap CountryPixmapGenerator::pmCache; QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel) { - int key = height * 10000 + (int) userLevel; - if (pmCache.contains(key)) - return pmCache.value(key); - - QString levelString; - if (userLevel.testFlag(ServerInfo_User::IsAdmin)) - levelString = "admin"; - else if (userLevel.testFlag(ServerInfo_User::IsModerator)) - levelString = "moderator"; - else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) - levelString = "registered"; - else - levelString = "normal"; - QSvgRenderer svg(QString(":/resources/userlevels/" + levelString + ".svg")); - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - - pmCache.insert(key, pixmap); - return pixmap; + int key = height * 10000 + (int) userLevel; + if (pmCache.contains(key)) + return pmCache.value(key); + + QString levelString; + if (userLevel.testFlag(ServerInfo_User::IsAdmin)) + levelString = "admin"; + else if (userLevel.testFlag(ServerInfo_User::IsModerator)) + levelString = "moderator"; + else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) + levelString = "registered"; + else + levelString = "normal"; + QSvgRenderer svg(QString(":/resources/userlevels/" + levelString + ".svg")); + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + + pmCache.insert(key, pixmap); + return pixmap; } QMap UserLevelPixmapGenerator::pmCache; diff --git a/cockatrice/src/pixmapgenerator.h b/cockatrice/src/pixmapgenerator.h index b371bd91..67a8b2b2 100644 --- a/cockatrice/src/pixmapgenerator.h +++ b/cockatrice/src/pixmapgenerator.h @@ -8,50 +8,50 @@ class PhasePixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int size, QString name); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int size, QString name); + static void clear() { pmCache.clear(); } }; class CounterPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int size, QString name, bool highlight); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int size, QString name, bool highlight); + static void clear() { pmCache.clear(); } }; class PingPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int size, int value, int max); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int size, int value, int max); + static void clear() { pmCache.clear(); } }; class GenderPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int height, int gender); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int height, int gender); + static void clear() { pmCache.clear(); } }; class CountryPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int height, const QString &countryCode); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int height, const QString &countryCode); + static void clear() { pmCache.clear(); } }; class UserLevelPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int height, UserLevelFlags userLevel); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int height, UserLevelFlags userLevel); + static void clear() { pmCache.clear(); } }; #endif diff --git a/cockatrice/src/player.h b/cockatrice/src/player.h index f55d0fd7..9eed7c07 100644 --- a/cockatrice/src/player.h +++ b/cockatrice/src/player.h @@ -57,246 +57,246 @@ class Event_ChangeZoneProperties; class PendingCommand; class PlayerArea : public QObject, public QGraphicsItem { - Q_OBJECT -private: - QBrush bgPixmapBrush; - QRectF bRect; + Q_OBJECT +private: + QBrush bgPixmapBrush; + QRectF bRect; private slots: - void updateBgPixmap(); + void updateBgPixmap(); public: - enum { Type = typeOther }; - int type() const { return Type; } - - PlayerArea(QGraphicsItem *parent = 0); - QRectF boundingRect() const { return bRect; } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - void setSize(qreal width, qreal height); + enum { Type = typeOther }; + int type() const { return Type; } + + PlayerArea(QGraphicsItem *parent = 0); + QRectF boundingRect() const { return bRect; } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + void setSize(qreal width, qreal height); }; class Player : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT signals: - void openDeckEditor(const DeckLoader *deck); - void newCardAdded(AbstractCardItem *card); - // Log events - void logSay(Player *player, QString message); - void logShuffle(Player *player, CardZone *zone); - void logRollDie(Player *player, int sides, int roll); - void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool _playerTarget); - void logCreateToken(Player *player, QString cardName, QString pt); - void logDrawCards(Player *player, int number); - void logUndoDraw(Player *player, QString cardName); - void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); - void logFlipCard(Player *player, QString cardName, bool faceDown); - void logDestroyCard(Player *player, QString cardName); - void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); - void logUnattachCard(Player *player, QString cardName); - void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); - void logSetTapped(Player *player, CardItem *card, bool tapped); - void logSetCounter(Player *player, QString counterName, int value, int oldValue); - void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); - void logSetPT(Player *player, CardItem *card, QString newPT); - void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); - void logDumpZone(Player *player, CardZone *zone, int numberCards); - void logStopDumpZone(Player *player, CardZone *zone); - void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); - void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); - - void sizeChanged(); - void gameConceded(); + void openDeckEditor(const DeckLoader *deck); + void newCardAdded(AbstractCardItem *card); + // Log events + void logSay(Player *player, QString message); + void logShuffle(Player *player, CardZone *zone); + void logRollDie(Player *player, int sides, int roll); + void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool _playerTarget); + void logCreateToken(Player *player, QString cardName, QString pt); + void logDrawCards(Player *player, int number); + void logUndoDraw(Player *player, QString cardName); + void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); + void logFlipCard(Player *player, QString cardName, bool faceDown); + void logDestroyCard(Player *player, QString cardName); + void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); + void logUnattachCard(Player *player, QString cardName); + void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); + void logSetTapped(Player *player, CardItem *card, bool tapped); + void logSetCounter(Player *player, QString counterName, int value, int oldValue); + void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); + void logSetPT(Player *player, CardItem *card, QString newPT); + void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); + void logDumpZone(Player *player, CardZone *zone, int numberCards); + void logStopDumpZone(Player *player, CardZone *zone); + void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); + void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); + + void sizeChanged(); + void gameConceded(); public slots: - void actUntapAll(); - void actRollDie(); - void actCreateToken(); - void actCreateAnotherToken(); - void actShuffle(); - void actDrawCard(); - void actDrawCards(); - void actUndoDraw(); + void actUntapAll(); + void actRollDie(); + void actCreateToken(); + void actCreateAnotherToken(); + void actShuffle(); + void actDrawCard(); + void actDrawCards(); + void actUndoDraw(); void actMulligan(); - void actMoveTopCardsToGrave(); - void actMoveTopCardsToExile(); - void actMoveTopCardToBottom(); + void actMoveTopCardsToGrave(); + void actMoveTopCardsToExile(); + void actMoveTopCardToBottom(); - void actViewLibrary(); - void actViewTopCards(); - void actAlwaysRevealTopCard(); - void actViewGraveyard(); - void actViewRfg(); - void actViewSideboard(); - - void actSayMessage(); + void actViewLibrary(); + void actViewTopCards(); + void actAlwaysRevealTopCard(); + void actViewGraveyard(); + void actViewRfg(); + void actViewSideboard(); + + void actSayMessage(); private slots: - void addPlayer(Player *player); - void removePlayer(Player *player); - void playerListActionTriggered(); - - void updateBoundingRect(); - void rearrangeZones(); - - void actOpenDeckInDeckEditor(); - void actCreatePredefinedToken(); - void cardMenuAction(); - void actCardCounterTrigger(); - void actAttach(); - void actUnattach(); - void actDrawArrow(); - void actIncPT(int deltaP, int deltaT); - void actSetPT(); - void actIncP(); - void actDecP(); - void actIncT(); - void actDecT(); - void actIncPT(); - void actDecPT(); - void actSetAnnotation(); - void actPlay(); - void actHide(); + void addPlayer(Player *player); + void removePlayer(Player *player); + void playerListActionTriggered(); + + void updateBoundingRect(); + void rearrangeZones(); + + void actOpenDeckInDeckEditor(); + void actCreatePredefinedToken(); + void cardMenuAction(); + void actCardCounterTrigger(); + void actAttach(); + void actUnattach(); + void actDrawArrow(); + void actIncPT(int deltaP, int deltaT); + void actSetPT(); + void actIncP(); + void actDecP(); + void actIncT(); + void actDecT(); + void actIncPT(); + void actDecPT(); + void actSetAnnotation(); + void actPlay(); + void actHide(); private: - TabGame *game; - QMenu *playerMenu, *handMenu, *graveMenu, *rfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu, - *mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard; - QList playerLists; - QList allPlayersActions; - QAction *aMoveHandToTopLibrary, *aMoveHandToBottomLibrary, *aMoveHandToGrave, *aMoveHandToRfg, - *aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg, - *aMoveRfgToTopLibrary, *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave, - *aViewLibrary, *aViewTopCards, *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, *aMoveTopCardToBottom, - *aViewGraveyard, *aViewRfg, *aViewSideboard, + TabGame *game; + QMenu *playerMenu, *handMenu, *graveMenu, *rfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu, + *mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard; + QList playerLists; + QList allPlayersActions; + QAction *aMoveHandToTopLibrary, *aMoveHandToBottomLibrary, *aMoveHandToGrave, *aMoveHandToRfg, + *aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg, + *aMoveRfgToTopLibrary, *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave, + *aViewLibrary, *aViewTopCards, *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, *aMoveTopCardToBottom, + *aViewGraveyard, *aViewRfg, *aViewSideboard, *aDrawCard, *aDrawCards, *aUndoDraw, *aMulligan, *aShuffle, - *aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken, - *aCardMenu; - - QList aAddCounter, aSetCounter, aRemoveCounter; - QAction *aPlay, - *aHide, - *aTap, *aUntap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone, - *aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToGraveyard, *aMoveToExile; + *aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken, + *aCardMenu; + + QList aAddCounter, aSetCounter, aRemoveCounter; + QAction *aPlay, + *aHide, + *aTap, *aUntap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone, + *aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToGraveyard, *aMoveToExile; - bool shortcutsActive; - int defaultNumberTopCards; - QString lastTokenName, lastTokenColor, lastTokenPT, lastTokenAnnotation; - bool lastTokenDestroy; - ServerInfo_User *userInfo; - int id; - bool active; - bool local; - bool mirrored; - bool handVisible; - bool conceded; - - bool dialogSemaphore; - bool clearCardsToDelete(); - QList cardsToDelete; - - DeckLoader *deck; - QStringList predefinedTokens; - - PlayerArea *playerArea; - QMap zones; - StackZone *stack; - TableZone *table; - HandZone *hand; - PlayerTarget *playerTarget; - - void setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards); + bool shortcutsActive; + int defaultNumberTopCards; + QString lastTokenName, lastTokenColor, lastTokenPT, lastTokenAnnotation; + bool lastTokenDestroy; + ServerInfo_User *userInfo; + int id; + bool active; + bool local; + bool mirrored; + bool handVisible; + bool conceded; + + bool dialogSemaphore; + bool clearCardsToDelete(); + QList cardsToDelete; + + DeckLoader *deck; + QStringList predefinedTokens; + + PlayerArea *playerArea; + QMap zones; + StackZone *stack; + TableZone *table; + HandZone *hand; + PlayerTarget *playerTarget; + + void setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards); - QRectF bRect; + QRectF bRect; - QMap counters; - QMap arrows; - void rearrangeCounters(); - - void initSayMenu(); - - void eventConnectionStateChanged(const Event_ConnectionStateChanged &event); - void eventGameSay(const Event_GameSay &event); - void eventShuffle(const Event_Shuffle &event); - void eventRollDie(const Event_RollDie &event); - void eventCreateArrow(const Event_CreateArrow &event); - void eventDeleteArrow(const Event_DeleteArrow &event); - void eventCreateToken(const Event_CreateToken &event); - void eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context); - void eventSetCardCounter(const Event_SetCardCounter &event); - void eventCreateCounter(const Event_CreateCounter &event); - void eventSetCounter(const Event_SetCounter &event); - void eventDelCounter(const Event_DelCounter &event); - void eventDumpZone(const Event_DumpZone &event); - void eventStopDumpZone(const Event_StopDumpZone &event); - void eventMoveCard(const Event_MoveCard &event, const GameEventContext &context); - void eventFlipCard(const Event_FlipCard &event); - void eventDestroyCard(const Event_DestroyCard &event); - void eventAttachCard(const Event_AttachCard &event); - void eventDrawCards(const Event_DrawCards &event); - void eventRevealCards(const Event_RevealCards &event); - void eventChangeZoneProperties(const Event_ChangeZoneProperties &event); + QMap counters; + QMap arrows; + void rearrangeCounters(); + + void initSayMenu(); + + void eventConnectionStateChanged(const Event_ConnectionStateChanged &event); + void eventGameSay(const Event_GameSay &event); + void eventShuffle(const Event_Shuffle &event); + void eventRollDie(const Event_RollDie &event); + void eventCreateArrow(const Event_CreateArrow &event); + void eventDeleteArrow(const Event_DeleteArrow &event); + void eventCreateToken(const Event_CreateToken &event); + void eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context); + void eventSetCardCounter(const Event_SetCardCounter &event); + void eventCreateCounter(const Event_CreateCounter &event); + void eventSetCounter(const Event_SetCounter &event); + void eventDelCounter(const Event_DelCounter &event); + void eventDumpZone(const Event_DumpZone &event); + void eventStopDumpZone(const Event_StopDumpZone &event); + void eventMoveCard(const Event_MoveCard &event, const GameEventContext &context); + void eventFlipCard(const Event_FlipCard &event); + void eventDestroyCard(const Event_DestroyCard &event); + void eventAttachCard(const Event_AttachCard &event); + void eventDrawCards(const Event_DrawCards &event); + void eventRevealCards(const Event_RevealCards &event); + void eventChangeZoneProperties(const Event_ChangeZoneProperties &event); public: - static const int counterAreaWidth = 55; - enum CardMenuActionType { cmTap, cmUntap, cmDoesntUntap, cmFlip, cmPeek, cmClone, cmMoveToTopLibrary, cmMoveToBottomLibrary, cmMoveToGraveyard, cmMoveToExile }; - - enum { Type = typeOther }; - int type() const { return Type; } - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - void playCard(CardItem *c, bool faceDown, bool tapped); - void addCard(CardItem *c); - void deleteCard(CardItem *c); - void addZone(CardZone *z); + static const int counterAreaWidth = 55; + enum CardMenuActionType { cmTap, cmUntap, cmDoesntUntap, cmFlip, cmPeek, cmClone, cmMoveToTopLibrary, cmMoveToBottomLibrary, cmMoveToGraveyard, cmMoveToExile }; + + enum { Type = typeOther }; + int type() const { return Type; } + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + void playCard(CardItem *c, bool faceDown, bool tapped); + void addCard(CardItem *c); + void deleteCard(CardItem *c); + void addZone(CardZone *z); - AbstractCounter *addCounter(const ServerInfo_Counter &counter); - AbstractCounter *addCounter(int counterId, const QString &name, QColor color, int radius, int value); - void delCounter(int counterId); - void clearCounters(); - - ArrowItem *addArrow(const ServerInfo_Arrow &arrow); - ArrowItem *addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color); - void delArrow(int arrowId); - void removeArrow(ArrowItem *arrow); - void clearArrows(); - PlayerTarget *getPlayerTarget() const { return playerTarget; } + AbstractCounter *addCounter(const ServerInfo_Counter &counter); + AbstractCounter *addCounter(int counterId, const QString &name, QColor color, int radius, int value); + void delCounter(int counterId); + void clearCounters(); + + ArrowItem *addArrow(const ServerInfo_Arrow &arrow); + ArrowItem *addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color); + void delArrow(int arrowId); + void removeArrow(ArrowItem *arrow); + void clearArrows(); + PlayerTarget *getPlayerTarget() const { return playerTarget; } - Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent); - ~Player(); - void retranslateUi(); - void clear(); - TabGame *getGame() const { return game; } - void setDeck(const DeckLoader &_deck); - QMenu *getPlayerMenu() const { return playerMenu; } - int getId() const { return id; } - QString getName() const; - ServerInfo_User *getUserInfo() const { return userInfo; } - bool getLocal() const { return local; } - bool getMirrored() const { return mirrored; } - const QMap &getZones() const { return zones; } - const QMap &getArrows() const { return arrows; } - void setCardMenu(QMenu *menu); - QMenu *getCardMenu() const; - void updateCardMenu(CardItem *card); - bool getActive() const { return active; } - void setActive(bool _active); - void setShortcutsActive(); - void setShortcutsInactive(); - void updateZones(); - - void setConceded(bool _conceded); - bool getConceded() const { return conceded; } - - qreal getMinimumWidth() const; - void setMirrored(bool _mirrored); - void processSceneSizeChange(int newPlayerWidth); - - void processPlayerInfo(const ServerInfo_Player &info); - void processCardAttachment(const ServerInfo_Player &info); - - void processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context); + Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent); + ~Player(); + void retranslateUi(); + void clear(); + TabGame *getGame() const { return game; } + void setDeck(const DeckLoader &_deck); + QMenu *getPlayerMenu() const { return playerMenu; } + int getId() const { return id; } + QString getName() const; + ServerInfo_User *getUserInfo() const { return userInfo; } + bool getLocal() const { return local; } + bool getMirrored() const { return mirrored; } + const QMap &getZones() const { return zones; } + const QMap &getArrows() const { return arrows; } + void setCardMenu(QMenu *menu); + QMenu *getCardMenu() const; + void updateCardMenu(CardItem *card); + bool getActive() const { return active; } + void setActive(bool _active); + void setShortcutsActive(); + void setShortcutsInactive(); + void updateZones(); + + void setConceded(bool _conceded); + bool getConceded() const { return conceded; } + + qreal getMinimumWidth() const; + void setMirrored(bool _mirrored); + void processSceneSizeChange(int newPlayerWidth); + + void processPlayerInfo(const ServerInfo_Player &info); + void processCardAttachment(const ServerInfo_Player &info); + + void processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context); - PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); - PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); - void sendGameCommand(PendingCommand *pend); - void sendGameCommand(const google::protobuf::Message &command); + PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); + PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); + void sendGameCommand(PendingCommand *pend); + void sendGameCommand(const google::protobuf::Message &command); }; #endif diff --git a/cockatrice/src/playerlistwidget.cpp b/cockatrice/src/playerlistwidget.cpp index 9c706ac9..f299cda9 100644 --- a/cockatrice/src/playerlistwidget.cpp +++ b/cockatrice/src/playerlistwidget.cpp @@ -17,63 +17,63 @@ #include "pb/serverinfo_playerproperties.pb.h" PlayerListItemDelegate::PlayerListItemDelegate(QObject *const parent) - : QStyledItemDelegate(parent) + : QStyledItemDelegate(parent) { } bool PlayerListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { - if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { - QMouseEvent *const mouseEvent = static_cast(event); - if (mouseEvent->button() == Qt::RightButton) { - static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); - return true; - } - } - return QStyledItemDelegate::editorEvent(event, model, option, index); + if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { + QMouseEvent *const mouseEvent = static_cast(event); + if (mouseEvent->button() == Qt::RightButton) { + static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); + return true; + } + } + return QStyledItemDelegate::editorEvent(event, model, option, index); } PlayerListTWI::PlayerListTWI() - : QTreeWidgetItem(Type) + : QTreeWidgetItem(Type) { } bool PlayerListTWI::operator<(const QTreeWidgetItem &other) const { - // Sort by spectator/player - if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole)) - return data(1, Qt::UserRole).toBool(); - - // Sort by player ID - return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt(); + // Sort by spectator/player + if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole)) + return data(1, Qt::UserRole).toBool(); + + // Sort by player ID + return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt(); } PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent) - : QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false) + : QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false) { - readyIcon = QIcon(":/resources/icon_ready_start.svg"); - notReadyIcon = QIcon(":/resources/icon_not_ready_start.svg"); - concededIcon = QIcon(":/resources/icon_conceded.svg"); - playerIcon = QIcon(":/resources/icon_player.svg"); - spectatorIcon = QIcon(":/resources/icon_spectator.svg"); - lockIcon = QIcon(":/resources/lock.svg"); - - if (tabSupervisor) { - itemDelegate = new PlayerListItemDelegate(this); - setItemDelegate(itemDelegate); - - userContextMenu = new UserContextMenu(tabSupervisor, this, game); - connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - } else - userContextMenu = 0; - - setMinimumHeight(60); - setIconSize(QSize(20, 15)); - setColumnCount(6); - setHeaderHidden(true); - setRootIsDecorated(false); - header()->setResizeMode(QHeaderView::ResizeToContents); - retranslateUi(); + readyIcon = QIcon(":/resources/icon_ready_start.svg"); + notReadyIcon = QIcon(":/resources/icon_not_ready_start.svg"); + concededIcon = QIcon(":/resources/icon_conceded.svg"); + playerIcon = QIcon(":/resources/icon_player.svg"); + spectatorIcon = QIcon(":/resources/icon_spectator.svg"); + lockIcon = QIcon(":/resources/lock.svg"); + + if (tabSupervisor) { + itemDelegate = new PlayerListItemDelegate(this); + setItemDelegate(itemDelegate); + + userContextMenu = new UserContextMenu(tabSupervisor, this, game); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + } else + userContextMenu = 0; + + setMinimumHeight(60); + setIconSize(QSize(20, 15)); + setColumnCount(6); + setHeaderHidden(true); + setRootIsDecorated(false); + header()->setResizeMode(QHeaderView::ResizeToContents); + retranslateUi(); } void PlayerListWidget::retranslateUi() @@ -82,97 +82,97 @@ void PlayerListWidget::retranslateUi() void PlayerListWidget::addPlayer(const ServerInfo_PlayerProperties &player) { - QTreeWidgetItem *newPlayer = new PlayerListTWI; - players.insert(player.player_id(), newPlayer); - updatePlayerProperties(player); - addTopLevelItem(newPlayer); - sortItems(1, Qt::AscendingOrder); + QTreeWidgetItem *newPlayer = new PlayerListTWI; + players.insert(player.player_id(), newPlayer); + updatePlayerProperties(player); + addTopLevelItem(newPlayer); + sortItems(1, Qt::AscendingOrder); } void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId) { - if (playerId == -1) - playerId = prop.player_id(); - - QTreeWidgetItem *player = players.value(playerId, 0); - if (!player) - return; - - if (prop.has_spectator()) { - player->setIcon(1, prop.spectator() ? spectatorIcon : playerIcon); - player->setData(1, Qt::UserRole, !prop.spectator()); - } - if (prop.has_conceded()) - player->setData(2, Qt::UserRole, prop.conceded()); - if (prop.has_ready_start()) - player->setData(2, Qt::UserRole + 1, prop.ready_start()); - if (prop.has_conceded() || prop.has_ready_start()) - player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon()) : (prop.ready_start() ? readyIcon : notReadyIcon)); - if (prop.has_user_info()) { - player->setData(3, Qt::UserRole, prop.user_info().user_level()); - player->setIcon(3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level())))); - player->setText(4, QString::fromStdString(prop.user_info().name())); - const QString country = QString::fromStdString(prop.user_info().country()); - if (!country.isEmpty()) - player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country))); - player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name())); - } - if (prop.has_player_id()) - player->setData(4, Qt::UserRole + 1, prop.player_id()); - if (prop.has_deck_hash()) - player->setText(5, QString::fromStdString(prop.deck_hash())); - if (prop.has_sideboard_locked()) - player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon()); - if (prop.has_ping_seconds()) - player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10))); + if (playerId == -1) + playerId = prop.player_id(); + + QTreeWidgetItem *player = players.value(playerId, 0); + if (!player) + return; + + if (prop.has_spectator()) { + player->setIcon(1, prop.spectator() ? spectatorIcon : playerIcon); + player->setData(1, Qt::UserRole, !prop.spectator()); + } + if (prop.has_conceded()) + player->setData(2, Qt::UserRole, prop.conceded()); + if (prop.has_ready_start()) + player->setData(2, Qt::UserRole + 1, prop.ready_start()); + if (prop.has_conceded() || prop.has_ready_start()) + player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon()) : (prop.ready_start() ? readyIcon : notReadyIcon)); + if (prop.has_user_info()) { + player->setData(3, Qt::UserRole, prop.user_info().user_level()); + player->setIcon(3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level())))); + player->setText(4, QString::fromStdString(prop.user_info().name())); + const QString country = QString::fromStdString(prop.user_info().country()); + if (!country.isEmpty()) + player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country))); + player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name())); + } + if (prop.has_player_id()) + player->setData(4, Qt::UserRole + 1, prop.player_id()); + if (prop.has_deck_hash()) + player->setText(5, QString::fromStdString(prop.deck_hash())); + if (prop.has_sideboard_locked()) + player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon()); + if (prop.has_ping_seconds()) + player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10))); } void PlayerListWidget::removePlayer(int playerId) { - QTreeWidgetItem *player = players.value(playerId, 0); - if (!player) - return; - players.remove(playerId); - delete takeTopLevelItem(indexOfTopLevelItem(player)); + QTreeWidgetItem *player = players.value(playerId, 0); + if (!player) + return; + players.remove(playerId); + delete takeTopLevelItem(indexOfTopLevelItem(player)); } void PlayerListWidget::setActivePlayer(int playerId) { - QMapIterator i(players); - while (i.hasNext()) { - i.next(); - QTreeWidgetItem *twi = i.value(); - QColor c = i.key() == playerId ? QColor(150, 255, 150) : Qt::white; - twi->setBackground(4, c); - } + QMapIterator i(players); + while (i.hasNext()) { + i.next(); + QTreeWidgetItem *twi = i.value(); + QColor c = i.key() == playerId ? QColor(150, 255, 150) : Qt::white; + twi->setBackground(4, c); + } } void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming) { - gameStarted = _gameStarted; - QMapIterator i(players); - while (i.hasNext()) { - QTreeWidgetItem *twi = i.next().value(); - if (gameStarted) { - if (resuming) - twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon()); - else { - twi->setData(2, Qt::UserRole, false); - twi->setIcon(2, QIcon()); - } - } else - twi->setIcon(2, notReadyIcon); - } + gameStarted = _gameStarted; + QMapIterator i(players); + while (i.hasNext()) { + QTreeWidgetItem *twi = i.next().value(); + if (gameStarted) { + if (resuming) + twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon()); + else { + twi->setData(2, Qt::UserRole, false); + twi->setIcon(2, QIcon()); + } + } else + twi->setIcon(2, notReadyIcon); + } } void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index) { - if (!userContextMenu) - return; - - const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString(); - int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt(); - UserLevelFlags userLevel(index.sibling(index.row(), 3).data(Qt::UserRole).toInt()); - - userContextMenu->showContextMenu(pos, userName, userLevel, playerId); + if (!userContextMenu) + return; + + const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString(); + int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt(); + UserLevelFlags userLevel(index.sibling(index.row(), 3).data(Qt::UserRole).toInt()); + + userContextMenu->showContextMenu(pos, userName, userLevel, playerId); } diff --git a/cockatrice/src/playerlistwidget.h b/cockatrice/src/playerlistwidget.h index c07799af..ff932ce7 100644 --- a/cockatrice/src/playerlistwidget.h +++ b/cockatrice/src/playerlistwidget.h @@ -14,38 +14,38 @@ class UserContextMenu; class PlayerListItemDelegate : public QStyledItemDelegate { public: - PlayerListItemDelegate(QObject *const parent); - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); + PlayerListItemDelegate(QObject *const parent); + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; class PlayerListTWI : public QTreeWidgetItem { public: - PlayerListTWI(); - bool operator<(const QTreeWidgetItem &other) const; + PlayerListTWI(); + bool operator<(const QTreeWidgetItem &other) const; }; class PlayerListWidget : public QTreeWidget { - Q_OBJECT + Q_OBJECT private: - PlayerListItemDelegate *itemDelegate; - QMap players; - TabSupervisor *tabSupervisor; - AbstractClient *client; - TabGame *game; - UserContextMenu *userContextMenu; - QIcon readyIcon, notReadyIcon, concededIcon, playerIcon, spectatorIcon, lockIcon; - bool gameStarted; + PlayerListItemDelegate *itemDelegate; + QMap players; + TabSupervisor *tabSupervisor; + AbstractClient *client; + TabGame *game; + UserContextMenu *userContextMenu; + QIcon readyIcon, notReadyIcon, concededIcon, playerIcon, spectatorIcon, lockIcon; + bool gameStarted; signals: - void openMessageDialog(const QString &userName, bool focus); + void openMessageDialog(const QString &userName, bool focus); public: - PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0); - void retranslateUi(); - void addPlayer(const ServerInfo_PlayerProperties &player); - void removePlayer(int playerId); - void setActivePlayer(int playerId); - void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1); - void setGameStarted(bool _gameStarted, bool resuming); - void showContextMenu(const QPoint &pos, const QModelIndex &index); + PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0); + void retranslateUi(); + void addPlayer(const ServerInfo_PlayerProperties &player); + void removePlayer(int playerId); + void setActivePlayer(int playerId); + void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1); + void setGameStarted(bool _gameStarted, bool resuming); + void showContextMenu(const QPoint &pos, const QModelIndex &index); }; #endif diff --git a/cockatrice/src/playertarget.cpp b/cockatrice/src/playertarget.cpp index 6e21fa65..eb18a332 100644 --- a/cockatrice/src/playertarget.cpp +++ b/cockatrice/src/playertarget.cpp @@ -8,149 +8,149 @@ #include PlayerCounter::PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent) - : AbstractCounter(_player, _id, _name, false, _value, parent) + : AbstractCounter(_player, _id, _name, false, _value, parent) { } QRectF PlayerCounter::boundingRect() const { - return QRectF(0, 0, 50, 30); + return QRectF(0, 0, 50, 30); } void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - const int radius = 8; - const qreal border = 1; - QPainterPath path(QPointF(50 - border / 2, border / 2)); - path.lineTo(radius, border / 2); - path.arcTo(border / 2, border / 2, 2 * radius, 2 * radius, 90, 90); - path.lineTo(border / 2, 30 - border / 2); - path.lineTo(50 - border / 2, 30 - border / 2); - path.closeSubpath(); - - QPen pen(QColor(100, 100, 100)); - pen.setWidth(border); - painter->setPen(pen); - painter->setBrush(hovered ? QColor(50, 50, 50, 160) : QColor(0, 0, 0, 160)); - - painter->drawPath(path); + const int radius = 8; + const qreal border = 1; + QPainterPath path(QPointF(50 - border / 2, border / 2)); + path.lineTo(radius, border / 2); + path.arcTo(border / 2, border / 2, 2 * radius, 2 * radius, 90, 90); + path.lineTo(border / 2, 30 - border / 2); + path.lineTo(50 - border / 2, 30 - border / 2); + path.closeSubpath(); + + QPen pen(QColor(100, 100, 100)); + pen.setWidth(border); + painter->setPen(pen); + painter->setBrush(hovered ? QColor(50, 50, 50, 160) : QColor(0, 0, 0, 160)); + + painter->drawPath(path); - QRectF translatedRect = painter->combinedTransform().mapRect(boundingRect()); - QSize translatedSize = translatedRect.size().toSize(); - painter->resetTransform(); - QFont font("Serif"); - font.setWeight(QFont::Bold); - font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9)); - painter->setFont(font); - painter->setPen(Qt::white); - painter->drawText(translatedRect, Qt::AlignCenter, QString::number(value)); + QRectF translatedRect = painter->combinedTransform().mapRect(boundingRect()); + QSize translatedSize = translatedRect.size().toSize(); + painter->resetTransform(); + QFont font("Serif"); + font.setWeight(QFont::Bold); + font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9)); + painter->setFont(font); + painter->setPen(Qt::white); + painter->drawText(translatedRect, Qt::AlignCenter, QString::number(value)); } PlayerTarget::PlayerTarget(Player *_owner, QGraphicsItem *parentItem) - : ArrowTarget(_owner, parentItem), playerCounter(0) + : ArrowTarget(_owner, parentItem), playerCounter(0) { - setCacheMode(DeviceCoordinateCache); - - const std::string &bmp = _owner->getUserInfo()->avatar_bmp(); - if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) - fullPixmap = QPixmap(); + setCacheMode(DeviceCoordinateCache); + + const std::string &bmp = _owner->getUserInfo()->avatar_bmp(); + if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) + fullPixmap = QPixmap(); } PlayerTarget::~PlayerTarget() { - // Explicit deletion is necessary in spite of parent/child relationship - // as we need this object to be alive to receive the destroyed() signal. - delete playerCounter; + // Explicit deletion is necessary in spite of parent/child relationship + // as we need this object to be alive to receive the destroyed() signal. + delete playerCounter; } QRectF PlayerTarget::boundingRect() const { - return QRectF(0, 0, 160, 64); + return QRectF(0, 0, 160, 64); } void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - const ServerInfo_User *const info = owner->getUserInfo(); + const ServerInfo_User *const info = owner->getUserInfo(); - const qreal border = 2; + const qreal border = 2; - QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border); - QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect); - QSize translatedSize = translatedRect.size().toSize(); - QPixmap cachedPixmap; - const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey()); + QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border); + QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect); + QSize translatedSize = translatedRect.size().toSize(); + QPixmap cachedPixmap; + const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey()); #if QT_VERSION >= 0x040600 - if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { + if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { #else - if (!QPixmapCache::find(cacheKey, cachedPixmap)) { + if (!QPixmapCache::find(cacheKey, cachedPixmap)) { #endif - cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); - - QPainter tempPainter(&cachedPixmap); - QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2); - grad.setColorAt(1, Qt::black); - grad.setColorAt(0, QColor(180, 180, 180)); - tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad); - - QPixmap tempPixmap; - if (fullPixmap.isNull()) - tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level())); - else - tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); - QPixmapCache::insert(cacheKey, cachedPixmap); - } - - painter->save(); - painter->resetTransform(); - painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0); - painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect()); - painter->restore(); + cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); + + QPainter tempPainter(&cachedPixmap); + QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2); + grad.setColorAt(1, Qt::black); + grad.setColorAt(0, QColor(180, 180, 180)); + tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad); + + QPixmap tempPixmap; + if (fullPixmap.isNull()) + tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level())); + else + tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); + + tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); + QPixmapCache::insert(cacheKey, cachedPixmap); + } + + painter->save(); + painter->resetTransform(); + painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0); + painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect()); + painter->restore(); - QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20); - painter->fillRect(nameRect, QColor(0, 0, 0, 160)); - QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect); - - painter->save(); - painter->resetTransform(); - - QString name = QString::fromStdString(info->name()); - if (name.size() > 13) - name = name.mid(0, 10) + "..."; - - QFont font; - font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9)); - painter->setFont(font); - painter->setPen(Qt::white); - painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name); - painter->restore(); + QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20); + painter->fillRect(nameRect, QColor(0, 0, 0, 160)); + QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect); + + painter->save(); + painter->resetTransform(); + + QString name = QString::fromStdString(info->name()); + if (name.size() > 13) + name = name.mid(0, 10) + "..."; + + QFont font; + font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9)); + painter->setFont(font); + painter->setPen(Qt::white); + painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name); + painter->restore(); - QPen pen(QColor(100, 100, 100)); - pen.setWidth(border); - pen.setJoinStyle(Qt::RoundJoin); - painter->setPen(pen); - painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); - - if (getBeingPointedAt()) - painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); + QPen pen(QColor(100, 100, 100)); + pen.setWidth(border); + pen.setJoinStyle(Qt::RoundJoin); + painter->setPen(pen); + painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); + + if (getBeingPointedAt()) + painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); } AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value) { - if (playerCounter) { - disconnect(playerCounter, 0, this, 0); - playerCounter->delCounter(); - } + if (playerCounter) { + disconnect(playerCounter, 0, this, 0); + playerCounter->delCounter(); + } - playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); - playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); - connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted())); - - return playerCounter; + playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); + playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); + connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted())); + + return playerCounter; } void PlayerTarget::counterDeleted() { - playerCounter = 0; + playerCounter = 0; } diff --git a/cockatrice/src/playertarget.h b/cockatrice/src/playertarget.h index fa3c3e01..8d36084c 100644 --- a/cockatrice/src/playertarget.h +++ b/cockatrice/src/playertarget.h @@ -9,30 +9,30 @@ class Player; class PlayerCounter : public AbstractCounter { - Q_OBJECT + Q_OBJECT public: - PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; class PlayerTarget : public ArrowTarget { - Q_OBJECT + Q_OBJECT private: - QPixmap fullPixmap; - PlayerCounter *playerCounter; + QPixmap fullPixmap; + PlayerCounter *playerCounter; public slots: - void counterDeleted(); + void counterDeleted(); public: - enum { Type = typePlayerTarget }; - int type() const { return Type; } - - PlayerTarget(Player *_player = 0, QGraphicsItem *parentItem = 0); - ~PlayerTarget(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - AbstractCounter *addCounter(int _counterId, const QString &_name, int _value); + enum { Type = typePlayerTarget }; + int type() const { return Type; } + + PlayerTarget(Player *_player = 0, QGraphicsItem *parentItem = 0); + ~PlayerTarget(); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + AbstractCounter *addCounter(int _counterId, const QString &_name, int _value); }; #endif diff --git a/cockatrice/src/qt-json/json.cpp b/cockatrice/src/qt-json/json.cpp index 6c20a8eb..1cda4453 100644 --- a/cockatrice/src/qt-json/json.cpp +++ b/cockatrice/src/qt-json/json.cpp @@ -131,30 +131,30 @@ QByteArray Json::serialize(const QVariant &data, bool &success) str = "[ " + join( values, ", " ) + " ]"; } - else if(data.type() == QVariant::Hash) // variant is a hash? - { - const QVariantHash vhash = data.toHash(); - QHashIterator it( vhash ); - str = "{ "; - QList pairs; + else if(data.type() == QVariant::Hash) // variant is a hash? + { + const QVariantHash vhash = data.toHash(); + QHashIterator it( vhash ); + str = "{ "; + QList pairs; - while(it.hasNext()) - { - it.next(); - QByteArray serializedValue = serialize(it.value()); + while(it.hasNext()) + { + it.next(); + QByteArray serializedValue = serialize(it.value()); - if(serializedValue.isNull()) - { - success = false; - break; - } + if(serializedValue.isNull()) + { + success = false; + break; + } - pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; - } + pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; + } - str += join(pairs, ", "); - str += " }"; - } + str += join(pairs, ", "); + str += " }"; + } else if(data.type() == QVariant::Map) // variant is a map? { const QVariantMap vmap = data.toMap(); diff --git a/cockatrice/src/remoteclient.cpp b/cockatrice/src/remoteclient.cpp index 3ef2c658..0eae13ab 100644 --- a/cockatrice/src/remoteclient.cpp +++ b/cockatrice/src/remoteclient.cpp @@ -12,220 +12,220 @@ static const unsigned int protocolVersion = 14; RemoteClient::RemoteClient(QObject *parent) - : AbstractClient(parent), timeRunning(0), lastDataReceived(0), messageInProgress(false), handshakeStarted(false), messageLength(0) + : AbstractClient(parent), timeRunning(0), lastDataReceived(0), messageInProgress(false), handshakeStarted(false), messageLength(0) { - timer = new QTimer(this); - timer->setInterval(1000); - connect(timer, SIGNAL(timeout()), this, SLOT(ping())); + timer = new QTimer(this); + timer->setInterval(1000); + connect(timer, SIGNAL(timeout()), this, SLOT(ping())); - socket = new QTcpSocket(this); - socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); - connect(socket, SIGNAL(connected()), this, SLOT(slotConnected())); - connect(socket, SIGNAL(readyRead()), this, SLOT(readData())); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketError(QAbstractSocket::SocketError))); - - connect(this, SIGNAL(serverIdentificationEventReceived(const Event_ServerIdentification &)), this, SLOT(processServerIdentificationEvent(const Event_ServerIdentification &))); - connect(this, SIGNAL(connectionClosedEventReceived(Event_ConnectionClosed)), this, SLOT(processConnectionClosedEvent(Event_ConnectionClosed))); - connect(this, SIGNAL(sigConnectToServer(QString, unsigned int, QString, QString)), this, SLOT(doConnectToServer(QString, unsigned int, QString, QString))); - connect(this, SIGNAL(sigDisconnectFromServer()), this, SLOT(doDisconnectFromServer())); + socket = new QTcpSocket(this); + socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); + connect(socket, SIGNAL(connected()), this, SLOT(slotConnected())); + connect(socket, SIGNAL(readyRead()), this, SLOT(readData())); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketError(QAbstractSocket::SocketError))); + + connect(this, SIGNAL(serverIdentificationEventReceived(const Event_ServerIdentification &)), this, SLOT(processServerIdentificationEvent(const Event_ServerIdentification &))); + connect(this, SIGNAL(connectionClosedEventReceived(Event_ConnectionClosed)), this, SLOT(processConnectionClosedEvent(Event_ConnectionClosed))); + connect(this, SIGNAL(sigConnectToServer(QString, unsigned int, QString, QString)), this, SLOT(doConnectToServer(QString, unsigned int, QString, QString))); + connect(this, SIGNAL(sigDisconnectFromServer()), this, SLOT(doDisconnectFromServer())); } RemoteClient::~RemoteClient() { - doDisconnectFromServer(); - thread()->quit(); + doDisconnectFromServer(); + thread()->quit(); } void RemoteClient::slotSocketError(QAbstractSocket::SocketError /*error*/) { - QString errorString = socket->errorString(); - doDisconnectFromServer(); - emit socketError(errorString); + QString errorString = socket->errorString(); + doDisconnectFromServer(); + emit socketError(errorString); } void RemoteClient::slotConnected() { - timeRunning = lastDataReceived = 0; - timer->start(); - - // dirty hack to be compatible with v14 server - sendCommandContainer(CommandContainer()); - getNewCmdId(); - // end of hack - - setStatus(StatusAwaitingWelcome); + timeRunning = lastDataReceived = 0; + timer->start(); + + // dirty hack to be compatible with v14 server + sendCommandContainer(CommandContainer()); + getNewCmdId(); + // end of hack + + setStatus(StatusAwaitingWelcome); } void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentification &event) { - if (event.protocol_version() != protocolVersion) { - emit protocolVersionMismatch(protocolVersion, event.protocol_version()); - setStatus(StatusDisconnecting); - return; - } - setStatus(StatusLoggingIn); - - Command_Login cmdLogin; - cmdLogin.set_user_name(userName.toStdString()); - cmdLogin.set_password(password.toStdString()); - - PendingCommand *pend = prepareSessionCommand(cmdLogin); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(loginResponse(Response))); - sendCommand(pend); + if (event.protocol_version() != protocolVersion) { + emit protocolVersionMismatch(protocolVersion, event.protocol_version()); + setStatus(StatusDisconnecting); + return; + } + setStatus(StatusLoggingIn); + + Command_Login cmdLogin; + cmdLogin.set_user_name(userName.toStdString()); + cmdLogin.set_password(password.toStdString()); + + PendingCommand *pend = prepareSessionCommand(cmdLogin); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(loginResponse(Response))); + sendCommand(pend); } void RemoteClient::processConnectionClosedEvent(const Event_ConnectionClosed & /*event*/) { - doDisconnectFromServer(); + doDisconnectFromServer(); } void RemoteClient::loginResponse(const Response &response) { - const Response_Login &resp = response.GetExtension(Response_Login::ext); - if (response.response_code() == Response::RespOk) { - setStatus(StatusLoggedIn); - emit userInfoChanged(resp.user_info()); - - QList buddyList; - for (int i = resp.buddy_list_size() - 1; i >= 0; --i) - buddyList.append(resp.buddy_list(i)); - emit buddyListReceived(buddyList); - - QList ignoreList; - for (int i = resp.ignore_list_size() - 1; i >= 0; --i) - ignoreList.append(resp.ignore_list(i)); - emit ignoreListReceived(ignoreList); - } else { - emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time()); - setStatus(StatusDisconnecting); - } + const Response_Login &resp = response.GetExtension(Response_Login::ext); + if (response.response_code() == Response::RespOk) { + setStatus(StatusLoggedIn); + emit userInfoChanged(resp.user_info()); + + QList buddyList; + for (int i = resp.buddy_list_size() - 1; i >= 0; --i) + buddyList.append(resp.buddy_list(i)); + emit buddyListReceived(buddyList); + + QList ignoreList; + for (int i = resp.ignore_list_size() - 1; i >= 0; --i) + ignoreList.append(resp.ignore_list(i)); + emit ignoreListReceived(ignoreList); + } else { + emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time()); + setStatus(StatusDisconnecting); + } } void RemoteClient::readData() { - lastDataReceived = timeRunning; - QByteArray data = socket->readAll(); + lastDataReceived = timeRunning; + QByteArray data = socket->readAll(); - inputBuffer.append(data); - - do { - if (!messageInProgress) { - if (inputBuffer.size() >= 4) { - // dirty hack to be compatible with v14 server that sends 60 bytes of garbage at the beginning - if (!handshakeStarted) { - handshakeStarted = true; - if (inputBuffer.startsWith("= 4) { + // dirty hack to be compatible with v14 server that sends 60 bytes of garbage at the beginning + if (!handshakeStarted) { + handshakeStarted = true; + if (inputBuffer.startsWith("> 8); - buf.data()[1] = (unsigned char) (size >> 16); - buf.data()[0] = (unsigned char) (size >> 24); - - socket->write(buf); + buf.resize(size + 4); + cont.SerializeToArray(buf.data() + 4, size); + buf.data()[3] = (unsigned char) size; + buf.data()[2] = (unsigned char) (size >> 8); + buf.data()[1] = (unsigned char) (size >> 16); + buf.data()[0] = (unsigned char) (size >> 24); + + socket->write(buf); } void RemoteClient::doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password) { - doDisconnectFromServer(); - - userName = _userName; - password = _password; - socket->connectToHost(hostname, port); - setStatus(StatusConnecting); + doDisconnectFromServer(); + + userName = _userName; + password = _password; + socket->connectToHost(hostname, port); + setStatus(StatusConnecting); } void RemoteClient::doDisconnectFromServer() { - timer->stop(); - - messageInProgress = false; - handshakeStarted = false; - messageLength = 0; + timer->stop(); + + messageInProgress = false; + handshakeStarted = false; + messageLength = 0; - QList pc = pendingCommands.values(); - for (int i = 0; i < pc.size(); i++) { - Response response; - response.set_response_code(Response::RespNotConnected); - response.set_cmd_id(pc[i]->getCommandContainer().cmd_id()); - pc[i]->processResponse(response); - - delete pc[i]; - } - pendingCommands.clear(); + QList pc = pendingCommands.values(); + for (int i = 0; i < pc.size(); i++) { + Response response; + response.set_response_code(Response::RespNotConnected); + response.set_cmd_id(pc[i]->getCommandContainer().cmd_id()); + pc[i]->processResponse(response); + + delete pc[i]; + } + pendingCommands.clear(); - setStatus(StatusDisconnected); - socket->close(); + setStatus(StatusDisconnected); + socket->close(); } void RemoteClient::ping() { - QMutableMapIterator i(pendingCommands); - while (i.hasNext()) { - PendingCommand *pend = i.next().value(); - if (pend->tick() > maxTimeout) { - i.remove(); - pend->deleteLater(); - } - } - - int maxTime = timeRunning - lastDataReceived; - emit maxPingTime(maxTime, maxTimeout); - if (maxTime >= maxTimeout) { - disconnectFromServer(); - emit serverTimeout(); - } else { - sendCommand(prepareSessionCommand(Command_Ping())); - ++timeRunning; - } + QMutableMapIterator i(pendingCommands); + while (i.hasNext()) { + PendingCommand *pend = i.next().value(); + if (pend->tick() > maxTimeout) { + i.remove(); + pend->deleteLater(); + } + } + + int maxTime = timeRunning - lastDataReceived; + emit maxPingTime(maxTime, maxTimeout); + if (maxTime >= maxTimeout) { + disconnectFromServer(); + emit serverTimeout(); + } else { + sendCommand(prepareSessionCommand(Command_Ping())); + ++timeRunning; + } } void RemoteClient::connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password) { - emit sigConnectToServer(hostname, port, _userName, _password); + emit sigConnectToServer(hostname, port, _userName, _password); } void RemoteClient::disconnectFromServer() { - emit sigDisconnectFromServer(); + emit sigDisconnectFromServer(); } diff --git a/cockatrice/src/remoteclient.h b/cockatrice/src/remoteclient.h index 19ca26f4..2cb84e90 100644 --- a/cockatrice/src/remoteclient.h +++ b/cockatrice/src/remoteclient.h @@ -7,45 +7,45 @@ class QTimer; class RemoteClient : public AbstractClient { - Q_OBJECT + Q_OBJECT signals: - void maxPingTime(int seconds, int maxSeconds); - void serverTimeout(); - void loginError(Response::ResponseCode resp, QString reasonStr, quint32 endTime); - void socketError(const QString &errorString); - void protocolVersionMismatch(int clientVersion, int serverVersion); - void protocolError(); - void sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void sigDisconnectFromServer(); + void maxPingTime(int seconds, int maxSeconds); + void serverTimeout(); + void loginError(Response::ResponseCode resp, QString reasonStr, quint32 endTime); + void socketError(const QString &errorString); + void protocolVersionMismatch(int clientVersion, int serverVersion); + void protocolError(); + void sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void sigDisconnectFromServer(); private slots: - void slotConnected(); - void readData(); - void slotSocketError(QAbstractSocket::SocketError error); - void ping(); - void processServerIdentificationEvent(const Event_ServerIdentification &event); - void processConnectionClosedEvent(const Event_ConnectionClosed &event); - void loginResponse(const Response &response); - void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void doDisconnectFromServer(); + void slotConnected(); + void readData(); + void slotSocketError(QAbstractSocket::SocketError error); + void ping(); + void processServerIdentificationEvent(const Event_ServerIdentification &event); + void processConnectionClosedEvent(const Event_ConnectionClosed &event); + void loginResponse(const Response &response); + void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void doDisconnectFromServer(); private: - static const int maxTimeout = 10; - int timeRunning, lastDataReceived; + static const int maxTimeout = 10; + int timeRunning, lastDataReceived; - QByteArray inputBuffer; - bool messageInProgress; - bool handshakeStarted; - int messageLength; - - QTimer *timer; - QTcpSocket *socket; -protected slots: - void sendCommandContainer(const CommandContainer &cont); + QByteArray inputBuffer; + bool messageInProgress; + bool handshakeStarted; + int messageLength; + + QTimer *timer; + QTcpSocket *socket; +protected slots: + void sendCommandContainer(const CommandContainer &cont); public: - RemoteClient(QObject *parent = 0); - ~RemoteClient(); - QString peerName() const { return socket->peerName(); } - void connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void disconnectFromServer(); + RemoteClient(QObject *parent = 0); + ~RemoteClient(); + QString peerName() const { return socket->peerName(); } + void connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void disconnectFromServer(); }; #endif diff --git a/cockatrice/src/remotedecklist_treewidget.cpp b/cockatrice/src/remotedecklist_treewidget.cpp index ae1aa294..b72df671 100644 --- a/cockatrice/src/remotedecklist_treewidget.cpp +++ b/cockatrice/src/remotedecklist_treewidget.cpp @@ -10,324 +10,324 @@ #include "pb/serverinfo_deckstorage.pb.h" RemoteDeckList_TreeModel::DirectoryNode::DirectoryNode(const QString &_name, RemoteDeckList_TreeModel::DirectoryNode *_parent) - : RemoteDeckList_TreeModel::Node(_name, _parent) + : RemoteDeckList_TreeModel::Node(_name, _parent) { } RemoteDeckList_TreeModel::DirectoryNode::~DirectoryNode() { - clearTree(); + clearTree(); } void RemoteDeckList_TreeModel::DirectoryNode::clearTree() { - for (int i = 0; i < size(); ++i) - delete at(i); - clear(); + for (int i = 0; i < size(); ++i) + delete at(i); + clear(); } QString RemoteDeckList_TreeModel::DirectoryNode::getPath() const { - if (parent) { - QString parentPath = parent->getPath(); - if (parentPath.isEmpty()) - return name; - else - return parentPath + "/" + name; - } else - return name; + if (parent) { + QString parentPath = parent->getPath(); + if (parentPath.isEmpty()) + return name; + else + return parentPath + "/" + name; + } else + return name; } RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeByPath(QStringList path) { - QString pathItem; - if (parent) { - if (path.isEmpty()) - return this; - pathItem = path.takeFirst(); - if (pathItem.isEmpty() && name.isEmpty()) - return this; - } - - for (int i = 0; i < size(); ++i) { - DirectoryNode *node = dynamic_cast(at(i)); - if (!node) - continue; - if (node->getName() == pathItem) - return node->getNodeByPath(path); - } - return 0; + QString pathItem; + if (parent) { + if (path.isEmpty()) + return this; + pathItem = path.takeFirst(); + if (pathItem.isEmpty() && name.isEmpty()) + return this; + } + + for (int i = 0; i < size(); ++i) { + DirectoryNode *node = dynamic_cast(at(i)); + if (!node) + continue; + if (node->getName() == pathItem) + return node->getNodeByPath(path); + } + return 0; } RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeById(int id) const { - for (int i = 0; i < size(); ++i) { - DirectoryNode *node = dynamic_cast(at(i)); - if (node) { - FileNode *result = node->getNodeById(id); - if (result) - return result; - } else { - FileNode *file = dynamic_cast(at(i)); - if (file->getId() == id) - return file; - } - } - return 0; + for (int i = 0; i < size(); ++i) { + DirectoryNode *node = dynamic_cast(at(i)); + if (node) { + FileNode *result = node->getNodeById(id); + if (result) + return result; + } else { + FileNode *file = dynamic_cast(at(i)); + if (file->getId() == id) + return file; + } + } + return 0; } RemoteDeckList_TreeModel::RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent) - : QAbstractItemModel(parent), client(_client) + : QAbstractItemModel(parent), client(_client) { - QFileIconProvider fip; - dirIcon = fip.icon(QFileIconProvider::Folder); - fileIcon = fip.icon(QFileIconProvider::File); + QFileIconProvider fip; + dirIcon = fip.icon(QFileIconProvider::Folder); + fileIcon = fip.icon(QFileIconProvider::File); - root = new DirectoryNode; - refreshTree(); + root = new DirectoryNode; + refreshTree(); } RemoteDeckList_TreeModel::~RemoteDeckList_TreeModel() { - delete root; + delete root; } int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const { - DirectoryNode *node = getNode(parent); - if (node) - return node->size(); - else - return 0; + DirectoryNode *node = getNode(parent); + if (node) + return node->size(); + else + return 0; } int RemoteDeckList_TreeModel::columnCount(const QModelIndex &/*parent*/) const { - return 3; + return 3; } QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if (index.column() >= 3) - return QVariant(); + if (!index.isValid()) + return QVariant(); + if (index.column() >= 3) + return QVariant(); - Node *temp = static_cast(index.internalPointer()); - FileNode *file = dynamic_cast(temp); - if (!file) { - DirectoryNode *node = dynamic_cast(temp); - switch (role) { - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return node->getName(); - default: - return QVariant(); - } - } - case Qt::DecorationRole: - return index.column() == 0 ? dirIcon : QVariant(); - default: return QVariant(); - } - } else { - switch (role) { - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return file->getName(); - case 1: return file->getId(); - case 2: return file->getUploadTime(); - default: - return QVariant(); - } - } - case Qt::DecorationRole: - return index.column() == 0 ? fileIcon : QVariant(); - case Qt::TextAlignmentRole: - return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft; - default: return QVariant(); - } - } + Node *temp = static_cast(index.internalPointer()); + FileNode *file = dynamic_cast(temp); + if (!file) { + DirectoryNode *node = dynamic_cast(temp); + switch (role) { + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return node->getName(); + default: + return QVariant(); + } + } + case Qt::DecorationRole: + return index.column() == 0 ? dirIcon : QVariant(); + default: return QVariant(); + } + } else { + switch (role) { + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return file->getName(); + case 1: return file->getId(); + case 2: return file->getUploadTime(); + default: + return QVariant(); + } + } + case Qt::DecorationRole: + return index.column() == 0 ? fileIcon : QVariant(); + case Qt::TextAlignmentRole: + return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft; + default: return QVariant(); + } + } } QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation != Qt::Horizontal) - return QVariant(); - switch (role) { - case Qt::TextAlignmentRole: - return section == 1 ? Qt::AlignRight : Qt::AlignLeft; - case Qt::DisplayRole: { - switch (section) { - case 0: return tr("Name"); - case 1: return tr("ID"); - case 2: return tr("Upload time"); - default: return QVariant(); - } - } - default: return QVariant(); - } + if (orientation != Qt::Horizontal) + return QVariant(); + switch (role) { + case Qt::TextAlignmentRole: + return section == 1 ? Qt::AlignRight : Qt::AlignLeft; + case Qt::DisplayRole: { + switch (section) { + case 0: return tr("Name"); + case 1: return tr("ID"); + case 2: return tr("Upload time"); + default: return QVariant(); + } + } + default: return QVariant(); + } } QModelIndex RemoteDeckList_TreeModel::index(int row, int column, const QModelIndex &parent) const { - if (!hasIndex(row, column, parent)) - return QModelIndex(); + if (!hasIndex(row, column, parent)) + return QModelIndex(); - DirectoryNode *parentNode = getNode(parent); - if (row >= parentNode->size()) - return QModelIndex(); + DirectoryNode *parentNode = getNode(parent); + if (row >= parentNode->size()) + return QModelIndex(); - return createIndex(row, column, parentNode->at(row)); + return createIndex(row, column, parentNode->at(row)); } QModelIndex RemoteDeckList_TreeModel::parent(const QModelIndex &ind) const { - if (!ind.isValid()) - return QModelIndex(); + if (!ind.isValid()) + return QModelIndex(); - return nodeToIndex(static_cast(ind.internalPointer())->getParent()); + return nodeToIndex(static_cast(ind.internalPointer())->getParent()); } Qt::ItemFlags RemoteDeckList_TreeModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } QModelIndex RemoteDeckList_TreeModel::nodeToIndex(Node *node) const { - if (node == root) - return QModelIndex(); - return createIndex(node->getParent()->indexOf(node), 0, node); + if (node == root) + return QModelIndex(); + return createIndex(node->getParent()->indexOf(node), 0, node); } void RemoteDeckList_TreeModel::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent) { - const ServerInfo_DeckStorage_File &fileInfo = file.file(); - QDateTime time; - time.setTime_t(fileInfo.creation_time()); - - beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); - parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent)); - endInsertRows(); + const ServerInfo_DeckStorage_File &fileInfo = file.file(); + QDateTime time; + time.setTime_t(fileInfo.creation_time()); + + beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); + parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent)); + endInsertRows(); } void RemoteDeckList_TreeModel::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent) { - DirectoryNode *newItem = addNamedFolderToTree(QString::fromStdString(folder.name()), parent); - const ServerInfo_DeckStorage_Folder &folderInfo = folder.folder(); - const int folderItemsSize = folderInfo.items_size(); - for (int i = 0; i < folderItemsSize; ++i) { - const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i); - if (subItem.has_folder()) - addFolderToTree(subItem, newItem); - else - addFileToTree(subItem, newItem); - } + DirectoryNode *newItem = addNamedFolderToTree(QString::fromStdString(folder.name()), parent); + const ServerInfo_DeckStorage_Folder &folderInfo = folder.folder(); + const int folderItemsSize = folderInfo.items_size(); + for (int i = 0; i < folderItemsSize; ++i) { + const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i); + if (subItem.has_folder()) + addFolderToTree(subItem, newItem); + else + addFileToTree(subItem, newItem); + } } RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::addNamedFolderToTree(const QString &name, DirectoryNode *parent) { - DirectoryNode *newItem = new DirectoryNode(name, parent); - beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); - parent->append(newItem); - endInsertRows(); - return newItem; + DirectoryNode *newItem = new DirectoryNode(name, parent); + beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); + parent->append(newItem); + endInsertRows(); + return newItem; } void RemoteDeckList_TreeModel::removeNode(RemoteDeckList_TreeModel::Node *node) { - int ind = node->getParent()->indexOf(node); - beginRemoveRows(nodeToIndex(node->getParent()), ind, ind); - node->getParent()->removeAt(ind); - endRemoveRows(); - delete node; + int ind = node->getParent()->indexOf(node); + beginRemoveRows(nodeToIndex(node->getParent()), ind, ind); + node->getParent()->removeAt(ind); + endRemoveRows(); + delete node; } void RemoteDeckList_TreeModel::refreshTree() { - PendingCommand *pend = client->prepareSessionCommand(Command_DeckList()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &))); - - client->sendCommand(pend); + PendingCommand *pend = client->prepareSessionCommand(Command_DeckList()); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &))); + + client->sendCommand(pend); } void RemoteDeckList_TreeModel::deckListFinished(const Response &r) { - const Response_DeckList &resp = r.GetExtension(Response_DeckList::ext); + const Response_DeckList &resp = r.GetExtension(Response_DeckList::ext); - root->clearTree(); - reset(); - - ServerInfo_DeckStorage_TreeItem tempRoot; - tempRoot.set_id(0); - tempRoot.mutable_folder()->CopyFrom(resp.root()); - addFolderToTree(tempRoot, root); - - emit treeRefreshed(); + root->clearTree(); + reset(); + + ServerInfo_DeckStorage_TreeItem tempRoot; + tempRoot.set_id(0); + tempRoot.mutable_folder()->CopyFrom(resp.root()); + addFolderToTree(tempRoot, root); + + emit treeRefreshed(); } RemoteDeckList_TreeWidget::RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent) - : QTreeView(parent) + : QTreeView(parent) { - treeModel = new RemoteDeckList_TreeModel(_client, this); - proxyModel = new QSortFilterProxyModel(this); - proxyModel->setSourceModel(treeModel); - proxyModel->setDynamicSortFilter(true); - proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); - setModel(proxyModel); - connect(treeModel, SIGNAL(treeRefreshed()), this, SLOT(expandAll())); + treeModel = new RemoteDeckList_TreeModel(_client, this); + proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(treeModel); + proxyModel->setDynamicSortFilter(true); + proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + setModel(proxyModel); + connect(treeModel, SIGNAL(treeRefreshed()), this, SLOT(expandAll())); - header()->setResizeMode(QHeaderView::ResizeToContents); - setUniformRowHeights(true); - setSortingEnabled(true); - proxyModel->sort(0, Qt::AscendingOrder); - header()->setSortIndicator(0, Qt::AscendingOrder); + header()->setResizeMode(QHeaderView::ResizeToContents); + setUniformRowHeights(true); + setSortingEnabled(true); + proxyModel->sort(0, Qt::AscendingOrder); + header()->setSortIndicator(0, Qt::AscendingOrder); } RemoteDeckList_TreeModel::Node *RemoteDeckList_TreeWidget::getNode(const QModelIndex &ind) const { - return treeModel->getNode(proxyModel->mapToSource(ind)); + return treeModel->getNode(proxyModel->mapToSource(ind)); } RemoteDeckList_TreeModel::Node *RemoteDeckList_TreeWidget::getCurrentItem() const { - return getNode(selectionModel()->currentIndex()); + return getNode(selectionModel()->currentIndex()); } RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeWidget::getNodeByPath(const QString &path) const { - return treeModel->getRoot()->getNodeByPath(path.split("/")); + return treeModel->getRoot()->getNodeByPath(path.split("/")); } RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeWidget::getNodeById(int id) const { - return treeModel->getRoot()->getNodeById(id); + return treeModel->getRoot()->getNodeById(id); } void RemoteDeckList_TreeWidget::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent) { - treeModel->addFileToTree(file, parent); + treeModel->addFileToTree(file, parent); } void RemoteDeckList_TreeWidget::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent) { - treeModel->addFolderToTree(folder, parent); + treeModel->addFolderToTree(folder, parent); } void RemoteDeckList_TreeWidget::addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent) { - treeModel->addNamedFolderToTree(name, parent); + treeModel->addNamedFolderToTree(name, parent); } void RemoteDeckList_TreeWidget::removeNode(RemoteDeckList_TreeModel::Node *node) { - treeModel->removeNode(node); + treeModel->removeNode(node); } void RemoteDeckList_TreeWidget::refreshTree() { - treeModel->refreshTree(); + treeModel->refreshTree(); } diff --git a/cockatrice/src/remotedecklist_treewidget.h b/cockatrice/src/remotedecklist_treewidget.h index 717ffa0c..ecb2ca18 100644 --- a/cockatrice/src/remotedecklist_treewidget.h +++ b/cockatrice/src/remotedecklist_treewidget.h @@ -11,92 +11,92 @@ class QSortFilterProxyModel; class ServerInfo_DeckStorage_TreeItem; class RemoteDeckList_TreeModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT public: - class DirectoryNode; - class FileNode; - class Node { - protected: - DirectoryNode *parent; - QString name; - public: - Node(const QString &_name, DirectoryNode *_parent = 0) - : parent(_parent), name(_name) { } - virtual ~Node() { }; - DirectoryNode *getParent() const { return parent; } - QString getName() const { return name; } - }; - class DirectoryNode : public Node, public QList { - public: - DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0); - ~DirectoryNode(); - void clearTree(); - QString getPath() const; - DirectoryNode *getNodeByPath(QStringList path); - FileNode *getNodeById(int id) const; - }; - class FileNode : public Node { - private: - int id; - QDateTime uploadTime; - public: - FileNode(const QString &_name, int _id, const QDateTime &_uploadTime, DirectoryNode *_parent = 0) - : Node(_name, _parent), id(_id), uploadTime(_uploadTime) { } - int getId() const { return id; } - QDateTime getUploadTime() const { return uploadTime; } - }; - - template T getNode(const QModelIndex &index) const - { - if (!index.isValid()) - return dynamic_cast(root); - return dynamic_cast(static_cast(index.internalPointer())); - } + class DirectoryNode; + class FileNode; + class Node { + protected: + DirectoryNode *parent; + QString name; + public: + Node(const QString &_name, DirectoryNode *_parent = 0) + : parent(_parent), name(_name) { } + virtual ~Node() { }; + DirectoryNode *getParent() const { return parent; } + QString getName() const { return name; } + }; + class DirectoryNode : public Node, public QList { + public: + DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0); + ~DirectoryNode(); + void clearTree(); + QString getPath() const; + DirectoryNode *getNodeByPath(QStringList path); + FileNode *getNodeById(int id) const; + }; + class FileNode : public Node { + private: + int id; + QDateTime uploadTime; + public: + FileNode(const QString &_name, int _id, const QDateTime &_uploadTime, DirectoryNode *_parent = 0) + : Node(_name, _parent), id(_id), uploadTime(_uploadTime) { } + int getId() const { return id; } + QDateTime getUploadTime() const { return uploadTime; } + }; + + template T getNode(const QModelIndex &index) const + { + if (!index.isValid()) + return dynamic_cast(root); + return dynamic_cast(static_cast(index.internalPointer())); + } private: - AbstractClient *client; - DirectoryNode *root; - - QIcon fileIcon, dirIcon; - - QModelIndex nodeToIndex(Node *node) const; + AbstractClient *client; + DirectoryNode *root; + + QIcon fileIcon, dirIcon; + + QModelIndex nodeToIndex(Node *node) const; signals: - void treeRefreshed(); + void treeRefreshed(); private slots: - void deckListFinished(const Response &r); + void deckListFinished(const Response &r); public: - RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent = 0); - ~RemoteDeckList_TreeModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - Qt::ItemFlags flags(const QModelIndex &index) const; + RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent = 0); + ~RemoteDeckList_TreeModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; - DirectoryNode *getRoot() const { return root; } - void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent); - void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent); - DirectoryNode *addNamedFolderToTree(const QString &name, DirectoryNode *parent); - void removeNode(Node *node); - void refreshTree(); + DirectoryNode *getRoot() const { return root; } + void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent); + void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent); + DirectoryNode *addNamedFolderToTree(const QString &name, DirectoryNode *parent); + void removeNode(Node *node); + void refreshTree(); }; class RemoteDeckList_TreeWidget : public QTreeView { private: - RemoteDeckList_TreeModel *treeModel; - QSortFilterProxyModel *proxyModel; + RemoteDeckList_TreeModel *treeModel; + QSortFilterProxyModel *proxyModel; public: - RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); - RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const; - RemoteDeckList_TreeModel::Node *getCurrentItem() const; - RemoteDeckList_TreeModel::DirectoryNode *getNodeByPath(const QString &path) const; - RemoteDeckList_TreeModel::FileNode *getNodeById(int id) const; - void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent); - void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent); - void addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent); - void removeNode(RemoteDeckList_TreeModel::Node *node); - void refreshTree(); + RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); + RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const; + RemoteDeckList_TreeModel::Node *getCurrentItem() const; + RemoteDeckList_TreeModel::DirectoryNode *getNodeByPath(const QString &path) const; + RemoteDeckList_TreeModel::FileNode *getNodeById(int id) const; + void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent); + void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent); + void addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent); + void removeNode(RemoteDeckList_TreeModel::Node *node); + void refreshTree(); }; #endif diff --git a/cockatrice/src/remotereplaylist_treewidget.cpp b/cockatrice/src/remotereplaylist_treewidget.cpp index ed2d823d..6184049e 100644 --- a/cockatrice/src/remotereplaylist_treewidget.cpp +++ b/cockatrice/src/remotereplaylist_treewidget.cpp @@ -12,286 +12,286 @@ const int RemoteReplayList_TreeModel::numberOfColumns = 6; RemoteReplayList_TreeModel::MatchNode::MatchNode(const ServerInfo_ReplayMatch &_matchInfo) - : RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo) + : RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo) { - for (int i = 0; i < matchInfo.replay_list_size(); ++i) - append(new ReplayNode(matchInfo.replay_list(i), this)); + for (int i = 0; i < matchInfo.replay_list_size(); ++i) + append(new ReplayNode(matchInfo.replay_list(i), this)); } RemoteReplayList_TreeModel::MatchNode::~MatchNode() { - for (int i = 0; i < size(); ++i) - delete at(i); + for (int i = 0; i < size(); ++i) + delete at(i); } void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo) { - matchInfo.MergeFrom(_matchInfo); + matchInfo.MergeFrom(_matchInfo); } RemoteReplayList_TreeModel::RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent) - : QAbstractItemModel(parent), client(_client) + : QAbstractItemModel(parent), client(_client) { - QFileIconProvider fip; - dirIcon = fip.icon(QFileIconProvider::Folder); - fileIcon = fip.icon(QFileIconProvider::File); - lockIcon = QIcon(":/resources/lock.svg"); + QFileIconProvider fip; + dirIcon = fip.icon(QFileIconProvider::Folder); + fileIcon = fip.icon(QFileIconProvider::File); + lockIcon = QIcon(":/resources/lock.svg"); - refreshTree(); + refreshTree(); } RemoteReplayList_TreeModel::~RemoteReplayList_TreeModel() { - clearTree(); + clearTree(); } int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const { - if (!parent.isValid()) - return replayMatches.size(); - - MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); - if (matchNode) - return matchNode->size(); - else - return 0; + if (!parent.isValid()) + return replayMatches.size(); + + MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); + if (matchNode) + return matchNode->size(); + else + return 0; } QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if (index.column() >= numberOfColumns) - return QVariant(); - - ReplayNode *replayNode = dynamic_cast(static_cast(index.internalPointer())); - if (replayNode) { - const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo(); - switch (role) { - case Qt::TextAlignmentRole: - return index.column() == 0 ? Qt::AlignRight : Qt::AlignLeft; - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return replayInfo.replay_id(); - case 1: return QString::fromStdString(replayInfo.replay_name()); - case 5: return replayInfo.duration(); - default: return QVariant(); - } - } - case Qt::DecorationRole: - return index.column() == 0 ? fileIcon : QVariant(); - } - } else { - MatchNode *matchNode = dynamic_cast(static_cast(index.internalPointer())); - const ServerInfo_ReplayMatch &matchInfo = matchNode->getMatchInfo(); - switch (role) { - case Qt::TextAlignmentRole: - switch (index.column()) { - case 0: - case 5: - return Qt::AlignRight; - default: - return Qt::AlignLeft; - } - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return matchInfo.game_id(); - case 1: return QString::fromStdString(matchInfo.game_name()); - case 2: { - QStringList playerList; - for (int i = 0; i < matchInfo.player_names_size(); ++i) - playerList.append(QString::fromStdString(matchInfo.player_names(i))); - return playerList.join(", "); - } - case 4: return QDateTime::fromTime_t(matchInfo.time_started()); - case 5: return matchInfo.length(); - default: return QVariant(); - } - } - case Qt::DecorationRole: - switch (index.column()) { - case 0: return dirIcon; - case 3: return matchInfo.do_not_hide() ? lockIcon : QVariant(); - default: return QVariant(); - } - } - } - return QVariant(); + if (!index.isValid()) + return QVariant(); + if (index.column() >= numberOfColumns) + return QVariant(); + + ReplayNode *replayNode = dynamic_cast(static_cast(index.internalPointer())); + if (replayNode) { + const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo(); + switch (role) { + case Qt::TextAlignmentRole: + return index.column() == 0 ? Qt::AlignRight : Qt::AlignLeft; + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return replayInfo.replay_id(); + case 1: return QString::fromStdString(replayInfo.replay_name()); + case 5: return replayInfo.duration(); + default: return QVariant(); + } + } + case Qt::DecorationRole: + return index.column() == 0 ? fileIcon : QVariant(); + } + } else { + MatchNode *matchNode = dynamic_cast(static_cast(index.internalPointer())); + const ServerInfo_ReplayMatch &matchInfo = matchNode->getMatchInfo(); + switch (role) { + case Qt::TextAlignmentRole: + switch (index.column()) { + case 0: + case 5: + return Qt::AlignRight; + default: + return Qt::AlignLeft; + } + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return matchInfo.game_id(); + case 1: return QString::fromStdString(matchInfo.game_name()); + case 2: { + QStringList playerList; + for (int i = 0; i < matchInfo.player_names_size(); ++i) + playerList.append(QString::fromStdString(matchInfo.player_names(i))); + return playerList.join(", "); + } + case 4: return QDateTime::fromTime_t(matchInfo.time_started()); + case 5: return matchInfo.length(); + default: return QVariant(); + } + } + case Qt::DecorationRole: + switch (index.column()) { + case 0: return dirIcon; + case 3: return matchInfo.do_not_hide() ? lockIcon : QVariant(); + default: return QVariant(); + } + } + } + return QVariant(); } QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation != Qt::Horizontal) - return QVariant(); - switch (role) { - case Qt::TextAlignmentRole: - switch (section) { - case 0: - case 5: - return Qt::AlignRight; - default: - return Qt::AlignLeft; - } - case Qt::DisplayRole: { - switch (section) { - case 0: return tr("ID"); - case 1: return tr("Name"); - case 2: return tr("Players"); - case 3: return tr("Keep"); - case 4: return tr("Time started"); - case 5: return tr("Duration (sec)"); - default: return QVariant(); - } - } - default: return QVariant(); - } + if (orientation != Qt::Horizontal) + return QVariant(); + switch (role) { + case Qt::TextAlignmentRole: + switch (section) { + case 0: + case 5: + return Qt::AlignRight; + default: + return Qt::AlignLeft; + } + case Qt::DisplayRole: { + switch (section) { + case 0: return tr("ID"); + case 1: return tr("Name"); + case 2: return tr("Players"); + case 3: return tr("Keep"); + case 4: return tr("Time started"); + case 5: return tr("Duration (sec)"); + default: return QVariant(); + } + } + default: return QVariant(); + } } QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelIndex &parent) const { - if (!hasIndex(row, column, parent)) - return QModelIndex(); - - MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); - if (matchNode) { - if (row >= matchNode->size()) - return QModelIndex(); - return createIndex(row, column, (void *) matchNode->at(row)); - } else { - if (row >= replayMatches.size()) - return QModelIndex(); - return createIndex(row, column, (void *) replayMatches[row]); - } + if (!hasIndex(row, column, parent)) + return QModelIndex(); + + MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); + if (matchNode) { + if (row >= matchNode->size()) + return QModelIndex(); + return createIndex(row, column, (void *) matchNode->at(row)); + } else { + if (row >= replayMatches.size()) + return QModelIndex(); + return createIndex(row, column, (void *) replayMatches[row]); + } } QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const { - MatchNode const *matchNode = dynamic_cast(static_cast(ind.internalPointer())); - if (matchNode) - return QModelIndex(); - else { - ReplayNode *replayNode = dynamic_cast(static_cast(ind.internalPointer())); - return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode); - } + MatchNode const *matchNode = dynamic_cast(static_cast(ind.internalPointer())); + if (matchNode) + return QModelIndex(); + else { + ReplayNode *replayNode = dynamic_cast(static_cast(ind.internalPointer())); + return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode); + } } Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } ServerInfo_Replay const* RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const { - if (!index.isValid()) - return 0; - - ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); - if (!node) - return 0; - return &node->getReplayInfo(); + if (!index.isValid()) + return 0; + + ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); + if (!node) + return 0; + return &node->getReplayInfo(); } ServerInfo_ReplayMatch const* RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const { - if (!index.isValid()) - return 0; - - MatchNode *node = dynamic_cast(static_cast(index.internalPointer())); - if (!node) { - ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); - if (!node) - return 0; - return &node->getParent()->getMatchInfo(); - } else - return &node->getMatchInfo(); + if (!index.isValid()) + return 0; + + MatchNode *node = dynamic_cast(static_cast(index.internalPointer())); + if (!node) { + ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); + if (!node) + return 0; + return &node->getParent()->getMatchInfo(); + } else + return &node->getMatchInfo(); } void RemoteReplayList_TreeModel::clearTree() { - for (int i = 0; i < replayMatches.size(); ++i) - delete replayMatches[i]; - replayMatches.clear(); + for (int i = 0; i < replayMatches.size(); ++i) + delete replayMatches[i]; + replayMatches.clear(); } void RemoteReplayList_TreeModel::refreshTree() { - PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &))); - - client->sendCommand(pend); + PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList()); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &))); + + client->sendCommand(pend); } void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { - beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size()); - replayMatches.append(new MatchNode(matchInfo)); - endInsertRows(); - - emit treeRefreshed(); + beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size()); + replayMatches.append(new MatchNode(matchInfo)); + endInsertRows(); + + emit treeRefreshed(); } void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { - for (int i = 0; i < replayMatches.size(); ++i) - if (replayMatches[i]->getMatchInfo().game_id() == gameId) { - replayMatches[i]->updateMatchInfo(matchInfo); - emit dataChanged(createIndex(i, 0, (void *) replayMatches[i]), createIndex(i, numberOfColumns - 1, (void *) replayMatches[i])); - break; - } + for (int i = 0; i < replayMatches.size(); ++i) + if (replayMatches[i]->getMatchInfo().game_id() == gameId) { + replayMatches[i]->updateMatchInfo(matchInfo); + emit dataChanged(createIndex(i, 0, (void *) replayMatches[i]), createIndex(i, numberOfColumns - 1, (void *) replayMatches[i])); + break; + } } void RemoteReplayList_TreeModel::removeMatchInfo(int gameId) { - for (int i = 0; i < replayMatches.size(); ++i) - if (replayMatches[i]->getMatchInfo().game_id() == gameId) { - beginRemoveRows(QModelIndex(), i, i); - replayMatches.removeAt(i); - endRemoveRows(); - break; - } + for (int i = 0; i < replayMatches.size(); ++i) + if (replayMatches[i]->getMatchInfo().game_id() == gameId) { + beginRemoveRows(QModelIndex(), i, i); + replayMatches.removeAt(i); + endRemoveRows(); + break; + } } void RemoteReplayList_TreeModel::replayListFinished(const Response &r) { - const Response_ReplayList &resp = r.GetExtension(Response_ReplayList::ext); - - beginResetModel(); - clearTree(); - - for (int i = 0; i < resp.match_list_size(); ++i) - replayMatches.append(new MatchNode(resp.match_list(i))); - - endResetModel(); - emit treeRefreshed(); + const Response_ReplayList &resp = r.GetExtension(Response_ReplayList::ext); + + beginResetModel(); + clearTree(); + + for (int i = 0; i < resp.match_list_size(); ++i) + replayMatches.append(new MatchNode(resp.match_list(i))); + + endResetModel(); + emit treeRefreshed(); } RemoteReplayList_TreeWidget::RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent) - : QTreeView(parent) + : QTreeView(parent) { - treeModel = new RemoteReplayList_TreeModel(_client, this); - proxyModel = new QSortFilterProxyModel(this); - proxyModel->setSourceModel(treeModel); - proxyModel->setDynamicSortFilter(true); - proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); - setModel(proxyModel); + treeModel = new RemoteReplayList_TreeModel(_client, this); + proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(treeModel); + proxyModel->setDynamicSortFilter(true); + proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + setModel(proxyModel); - header()->setResizeMode(QHeaderView::ResizeToContents); - header()->setStretchLastSection(false); - setUniformRowHeights(true); - setSortingEnabled(true); - proxyModel->sort(0, Qt::AscendingOrder); - header()->setSortIndicator(0, Qt::AscendingOrder); + header()->setResizeMode(QHeaderView::ResizeToContents); + header()->setStretchLastSection(false); + setUniformRowHeights(true); + setSortingEnabled(true); + proxyModel->sort(0, Qt::AscendingOrder); + header()->setSortIndicator(0, Qt::AscendingOrder); } ServerInfo_Replay const *RemoteReplayList_TreeWidget::getCurrentReplay() const { - return treeModel->getReplay(proxyModel->mapToSource(selectionModel()->currentIndex())); + return treeModel->getReplay(proxyModel->mapToSource(selectionModel()->currentIndex())); } ServerInfo_ReplayMatch const *RemoteReplayList_TreeWidget::getCurrentReplayMatch() const { - return treeModel->getReplayMatch(proxyModel->mapToSource(selectionModel()->currentIndex())); + return treeModel->getReplayMatch(proxyModel->mapToSource(selectionModel()->currentIndex())); } diff --git a/cockatrice/src/remotereplaylist_treewidget.h b/cockatrice/src/remotereplaylist_treewidget.h index 7397d21d..986e2fa4 100644 --- a/cockatrice/src/remotereplaylist_treewidget.h +++ b/cockatrice/src/remotereplaylist_treewidget.h @@ -12,82 +12,82 @@ class AbstractClient; class QSortFilterProxyModel; class RemoteReplayList_TreeModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT private: - class MatchNode; - class ReplayNode; - class Node { - protected: - QString name; - public: - Node(const QString &_name) - : name(_name) { } - virtual ~Node() { }; - QString getName() const { return name; } - }; - class MatchNode : public Node, public QList { - private: - ServerInfo_ReplayMatch matchInfo; - public: - MatchNode(const ServerInfo_ReplayMatch &_matchInfo); - ~MatchNode(); - void clearTree(); - const ServerInfo_ReplayMatch &getMatchInfo() { return matchInfo; } - void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo); - }; - class ReplayNode : public Node { - private: - MatchNode *parent; - ServerInfo_Replay replayInfo; - public: - ReplayNode(const ServerInfo_Replay &_replayInfo, MatchNode *_parent) - : Node(QString::fromStdString(_replayInfo.replay_name())), parent(_parent), replayInfo(_replayInfo) { } - MatchNode *getParent() const { return parent; } - const ServerInfo_Replay &getReplayInfo() { return replayInfo; } - }; - - AbstractClient *client; - QList replayMatches; - - QIcon dirIcon, fileIcon, lockIcon; - void clearTree(); - - static const int numberOfColumns; + class MatchNode; + class ReplayNode; + class Node { + protected: + QString name; + public: + Node(const QString &_name) + : name(_name) { } + virtual ~Node() { }; + QString getName() const { return name; } + }; + class MatchNode : public Node, public QList { + private: + ServerInfo_ReplayMatch matchInfo; + public: + MatchNode(const ServerInfo_ReplayMatch &_matchInfo); + ~MatchNode(); + void clearTree(); + const ServerInfo_ReplayMatch &getMatchInfo() { return matchInfo; } + void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo); + }; + class ReplayNode : public Node { + private: + MatchNode *parent; + ServerInfo_Replay replayInfo; + public: + ReplayNode(const ServerInfo_Replay &_replayInfo, MatchNode *_parent) + : Node(QString::fromStdString(_replayInfo.replay_name())), parent(_parent), replayInfo(_replayInfo) { } + MatchNode *getParent() const { return parent; } + const ServerInfo_Replay &getReplayInfo() { return replayInfo; } + }; + + AbstractClient *client; + QList replayMatches; + + QIcon dirIcon, fileIcon, lockIcon; + void clearTree(); + + static const int numberOfColumns; signals: - void treeRefreshed(); + void treeRefreshed(); private slots: - void replayListFinished(const Response &r); + void replayListFinished(const Response &r); public: - RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent = 0); - ~RemoteReplayList_TreeModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return numberOfColumns; } - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - void refreshTree(); - ServerInfo_Replay const* getReplay(const QModelIndex &index) const; - ServerInfo_ReplayMatch const* getReplayMatch(const QModelIndex &index) const; - void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo); - void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo); - void removeMatchInfo(int gameId); + RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent = 0); + ~RemoteReplayList_TreeModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return numberOfColumns; } + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + void refreshTree(); + ServerInfo_Replay const* getReplay(const QModelIndex &index) const; + ServerInfo_ReplayMatch const* getReplayMatch(const QModelIndex &index) const; + void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo); + void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo); + void removeMatchInfo(int gameId); }; class RemoteReplayList_TreeWidget : public QTreeView { private: - RemoteReplayList_TreeModel *treeModel; - QSortFilterProxyModel *proxyModel; - ServerInfo_Replay const *getNode(const QModelIndex &ind) const; + RemoteReplayList_TreeModel *treeModel; + QSortFilterProxyModel *proxyModel; + ServerInfo_Replay const *getNode(const QModelIndex &ind) const; public: - RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); - ServerInfo_Replay const *getCurrentReplay() const; - ServerInfo_ReplayMatch const *getCurrentReplayMatch() const; - void refreshTree(); - void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { treeModel->addMatchInfo(matchInfo); } - void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { treeModel->updateMatchInfo(gameId, matchInfo); } - void removeMatchInfo(int gameId) { treeModel->removeMatchInfo(gameId); } + RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); + ServerInfo_Replay const *getCurrentReplay() const; + ServerInfo_ReplayMatch const *getCurrentReplayMatch() const; + void refreshTree(); + void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { treeModel->addMatchInfo(matchInfo); } + void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { treeModel->updateMatchInfo(gameId, matchInfo); } + void removeMatchInfo(int gameId) { treeModel->removeMatchInfo(gameId); } }; #endif diff --git a/cockatrice/src/replay_timeline_widget.cpp b/cockatrice/src/replay_timeline_widget.cpp index 071cb7b6..7934fb0e 100644 --- a/cockatrice/src/replay_timeline_widget.cpp +++ b/cockatrice/src/replay_timeline_widget.cpp @@ -5,97 +5,97 @@ #include ReplayTimelineWidget::ReplayTimelineWidget(QWidget *parent) - : QWidget(parent), maxBinValue(1), maxTime(1), timeScaleFactor(1.0), currentTime(0), currentEvent(0) + : QWidget(parent), maxBinValue(1), maxTime(1), timeScaleFactor(1.0), currentTime(0), currentEvent(0) { - replayTimer = new QTimer(this); - connect(replayTimer, SIGNAL(timeout()), this, SLOT(replayTimerTimeout())); + replayTimer = new QTimer(this); + connect(replayTimer, SIGNAL(timeout()), this, SLOT(replayTimerTimeout())); } const int ReplayTimelineWidget::binLength = 5000; void ReplayTimelineWidget::setTimeline(const QList &_replayTimeline) { - replayTimeline = _replayTimeline; - histogram.clear(); - int binEndTime = binLength - 1; - int binValue = 0; - for (int i = 0; i < replayTimeline.size(); ++i) { - if (replayTimeline[i] > binEndTime) { - histogram.append(binValue); - if (binValue > maxBinValue) - maxBinValue = binValue; - while (replayTimeline[i] > binEndTime + binLength) { - histogram.append(0); - binEndTime += binLength; - } - binValue = 1; - binEndTime += binLength; - } else - ++binValue; - } - histogram.append(binValue); - if (!replayTimeline.isEmpty()) - maxTime = replayTimeline.last(); - - update(); + replayTimeline = _replayTimeline; + histogram.clear(); + int binEndTime = binLength - 1; + int binValue = 0; + for (int i = 0; i < replayTimeline.size(); ++i) { + if (replayTimeline[i] > binEndTime) { + histogram.append(binValue); + if (binValue > maxBinValue) + maxBinValue = binValue; + while (replayTimeline[i] > binEndTime + binLength) { + histogram.append(0); + binEndTime += binLength; + } + binValue = 1; + binEndTime += binLength; + } else + ++binValue; + } + histogram.append(binValue); + if (!replayTimeline.isEmpty()) + maxTime = replayTimeline.last(); + + update(); } void ReplayTimelineWidget::paintEvent(QPaintEvent *event) { - QPainter painter(this); - painter.drawRect(0, 0, width() - 1, height() - 1); - - qreal binWidth = (qreal) width() / histogram.size(); - QPainterPath path; - path.moveTo(0, height() - 1); - for (int i = 0; i < histogram.size(); ++i) - path.lineTo(round(i * binWidth), (height() - 1) * (1.0 - (qreal) histogram[i] / maxBinValue)); - path.lineTo(width() - 1, height() - 1); - path.lineTo(0, height() - 1); - painter.fillPath(path, Qt::black); - - const QColor barColor = QColor::fromHsv(120, 255, 255, 100); - painter.fillRect(0, 0, (width() - 1) * currentTime / maxTime, height() - 1, barColor); + QPainter painter(this); + painter.drawRect(0, 0, width() - 1, height() - 1); + + qreal binWidth = (qreal) width() / histogram.size(); + QPainterPath path; + path.moveTo(0, height() - 1); + for (int i = 0; i < histogram.size(); ++i) + path.lineTo(round(i * binWidth), (height() - 1) * (1.0 - (qreal) histogram[i] / maxBinValue)); + path.lineTo(width() - 1, height() - 1); + path.lineTo(0, height() - 1); + painter.fillPath(path, Qt::black); + + const QColor barColor = QColor::fromHsv(120, 255, 255, 100); + painter.fillRect(0, 0, (width() - 1) * currentTime / maxTime, height() - 1, barColor); } QSize ReplayTimelineWidget::sizeHint() const { - return QSize(-1, 50); + return QSize(-1, 50); } QSize ReplayTimelineWidget::minimumSizeHint() const { - return QSize(400, 50); + return QSize(400, 50); } void ReplayTimelineWidget::replayTimerTimeout() { - currentTime += 200; - while ((currentEvent < replayTimeline.size()) && (replayTimeline[currentEvent] < currentTime)) { - emit processNextEvent(); - ++currentEvent; - } - if (currentEvent == replayTimeline.size()) { - emit replayFinished(); - replayTimer->stop(); - } - - if (!(currentTime % 1000)) - update(); + currentTime += 200; + while ((currentEvent < replayTimeline.size()) && (replayTimeline[currentEvent] < currentTime)) { + emit processNextEvent(); + ++currentEvent; + } + if (currentEvent == replayTimeline.size()) { + emit replayFinished(); + replayTimer->stop(); + } + + if (!(currentTime % 1000)) + update(); } void ReplayTimelineWidget::setTimeScaleFactor(qreal _timeScaleFactor) { - timeScaleFactor = _timeScaleFactor; - replayTimer->setInterval(200 / timeScaleFactor); + timeScaleFactor = _timeScaleFactor; + replayTimer->setInterval(200 / timeScaleFactor); } void ReplayTimelineWidget::startReplay() { - replayTimer->start(200 / timeScaleFactor); + replayTimer->start(200 / timeScaleFactor); } void ReplayTimelineWidget::stopReplay() { - replayTimer->stop(); + replayTimer->stop(); } diff --git a/cockatrice/src/replay_timeline_widget.h b/cockatrice/src/replay_timeline_widget.h index 3a1b6712..8c668393 100644 --- a/cockatrice/src/replay_timeline_widget.h +++ b/cockatrice/src/replay_timeline_widget.h @@ -8,33 +8,33 @@ class QPaintEvent; class QTimer; class ReplayTimelineWidget : public QWidget { - Q_OBJECT + Q_OBJECT signals: - void processNextEvent(); - void replayFinished(); + void processNextEvent(); + void replayFinished(); private: - QTimer *replayTimer; - QList replayTimeline; - QList histogram; - static const int binLength; - int maxBinValue, maxTime; - qreal timeScaleFactor; - int currentTime; - int currentEvent; + QTimer *replayTimer; + QList replayTimeline; + QList histogram; + static const int binLength; + int maxBinValue, maxTime; + qreal timeScaleFactor; + int currentTime; + int currentEvent; private slots: - void replayTimerTimeout(); + void replayTimerTimeout(); public: - ReplayTimelineWidget(QWidget *parent = 0); - void setTimeline(const QList &_replayTimeline); - QSize sizeHint() const; - QSize minimumSizeHint() const; - void setTimeScaleFactor(qreal _timeScaleFactor); - int getCurrentEvent() const { return currentEvent; } + ReplayTimelineWidget(QWidget *parent = 0); + void setTimeline(const QList &_replayTimeline); + QSize sizeHint() const; + QSize minimumSizeHint() const; + void setTimeScaleFactor(qreal _timeScaleFactor); + int getCurrentEvent() const { return currentEvent; } public slots: - void startReplay(); - void stopReplay(); + void startReplay(); + void stopReplay(); protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent *event); }; #endif diff --git a/cockatrice/src/selectzone.cpp b/cockatrice/src/selectzone.cpp index f7168b2e..be966352 100644 --- a/cockatrice/src/selectzone.cpp +++ b/cockatrice/src/selectzone.cpp @@ -5,52 +5,52 @@ #include SelectZone::SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool isView) - : CardZone(_player, _name, _hasCardAttr, _isShufflable, _contentsKnown, parent, isView) + : CardZone(_player, _name, _hasCardAttr, _isShufflable, _contentsKnown, parent, isView) { } void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (event->buttons().testFlag(Qt::LeftButton)) { - QPointF pos = event->pos(); - if (pos.x() < 0) - pos.setX(0); - QRectF br = boundingRect(); - if (pos.x() > br.width()) - pos.setX(br.width()); - if (pos.y() < 0) - pos.setY(0); - if (pos.y() > br.height()) - pos.setY(br.height()); - - QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); - for (int i = 0; i < cards.size(); ++i) { - if (cards[i]->getAttachedTo()) - if (cards[i]->getAttachedTo()->getZone() != this) - continue; - cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect()))); - } - static_cast(scene())->resizeRubberBand(deviceTransform(static_cast(scene())->getViewportTransform()).map(pos)); - event->accept(); - } + if (event->buttons().testFlag(Qt::LeftButton)) { + QPointF pos = event->pos(); + if (pos.x() < 0) + pos.setX(0); + QRectF br = boundingRect(); + if (pos.x() > br.width()) + pos.setX(br.width()); + if (pos.y() < 0) + pos.setY(0); + if (pos.y() > br.height()) + pos.setY(br.height()); + + QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); + for (int i = 0; i < cards.size(); ++i) { + if (cards[i]->getAttachedTo()) + if (cards[i]->getAttachedTo()->getZone() != this) + continue; + cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect()))); + } + static_cast(scene())->resizeRubberBand(deviceTransform(static_cast(scene())->getViewportTransform()).map(pos)); + event->accept(); + } } void SelectZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - scene()->clearSelection(); - - selectionOrigin = event->pos(); - static_cast(scene())->startRubberBand(event->scenePos()); - event->accept(); - } else - CardZone::mousePressEvent(event); + if (event->button() == Qt::LeftButton) { + scene()->clearSelection(); + + selectionOrigin = event->pos(); + static_cast(scene())->startRubberBand(event->scenePos()); + event->accept(); + } else + CardZone::mousePressEvent(event); } void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - selectionOrigin = QPoint(); - static_cast(scene())->stopRubberBand(); - event->accept(); + selectionOrigin = QPoint(); + static_cast(scene())->stopRubberBand(); + event->accept(); } diff --git a/cockatrice/src/selectzone.h b/cockatrice/src/selectzone.h index 23e82d1c..347e9a52 100644 --- a/cockatrice/src/selectzone.h +++ b/cockatrice/src/selectzone.h @@ -4,15 +4,15 @@ #include "cardzone.h" class SelectZone : public CardZone { - Q_OBJECT + Q_OBJECT private: - QPointF selectionOrigin; + QPointF selectionOrigin; protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); public: - SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool isView = false); + SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool isView = false); }; #endif diff --git a/cockatrice/src/setsmodel.cpp b/cockatrice/src/setsmodel.cpp index f0ca77e7..f11d73c4 100644 --- a/cockatrice/src/setsmodel.cpp +++ b/cockatrice/src/setsmodel.cpp @@ -1,9 +1,9 @@ #include "setsmodel.h" SetsModel::SetsModel(CardDatabase *_db, QObject *parent) - : QAbstractTableModel(parent), sets(_db->getSetList()) + : QAbstractTableModel(parent), sets(_db->getSetList()) { - sets.sortByKey(); + sets.sortByKey(); } SetsModel::~SetsModel() @@ -12,82 +12,82 @@ SetsModel::~SetsModel() int SetsModel::rowCount(const QModelIndex &parent) const { - if (parent.isValid()) - return 0; - else - return sets.size(); + if (parent.isValid()) + return 0; + else + return sets.size(); } QVariant SetsModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || (index.column() >= 2) || (index.row() >= rowCount()) || (role != Qt::DisplayRole)) - return QVariant(); + if (!index.isValid() || (index.column() >= 2) || (index.row() >= rowCount()) || (role != Qt::DisplayRole)) + return QVariant(); - CardSet *set = sets[index.row()]; - switch (index.column()) { - case 0: return set->getShortName(); - case 1: return set->getLongName(); - default: return QVariant(); - } + CardSet *set = sets[index.row()]; + switch (index.column()) { + case 0: return set->getShortName(); + case 1: return set->getLongName(); + default: return QVariant(); + } } QVariant SetsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - return QVariant(); - switch (section) { - case 0: return tr("Short name"); - case 1: return tr("Long name"); - default: return QVariant(); - } + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) + return QVariant(); + switch (section) { + case 0: return tr("Short name"); + case 1: return tr("Long name"); + default: return QVariant(); + } } Qt::ItemFlags SetsModel::flags(const QModelIndex &index) const { - Qt::ItemFlags result = QAbstractTableModel::flags(index); - return result | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; + Qt::ItemFlags result = QAbstractTableModel::flags(index); + return result | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; } Qt::DropActions SetsModel::supportedDropActions() const { - return Qt::MoveAction; + return Qt::MoveAction; } QMimeData *SetsModel::mimeData(const QModelIndexList &indexes) const { - if (indexes.isEmpty()) - return 0; + if (indexes.isEmpty()) + return 0; - SetsMimeData *result = new SetsMimeData(indexes[0].row()); - return qobject_cast(result); + SetsMimeData *result = new SetsMimeData(indexes[0].row()); + return qobject_cast(result); } bool SetsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /*column*/, const QModelIndex &parent) { - if (action != Qt::MoveAction) - return false; - if (row == -1) { - if (!parent.isValid()) - return false; - row = parent.row(); - } - int oldRow = qobject_cast(data)->getOldRow(); - beginRemoveRows(QModelIndex(), oldRow, oldRow); - CardSet *temp = sets.takeAt(oldRow); - endRemoveRows(); - if (oldRow < row) - row--; - beginInsertRows(QModelIndex(), row, row); - sets.insert(row, temp); - endInsertRows(); + if (action != Qt::MoveAction) + return false; + if (row == -1) { + if (!parent.isValid()) + return false; + row = parent.row(); + } + int oldRow = qobject_cast(data)->getOldRow(); + beginRemoveRows(QModelIndex(), oldRow, oldRow); + CardSet *temp = sets.takeAt(oldRow); + endRemoveRows(); + if (oldRow < row) + row--; + beginInsertRows(QModelIndex(), row, row); + sets.insert(row, temp); + endInsertRows(); - for (int i = 0; i < sets.size(); i++) - sets[i]->setSortKey(i); + for (int i = 0; i < sets.size(); i++) + sets[i]->setSortKey(i); - return true; + return true; } QStringList SetsModel::mimeTypes() const { - return QStringList() << "application/x-cockatricecardset"; + return QStringList() << "application/x-cockatricecardset"; } diff --git a/cockatrice/src/setsmodel.h b/cockatrice/src/setsmodel.h index 5d61b57c..74d29443 100644 --- a/cockatrice/src/setsmodel.h +++ b/cockatrice/src/setsmodel.h @@ -6,32 +6,32 @@ #include "carddatabase.h" class SetsMimeData : public QMimeData { - Q_OBJECT + Q_OBJECT private: - int oldRow; + int oldRow; public: - SetsMimeData(int _oldRow) : oldRow(_oldRow) { } - int getOldRow() const { return oldRow; } - QStringList formats() const { return QStringList() << "application/x-cockatricecardset"; } + SetsMimeData(int _oldRow) : oldRow(_oldRow) { } + int getOldRow() const { return oldRow; } + QStringList formats() const { return QStringList() << "application/x-cockatricecardset"; } }; class SetsModel : public QAbstractTableModel { - Q_OBJECT + Q_OBJECT public: - SetsModel(CardDatabase *_db, QObject *parent = 0); - ~SetsModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/) const { return 2; } - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - Qt::DropActions supportedDropActions() const; + SetsModel(CardDatabase *_db, QObject *parent = 0); + ~SetsModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/) const { return 2; } + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + Qt::DropActions supportedDropActions() const; - QMimeData *mimeData(const QModelIndexList &indexes) const; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); - QStringList mimeTypes() const; + QMimeData *mimeData(const QModelIndexList &indexes) const; + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); + QStringList mimeTypes() const; private: - SetList sets; + SetList sets; }; #endif diff --git a/cockatrice/src/settingscache.cpp b/cockatrice/src/settingscache.cpp index 1c2e9b34..b73d6d86 100644 --- a/cockatrice/src/settingscache.cpp +++ b/cockatrice/src/settingscache.cpp @@ -3,233 +3,233 @@ SettingsCache::SettingsCache() { - settings = new QSettings(this); - - lang = settings->value("personal/lang").toString(); - - deckPath = settings->value("paths/decks").toString(); - replaysPath = settings->value("paths/replays").toString(); - picsPath = settings->value("paths/pics").toString(); - cardDatabasePath = settings->value("paths/carddatabase").toString(); - tokenDatabasePath = settings->value("paths/tokendatabase").toString(); - - handBgPath = settings->value("zonebg/hand").toString(); - stackBgPath = settings->value("zonebg/stack").toString(); - tableBgPath = settings->value("zonebg/table").toString(); - playerBgPath = settings->value("zonebg/playerarea").toString(); - cardBackPicturePath = settings->value("paths/cardbackpicture").toString(); - - mainWindowGeometry = settings->value("interface/main_window_geometry").toByteArray(); - picDownload = settings->value("personal/picturedownload", true).toBool(); - notificationsEnabled = settings->value("interface/notificationsenabled", true).toBool(); - doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool(); - playToStack = settings->value("interface/playtostack", false).toBool(); - cardInfoMinimized = settings->value("interface/cardinfominimized", 0).toInt(); - tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray(); - displayCardNames = settings->value("cards/displaycardnames", true).toBool(); - horizontalHand = settings->value("hand/horizontal", true).toBool(); - invertVerticalCoordinate = settings->value("table/invert_vertical", false).toBool(); - minPlayersForMultiColumnLayout = settings->value("interface/min_players_multicolumn", 5).toInt(); - tapAnimation = settings->value("cards/tapanimation", true).toBool(); - - zoneViewSortByName = settings->value("zoneview/sortbyname", true).toBool(); - zoneViewSortByType = settings->value("zoneview/sortbytype", true).toBool(); - - soundEnabled = settings->value("sound/enabled", false).toBool(); - soundPath = settings->value("sound/path").toString(); - - priceTagFeature = settings->value("deckeditor/pricetags", false).toBool(); - - ignoreUnregisteredUsers = settings->value("chat/ignore_unregistered", false).toBool(); + settings = new QSettings(this); + + lang = settings->value("personal/lang").toString(); + + deckPath = settings->value("paths/decks").toString(); + replaysPath = settings->value("paths/replays").toString(); + picsPath = settings->value("paths/pics").toString(); + cardDatabasePath = settings->value("paths/carddatabase").toString(); + tokenDatabasePath = settings->value("paths/tokendatabase").toString(); + + handBgPath = settings->value("zonebg/hand").toString(); + stackBgPath = settings->value("zonebg/stack").toString(); + tableBgPath = settings->value("zonebg/table").toString(); + playerBgPath = settings->value("zonebg/playerarea").toString(); + cardBackPicturePath = settings->value("paths/cardbackpicture").toString(); + + mainWindowGeometry = settings->value("interface/main_window_geometry").toByteArray(); + picDownload = settings->value("personal/picturedownload", true).toBool(); + notificationsEnabled = settings->value("interface/notificationsenabled", true).toBool(); + doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool(); + playToStack = settings->value("interface/playtostack", false).toBool(); + cardInfoMinimized = settings->value("interface/cardinfominimized", 0).toInt(); + tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray(); + displayCardNames = settings->value("cards/displaycardnames", true).toBool(); + horizontalHand = settings->value("hand/horizontal", true).toBool(); + invertVerticalCoordinate = settings->value("table/invert_vertical", false).toBool(); + minPlayersForMultiColumnLayout = settings->value("interface/min_players_multicolumn", 5).toInt(); + tapAnimation = settings->value("cards/tapanimation", true).toBool(); + + zoneViewSortByName = settings->value("zoneview/sortbyname", true).toBool(); + zoneViewSortByType = settings->value("zoneview/sortbytype", true).toBool(); + + soundEnabled = settings->value("sound/enabled", false).toBool(); + soundPath = settings->value("sound/path").toString(); + + priceTagFeature = settings->value("deckeditor/pricetags", false).toBool(); + + ignoreUnregisteredUsers = settings->value("chat/ignore_unregistered", false).toBool(); } void SettingsCache::setLang(const QString &_lang) { - lang = _lang; - settings->setValue("personal/lang", lang); - emit langChanged(); + lang = _lang; + settings->setValue("personal/lang", lang); + emit langChanged(); } void SettingsCache::setDeckPath(const QString &_deckPath) { - deckPath = _deckPath; - settings->setValue("paths/decks", deckPath); + deckPath = _deckPath; + settings->setValue("paths/decks", deckPath); } void SettingsCache::setReplaysPath(const QString &_replaysPath) { - replaysPath = _replaysPath; - settings->setValue("paths/replays", replaysPath); + replaysPath = _replaysPath; + settings->setValue("paths/replays", replaysPath); } void SettingsCache::setPicsPath(const QString &_picsPath) { - picsPath = _picsPath; - settings->setValue("paths/pics", picsPath); - emit picsPathChanged(); + picsPath = _picsPath; + settings->setValue("paths/pics", picsPath); + emit picsPathChanged(); } void SettingsCache::setCardDatabasePath(const QString &_cardDatabasePath) { - cardDatabasePath = _cardDatabasePath; - settings->setValue("paths/carddatabase", cardDatabasePath); - emit cardDatabasePathChanged(); + cardDatabasePath = _cardDatabasePath; + settings->setValue("paths/carddatabase", cardDatabasePath); + emit cardDatabasePathChanged(); } void SettingsCache::setTokenDatabasePath(const QString &_tokenDatabasePath) { - tokenDatabasePath = _tokenDatabasePath; - settings->setValue("paths/tokendatabase", tokenDatabasePath); - emit tokenDatabasePathChanged(); + tokenDatabasePath = _tokenDatabasePath; + settings->setValue("paths/tokendatabase", tokenDatabasePath); + emit tokenDatabasePathChanged(); } void SettingsCache::setHandBgPath(const QString &_handBgPath) { - handBgPath = _handBgPath; - settings->setValue("zonebg/hand", handBgPath); - emit handBgPathChanged(); + handBgPath = _handBgPath; + settings->setValue("zonebg/hand", handBgPath); + emit handBgPathChanged(); } void SettingsCache::setStackBgPath(const QString &_stackBgPath) { - stackBgPath = _stackBgPath; - settings->setValue("zonebg/stack", stackBgPath); - emit stackBgPathChanged(); + stackBgPath = _stackBgPath; + settings->setValue("zonebg/stack", stackBgPath); + emit stackBgPathChanged(); } void SettingsCache::setTableBgPath(const QString &_tableBgPath) { - tableBgPath = _tableBgPath; - settings->setValue("zonebg/table", tableBgPath); - emit tableBgPathChanged(); + tableBgPath = _tableBgPath; + settings->setValue("zonebg/table", tableBgPath); + emit tableBgPathChanged(); } void SettingsCache::setPlayerBgPath(const QString &_playerBgPath) { - playerBgPath = _playerBgPath; - settings->setValue("zonebg/playerarea", playerBgPath); - emit playerBgPathChanged(); + playerBgPath = _playerBgPath; + settings->setValue("zonebg/playerarea", playerBgPath); + emit playerBgPathChanged(); } void SettingsCache::setCardBackPicturePath(const QString &_cardBackPicturePath) { - cardBackPicturePath = _cardBackPicturePath; - settings->setValue("paths/cardbackpicture", cardBackPicturePath); - emit cardBackPicturePathChanged(); + cardBackPicturePath = _cardBackPicturePath; + settings->setValue("paths/cardbackpicture", cardBackPicturePath); + emit cardBackPicturePathChanged(); } void SettingsCache::setPicDownload(int _picDownload) { - picDownload = _picDownload; - settings->setValue("personal/picturedownload", picDownload); - emit picDownloadChanged(); + picDownload = _picDownload; + settings->setValue("personal/picturedownload", picDownload); + emit picDownloadChanged(); } void SettingsCache::setNotificationsEnabled(int _notificationsEnabled) { - notificationsEnabled = _notificationsEnabled; - settings->setValue("interface/notificationsenabled", notificationsEnabled); + notificationsEnabled = _notificationsEnabled; + settings->setValue("interface/notificationsenabled", notificationsEnabled); } void SettingsCache::setDoubleClickToPlay(int _doubleClickToPlay) { - doubleClickToPlay = _doubleClickToPlay; - settings->setValue("interface/doubleclicktoplay", doubleClickToPlay); + doubleClickToPlay = _doubleClickToPlay; + settings->setValue("interface/doubleclicktoplay", doubleClickToPlay); } void SettingsCache::setPlayToStack(int _playToStack) { - playToStack = _playToStack; - settings->setValue("interface/playtostack", playToStack); + playToStack = _playToStack; + settings->setValue("interface/playtostack", playToStack); } void SettingsCache::setCardInfoMinimized(int _cardInfoMinimized) { cardInfoMinimized = _cardInfoMinimized; - settings->setValue("interface/cardinfominimized", cardInfoMinimized); + settings->setValue("interface/cardinfominimized", cardInfoMinimized); } void SettingsCache::setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes) { - tabGameSplitterSizes = _tabGameSplitterSizes; - settings->setValue("interface/tabgame_splittersizes", tabGameSplitterSizes); + tabGameSplitterSizes = _tabGameSplitterSizes; + settings->setValue("interface/tabgame_splittersizes", tabGameSplitterSizes); } void SettingsCache::setDisplayCardNames(int _displayCardNames) { - displayCardNames = _displayCardNames; - settings->setValue("cards/displaycardnames", displayCardNames); - emit displayCardNamesChanged(); + displayCardNames = _displayCardNames; + settings->setValue("cards/displaycardnames", displayCardNames); + emit displayCardNamesChanged(); } void SettingsCache::setHorizontalHand(int _horizontalHand) { - horizontalHand = _horizontalHand; - settings->setValue("hand/horizontal", horizontalHand); - emit horizontalHandChanged(); + horizontalHand = _horizontalHand; + settings->setValue("hand/horizontal", horizontalHand); + emit horizontalHandChanged(); } void SettingsCache::setInvertVerticalCoordinate(int _invertVerticalCoordinate) { - invertVerticalCoordinate = _invertVerticalCoordinate; - settings->setValue("table/invert_vertical", invertVerticalCoordinate); - emit invertVerticalCoordinateChanged(); + invertVerticalCoordinate = _invertVerticalCoordinate; + settings->setValue("table/invert_vertical", invertVerticalCoordinate); + emit invertVerticalCoordinateChanged(); } void SettingsCache::setMinPlayersForMultiColumnLayout(int _minPlayersForMultiColumnLayout) { - minPlayersForMultiColumnLayout = _minPlayersForMultiColumnLayout; - settings->setValue("interface/min_players_multicolumn", minPlayersForMultiColumnLayout); - emit minPlayersForMultiColumnLayoutChanged(); + minPlayersForMultiColumnLayout = _minPlayersForMultiColumnLayout; + settings->setValue("interface/min_players_multicolumn", minPlayersForMultiColumnLayout); + emit minPlayersForMultiColumnLayoutChanged(); } void SettingsCache::setTapAnimation(int _tapAnimation) { - tapAnimation = _tapAnimation; - settings->setValue("cards/tapanimation", tapAnimation); + tapAnimation = _tapAnimation; + settings->setValue("cards/tapanimation", tapAnimation); } void SettingsCache::setZoneViewSortByName(int _zoneViewSortByName) { - zoneViewSortByName = _zoneViewSortByName; - settings->setValue("zoneview/sortbyname", zoneViewSortByName); + zoneViewSortByName = _zoneViewSortByName; + settings->setValue("zoneview/sortbyname", zoneViewSortByName); } void SettingsCache::setZoneViewSortByType(int _zoneViewSortByType) { - zoneViewSortByType = _zoneViewSortByType; - settings->setValue("zoneview/sortbytype", zoneViewSortByType); + zoneViewSortByType = _zoneViewSortByType; + settings->setValue("zoneview/sortbytype", zoneViewSortByType); } void SettingsCache::setSoundEnabled(int _soundEnabled) { - soundEnabled = _soundEnabled; - settings->setValue("sound/enabled", soundEnabled); - emit soundEnabledChanged(); + soundEnabled = _soundEnabled; + settings->setValue("sound/enabled", soundEnabled); + emit soundEnabledChanged(); } void SettingsCache::setSoundPath(const QString &_soundPath) { - soundPath = _soundPath; - settings->setValue("sound/path", soundPath); - emit soundPathChanged(); + soundPath = _soundPath; + settings->setValue("sound/path", soundPath); + emit soundPathChanged(); } void SettingsCache::setPriceTagFeature(int _priceTagFeature) { - priceTagFeature = _priceTagFeature; - settings->setValue("deckeditor/pricetags", priceTagFeature); + priceTagFeature = _priceTagFeature; + settings->setValue("deckeditor/pricetags", priceTagFeature); } void SettingsCache::setIgnoreUnregisteredUsers(bool _ignoreUnregisteredUsers) { - ignoreUnregisteredUsers = _ignoreUnregisteredUsers; - settings->setValue("chat/ignore_unregistered", ignoreUnregisteredUsers); - emit ignoreUnregisteredUsersChanged(); + ignoreUnregisteredUsers = _ignoreUnregisteredUsers; + settings->setValue("chat/ignore_unregistered", ignoreUnregisteredUsers); + emit ignoreUnregisteredUsersChanged(); } void SettingsCache::setMainWindowGeometry(const QByteArray &_mainWindowGeometry) { - mainWindowGeometry = _mainWindowGeometry; - settings->setValue("interface/main_window_geometry", mainWindowGeometry); + mainWindowGeometry = _mainWindowGeometry; + settings->setValue("interface/main_window_geometry", mainWindowGeometry); } diff --git a/cockatrice/src/settingscache.h b/cockatrice/src/settingscache.h index 72b60087..6c28227a 100644 --- a/cockatrice/src/settingscache.h +++ b/cockatrice/src/settingscache.h @@ -6,109 +6,109 @@ class QSettings; class SettingsCache : public QObject { - Q_OBJECT + Q_OBJECT signals: - void langChanged(); - void picsPathChanged(); - void cardDatabasePathChanged(); - void tokenDatabasePathChanged(); - void handBgPathChanged(); - void stackBgPathChanged(); - void tableBgPathChanged(); - void playerBgPathChanged(); - void cardBackPicturePathChanged(); - void picDownloadChanged(); - void displayCardNamesChanged(); - void horizontalHandChanged(); - void invertVerticalCoordinateChanged(); - void minPlayersForMultiColumnLayoutChanged(); - void soundEnabledChanged(); - void soundPathChanged(); - void ignoreUnregisteredUsersChanged(); + void langChanged(); + void picsPathChanged(); + void cardDatabasePathChanged(); + void tokenDatabasePathChanged(); + void handBgPathChanged(); + void stackBgPathChanged(); + void tableBgPathChanged(); + void playerBgPathChanged(); + void cardBackPicturePathChanged(); + void picDownloadChanged(); + void displayCardNamesChanged(); + void horizontalHandChanged(); + void invertVerticalCoordinateChanged(); + void minPlayersForMultiColumnLayoutChanged(); + void soundEnabledChanged(); + void soundPathChanged(); + void ignoreUnregisteredUsersChanged(); private: - QSettings *settings; - - QByteArray mainWindowGeometry; - QString lang; - QString deckPath, replaysPath, picsPath, cardDatabasePath, tokenDatabasePath; - QString handBgPath, stackBgPath, tableBgPath, playerBgPath, cardBackPicturePath; - bool picDownload; - bool notificationsEnabled; - bool doubleClickToPlay; - bool playToStack; - int cardInfoMinimized; - QByteArray tabGameSplitterSizes; - bool displayCardNames; - bool horizontalHand; - bool invertVerticalCoordinate; - int minPlayersForMultiColumnLayout; - bool tapAnimation; - bool zoneViewSortByName, zoneViewSortByType; - bool soundEnabled; - QString soundPath; - bool priceTagFeature; - bool ignoreUnregisteredUsers; + QSettings *settings; + + QByteArray mainWindowGeometry; + QString lang; + QString deckPath, replaysPath, picsPath, cardDatabasePath, tokenDatabasePath; + QString handBgPath, stackBgPath, tableBgPath, playerBgPath, cardBackPicturePath; + bool picDownload; + bool notificationsEnabled; + bool doubleClickToPlay; + bool playToStack; + int cardInfoMinimized; + QByteArray tabGameSplitterSizes; + bool displayCardNames; + bool horizontalHand; + bool invertVerticalCoordinate; + int minPlayersForMultiColumnLayout; + bool tapAnimation; + bool zoneViewSortByName, zoneViewSortByType; + bool soundEnabled; + QString soundPath; + bool priceTagFeature; + bool ignoreUnregisteredUsers; public: - SettingsCache(); - const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; } - QString getLang() const { return lang; } - QString getDeckPath() const { return deckPath; } - QString getReplaysPath() const { return replaysPath; } - QString getPicsPath() const { return picsPath; } - QString getCardDatabasePath() const { return cardDatabasePath; } - QString getTokenDatabasePath() const { return tokenDatabasePath; } - QString getHandBgPath() const { return handBgPath; } - QString getStackBgPath() const { return stackBgPath; } - QString getTableBgPath() const { return tableBgPath; } - QString getPlayerBgPath() const { return playerBgPath; } - QString getCardBackPicturePath() const { return cardBackPicturePath; } - bool getPicDownload() const { return picDownload; } - bool getNotificationsEnabled() const { return notificationsEnabled; } - bool getDoubleClickToPlay() const { return doubleClickToPlay; } - bool getPlayToStack() const { return playToStack; } - int getCardInfoMinimized() const { return cardInfoMinimized; } - QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; } - bool getDisplayCardNames() const { return displayCardNames; } - bool getHorizontalHand() const { return horizontalHand; } - bool getInvertVerticalCoordinate() const { return invertVerticalCoordinate; } - int getMinPlayersForMultiColumnLayout() const { return minPlayersForMultiColumnLayout; } - bool getTapAnimation() const { return tapAnimation; } - bool getZoneViewSortByName() const { return zoneViewSortByName; } - bool getZoneViewSortByType() const { return zoneViewSortByType; } - bool getSoundEnabled() const { return soundEnabled; } - QString getSoundPath() const { return soundPath; } - bool getPriceTagFeature() const { return priceTagFeature; } - bool getIgnoreUnregisteredUsers() const { return ignoreUnregisteredUsers; } + SettingsCache(); + const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; } + QString getLang() const { return lang; } + QString getDeckPath() const { return deckPath; } + QString getReplaysPath() const { return replaysPath; } + QString getPicsPath() const { return picsPath; } + QString getCardDatabasePath() const { return cardDatabasePath; } + QString getTokenDatabasePath() const { return tokenDatabasePath; } + QString getHandBgPath() const { return handBgPath; } + QString getStackBgPath() const { return stackBgPath; } + QString getTableBgPath() const { return tableBgPath; } + QString getPlayerBgPath() const { return playerBgPath; } + QString getCardBackPicturePath() const { return cardBackPicturePath; } + bool getPicDownload() const { return picDownload; } + bool getNotificationsEnabled() const { return notificationsEnabled; } + bool getDoubleClickToPlay() const { return doubleClickToPlay; } + bool getPlayToStack() const { return playToStack; } + int getCardInfoMinimized() const { return cardInfoMinimized; } + QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; } + bool getDisplayCardNames() const { return displayCardNames; } + bool getHorizontalHand() const { return horizontalHand; } + bool getInvertVerticalCoordinate() const { return invertVerticalCoordinate; } + int getMinPlayersForMultiColumnLayout() const { return minPlayersForMultiColumnLayout; } + bool getTapAnimation() const { return tapAnimation; } + bool getZoneViewSortByName() const { return zoneViewSortByName; } + bool getZoneViewSortByType() const { return zoneViewSortByType; } + bool getSoundEnabled() const { return soundEnabled; } + QString getSoundPath() const { return soundPath; } + bool getPriceTagFeature() const { return priceTagFeature; } + bool getIgnoreUnregisteredUsers() const { return ignoreUnregisteredUsers; } public slots: - void setMainWindowGeometry(const QByteArray &_mainWindowGeometry); - void setLang(const QString &_lang); - void setDeckPath(const QString &_deckPath); - void setReplaysPath(const QString &_replaysPath); - void setPicsPath(const QString &_picsPath); - void setCardDatabasePath(const QString &_cardDatabasePath); - void setTokenDatabasePath(const QString &_tokenDatabasePath); - void setHandBgPath(const QString &_handBgPath); - void setStackBgPath(const QString &_stackBgPath); - void setTableBgPath(const QString &_tableBgPath); - void setPlayerBgPath(const QString &_playerBgPath); - void setCardBackPicturePath(const QString &_cardBackPicturePath); - void setPicDownload(int _picDownload); - void setNotificationsEnabled(int _notificationsEnabled); - void setDoubleClickToPlay(int _doubleClickToPlay); - void setPlayToStack(int _playToStack); - void setCardInfoMinimized(int _cardInfoMinimized); - void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes); - void setDisplayCardNames(int _displayCardNames); - void setHorizontalHand(int _horizontalHand); - void setInvertVerticalCoordinate(int _invertVerticalCoordinate); - void setMinPlayersForMultiColumnLayout(int _minPlayersForMultiColumnLayout); - void setTapAnimation(int _tapAnimation); - void setZoneViewSortByName(int _zoneViewSortByName); - void setZoneViewSortByType(int _zoneViewSortByType); - void setSoundEnabled(int _soundEnabled); - void setSoundPath(const QString &_soundPath); - void setPriceTagFeature(int _priceTagFeature); - void setIgnoreUnregisteredUsers(bool _ignoreUnregisteredUsers); + void setMainWindowGeometry(const QByteArray &_mainWindowGeometry); + void setLang(const QString &_lang); + void setDeckPath(const QString &_deckPath); + void setReplaysPath(const QString &_replaysPath); + void setPicsPath(const QString &_picsPath); + void setCardDatabasePath(const QString &_cardDatabasePath); + void setTokenDatabasePath(const QString &_tokenDatabasePath); + void setHandBgPath(const QString &_handBgPath); + void setStackBgPath(const QString &_stackBgPath); + void setTableBgPath(const QString &_tableBgPath); + void setPlayerBgPath(const QString &_playerBgPath); + void setCardBackPicturePath(const QString &_cardBackPicturePath); + void setPicDownload(int _picDownload); + void setNotificationsEnabled(int _notificationsEnabled); + void setDoubleClickToPlay(int _doubleClickToPlay); + void setPlayToStack(int _playToStack); + void setCardInfoMinimized(int _cardInfoMinimized); + void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes); + void setDisplayCardNames(int _displayCardNames); + void setHorizontalHand(int _horizontalHand); + void setInvertVerticalCoordinate(int _invertVerticalCoordinate); + void setMinPlayersForMultiColumnLayout(int _minPlayersForMultiColumnLayout); + void setTapAnimation(int _tapAnimation); + void setZoneViewSortByName(int _zoneViewSortByName); + void setZoneViewSortByType(int _zoneViewSortByType); + void setSoundEnabled(int _soundEnabled); + void setSoundPath(const QString &_soundPath); + void setPriceTagFeature(int _priceTagFeature); + void setIgnoreUnregisteredUsers(bool _ignoreUnregisteredUsers); }; extern SettingsCache *settingsCache; diff --git a/cockatrice/src/soundengine.cpp b/cockatrice/src/soundengine.cpp index 35d179fd..5847c9ae 100644 --- a/cockatrice/src/soundengine.cpp +++ b/cockatrice/src/soundengine.cpp @@ -6,91 +6,91 @@ #include SoundEngine::SoundEngine(QObject *parent) - : QObject(parent), audio(0) + : QObject(parent), audio(0) { - inputBuffer = new QBuffer(this); - - connect(settingsCache, SIGNAL(soundPathChanged()), this, SLOT(cacheData())); - connect(settingsCache, SIGNAL(soundEnabledChanged()), this, SLOT(soundEnabledChanged())); - cacheData(); - soundEnabledChanged(); + inputBuffer = new QBuffer(this); + + connect(settingsCache, SIGNAL(soundPathChanged()), this, SLOT(cacheData())); + connect(settingsCache, SIGNAL(soundEnabledChanged()), this, SLOT(soundEnabledChanged())); + cacheData(); + soundEnabledChanged(); } void SoundEngine::cacheData() { - static const QStringList fileNames = QStringList() - << "notification" << "draw" << "playcard" << "shuffle" << "tap" << "untap" << "cuckoo"; - for (int i = 0; i < fileNames.size(); ++i) { - QFile file(settingsCache->getSoundPath() + "/" + fileNames[i] + ".raw"); - file.open(QIODevice::ReadOnly); - audioData.insert(fileNames[i], file.readAll()); - file.close(); - } + static const QStringList fileNames = QStringList() + << "notification" << "draw" << "playcard" << "shuffle" << "tap" << "untap" << "cuckoo"; + for (int i = 0; i < fileNames.size(); ++i) { + QFile file(settingsCache->getSoundPath() + "/" + fileNames[i] + ".raw"); + file.open(QIODevice::ReadOnly); + audioData.insert(fileNames[i], file.readAll()); + file.close(); + } } void SoundEngine::soundEnabledChanged() { - if (settingsCache->getSoundEnabled()) { - qDebug("SoundEngine: enabling sound"); - QAudioFormat format; - format.setFrequency(44100); - format.setChannels(1); - format.setSampleSize(16); - format.setCodec("audio/pcm"); - format.setByteOrder(QAudioFormat::LittleEndian); - format.setSampleType(QAudioFormat::SignedInt); - audio = new QAudioOutput(format, this); - } else if (audio) { - qDebug("SoundEngine: disabling sound"); - audio->stop(); - audio->deleteLater(); - audio = 0; - } + if (settingsCache->getSoundEnabled()) { + qDebug("SoundEngine: enabling sound"); + QAudioFormat format; + format.setFrequency(44100); + format.setChannels(1); + format.setSampleSize(16); + format.setCodec("audio/pcm"); + format.setByteOrder(QAudioFormat::LittleEndian); + format.setSampleType(QAudioFormat::SignedInt); + audio = new QAudioOutput(format, this); + } else if (audio) { + qDebug("SoundEngine: disabling sound"); + audio->stop(); + audio->deleteLater(); + audio = 0; + } } void SoundEngine::playSound(const QString &fileName) { - if (!audio) - return; - - audio->stop(); - inputBuffer->close(); - inputBuffer->setData(audioData[fileName]); - inputBuffer->open(QIODevice::ReadOnly); - audio->start(inputBuffer); + if (!audio) + return; + + audio->stop(); + inputBuffer->close(); + inputBuffer->setData(audioData[fileName]); + inputBuffer->open(QIODevice::ReadOnly); + audio->start(inputBuffer); } void SoundEngine::notification() { - playSound("notification"); + playSound("notification"); } void SoundEngine::draw() { - playSound("draw"); + playSound("draw"); } void SoundEngine::playCard() { - playSound("playcard"); + playSound("playcard"); } void SoundEngine::shuffle() { - playSound("shuffle"); + playSound("shuffle"); } void SoundEngine::tap() { - playSound("tap"); + playSound("tap"); } void SoundEngine::untap() { - playSound("untap"); + playSound("untap"); } void SoundEngine::cuckoo() { - playSound("cuckoo"); + playSound("cuckoo"); } diff --git a/cockatrice/src/soundengine.h b/cockatrice/src/soundengine.h index 89dd6751..a3071fda 100644 --- a/cockatrice/src/soundengine.h +++ b/cockatrice/src/soundengine.h @@ -8,25 +8,25 @@ class QAudioOutput; class QBuffer; class SoundEngine : public QObject { - Q_OBJECT + Q_OBJECT private: - void playSound(const QString &fileName); - QMap audioData; - QBuffer *inputBuffer; - QAudioOutput *audio; + void playSound(const QString &fileName); + QMap audioData; + QBuffer *inputBuffer; + QAudioOutput *audio; private slots: - void cacheData(); - void soundEnabledChanged(); + void cacheData(); + void soundEnabledChanged(); public: - SoundEngine(QObject *parent = 0); + SoundEngine(QObject *parent = 0); public slots: - void notification(); - void draw(); - void playCard(); - void shuffle(); - void tap(); - void untap(); - void cuckoo(); + void notification(); + void draw(); + void playCard(); + void shuffle(); + void tap(); + void untap(); + void cuckoo(); }; extern SoundEngine *soundEngine; diff --git a/cockatrice/src/stackzone.cpp b/cockatrice/src/stackzone.cpp index 216dac99..f3e4767c 100644 --- a/cockatrice/src/stackzone.cpp +++ b/cockatrice/src/stackzone.cpp @@ -10,100 +10,100 @@ #include "pb/command_move_card.pb.h" StackZone::StackZone(Player *_p, int _zoneHeight, QGraphicsItem *parent) - : SelectZone(_p, "stack", false, false, true, parent), zoneHeight(_zoneHeight) + : SelectZone(_p, "stack", false, false, true, parent), zoneHeight(_zoneHeight) { - connect(settingsCache, SIGNAL(stackBgPathChanged()), this, SLOT(updateBgPixmap())); - updateBgPixmap(); - setCacheMode(DeviceCoordinateCache); + connect(settingsCache, SIGNAL(stackBgPathChanged()), this, SLOT(updateBgPixmap())); + updateBgPixmap(); + setCacheMode(DeviceCoordinateCache); } void StackZone::updateBgPixmap() { - QString bgPath = settingsCache->getStackBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); - update(); + QString bgPath = settingsCache->getStackBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); + update(); } void StackZone::addCardImpl(CardItem *card, int x, int /*y*/) { - if (x == -1) - x = cards.size(); - cards.insert(x, card); + if (x == -1) + x = cards.size(); + cards.insert(x, card); - if (!cards.getContentsKnown()) { - card->setId(-1); - card->setName(); - } - card->setParentItem(this); - card->resetState(); - card->setVisible(true); - card->update(); + if (!cards.getContentsKnown()) { + card->setId(-1); + card->setName(); + } + card->setParentItem(this); + card->resetState(); + card->setVisible(true); + card->update(); } QRectF StackZone::boundingRect() const { - return QRectF(0, 0, 100, zoneHeight); + return QRectF(0, 0, 100, zoneHeight); } void StackZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), QColor(113, 43, 43)); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), QColor(113, 43, 43)); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); } void StackZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) { - if (startZone == this) - return; - - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(0); - cmd.set_y(0); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + if (startZone == this) + return; + + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(0); + cmd.set_y(0); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - player->sendGameCommand(cmd); + player->sendGameCommand(cmd); } void StackZone::reorganizeCards() { - if (!cards.isEmpty()) { - QList arrowsToUpdate; - - const int cardCount = cards.size(); - qreal totalWidth = boundingRect().width(); - qreal totalHeight = boundingRect().height(); - qreal cardWidth = cards.at(0)->boundingRect().width(); - qreal cardHeight = cards.at(0)->boundingRect().height(); - qreal xspace = 5; - qreal x1 = xspace; - qreal x2 = totalWidth - xspace - cardWidth; - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cards.at(i); - qreal x = i % 2 ? x2 : x1; - // If the total height of the cards is smaller than the available height, - // the cards do not need to overlap and are displayed in the center of the area. - if (cardHeight * cardCount > totalHeight) - c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); - else - c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); - c->setRealZValue(i); - - arrowsToUpdate.append(c->getArrowsFrom()); - arrowsToUpdate.append(c->getArrowsTo()); - } - QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); - while (arrowIterator.hasNext()) - arrowIterator.next()->updatePath(); - } - update(); + if (!cards.isEmpty()) { + QList arrowsToUpdate; + + const int cardCount = cards.size(); + qreal totalWidth = boundingRect().width(); + qreal totalHeight = boundingRect().height(); + qreal cardWidth = cards.at(0)->boundingRect().width(); + qreal cardHeight = cards.at(0)->boundingRect().height(); + qreal xspace = 5; + qreal x1 = xspace; + qreal x2 = totalWidth - xspace - cardWidth; + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + qreal x = i % 2 ? x2 : x1; + // If the total height of the cards is smaller than the available height, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardHeight * cardCount > totalHeight) + c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); + else + c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setRealZValue(i); + + arrowsToUpdate.append(c->getArrowsFrom()); + arrowsToUpdate.append(c->getArrowsTo()); + } + QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); + while (arrowIterator.hasNext()) + arrowIterator.next()->updatePath(); + } + update(); } diff --git a/cockatrice/src/stackzone.h b/cockatrice/src/stackzone.h index 5fb2878b..948d3bcb 100644 --- a/cockatrice/src/stackzone.h +++ b/cockatrice/src/stackzone.h @@ -4,20 +4,20 @@ #include "selectzone.h" class StackZone : public SelectZone { - Q_OBJECT + Q_OBJECT private: - qreal zoneHeight; - QPixmap bgPixmap; + qreal zoneHeight; + QPixmap bgPixmap; private slots: - void updateBgPixmap(); + void updateBgPixmap(); public: - StackZone(Player *_p, int _zoneHeight, QGraphicsItem *parent = 0); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); + StackZone(Player *_p, int _zoneHeight, QGraphicsItem *parent = 0); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); protected: - void addCardImpl(CardItem *card, int x, int y); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/tab.cpp b/cockatrice/src/tab.cpp index 0c20a821..28838ed2 100644 --- a/cockatrice/src/tab.cpp +++ b/cockatrice/src/tab.cpp @@ -4,28 +4,28 @@ #include #include Tab::Tab(TabSupervisor *_tabSupervisor, QWidget *parent) - : QWidget(parent), tabSupervisor(_tabSupervisor), contentsChanged(false), infoPopup(0) + : QWidget(parent), tabSupervisor(_tabSupervisor), contentsChanged(false), infoPopup(0) { } void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName) { - infoPopup = new CardInfoWidget(CardInfoWidget::ModePopUp, cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); - infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); - QRect screenRect = qApp->desktop()->screenGeometry(this); - infoPopup->move( - qMax(screenRect.left(), qMin(pos.x() - infoPopup->width() / 2, screenRect.left() + screenRect.width() - infoPopup->width())), - qMax(screenRect.top(), qMin(pos.y() - infoPopup->height() / 2, screenRect.top() + screenRect.height() - infoPopup->height())) - ); - infoPopup->show(); + infoPopup = new CardInfoWidget(CardInfoWidget::ModePopUp, cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); + infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); + QRect screenRect = qApp->desktop()->screenGeometry(this); + infoPopup->move( + qMax(screenRect.left(), qMin(pos.x() - infoPopup->width() / 2, screenRect.left() + screenRect.width() - infoPopup->width())), + qMax(screenRect.top(), qMin(pos.y() - infoPopup->height() / 2, screenRect.top() + screenRect.height() - infoPopup->height())) + ); + infoPopup->show(); } void Tab::deleteCardInfoPopup(const QString &cardName) { - if (infoPopup) { - if ((infoPopup->getCardName() == cardName) || (cardName == "_")) { - infoPopup->deleteLater(); - infoPopup = 0; - } - } + if (infoPopup) { + if ((infoPopup->getCardName() == cardName) || (cardName == "_")) { + infoPopup->deleteLater(); + infoPopup = 0; + } + } } diff --git a/cockatrice/src/tab.h b/cockatrice/src/tab.h index 445180fd..65473121 100644 --- a/cockatrice/src/tab.h +++ b/cockatrice/src/tab.h @@ -8,29 +8,29 @@ class TabSupervisor; class CardInfoWidget; class Tab : public QWidget { - Q_OBJECT + Q_OBJECT signals: - void userEvent(bool globalEvent = true); - void tabTextChanged(Tab *tab, const QString &newTabText); + void userEvent(bool globalEvent = true); + void tabTextChanged(Tab *tab, const QString &newTabText); protected: - TabSupervisor *tabSupervisor; - void addTabMenu(QMenu *menu) { tabMenus.append(menu); } + TabSupervisor *tabSupervisor; + void addTabMenu(QMenu *menu) { tabMenus.append(menu); } protected slots: - void showCardInfoPopup(const QPoint &pos, const QString &cardName); - void deleteCardInfoPopup(const QString &cardName); + void showCardInfoPopup(const QPoint &pos, const QString &cardName); + void deleteCardInfoPopup(const QString &cardName); private: - bool contentsChanged; - CardInfoWidget *infoPopup; - QList tabMenus; + bool contentsChanged; + CardInfoWidget *infoPopup; + QList tabMenus; public: - Tab(TabSupervisor *_tabSupervisor, QWidget *parent = 0); - const QList &getTabMenus() const { return tabMenus; } - TabSupervisor *getTabSupervisor() const { return tabSupervisor; } - bool getContentsChanged() const { return contentsChanged; } - void setContentsChanged(bool _contentsChanged) { contentsChanged = _contentsChanged; } - virtual QString getTabText() const = 0; - virtual void retranslateUi() = 0; - virtual void closeRequest() { } + Tab(TabSupervisor *_tabSupervisor, QWidget *parent = 0); + const QList &getTabMenus() const { return tabMenus; } + TabSupervisor *getTabSupervisor() const { return tabSupervisor; } + bool getContentsChanged() const { return contentsChanged; } + void setContentsChanged(bool _contentsChanged) { contentsChanged = _contentsChanged; } + virtual QString getTabText() const = 0; + virtual void retranslateUi() = 0; + virtual void closeRequest() { } }; #endif diff --git a/cockatrice/src/tab_admin.cpp b/cockatrice/src/tab_admin.cpp index 53189707..71018186 100644 --- a/cockatrice/src/tab_admin.cpp +++ b/cockatrice/src/tab_admin.cpp @@ -14,119 +14,119 @@ #include "pb/admin_commands.pb.h" ShutdownDialog::ShutdownDialog(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - QLabel *reasonLabel = new QLabel(tr("&Reason for shutdown:")); - reasonEdit = new QLineEdit; - reasonLabel->setBuddy(reasonEdit); - QLabel *minutesLabel = new QLabel(tr("&Time until shutdown (minutes):")); - minutesEdit = new QSpinBox; - minutesLabel->setBuddy(minutesEdit); - minutesEdit->setMinimum(0); - minutesEdit->setValue(5); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(reasonLabel, 0, 0); - mainLayout->addWidget(reasonEdit, 0, 1); - mainLayout->addWidget(minutesLabel, 1, 0); - mainLayout->addWidget(minutesEdit, 1, 1); - mainLayout->addWidget(buttonBox, 2, 0, 1, 2); - - setLayout(mainLayout); - setWindowTitle(tr("Shut down server")); + QLabel *reasonLabel = new QLabel(tr("&Reason for shutdown:")); + reasonEdit = new QLineEdit; + reasonLabel->setBuddy(reasonEdit); + QLabel *minutesLabel = new QLabel(tr("&Time until shutdown (minutes):")); + minutesEdit = new QSpinBox; + minutesLabel->setBuddy(minutesEdit); + minutesEdit->setMinimum(0); + minutesEdit->setValue(5); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QGridLayout *mainLayout = new QGridLayout; + mainLayout->addWidget(reasonLabel, 0, 0); + mainLayout->addWidget(reasonEdit, 0, 1); + mainLayout->addWidget(minutesLabel, 1, 0); + mainLayout->addWidget(minutesEdit, 1, 1); + mainLayout->addWidget(buttonBox, 2, 0, 1, 2); + + setLayout(mainLayout); + setWindowTitle(tr("Shut down server")); } QString ShutdownDialog::getReason() const { - return reasonEdit->text(); + return reasonEdit->text(); } int ShutdownDialog::getMinutes() const { - return minutesEdit->value(); + return minutesEdit->value(); } TabAdmin::TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool _fullAdmin, QWidget *parent) - : Tab(_tabSupervisor, parent), locked(true), client(_client), fullAdmin(_fullAdmin) + : Tab(_tabSupervisor, parent), locked(true), client(_client), fullAdmin(_fullAdmin) { - updateServerMessageButton = new QPushButton; - connect(updateServerMessageButton, SIGNAL(clicked()), this, SLOT(actUpdateServerMessage())); - shutdownServerButton = new QPushButton; - connect(shutdownServerButton, SIGNAL(clicked()), this, SLOT(actShutdownServer())); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(updateServerMessageButton); - vbox->addWidget(shutdownServerButton); - vbox->addStretch(); - - adminGroupBox = new QGroupBox; - adminGroupBox->setLayout(vbox); - adminGroupBox->setEnabled(false); - - unlockButton = new QPushButton; - connect(unlockButton, SIGNAL(clicked()), this, SLOT(actUnlock())); - lockButton = new QPushButton; - lockButton->setEnabled(false); - connect(lockButton, SIGNAL(clicked()), this, SLOT(actLock())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(adminGroupBox); - mainLayout->addWidget(unlockButton); - mainLayout->addWidget(lockButton); - - retranslateUi(); - setLayout(mainLayout); + updateServerMessageButton = new QPushButton; + connect(updateServerMessageButton, SIGNAL(clicked()), this, SLOT(actUpdateServerMessage())); + shutdownServerButton = new QPushButton; + connect(shutdownServerButton, SIGNAL(clicked()), this, SLOT(actShutdownServer())); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(updateServerMessageButton); + vbox->addWidget(shutdownServerButton); + vbox->addStretch(); + + adminGroupBox = new QGroupBox; + adminGroupBox->setLayout(vbox); + adminGroupBox->setEnabled(false); + + unlockButton = new QPushButton; + connect(unlockButton, SIGNAL(clicked()), this, SLOT(actUnlock())); + lockButton = new QPushButton; + lockButton->setEnabled(false); + connect(lockButton, SIGNAL(clicked()), this, SLOT(actLock())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(adminGroupBox); + mainLayout->addWidget(unlockButton); + mainLayout->addWidget(lockButton); + + retranslateUi(); + setLayout(mainLayout); } void TabAdmin::retranslateUi() { - updateServerMessageButton->setText(tr("Update server &message")); - shutdownServerButton->setText(tr("&Shut down server")); - adminGroupBox->setTitle(tr("Server administration functions")); - - unlockButton->setText(tr("&Unlock functions")); - lockButton->setText(tr("&Lock functions")); + updateServerMessageButton->setText(tr("Update server &message")); + shutdownServerButton->setText(tr("&Shut down server")); + adminGroupBox->setTitle(tr("Server administration functions")); + + unlockButton->setText(tr("&Unlock functions")); + lockButton->setText(tr("&Lock functions")); } void TabAdmin::actUpdateServerMessage() { - client->sendCommand(client->prepareAdminCommand(Command_UpdateServerMessage())); + client->sendCommand(client->prepareAdminCommand(Command_UpdateServerMessage())); } void TabAdmin::actShutdownServer() { - ShutdownDialog dlg; - if (dlg.exec()) { - Command_ShutdownServer cmd; - cmd.set_reason(dlg.getReason().toStdString()); - cmd.set_minutes(dlg.getMinutes()); - - client->sendCommand(client->prepareAdminCommand(cmd)); - } + ShutdownDialog dlg; + if (dlg.exec()) { + Command_ShutdownServer cmd; + cmd.set_reason(dlg.getReason().toStdString()); + cmd.set_minutes(dlg.getMinutes()); + + client->sendCommand(client->prepareAdminCommand(cmd)); + } } void TabAdmin::actUnlock() { - if (QMessageBox::question(this, tr("Unlock administration functions"), tr("Do you really want to unlock the administration functions?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - if (fullAdmin) - adminGroupBox->setEnabled(true); - lockButton->setEnabled(true); - unlockButton->setEnabled(false); - locked = false; - emit adminLockChanged(false); - } + if (QMessageBox::question(this, tr("Unlock administration functions"), tr("Do you really want to unlock the administration functions?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + if (fullAdmin) + adminGroupBox->setEnabled(true); + lockButton->setEnabled(true); + unlockButton->setEnabled(false); + locked = false; + emit adminLockChanged(false); + } } void TabAdmin::actLock() { - if (fullAdmin) - adminGroupBox->setEnabled(false); - lockButton->setEnabled(false); - unlockButton->setEnabled(true); - locked = true; - emit adminLockChanged(true); + if (fullAdmin) + adminGroupBox->setEnabled(false); + lockButton->setEnabled(false); + unlockButton->setEnabled(true); + locked = true; + emit adminLockChanged(true); } diff --git a/cockatrice/src/tab_admin.h b/cockatrice/src/tab_admin.h index 7d5e9175..cc5ae6a9 100644 --- a/cockatrice/src/tab_admin.h +++ b/cockatrice/src/tab_admin.h @@ -12,38 +12,38 @@ class QSpinBox; class QLineEdit; class ShutdownDialog : public QDialog { - Q_OBJECT + Q_OBJECT private: - QLineEdit *reasonEdit; - QSpinBox *minutesEdit; + QLineEdit *reasonEdit; + QSpinBox *minutesEdit; public: - ShutdownDialog(QWidget *parent = 0); - QString getReason() const; - int getMinutes() const; + ShutdownDialog(QWidget *parent = 0); + QString getReason() const; + int getMinutes() const; }; class TabAdmin : public Tab { - Q_OBJECT + Q_OBJECT private: - bool locked; - AbstractClient *client; - bool fullAdmin; - QPushButton *updateServerMessageButton, *shutdownServerButton; - QGroupBox *adminGroupBox; - QPushButton *unlockButton, *lockButton; + bool locked; + AbstractClient *client; + bool fullAdmin; + QPushButton *updateServerMessageButton, *shutdownServerButton; + QGroupBox *adminGroupBox; + QPushButton *unlockButton, *lockButton; signals: - void adminLockChanged(bool lock); + void adminLockChanged(bool lock); private slots: - void actUpdateServerMessage(); - void actShutdownServer(); - - void actUnlock(); - void actLock(); + void actUpdateServerMessage(); + void actShutdownServer(); + + void actUnlock(); + void actLock(); public: - TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool _fullAdmin, QWidget *parent = 0); - void retranslateUi(); - QString getTabText() const { return tr("Administration"); } - bool getLocked() const { return locked; } + TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool _fullAdmin, QWidget *parent = 0); + void retranslateUi(); + QString getTabText() const { return tr("Administration"); } + bool getLocked() const { return locked; } }; #endif diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index f7c035c8..80709a84 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -37,111 +37,111 @@ void SearchLineEdit::keyPressEvent(QKeyEvent *event) { - if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down))) - QCoreApplication::sendEvent(treeView, event); - QLineEdit::keyPressEvent(event); + if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down))) + QCoreApplication::sendEvent(treeView, event); + QLineEdit::keyPressEvent(event); } TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) - : Tab(_tabSupervisor, parent), modified(false) + : Tab(_tabSupervisor, parent), modified(false) { - aSearch = new QAction(QString(), this); - aSearch->setIcon(QIcon(":/resources/icon_search.svg")); - connect(aSearch, SIGNAL(triggered()), this, SLOT(actSearch())); - aClearSearch = new QAction(QString(), this); - aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); - connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); + aSearch = new QAction(QString(), this); + aSearch->setIcon(QIcon(":/resources/icon_search.svg")); + connect(aSearch, SIGNAL(triggered()), this, SLOT(actSearch())); + aClearSearch = new QAction(QString(), this); + aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); + connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); - searchLabel = new QLabel(); - searchEdit = new SearchLineEdit; - searchLabel->setBuddy(searchEdit); - connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); - connect(searchEdit, SIGNAL(returnPressed()), this, SLOT(actAddCard())); - QToolButton *searchButton = new QToolButton; - searchButton->setDefaultAction(aSearch); - QToolButton *clearSearchButton = new QToolButton; - clearSearchButton->setDefaultAction(aClearSearch); + searchLabel = new QLabel(); + searchEdit = new SearchLineEdit; + searchLabel->setBuddy(searchEdit); + connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); + connect(searchEdit, SIGNAL(returnPressed()), this, SLOT(actAddCard())); + QToolButton *searchButton = new QToolButton; + searchButton->setDefaultAction(aSearch); + QToolButton *clearSearchButton = new QToolButton; + clearSearchButton->setDefaultAction(aClearSearch); - QHBoxLayout *searchLayout = new QHBoxLayout; - searchLayout->addWidget(searchLabel); - searchLayout->addWidget(searchEdit); - searchLayout->addWidget(searchButton); - searchLayout->addWidget(clearSearchButton); + QHBoxLayout *searchLayout = new QHBoxLayout; + searchLayout->addWidget(searchLabel); + searchLayout->addWidget(searchEdit); + searchLayout->addWidget(searchButton); + searchLayout->addWidget(clearSearchButton); - databaseModel = new CardDatabaseModel(db, this); - databaseDisplayModel = new CardDatabaseDisplayModel(this); - databaseDisplayModel->setSourceModel(databaseModel); - databaseDisplayModel->setFilterKeyColumn(0); - databaseDisplayModel->sort(0, Qt::AscendingOrder); - databaseView = new QTreeView(); - databaseView->setModel(databaseDisplayModel); - databaseView->setUniformRowHeights(true); - databaseView->setRootIsDecorated(false); - databaseView->setAlternatingRowColors(true); - databaseView->setSortingEnabled(true); - databaseView->sortByColumn(0, Qt::AscendingOrder); - databaseView->resizeColumnToContents(0); - connect(databaseView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoLeft(const QModelIndex &, const QModelIndex &))); - connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard())); - searchEdit->setTreeView(databaseView); + databaseModel = new CardDatabaseModel(db, this); + databaseDisplayModel = new CardDatabaseDisplayModel(this); + databaseDisplayModel->setSourceModel(databaseModel); + databaseDisplayModel->setFilterKeyColumn(0); + databaseDisplayModel->sort(0, Qt::AscendingOrder); + databaseView = new QTreeView(); + databaseView->setModel(databaseDisplayModel); + databaseView->setUniformRowHeights(true); + databaseView->setRootIsDecorated(false); + databaseView->setAlternatingRowColors(true); + databaseView->setSortingEnabled(true); + databaseView->sortByColumn(0, Qt::AscendingOrder); + databaseView->resizeColumnToContents(0); + connect(databaseView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoLeft(const QModelIndex &, const QModelIndex &))); + connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard())); + searchEdit->setTreeView(databaseView); - QVBoxLayout *leftFrame = new QVBoxLayout; - leftFrame->addLayout(searchLayout); - leftFrame->addWidget(databaseView); + QVBoxLayout *leftFrame = new QVBoxLayout; + leftFrame->addLayout(searchLayout); + leftFrame->addWidget(databaseView); - cardInfo = new CardInfoWidget(CardInfoWidget::ModeDeckEditor); - cardInfo->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); + cardInfo = new CardInfoWidget(CardInfoWidget::ModeDeckEditor); + cardInfo->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); - QToolBar *verticalToolBar = new QToolBar; - verticalToolBar->setOrientation(Qt::Vertical); - verticalToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - verticalToolBar->setIconSize(QSize(24, 24)); - QHBoxLayout *verticalToolBarLayout = new QHBoxLayout; - verticalToolBarLayout->addStretch(); - verticalToolBarLayout->addWidget(verticalToolBar); - verticalToolBarLayout->addStretch(); + QToolBar *verticalToolBar = new QToolBar; + verticalToolBar->setOrientation(Qt::Vertical); + verticalToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + verticalToolBar->setIconSize(QSize(24, 24)); + QHBoxLayout *verticalToolBarLayout = new QHBoxLayout; + verticalToolBarLayout->addStretch(); + verticalToolBarLayout->addWidget(verticalToolBar); + verticalToolBarLayout->addStretch(); - QVBoxLayout *middleFrame = new QVBoxLayout; - middleFrame->addWidget(cardInfo, 10); - middleFrame->addLayout(verticalToolBarLayout); + QVBoxLayout *middleFrame = new QVBoxLayout; + middleFrame->addWidget(cardInfo, 10); + middleFrame->addLayout(verticalToolBarLayout); - deckModel = new DeckListModel(this); - connect(deckModel, SIGNAL(deckHashChanged()), this, SLOT(updateHash())); - deckView = new QTreeView(); - deckView->setModel(deckModel); - deckView->setUniformRowHeights(true); - deckView->header()->setResizeMode(QHeaderView::ResizeToContents); - connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); + deckModel = new DeckListModel(this); + connect(deckModel, SIGNAL(deckHashChanged()), this, SLOT(updateHash())); + deckView = new QTreeView(); + deckView->setModel(deckModel); + deckView->setUniformRowHeights(true); + deckView->header()->setResizeMode(QHeaderView::ResizeToContents); + connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); - nameLabel = new QLabel(); - nameEdit = new QLineEdit; - nameLabel->setBuddy(nameEdit); - connect(nameEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateName(const QString &))); - commentsLabel = new QLabel(); - commentsEdit = new QTextEdit; - commentsEdit->setMaximumHeight(70); - commentsLabel->setBuddy(commentsEdit); - connect(commentsEdit, SIGNAL(textChanged()), this, SLOT(updateComments())); - hashLabel1 = new QLabel(); - hashLabel = new QLabel; + nameLabel = new QLabel(); + nameEdit = new QLineEdit; + nameLabel->setBuddy(nameEdit); + connect(nameEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateName(const QString &))); + commentsLabel = new QLabel(); + commentsEdit = new QTextEdit; + commentsEdit->setMaximumHeight(70); + commentsLabel->setBuddy(commentsEdit); + connect(commentsEdit, SIGNAL(textChanged()), this, SLOT(updateComments())); + hashLabel1 = new QLabel(); + hashLabel = new QLabel; - QGridLayout *grid = new QGridLayout; - grid->addWidget(nameLabel, 0, 0); - grid->addWidget(nameEdit, 0, 1); + QGridLayout *grid = new QGridLayout; + grid->addWidget(nameLabel, 0, 0); + grid->addWidget(nameEdit, 0, 1); - grid->addWidget(commentsLabel, 1, 0); - grid->addWidget(commentsEdit, 1, 1); - - grid->addWidget(hashLabel1, 2, 0); - grid->addWidget(hashLabel, 2, 1); + grid->addWidget(commentsLabel, 1, 0); + grid->addWidget(commentsEdit, 1, 1); + + grid->addWidget(hashLabel1, 2, 0); + grid->addWidget(hashLabel, 2, 1); // Update price aUpdatePrices = new QAction(QString(), this); aUpdatePrices->setIcon(QIcon(":/resources/icon_update.png")); connect(aUpdatePrices, SIGNAL(triggered()), this, SLOT(actUpdatePrices())); - if (!settingsCache->getPriceTagFeature()) - aUpdatePrices->setVisible(false); - + if (!settingsCache->getPriceTagFeature()) + aUpdatePrices->setVisible(false); + QToolBar *deckToolBar = new QToolBar; deckToolBar->setOrientation(Qt::Vertical); deckToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); @@ -151,472 +151,472 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) deckToolbarLayout->addStretch(); deckToolbarLayout->addWidget(deckToolBar); deckToolbarLayout->addStretch(); - - QVBoxLayout *rightFrame = new QVBoxLayout; - rightFrame->addLayout(grid); - rightFrame->addWidget(deckView, 10); + + QVBoxLayout *rightFrame = new QVBoxLayout; + rightFrame->addLayout(grid); + rightFrame->addWidget(deckView, 10); rightFrame->addLayout(deckToolbarLayout); - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addLayout(leftFrame, 10); - mainLayout->addLayout(middleFrame); - mainLayout->addLayout(rightFrame, 10); - setLayout(mainLayout); - - aNewDeck = new QAction(QString(), this); - aNewDeck->setShortcuts(QKeySequence::New); - connect(aNewDeck, SIGNAL(triggered()), this, SLOT(actNewDeck())); - aLoadDeck = new QAction(QString(), this); - aLoadDeck->setShortcuts(QKeySequence::Open); - connect(aLoadDeck, SIGNAL(triggered()), this, SLOT(actLoadDeck())); - aSaveDeck = new QAction(QString(), this); - aSaveDeck->setShortcuts(QKeySequence::Save); - connect(aSaveDeck, SIGNAL(triggered()), this, SLOT(actSaveDeck())); - aSaveDeckAs = new QAction(QString(), this); -// aSaveDeckAs->setShortcuts(QKeySequence::SaveAs); - connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs())); - aLoadDeckFromClipboard = new QAction(QString(), this); - connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard())); - aLoadDeckFromClipboard->setShortcuts(QKeySequence::Paste); - aSaveDeckToClipboard = new QAction(QString(), this); - connect(aSaveDeckToClipboard, SIGNAL(triggered()), this, SLOT(actSaveDeckToClipboard())); - aSaveDeckToClipboard->setShortcuts(QKeySequence::Copy); - aPrintDeck = new QAction(QString(), this); - aPrintDeck->setShortcuts(QKeySequence::Print); - connect(aPrintDeck, SIGNAL(triggered()), this, SLOT(actPrintDeck())); - aAnalyzeDeck = new QAction(QString(), this); - connect(aAnalyzeDeck, SIGNAL(triggered()), this, SLOT(actAnalyzeDeck())); - aClose = new QAction(QString(), this); - connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest())); + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addLayout(leftFrame, 10); + mainLayout->addLayout(middleFrame); + mainLayout->addLayout(rightFrame, 10); + setLayout(mainLayout); + + aNewDeck = new QAction(QString(), this); + aNewDeck->setShortcuts(QKeySequence::New); + connect(aNewDeck, SIGNAL(triggered()), this, SLOT(actNewDeck())); + aLoadDeck = new QAction(QString(), this); + aLoadDeck->setShortcuts(QKeySequence::Open); + connect(aLoadDeck, SIGNAL(triggered()), this, SLOT(actLoadDeck())); + aSaveDeck = new QAction(QString(), this); + aSaveDeck->setShortcuts(QKeySequence::Save); + connect(aSaveDeck, SIGNAL(triggered()), this, SLOT(actSaveDeck())); + aSaveDeckAs = new QAction(QString(), this); +// aSaveDeckAs->setShortcuts(QKeySequence::SaveAs); + connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs())); + aLoadDeckFromClipboard = new QAction(QString(), this); + connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard())); + aLoadDeckFromClipboard->setShortcuts(QKeySequence::Paste); + aSaveDeckToClipboard = new QAction(QString(), this); + connect(aSaveDeckToClipboard, SIGNAL(triggered()), this, SLOT(actSaveDeckToClipboard())); + aSaveDeckToClipboard->setShortcuts(QKeySequence::Copy); + aPrintDeck = new QAction(QString(), this); + aPrintDeck->setShortcuts(QKeySequence::Print); + connect(aPrintDeck, SIGNAL(triggered()), this, SLOT(actPrintDeck())); + aAnalyzeDeck = new QAction(QString(), this); + connect(aAnalyzeDeck, SIGNAL(triggered()), this, SLOT(actAnalyzeDeck())); + aClose = new QAction(QString(), this); + connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest())); - aEditSets = new QAction(QString(), this); - connect(aEditSets, SIGNAL(triggered()), this, SLOT(actEditSets())); - aEditTokens = new QAction(QString(), this); - connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens())); + aEditSets = new QAction(QString(), this); + connect(aEditSets, SIGNAL(triggered()), this, SLOT(actEditSets())); + aEditTokens = new QAction(QString(), this); + connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens())); - deckMenu = new QMenu(this); - deckMenu->addAction(aNewDeck); - deckMenu->addAction(aLoadDeck); - deckMenu->addAction(aSaveDeck); - deckMenu->addAction(aSaveDeckAs); - deckMenu->addSeparator(); - deckMenu->addAction(aLoadDeckFromClipboard); - deckMenu->addAction(aSaveDeckToClipboard); - deckMenu->addSeparator(); - deckMenu->addAction(aPrintDeck); - deckMenu->addSeparator(); - deckMenu->addAction(aAnalyzeDeck); - deckMenu->addSeparator(); - deckMenu->addAction(aClose); - addTabMenu(deckMenu); + deckMenu = new QMenu(this); + deckMenu->addAction(aNewDeck); + deckMenu->addAction(aLoadDeck); + deckMenu->addAction(aSaveDeck); + deckMenu->addAction(aSaveDeckAs); + deckMenu->addSeparator(); + deckMenu->addAction(aLoadDeckFromClipboard); + deckMenu->addAction(aSaveDeckToClipboard); + deckMenu->addSeparator(); + deckMenu->addAction(aPrintDeck); + deckMenu->addSeparator(); + deckMenu->addAction(aAnalyzeDeck); + deckMenu->addSeparator(); + deckMenu->addAction(aClose); + addTabMenu(deckMenu); - dbMenu = new QMenu(this); - dbMenu->addAction(aEditSets); - dbMenu->addAction(aEditTokens); - dbMenu->addSeparator(); - dbMenu->addAction(aSearch); - dbMenu->addAction(aClearSearch); - addTabMenu(dbMenu); + dbMenu = new QMenu(this); + dbMenu->addAction(aEditSets); + dbMenu->addAction(aEditTokens); + dbMenu->addSeparator(); + dbMenu->addAction(aSearch); + dbMenu->addAction(aClearSearch); + addTabMenu(dbMenu); - aAddCard = new QAction(QString(), this); - aAddCard->setIcon(QIcon(":/resources/arrow_right_green.svg")); - connect(aAddCard, SIGNAL(triggered()), this, SLOT(actAddCard())); - aAddCardToSideboard = new QAction(QString(), this); + aAddCard = new QAction(QString(), this); + aAddCard->setIcon(QIcon(":/resources/arrow_right_green.svg")); + connect(aAddCard, SIGNAL(triggered()), this, SLOT(actAddCard())); + aAddCardToSideboard = new QAction(QString(), this); aAddCardToSideboard->setIcon(QIcon(":/resources/add_to_sideboard.svg")); - connect(aAddCardToSideboard, SIGNAL(triggered()), this, SLOT(actAddCardToSideboard())); - aRemoveCard = new QAction(QString(), this); + connect(aAddCardToSideboard, SIGNAL(triggered()), this, SLOT(actAddCardToSideboard())); + aRemoveCard = new QAction(QString(), this); aRemoveCard->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aRemoveCard, SIGNAL(triggered()), this, SLOT(actRemoveCard())); - aIncrement = new QAction(QString(), this); + connect(aRemoveCard, SIGNAL(triggered()), this, SLOT(actRemoveCard())); + aIncrement = new QAction(QString(), this); aIncrement->setIcon(QIcon(":/resources/increment.svg")); - connect(aIncrement, SIGNAL(triggered()), this, SLOT(actIncrement())); - aDecrement = new QAction(QString(), this); + connect(aIncrement, SIGNAL(triggered()), this, SLOT(actIncrement())); + aDecrement = new QAction(QString(), this); aDecrement->setIcon(QIcon(":/resources/decrement.svg")); - connect(aDecrement, SIGNAL(triggered()), this, SLOT(actDecrement())); + connect(aDecrement, SIGNAL(triggered()), this, SLOT(actDecrement())); - verticalToolBar->addAction(aAddCard); - verticalToolBar->addAction(aAddCardToSideboard); - verticalToolBar->addAction(aRemoveCard); - verticalToolBar->addAction(aIncrement); - verticalToolBar->addAction(aDecrement); - verticalToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - - dlgCardSearch = new DlgCardSearch(this); - - retranslateUi(); - - resize(950, 700); + verticalToolBar->addAction(aAddCard); + verticalToolBar->addAction(aAddCardToSideboard); + verticalToolBar->addAction(aRemoveCard); + verticalToolBar->addAction(aIncrement); + verticalToolBar->addAction(aDecrement); + verticalToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + + dlgCardSearch = new DlgCardSearch(this); + + retranslateUi(); + + resize(950, 700); } TabDeckEditor::~TabDeckEditor() { - emit deckEditorClosing(this); + emit deckEditorClosing(this); } void TabDeckEditor::retranslateUi() { - aSearch->setText(tr("&Search...")); - aClearSearch->setText(tr("&Clear search")); - searchLabel->setText(tr("&Search for:")); - - nameLabel->setText(tr("Deck &name:")); - commentsLabel->setText(tr("&Comments:")); - hashLabel1->setText(tr("Hash:")); - - aUpdatePrices->setText(tr("&Update prices")); + aSearch->setText(tr("&Search...")); + aClearSearch->setText(tr("&Clear search")); + searchLabel->setText(tr("&Search for:")); + + nameLabel->setText(tr("Deck &name:")); + commentsLabel->setText(tr("&Comments:")); + hashLabel1->setText(tr("Hash:")); + + aUpdatePrices->setText(tr("&Update prices")); aUpdatePrices->setShortcut(tr("Ctrl+U")); aNewDeck->setText(tr("&New deck")); aLoadDeck->setText(tr("&Load deck...")); aSaveDeck->setText(tr("&Save deck")); - aSaveDeckAs->setText(tr("Save deck &as...")); - aLoadDeckFromClipboard->setText(tr("Load deck from cl&ipboard...")); - aSaveDeckToClipboard->setText(tr("Save deck to clip&board")); - aPrintDeck->setText(tr("&Print deck...")); - aAnalyzeDeck->setText(tr("&Analyze deck on deckstats.net")); - aClose->setText(tr("&Close")); - aClose->setShortcut(tr("Ctrl+Q")); - - aAddCard->setText(tr("Add card to &maindeck")); - aAddCard->setShortcuts(QList() << QKeySequence(tr("Return")) << QKeySequence(tr("Enter"))); - aAddCardToSideboard->setText(tr("Add card to &sideboard")); - aAddCardToSideboard->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); - aRemoveCard->setText(tr("&Remove row")); - aRemoveCard->setShortcut(tr("Del")); - aIncrement->setText(tr("&Increment number")); - aIncrement->setShortcut(tr("+")); - aDecrement->setText(tr("&Decrement number")); - aDecrement->setShortcut(tr("-")); - - deckMenu->setTitle(tr("&Deck editor")); - dbMenu->setTitle(tr("C&ard database")); - - aEditSets->setText(tr("&Edit sets...")); - aEditTokens->setText(tr("Edit &tokens...")); + aSaveDeckAs->setText(tr("Save deck &as...")); + aLoadDeckFromClipboard->setText(tr("Load deck from cl&ipboard...")); + aSaveDeckToClipboard->setText(tr("Save deck to clip&board")); + aPrintDeck->setText(tr("&Print deck...")); + aAnalyzeDeck->setText(tr("&Analyze deck on deckstats.net")); + aClose->setText(tr("&Close")); + aClose->setShortcut(tr("Ctrl+Q")); + + aAddCard->setText(tr("Add card to &maindeck")); + aAddCard->setShortcuts(QList() << QKeySequence(tr("Return")) << QKeySequence(tr("Enter"))); + aAddCardToSideboard->setText(tr("Add card to &sideboard")); + aAddCardToSideboard->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); + aRemoveCard->setText(tr("&Remove row")); + aRemoveCard->setShortcut(tr("Del")); + aIncrement->setText(tr("&Increment number")); + aIncrement->setShortcut(tr("+")); + aDecrement->setText(tr("&Decrement number")); + aDecrement->setShortcut(tr("-")); + + deckMenu->setTitle(tr("&Deck editor")); + dbMenu->setTitle(tr("C&ard database")); + + aEditSets->setText(tr("&Edit sets...")); + aEditTokens->setText(tr("Edit &tokens...")); } QString TabDeckEditor::getTabText() const { - QString result = tr("Deck: %1").arg(nameEdit->text()); - if (modified) - result.prepend("* "); - return result; + QString result = tr("Deck: %1").arg(nameEdit->text()); + if (modified) + result.prepend("* "); + return result; } void TabDeckEditor::updateName(const QString &name) { - deckModel->getDeckList()->setName(name); - setModified(true); + deckModel->getDeckList()->setName(name); + setModified(true); } void TabDeckEditor::updateComments() { - deckModel->getDeckList()->setComments(commentsEdit->toPlainText()); - setModified(true); + deckModel->getDeckList()->setComments(commentsEdit->toPlainText()); + setModified(true); } void TabDeckEditor::updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &/*previous*/) { - cardInfo->setCard(current.sibling(current.row(), 0).data().toString()); + cardInfo->setCard(current.sibling(current.row(), 0).data().toString()); } void TabDeckEditor::updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &/*previous*/) { - if (!current.isValid()) - return; - if (!current.model()->hasChildren(current.sibling(current.row(), 0))) - cardInfo->setCard(current.sibling(current.row(), 1).data().toString()); + if (!current.isValid()) + return; + if (!current.model()->hasChildren(current.sibling(current.row(), 0))) + cardInfo->setCard(current.sibling(current.row(), 1).data().toString()); } void TabDeckEditor::updateSearch(const QString &search) { - databaseDisplayModel->setCardNameBeginning(search); - QModelIndexList sel = databaseView->selectionModel()->selectedRows(); - if (sel.isEmpty() && databaseDisplayModel->rowCount()) - databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + databaseDisplayModel->setCardNameBeginning(search); + QModelIndexList sel = databaseView->selectionModel()->selectedRows(); + if (sel.isEmpty() && databaseDisplayModel->rowCount()) + databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } void TabDeckEditor::updateHash() { - hashLabel->setText(deckModel->getDeckList()->getDeckHash()); + hashLabel->setText(deckModel->getDeckList()->getDeckHash()); } bool TabDeckEditor::confirmClose() { - if (modified) { - QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Are you sure?"), - tr("The decklist has been modified.\nDo you want to save the changes?"), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); - if (ret == QMessageBox::Save) - return actSaveDeck(); - else if (ret == QMessageBox::Cancel) - return false; - } - return true; + if (modified) { + QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Are you sure?"), + tr("The decklist has been modified.\nDo you want to save the changes?"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + if (ret == QMessageBox::Save) + return actSaveDeck(); + else if (ret == QMessageBox::Cancel) + return false; + } + return true; } void TabDeckEditor::closeRequest() { - if (confirmClose()) - deleteLater(); + if (confirmClose()) + deleteLater(); } void TabDeckEditor::actNewDeck() { - if (!confirmClose()) - return; + if (!confirmClose()) + return; - deckModel->cleanList(); - nameEdit->setText(QString()); - commentsEdit->setText(QString()); - hashLabel->setText(QString()); - setModified(false); + deckModel->cleanList(); + nameEdit->setText(QString()); + commentsEdit->setText(QString()); + hashLabel->setText(QString()); + setModified(false); } void TabDeckEditor::actLoadDeck() { - if (!confirmClose()) - return; + if (!confirmClose()) + return; - QFileDialog dialog(this, tr("Load deck")); - dialog.setDirectory(settingsCache->getDeckPath()); - dialog.setNameFilters(DeckLoader::fileNameFilters); - if (!dialog.exec()) - return; + QFileDialog dialog(this, tr("Load deck")); + dialog.setDirectory(settingsCache->getDeckPath()); + dialog.setNameFilters(DeckLoader::fileNameFilters); + if (!dialog.exec()) + return; - QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); - - DeckLoader *l = new DeckLoader; - if (l->loadFromFile(fileName, fmt)) - setDeck(l); - else - delete l; + QString fileName = dialog.selectedFiles().at(0); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); + + DeckLoader *l = new DeckLoader; + if (l->loadFromFile(fileName, fmt)) + setDeck(l); + else + delete l; } void TabDeckEditor::saveDeckRemoteFinished(const Response &response) { - if (response.response_code() != Response::RespOk) - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.")); - else - setModified(false); + if (response.response_code() != Response::RespOk) + QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.")); + else + setModified(false); } bool TabDeckEditor::actSaveDeck() { - DeckLoader *const deck = deckModel->getDeckList(); - if (deck->getLastRemoteDeckId() != -1) { - Command_DeckUpload cmd; - cmd.set_deck_id(deck->getLastRemoteDeckId()); - cmd.set_deck_list(deck->writeToString_Native().toStdString()); - - PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(saveDeckRemoteFinished(Response))); - tabSupervisor->getClient()->sendCommand(pend); - - return true; - } else if (deck->getLastFileName().isEmpty()) - return actSaveDeckAs(); - else if (deck->saveToFile(deck->getLastFileName(), deck->getLastFileFormat())) { - setModified(false); - return true; - } - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); - return false; + DeckLoader *const deck = deckModel->getDeckList(); + if (deck->getLastRemoteDeckId() != -1) { + Command_DeckUpload cmd; + cmd.set_deck_id(deck->getLastRemoteDeckId()); + cmd.set_deck_list(deck->writeToString_Native().toStdString()); + + PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(saveDeckRemoteFinished(Response))); + tabSupervisor->getClient()->sendCommand(pend); + + return true; + } else if (deck->getLastFileName().isEmpty()) + return actSaveDeckAs(); + else if (deck->saveToFile(deck->getLastFileName(), deck->getLastFileFormat())) { + setModified(false); + return true; + } + QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); + return false; } bool TabDeckEditor::actSaveDeckAs() { - QFileDialog dialog(this, tr("Save deck")); - dialog.setDirectory(settingsCache->getDeckPath()); - dialog.setAcceptMode(QFileDialog::AcceptSave); - dialog.setConfirmOverwrite(true); - dialog.setDefaultSuffix("cod"); - dialog.setNameFilters(DeckLoader::fileNameFilters); - dialog.selectFile(deckModel->getDeckList()->getName()); - if (!dialog.exec()) - return false; + QFileDialog dialog(this, tr("Save deck")); + dialog.setDirectory(settingsCache->getDeckPath()); + dialog.setAcceptMode(QFileDialog::AcceptSave); + dialog.setConfirmOverwrite(true); + dialog.setDefaultSuffix("cod"); + dialog.setNameFilters(DeckLoader::fileNameFilters); + dialog.selectFile(deckModel->getDeckList()->getName()); + if (!dialog.exec()) + return false; - QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); + QString fileName = dialog.selectedFiles().at(0); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); - if (!deckModel->getDeckList()->saveToFile(fileName, fmt)) { - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); - return false; - } - setModified(false); - return true; + if (!deckModel->getDeckList()->saveToFile(fileName, fmt)) { + QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); + return false; + } + setModified(false); + return true; } void TabDeckEditor::actLoadDeckFromClipboard() { - if (!confirmClose()) - return; - - DlgLoadDeckFromClipboard dlg; - if (!dlg.exec()) - return; - - setDeck(dlg.getDeckList()); - setModified(true); + if (!confirmClose()) + return; + + DlgLoadDeckFromClipboard dlg; + if (!dlg.exec()) + return; + + setDeck(dlg.getDeckList()); + setModified(true); } void TabDeckEditor::actSaveDeckToClipboard() { - QString buffer; - QTextStream stream(&buffer); - deckModel->getDeckList()->saveToStream_Plain(stream); - QApplication::clipboard()->setText(buffer, QClipboard::Clipboard); - QApplication::clipboard()->setText(buffer, QClipboard::Selection); + QString buffer; + QTextStream stream(&buffer); + deckModel->getDeckList()->saveToStream_Plain(stream); + QApplication::clipboard()->setText(buffer, QClipboard::Clipboard); + QApplication::clipboard()->setText(buffer, QClipboard::Selection); } void TabDeckEditor::actPrintDeck() { - QPrintPreviewDialog *dlg = new QPrintPreviewDialog(this); - connect(dlg, SIGNAL(paintRequested(QPrinter *)), deckModel, SLOT(printDeckList(QPrinter *))); - dlg->exec(); + QPrintPreviewDialog *dlg = new QPrintPreviewDialog(this); + connect(dlg, SIGNAL(paintRequested(QPrinter *)), deckModel, SLOT(printDeckList(QPrinter *))); + dlg->exec(); } void TabDeckEditor::actAnalyzeDeck() { - DeckStatsInterface *interface = new DeckStatsInterface(this); // it deletes itself when done - interface->analyzeDeck(deckModel->getDeckList()); + DeckStatsInterface *interface = new DeckStatsInterface(this); // it deletes itself when done + interface->analyzeDeck(deckModel->getDeckList()); } void TabDeckEditor::actEditSets() { - WndSets *w = new WndSets; - w->setWindowModality(Qt::WindowModal); - w->show(); + WndSets *w = new WndSets; + w->setWindowModality(Qt::WindowModal); + w->show(); } void TabDeckEditor::actEditTokens() { - DlgEditTokens dlg(databaseModel); - dlg.exec(); - db->saveToFile(settingsCache->getTokenDatabasePath(), true); + DlgEditTokens dlg(databaseModel); + dlg.exec(); + db->saveToFile(settingsCache->getTokenDatabasePath(), true); } void TabDeckEditor::actSearch() { - if (dlgCardSearch->exec()) { - searchEdit->clear(); - databaseDisplayModel->setCardName(dlgCardSearch->getCardName()); - databaseDisplayModel->setCardText(dlgCardSearch->getCardText()); - databaseDisplayModel->setCardTypes(dlgCardSearch->getCardTypes()); - databaseDisplayModel->setCardColors(dlgCardSearch->getCardColors()); - } + if (dlgCardSearch->exec()) { + searchEdit->clear(); + databaseDisplayModel->setCardName(dlgCardSearch->getCardName()); + databaseDisplayModel->setCardText(dlgCardSearch->getCardText()); + databaseDisplayModel->setCardTypes(dlgCardSearch->getCardTypes()); + databaseDisplayModel->setCardColors(dlgCardSearch->getCardColors()); + } } void TabDeckEditor::actClearSearch() { - databaseDisplayModel->clearSearch(); + databaseDisplayModel->clearSearch(); } void TabDeckEditor::recursiveExpand(const QModelIndex &index) { - if (index.parent().isValid()) - recursiveExpand(index.parent()); - deckView->expand(index); + if (index.parent().isValid()) + recursiveExpand(index.parent()); + deckView->expand(index); } void TabDeckEditor::addCardHelper(QString zoneName) { - const QModelIndex currentIndex = databaseView->selectionModel()->currentIndex(); - if (!currentIndex.isValid()) - return; - const QString cardName = currentIndex.sibling(currentIndex.row(), 0).data().toString(); - - CardInfo *info = db->getCard(cardName); - if (info->getIsToken()) - zoneName = "tokens"; - - QModelIndex newCardIndex = deckModel->addCard(cardName, zoneName); - recursiveExpand(newCardIndex); - deckView->setCurrentIndex(newCardIndex); + const QModelIndex currentIndex = databaseView->selectionModel()->currentIndex(); + if (!currentIndex.isValid()) + return; + const QString cardName = currentIndex.sibling(currentIndex.row(), 0).data().toString(); + + CardInfo *info = db->getCard(cardName); + if (info->getIsToken()) + zoneName = "tokens"; + + QModelIndex newCardIndex = deckModel->addCard(cardName, zoneName); + recursiveExpand(newCardIndex); + deckView->setCurrentIndex(newCardIndex); - setModified(true); + setModified(true); } void TabDeckEditor::actAddCard() { - addCardHelper("main"); + addCardHelper("main"); } void TabDeckEditor::actAddCardToSideboard() { - addCardHelper("side"); + addCardHelper("side"); } void TabDeckEditor::actRemoveCard() { - const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - if (!currentIndex.isValid() || deckModel->hasChildren(currentIndex)) - return; - deckModel->removeRow(currentIndex.row(), currentIndex.parent()); - setModified(true); + const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); + if (!currentIndex.isValid() || deckModel->hasChildren(currentIndex)) + return; + deckModel->removeRow(currentIndex.row(), currentIndex.parent()); + setModified(true); } void TabDeckEditor::actIncrement() { - const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - if (!currentIndex.isValid()) - return; - const QModelIndex numberIndex = currentIndex.sibling(currentIndex.row(), 0); - const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); - deckView->setCurrentIndex(numberIndex); - deckModel->setData(numberIndex, count + 1, Qt::EditRole); - setModified(true); + const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); + if (!currentIndex.isValid()) + return; + const QModelIndex numberIndex = currentIndex.sibling(currentIndex.row(), 0); + const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); + deckView->setCurrentIndex(numberIndex); + deckModel->setData(numberIndex, count + 1, Qt::EditRole); + setModified(true); } void TabDeckEditor::actDecrement() { - const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - if (!currentIndex.isValid()) - return; - const QModelIndex numberIndex = currentIndex.sibling(currentIndex.row(), 0); - const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); - deckView->setCurrentIndex(numberIndex); - if (count == 1) - deckModel->removeRow(currentIndex.row(), currentIndex.parent()); - else - deckModel->setData(numberIndex, count - 1, Qt::EditRole); - setModified(true); + const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); + if (!currentIndex.isValid()) + return; + const QModelIndex numberIndex = currentIndex.sibling(currentIndex.row(), 0); + const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); + deckView->setCurrentIndex(numberIndex); + if (count == 1) + deckModel->removeRow(currentIndex.row(), currentIndex.parent()); + else + deckModel->setData(numberIndex, count - 1, Qt::EditRole); + setModified(true); } void TabDeckEditor::actUpdatePrices() { - aUpdatePrices->setDisabled(true); - PriceUpdater *up = new PriceUpdater(deckModel->getDeckList()); - connect(up, SIGNAL(finishedUpdate()), this, SLOT(finishedUpdatingPrices())); - up->updatePrices(); + aUpdatePrices->setDisabled(true); + PriceUpdater *up = new PriceUpdater(deckModel->getDeckList()); + connect(up, SIGNAL(finishedUpdate()), this, SLOT(finishedUpdatingPrices())); + up->updatePrices(); } void TabDeckEditor::finishedUpdatingPrices() { - deckModel->pricesUpdated(); - setModified(true); - aUpdatePrices->setDisabled(false); + deckModel->pricesUpdated(); + setModified(true); + aUpdatePrices->setDisabled(false); } void TabDeckEditor::setDeck(DeckLoader *_deck) { - deckModel->setDeckList(_deck); + deckModel->setDeckList(_deck); - nameEdit->setText(deckModel->getDeckList()->getName()); - commentsEdit->setText(deckModel->getDeckList()->getComments()); - updateHash(); - deckModel->sort(1); - deckView->expandAll(); - setModified(false); - - db->cacheCardPixmaps(deckModel->getDeckList()->getCardList()); - deckView->expandAll(); - setModified(false); + nameEdit->setText(deckModel->getDeckList()->getName()); + commentsEdit->setText(deckModel->getDeckList()->getComments()); + updateHash(); + deckModel->sort(1); + deckView->expandAll(); + setModified(false); + + db->cacheCardPixmaps(deckModel->getDeckList()->getCardList()); + deckView->expandAll(); + setModified(false); } void TabDeckEditor::setModified(bool _modified) { - modified = _modified; - emit tabTextChanged(this, getTabText()); + modified = _modified; + emit tabTextChanged(this, getTabText()); } diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 73ee8a14..e482d929 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -18,87 +18,87 @@ class DeckLoader; class Response; class SearchLineEdit : public QLineEdit { - private: - QTreeView *treeView; - protected: - void keyPressEvent(QKeyEvent *event); - public: - SearchLineEdit() : QLineEdit(), treeView(0) { } - void setTreeView(QTreeView *_treeView) { treeView = _treeView; } + private: + QTreeView *treeView; + protected: + void keyPressEvent(QKeyEvent *event); + public: + SearchLineEdit() : QLineEdit(), treeView(0) { } + void setTreeView(QTreeView *_treeView) { treeView = _treeView; } }; class TabDeckEditor : public Tab { - Q_OBJECT + Q_OBJECT private slots: - void updateName(const QString &name); - void updateComments(); - void updateHash(); - void updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &previous); - void updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &previous); - void updateSearch(const QString &search); + void updateName(const QString &name); + void updateComments(); + void updateHash(); + void updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &previous); + void updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &previous); + void updateSearch(const QString &search); - void actNewDeck(); - void actLoadDeck(); - bool actSaveDeck(); - bool actSaveDeckAs(); - void actLoadDeckFromClipboard(); - void actSaveDeckToClipboard(); - void actPrintDeck(); - void actAnalyzeDeck(); + void actNewDeck(); + void actLoadDeck(); + bool actSaveDeck(); + bool actSaveDeckAs(); + void actLoadDeckFromClipboard(); + void actSaveDeckToClipboard(); + void actPrintDeck(); + void actAnalyzeDeck(); - void actEditSets(); - void actEditTokens(); - - void actSearch(); - void actClearSearch(); + void actEditSets(); + void actEditTokens(); + + void actSearch(); + void actClearSearch(); - void actAddCard(); - void actAddCardToSideboard(); - void actRemoveCard(); - void actIncrement(); - void actDecrement(); + void actAddCard(); + void actAddCardToSideboard(); + void actRemoveCard(); + void actIncrement(); + void actDecrement(); void actUpdatePrices(); void finishedUpdatingPrices(); - void saveDeckRemoteFinished(const Response &r); + void saveDeckRemoteFinished(const Response &r); private: - void addCardHelper(QString zoneName); - void recursiveExpand(const QModelIndex &index); - bool confirmClose(); + void addCardHelper(QString zoneName); + void recursiveExpand(const QModelIndex &index); + bool confirmClose(); - CardDatabaseModel *databaseModel; - CardDatabaseDisplayModel *databaseDisplayModel; - DeckListModel *deckModel; - QTreeView *databaseView; - QTreeView *deckView; - CardInfoWidget *cardInfo; - QLabel *searchLabel; - SearchLineEdit *searchEdit; - QLabel *nameLabel; - QLineEdit *nameEdit; - QLabel *commentsLabel; - QTextEdit *commentsEdit; - QLabel *hashLabel1; - QLabel *hashLabel; - DlgCardSearch *dlgCardSearch; + CardDatabaseModel *databaseModel; + CardDatabaseDisplayModel *databaseDisplayModel; + DeckListModel *deckModel; + QTreeView *databaseView; + QTreeView *deckView; + CardInfoWidget *cardInfo; + QLabel *searchLabel; + SearchLineEdit *searchEdit; + QLabel *nameLabel; + QLineEdit *nameEdit; + QLabel *commentsLabel; + QTextEdit *commentsEdit; + QLabel *hashLabel1; + QLabel *hashLabel; + DlgCardSearch *dlgCardSearch; - QMenu *deckMenu, *dbMenu; - QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; - QAction *aEditSets, *aEditTokens, *aSearch, *aClearSearch; + QMenu *deckMenu, *dbMenu; + QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; + QAction *aEditSets, *aEditTokens, *aSearch, *aClearSearch; QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement, *aUpdatePrices; - - bool modified; + + bool modified; public: - TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent = 0); - ~TabDeckEditor(); - void retranslateUi(); - QString getTabText() const; - void setDeck(DeckLoader *_deckLoader); - void setModified(bool _windowModified); + TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent = 0); + ~TabDeckEditor(); + void retranslateUi(); + QString getTabText() const; + void setDeck(DeckLoader *_deckLoader); + void setModified(bool _windowModified); public slots: - void closeRequest(); + void closeRequest(); signals: - void deckEditorClosing(TabDeckEditor *tab); + void deckEditorClosing(TabDeckEditor *tab); }; #endif diff --git a/cockatrice/src/tab_deck_storage.cpp b/cockatrice/src/tab_deck_storage.cpp index 10ddb354..7e7d30ed 100644 --- a/cockatrice/src/tab_deck_storage.cpp +++ b/cockatrice/src/tab_deck_storage.cpp @@ -27,323 +27,323 @@ #include "pb/command_deck_del.pb.h" TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client) - : Tab(_tabSupervisor), client(_client) + : Tab(_tabSupervisor), client(_client) { - localDirModel = new QFileSystemModel(this); - localDirModel->setRootPath(settingsCache->getDeckPath()); - localDirModel->sort(0, Qt::AscendingOrder); - - localDirView = new QTreeView; - localDirView->setModel(localDirModel); - localDirView->setColumnHidden(1, true); - localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); - localDirView->setSortingEnabled(true); - localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); - localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); - - leftToolBar = new QToolBar; - leftToolBar->setOrientation(Qt::Horizontal); - leftToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *leftToolBarLayout = new QHBoxLayout; - leftToolBarLayout->addStretch(); - leftToolBarLayout->addWidget(leftToolBar); - leftToolBarLayout->addStretch(); + localDirModel = new QFileSystemModel(this); + localDirModel->setRootPath(settingsCache->getDeckPath()); + localDirModel->sort(0, Qt::AscendingOrder); + + localDirView = new QTreeView; + localDirView->setModel(localDirModel); + localDirView->setColumnHidden(1, true); + localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); + localDirView->setSortingEnabled(true); + localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); + localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); + + leftToolBar = new QToolBar; + leftToolBar->setOrientation(Qt::Horizontal); + leftToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *leftToolBarLayout = new QHBoxLayout; + leftToolBarLayout->addStretch(); + leftToolBarLayout->addWidget(leftToolBar); + leftToolBarLayout->addStretch(); - QVBoxLayout *leftVbox = new QVBoxLayout; - leftVbox->addWidget(localDirView); - leftVbox->addLayout(leftToolBarLayout); - leftGroupBox = new QGroupBox; - leftGroupBox->setLayout(leftVbox); - - rightToolBar = new QToolBar; - rightToolBar->setOrientation(Qt::Horizontal); - rightToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *rightToolBarLayout = new QHBoxLayout; - rightToolBarLayout->addStretch(); - rightToolBarLayout->addWidget(rightToolBar); - rightToolBarLayout->addStretch(); + QVBoxLayout *leftVbox = new QVBoxLayout; + leftVbox->addWidget(localDirView); + leftVbox->addLayout(leftToolBarLayout); + leftGroupBox = new QGroupBox; + leftGroupBox->setLayout(leftVbox); + + rightToolBar = new QToolBar; + rightToolBar->setOrientation(Qt::Horizontal); + rightToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *rightToolBarLayout = new QHBoxLayout; + rightToolBarLayout->addStretch(); + rightToolBarLayout->addWidget(rightToolBar); + rightToolBarLayout->addStretch(); - serverDirView = new RemoteDeckList_TreeWidget(client); + serverDirView = new RemoteDeckList_TreeWidget(client); - QVBoxLayout *rightVbox = new QVBoxLayout; - rightVbox->addWidget(serverDirView); - rightVbox->addLayout(rightToolBarLayout); - rightGroupBox = new QGroupBox; - rightGroupBox->setLayout(rightVbox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addWidget(leftGroupBox); - hbox->addWidget(rightGroupBox); - - aOpenLocalDeck = new QAction(this); - aOpenLocalDeck->setIcon(QIcon(":/resources/pencil.svg")); - connect(aOpenLocalDeck, SIGNAL(triggered()), this, SLOT(actOpenLocalDeck())); - aUpload = new QAction(this); - aUpload->setIcon(QIcon(":/resources/arrow_right_green.svg")); - connect(aUpload, SIGNAL(triggered()), this, SLOT(actUpload())); - aDeleteLocalDeck = new QAction(this); - aDeleteLocalDeck->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteLocalDeck, SIGNAL(triggered()), this, SLOT(actDeleteLocalDeck())); - aOpenRemoteDeck = new QAction(this); - aOpenRemoteDeck->setIcon(QIcon(":/resources/pencil.svg")); - connect(aOpenRemoteDeck, SIGNAL(triggered()), this, SLOT(actOpenRemoteDeck())); - aDownload = new QAction(this); - aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); - connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); - aNewFolder = new QAction(this); - aNewFolder->setIcon(qApp->style()->standardIcon(QStyle::SP_FileDialogNewFolder)); - connect(aNewFolder, SIGNAL(triggered()), this, SLOT(actNewFolder())); - aDeleteRemoteDeck = new QAction(this); - aDeleteRemoteDeck->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteRemoteDeck, SIGNAL(triggered()), this, SLOT(actDeleteRemoteDeck())); - - leftToolBar->addAction(aOpenLocalDeck); - leftToolBar->addAction(aUpload); - leftToolBar->addAction(aDeleteLocalDeck); - rightToolBar->addAction(aOpenRemoteDeck); - rightToolBar->addAction(aDownload); - rightToolBar->addAction(aNewFolder); - rightToolBar->addAction(aDeleteRemoteDeck); - - retranslateUi(); - setLayout(hbox); + QVBoxLayout *rightVbox = new QVBoxLayout; + rightVbox->addWidget(serverDirView); + rightVbox->addLayout(rightToolBarLayout); + rightGroupBox = new QGroupBox; + rightGroupBox->setLayout(rightVbox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(leftGroupBox); + hbox->addWidget(rightGroupBox); + + aOpenLocalDeck = new QAction(this); + aOpenLocalDeck->setIcon(QIcon(":/resources/pencil.svg")); + connect(aOpenLocalDeck, SIGNAL(triggered()), this, SLOT(actOpenLocalDeck())); + aUpload = new QAction(this); + aUpload->setIcon(QIcon(":/resources/arrow_right_green.svg")); + connect(aUpload, SIGNAL(triggered()), this, SLOT(actUpload())); + aDeleteLocalDeck = new QAction(this); + aDeleteLocalDeck->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteLocalDeck, SIGNAL(triggered()), this, SLOT(actDeleteLocalDeck())); + aOpenRemoteDeck = new QAction(this); + aOpenRemoteDeck->setIcon(QIcon(":/resources/pencil.svg")); + connect(aOpenRemoteDeck, SIGNAL(triggered()), this, SLOT(actOpenRemoteDeck())); + aDownload = new QAction(this); + aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); + connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); + aNewFolder = new QAction(this); + aNewFolder->setIcon(qApp->style()->standardIcon(QStyle::SP_FileDialogNewFolder)); + connect(aNewFolder, SIGNAL(triggered()), this, SLOT(actNewFolder())); + aDeleteRemoteDeck = new QAction(this); + aDeleteRemoteDeck->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteRemoteDeck, SIGNAL(triggered()), this, SLOT(actDeleteRemoteDeck())); + + leftToolBar->addAction(aOpenLocalDeck); + leftToolBar->addAction(aUpload); + leftToolBar->addAction(aDeleteLocalDeck); + rightToolBar->addAction(aOpenRemoteDeck); + rightToolBar->addAction(aDownload); + rightToolBar->addAction(aNewFolder); + rightToolBar->addAction(aDeleteRemoteDeck); + + retranslateUi(); + setLayout(hbox); } void TabDeckStorage::retranslateUi() { - leftGroupBox->setTitle(tr("Local file system")); - rightGroupBox->setTitle(tr("Server deck storage")); - - aOpenLocalDeck->setText(tr("Open in deck editor")); - aUpload->setText(tr("Upload deck")); - aOpenRemoteDeck->setText(tr("Open in deck editor")); - aDownload->setText(tr("Download deck")); - aNewFolder->setText(tr("New folder")); - aDeleteLocalDeck->setText(tr("Delete")); - aDeleteRemoteDeck->setText(tr("Delete")); + leftGroupBox->setTitle(tr("Local file system")); + rightGroupBox->setTitle(tr("Server deck storage")); + + aOpenLocalDeck->setText(tr("Open in deck editor")); + aUpload->setText(tr("Upload deck")); + aOpenRemoteDeck->setText(tr("Open in deck editor")); + aDownload->setText(tr("Download deck")); + aNewFolder->setText(tr("New folder")); + aDeleteLocalDeck->setText(tr("Delete")); + aDeleteRemoteDeck->setText(tr("Delete")); } void TabDeckStorage::actOpenLocalDeck() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (localDirModel->isDir(curLeft)) - return; - QString filePath = localDirModel->filePath(curLeft); - - DeckLoader deckLoader; - if (!deckLoader.loadFromFile(filePath, DeckLoader::CockatriceFormat)) - return; - - emit openDeckEditor(&deckLoader); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (localDirModel->isDir(curLeft)) + return; + QString filePath = localDirModel->filePath(curLeft); + + DeckLoader deckLoader; + if (!deckLoader.loadFromFile(filePath, DeckLoader::CockatriceFormat)) + return; + + emit openDeckEditor(&deckLoader); } void TabDeckStorage::actUpload() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (localDirModel->isDir(curLeft)) - return; - QString filePath = localDirModel->filePath(curLeft); - QFile deckFile(filePath); - QFileInfo deckFileInfo(deckFile); - DeckLoader deck; - if (!deck.loadFromFile(filePath, DeckLoader::CockatriceFormat)) - return; - if (deck.getName().isEmpty()) { - bool ok; - QString deckName = QInputDialog::getText(this, tr("Enter deck name"), tr("This decklist does not have a name.\nPlease enter a name:"), QLineEdit::Normal, deckFileInfo.completeBaseName(), &ok); - if (!ok) - return; - if (deckName.isEmpty()) - deckName = tr("Unnamed deck"); - deck.setName(deckName); - } - - QString targetPath; - RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); - if (!curRight) - return; - if (!dynamic_cast(curRight)) - curRight = curRight->getParent(); - targetPath = dynamic_cast(curRight)->getPath(); - - Command_DeckUpload cmd; - cmd.set_path(targetPath.toStdString()); - cmd.set_deck_list(deck.writeToString_Native().toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(uploadFinished(Response, CommandContainer))); - client->sendCommand(pend); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (localDirModel->isDir(curLeft)) + return; + QString filePath = localDirModel->filePath(curLeft); + QFile deckFile(filePath); + QFileInfo deckFileInfo(deckFile); + DeckLoader deck; + if (!deck.loadFromFile(filePath, DeckLoader::CockatriceFormat)) + return; + if (deck.getName().isEmpty()) { + bool ok; + QString deckName = QInputDialog::getText(this, tr("Enter deck name"), tr("This decklist does not have a name.\nPlease enter a name:"), QLineEdit::Normal, deckFileInfo.completeBaseName(), &ok); + if (!ok) + return; + if (deckName.isEmpty()) + deckName = tr("Unnamed deck"); + deck.setName(deckName); + } + + QString targetPath; + RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); + if (!curRight) + return; + if (!dynamic_cast(curRight)) + curRight = curRight->getParent(); + targetPath = dynamic_cast(curRight)->getPath(); + + Command_DeckUpload cmd; + cmd.set_path(targetPath.toStdString()); + cmd.set_deck_list(deck.writeToString_Native().toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(uploadFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabDeckStorage::uploadFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Response_DeckUpload &resp = r.GetExtension(Response_DeckUpload::ext); - const Command_DeckUpload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckUpload::ext); - - serverDirView->addFileToTree(resp.new_file(), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); + if (r.response_code() != Response::RespOk) + return; + + const Response_DeckUpload &resp = r.GetExtension(Response_DeckUpload::ext); + const Command_DeckUpload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckUpload::ext); + + serverDirView->addFileToTree(resp.new_file(), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); } void TabDeckStorage::actDeleteLocalDeck() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - localDirModel->remove(curLeft); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + localDirModel->remove(curLeft); } void TabDeckStorage::actOpenRemoteDeck() { - RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); - if (!curRight) - return; - - Command_DeckDownload cmd; - cmd.set_deck_id(curRight->getId()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteDeckFinished(Response, CommandContainer))); - client->sendCommand(pend); + RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); + if (!curRight) + return; + + Command_DeckDownload cmd; + cmd.set_deck_id(curRight->getId()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteDeckFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabDeckStorage::openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); - const Command_DeckDownload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDownload::ext); - - DeckLoader loader; - if (!loader.loadFromRemote(QString::fromStdString(resp.deck()), cmd.deck_id())) - return; - - emit openDeckEditor(&loader); + if (r.response_code() != Response::RespOk) + return; + + const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); + const Command_DeckDownload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDownload::ext); + + DeckLoader loader; + if (!loader.loadFromRemote(QString::fromStdString(resp.deck()), cmd.deck_id())) + return; + + emit openDeckEditor(&loader); } void TabDeckStorage::actDownload() { - QString filePath; - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (!curLeft.isValid()) - filePath = localDirModel->rootPath(); - else { - while (!localDirModel->isDir(curLeft)) - curLeft = curLeft.parent(); - filePath = localDirModel->filePath(curLeft); - } + QString filePath; + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (!curLeft.isValid()) + filePath = localDirModel->rootPath(); + else { + while (!localDirModel->isDir(curLeft)) + curLeft = curLeft.parent(); + filePath = localDirModel->filePath(curLeft); + } - RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); - if (!curRight) - return; - filePath += QString("/deck_%1.cod").arg(curRight->getId()); - - Command_DeckDownload cmd; - cmd.set_deck_id(curRight->getId()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - pend->setExtraData(filePath); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); - client->sendCommand(pend); + RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); + if (!curRight) + return; + filePath += QString("/deck_%1.cod").arg(curRight->getId()); + + Command_DeckDownload cmd; + cmd.set_deck_id(curRight->getId()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + pend->setExtraData(filePath); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); + client->sendCommand(pend); } void TabDeckStorage::downloadFinished(const Response &r, const CommandContainer &/*commandContainer*/, const QVariant &extraData) { - if (r.response_code() != Response::RespOk) - return; - - const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); - QString filePath = extraData.toString(); - - DeckLoader deck(QString::fromStdString(resp.deck())); - deck.saveToFile(filePath, DeckLoader::CockatriceFormat); + if (r.response_code() != Response::RespOk) + return; + + const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); + QString filePath = extraData.toString(); + + DeckLoader deck(QString::fromStdString(resp.deck())); + deck.saveToFile(filePath, DeckLoader::CockatriceFormat); } void TabDeckStorage::actNewFolder() { - QString folderName = QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:")); - if (folderName.isEmpty()) - return; + QString folderName = QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:")); + if (folderName.isEmpty()) + return; - QString targetPath; - RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); - if (!curRight) - return; - if (!dynamic_cast(curRight)) - curRight = curRight->getParent(); - RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); - targetPath = dir->getPath(); - - Command_DeckNewDir cmd; - cmd.set_path(targetPath.toStdString()); - cmd.set_dir_name(folderName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(newFolderFinished(Response, CommandContainer))); - client->sendCommand(pend); + QString targetPath; + RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); + if (!curRight) + return; + if (!dynamic_cast(curRight)) + curRight = curRight->getParent(); + RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); + targetPath = dir->getPath(); + + Command_DeckNewDir cmd; + cmd.set_path(targetPath.toStdString()); + cmd.set_dir_name(folderName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(newFolderFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabDeckStorage::newFolderFinished(const Response &response, const CommandContainer &commandContainer) { - if (response.response_code() != Response::RespOk) - return; - - const Command_DeckNewDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckNewDir::ext); - serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); + if (response.response_code() != Response::RespOk) + return; + + const Command_DeckNewDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckNewDir::ext); + serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); } void TabDeckStorage::actDeleteRemoteDeck() { - PendingCommand *pend; - RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); - if (!curRight) - return; - RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); - if (dir) { - QString path = dir->getPath(); - if (path.isEmpty()) - return; - if (QMessageBox::warning(this, tr("Delete remote folder"), tr("Are you sure you want to delete \"%1\"?").arg(path), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - Command_DeckDelDir cmd; - cmd.set_path(path.toStdString()); - pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteFolderFinished(Response, CommandContainer))); - } else { - RemoteDeckList_TreeModel::FileNode *deckNode = dynamic_cast(curRight); - if (QMessageBox::warning(this, tr("Delete remote deck"), tr("Are you sure you want to delete \"%1\"?").arg(deckNode->getName()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - Command_DeckDel cmd; - cmd.set_deck_id(deckNode->getId()); - pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteDeckFinished(Response, CommandContainer))); - } - - client->sendCommand(pend); + PendingCommand *pend; + RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); + if (!curRight) + return; + RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); + if (dir) { + QString path = dir->getPath(); + if (path.isEmpty()) + return; + if (QMessageBox::warning(this, tr("Delete remote folder"), tr("Are you sure you want to delete \"%1\"?").arg(path), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + Command_DeckDelDir cmd; + cmd.set_path(path.toStdString()); + pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteFolderFinished(Response, CommandContainer))); + } else { + RemoteDeckList_TreeModel::FileNode *deckNode = dynamic_cast(curRight); + if (QMessageBox::warning(this, tr("Delete remote deck"), tr("Are you sure you want to delete \"%1\"?").arg(deckNode->getName()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + Command_DeckDel cmd; + cmd.set_deck_id(deckNode->getId()); + pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteDeckFinished(Response, CommandContainer))); + } + + client->sendCommand(pend); } void TabDeckStorage::deleteDeckFinished(const Response &response, const CommandContainer &commandContainer) { - if (response.response_code() != Response::RespOk) - return; - - const Command_DeckDel &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDel::ext); - RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeById(cmd.deck_id()); - if (toDelete) - serverDirView->removeNode(toDelete); + if (response.response_code() != Response::RespOk) + return; + + const Command_DeckDel &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDel::ext); + RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeById(cmd.deck_id()); + if (toDelete) + serverDirView->removeNode(toDelete); } void TabDeckStorage::deleteFolderFinished(const Response &response, const CommandContainer &commandContainer) { - if (response.response_code() != Response::RespOk) - return; - - const Command_DeckDelDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDelDir::ext); - RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeByPath(QString::fromStdString(cmd.path())); - if (toDelete) - serverDirView->removeNode(toDelete); + if (response.response_code() != Response::RespOk) + return; + + const Command_DeckDelDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDelDir::ext); + RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeByPath(QString::fromStdString(cmd.path())); + if (toDelete) + serverDirView->removeNode(toDelete); } diff --git a/cockatrice/src/tab_deck_storage.h b/cockatrice/src/tab_deck_storage.h index a3ef7fc4..c6567ff1 100644 --- a/cockatrice/src/tab_deck_storage.h +++ b/cockatrice/src/tab_deck_storage.h @@ -16,42 +16,42 @@ class Response; class DeckLoader; class TabDeckStorage : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - QTreeView *localDirView; - QFileSystemModel *localDirModel; - QToolBar *leftToolBar, *rightToolBar; - RemoteDeckList_TreeWidget *serverDirView; - QGroupBox *leftGroupBox, *rightGroupBox; - - QAction *aOpenLocalDeck, *aUpload, *aDeleteLocalDeck, *aOpenRemoteDeck, *aDownload, *aNewFolder, *aDeleteRemoteDeck; + AbstractClient *client; + QTreeView *localDirView; + QFileSystemModel *localDirModel; + QToolBar *leftToolBar, *rightToolBar; + RemoteDeckList_TreeWidget *serverDirView; + QGroupBox *leftGroupBox, *rightGroupBox; + + QAction *aOpenLocalDeck, *aUpload, *aDeleteLocalDeck, *aOpenRemoteDeck, *aDownload, *aNewFolder, *aDeleteRemoteDeck; private slots: - void actOpenLocalDeck(); - - void actUpload(); - void uploadFinished(const Response &r, const CommandContainer &commandContainer); - - void actDeleteLocalDeck(); - - void actOpenRemoteDeck(); - void openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer); - - void actDownload(); - void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); + void actOpenLocalDeck(); + + void actUpload(); + void uploadFinished(const Response &r, const CommandContainer &commandContainer); + + void actDeleteLocalDeck(); + + void actOpenRemoteDeck(); + void openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer); + + void actDownload(); + void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); - void actNewFolder(); - void newFolderFinished(const Response &response, const CommandContainer &commandContainer); + void actNewFolder(); + void newFolderFinished(const Response &response, const CommandContainer &commandContainer); - void actDeleteRemoteDeck(); - void deleteFolderFinished(const Response &response, const CommandContainer &commandContainer); - void deleteDeckFinished(const Response &response, const CommandContainer &commandContainer); + void actDeleteRemoteDeck(); + void deleteFolderFinished(const Response &response, const CommandContainer &commandContainer); + void deleteDeckFinished(const Response &response, const CommandContainer &commandContainer); public: - TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client); - void retranslateUi(); - QString getTabText() const { return tr("Deck storage"); } + TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client); + void retranslateUi(); + QString getTabText() const { return tr("Deck storage"); } signals: - void openDeckEditor(const DeckLoader *deckLoader); + void openDeckEditor(const DeckLoader *deckLoader); }; #endif diff --git a/cockatrice/src/tab_game.cpp b/cockatrice/src/tab_game.cpp index 4bbd31a2..f237589e 100644 --- a/cockatrice/src/tab_game.cpp +++ b/cockatrice/src/tab_game.cpp @@ -64,1131 +64,1131 @@ #include "get_pb_extension.h" ToggleButton::ToggleButton(QWidget *parent) - : QPushButton(parent), state(false) + : QPushButton(parent), state(false) { } void ToggleButton::paintEvent(QPaintEvent *event) { - QPushButton::paintEvent(event); - - QPainter painter(this); - if (state) - painter.setPen(QPen(Qt::green, 3)); - else - painter.setPen(QPen(Qt::red, 3)); - painter.drawRect(1, 1, width() - 3, height() - 3); + QPushButton::paintEvent(event); + + QPainter painter(this); + if (state) + painter.setPen(QPen(Qt::green, 3)); + else + painter.setPen(QPen(Qt::red, 3)); + painter.drawRect(1, 1, width() - 3, height() - 3); } void ToggleButton::setState(bool _state) { - state = _state; - emit stateChanged(); - update(); + state = _state; + emit stateChanged(); + update(); } DeckViewContainer::DeckViewContainer(int _playerId, TabGame *parent) - : QWidget(parent), playerId(_playerId) + : QWidget(parent), playerId(_playerId) { - loadLocalButton = new QPushButton; - loadRemoteButton = new QPushButton; - readyStartButton = new ToggleButton; - readyStartButton->setEnabled(false); - sideboardLockButton = new ToggleButton; - sideboardLockButton->setEnabled(false); - - connect(loadLocalButton, SIGNAL(clicked()), this, SLOT(loadLocalDeck())); - connect(loadRemoteButton, SIGNAL(clicked()), this, SLOT(loadRemoteDeck())); - connect(readyStartButton, SIGNAL(clicked()), this, SLOT(readyStart())); - connect(sideboardLockButton, SIGNAL(clicked()), this, SLOT(sideboardLockButtonClicked())); - connect(sideboardLockButton, SIGNAL(stateChanged()), this, SLOT(updateSideboardLockButtonText())); - - QHBoxLayout *buttonHBox = new QHBoxLayout; - buttonHBox->addWidget(loadLocalButton); - buttonHBox->addWidget(loadRemoteButton); - buttonHBox->addWidget(readyStartButton); - buttonHBox->addWidget(sideboardLockButton); - buttonHBox->addStretch(); - deckView = new DeckView; - connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); - connect(deckView, SIGNAL(sideboardPlanChanged()), this, SLOT(sideboardPlanChanged())); - - QVBoxLayout *deckViewLayout = new QVBoxLayout; - deckViewLayout->addLayout(buttonHBox); - deckViewLayout->addWidget(deckView); - setLayout(deckViewLayout); - - retranslateUi(); + loadLocalButton = new QPushButton; + loadRemoteButton = new QPushButton; + readyStartButton = new ToggleButton; + readyStartButton->setEnabled(false); + sideboardLockButton = new ToggleButton; + sideboardLockButton->setEnabled(false); + + connect(loadLocalButton, SIGNAL(clicked()), this, SLOT(loadLocalDeck())); + connect(loadRemoteButton, SIGNAL(clicked()), this, SLOT(loadRemoteDeck())); + connect(readyStartButton, SIGNAL(clicked()), this, SLOT(readyStart())); + connect(sideboardLockButton, SIGNAL(clicked()), this, SLOT(sideboardLockButtonClicked())); + connect(sideboardLockButton, SIGNAL(stateChanged()), this, SLOT(updateSideboardLockButtonText())); + + QHBoxLayout *buttonHBox = new QHBoxLayout; + buttonHBox->addWidget(loadLocalButton); + buttonHBox->addWidget(loadRemoteButton); + buttonHBox->addWidget(readyStartButton); + buttonHBox->addWidget(sideboardLockButton); + buttonHBox->addStretch(); + deckView = new DeckView; + connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); + connect(deckView, SIGNAL(sideboardPlanChanged()), this, SLOT(sideboardPlanChanged())); + + QVBoxLayout *deckViewLayout = new QVBoxLayout; + deckViewLayout->addLayout(buttonHBox); + deckViewLayout->addWidget(deckView); + setLayout(deckViewLayout); + + retranslateUi(); } void DeckViewContainer::retranslateUi() { - loadLocalButton->setText(tr("Load &local deck")); - loadRemoteButton->setText(tr("Load d&eck from server")); - readyStartButton->setText(tr("Ready to s&tart")); - updateSideboardLockButtonText(); + loadLocalButton->setText(tr("Load &local deck")); + loadRemoteButton->setText(tr("Load d&eck from server")); + readyStartButton->setText(tr("Ready to s&tart")); + updateSideboardLockButtonText(); } void DeckViewContainer::setButtonsVisible(bool _visible) { - loadLocalButton->setVisible(_visible); - loadRemoteButton->setVisible(_visible); - readyStartButton->setVisible(_visible); - sideboardLockButton->setVisible(_visible); + loadLocalButton->setVisible(_visible); + loadRemoteButton->setVisible(_visible); + readyStartButton->setVisible(_visible); + sideboardLockButton->setVisible(_visible); } void DeckViewContainer::updateSideboardLockButtonText() { - if (sideboardLockButton->getState()) - sideboardLockButton->setText(tr("S&ideboard unlocked")); - else - sideboardLockButton->setText(tr("S&ideboard locked")); + if (sideboardLockButton->getState()) + sideboardLockButton->setText(tr("S&ideboard unlocked")); + else + sideboardLockButton->setText(tr("S&ideboard locked")); } void DeckViewContainer::loadLocalDeck() { - QFileDialog dialog(this, tr("Load deck")); - dialog.setDirectory(settingsCache->getDeckPath()); - dialog.setNameFilters(DeckLoader::fileNameFilters); - if (!dialog.exec()) - return; + QFileDialog dialog(this, tr("Load deck")); + dialog.setDirectory(settingsCache->getDeckPath()); + dialog.setNameFilters(DeckLoader::fileNameFilters); + if (!dialog.exec()) + return; - QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); - DeckLoader deck; - if (!deck.loadFromFile(fileName, fmt)) { - QMessageBox::critical(this, tr("Error"), tr("The selected file could not be loaded.")); - return; - } - - Command_DeckSelect cmd; - cmd.set_deck(deck.writeToString_Native().toStdString()); - PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); - static_cast(parent())->sendGameCommand(pend, playerId); + QString fileName = dialog.selectedFiles().at(0); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); + DeckLoader deck; + if (!deck.loadFromFile(fileName, fmt)) { + QMessageBox::critical(this, tr("Error"), tr("The selected file could not be loaded.")); + return; + } + + Command_DeckSelect cmd; + cmd.set_deck(deck.writeToString_Native().toStdString()); + PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); + static_cast(parent())->sendGameCommand(pend, playerId); } void DeckViewContainer::loadRemoteDeck() { - DlgLoadRemoteDeck dlg(static_cast(parent())->getClientForPlayer(playerId)); - if (dlg.exec()) { - Command_DeckSelect cmd; - cmd.set_deck_id(dlg.getDeckId()); - PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); - static_cast(parent())->sendGameCommand(pend, playerId); - } + DlgLoadRemoteDeck dlg(static_cast(parent())->getClientForPlayer(playerId)); + if (dlg.exec()) { + Command_DeckSelect cmd; + cmd.set_deck_id(dlg.getDeckId()); + PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); + static_cast(parent())->sendGameCommand(pend, playerId); + } } void DeckViewContainer::deckSelectFinished(const Response &r) { - const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); - DeckLoader newDeck(QString::fromStdString(resp.deck())); - db->cacheCardPixmaps(newDeck.getCardList()); - setDeck(newDeck); + const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); + DeckLoader newDeck(QString::fromStdString(resp.deck())); + db->cacheCardPixmaps(newDeck.getCardList()); + setDeck(newDeck); } void DeckViewContainer::readyStart() { - Command_ReadyStart cmd; - cmd.set_ready(!readyStartButton->getState()); - static_cast(parent())->sendGameCommand(cmd, playerId); + Command_ReadyStart cmd; + cmd.set_ready(!readyStartButton->getState()); + static_cast(parent())->sendGameCommand(cmd, playerId); } void DeckViewContainer::sideboardLockButtonClicked() { - Command_SetSideboardLock cmd; - cmd.set_locked(sideboardLockButton->getState()); - - static_cast(parent())->sendGameCommand(cmd, playerId); + Command_SetSideboardLock cmd; + cmd.set_locked(sideboardLockButton->getState()); + + static_cast(parent())->sendGameCommand(cmd, playerId); } void DeckViewContainer::sideboardPlanChanged() { - Command_SetSideboardPlan cmd; - const QList &newPlan = deckView->getSideboardPlan(); - for (int i = 0; i < newPlan.size(); ++i) - cmd.add_move_list()->CopyFrom(newPlan[i]); - static_cast(parent())->sendGameCommand(cmd, playerId); + Command_SetSideboardPlan cmd; + const QList &newPlan = deckView->getSideboardPlan(); + for (int i = 0; i < newPlan.size(); ++i) + cmd.add_move_list()->CopyFrom(newPlan[i]); + static_cast(parent())->sendGameCommand(cmd, playerId); } void DeckViewContainer::setReadyStart(bool ready) { - readyStartButton->setState(ready); - deckView->setLocked(ready || !sideboardLockButton->getState()); + readyStartButton->setState(ready); + deckView->setLocked(ready || !sideboardLockButton->getState()); } void DeckViewContainer::setSideboardLocked(bool locked) { - sideboardLockButton->setState(!locked); - deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState()); - if (locked) - deckView->resetSideboardPlan(); + sideboardLockButton->setState(!locked); + deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState()); + if (locked) + deckView->resetSideboardPlan(); } void DeckViewContainer::setDeck(const DeckLoader &deck) { - deckView->setDeck(deck); - readyStartButton->setEnabled(true); - sideboardLockButton->setState(false); - sideboardLockButton->setEnabled(true); + deckView->setDeck(deck); + readyStartButton->setEnabled(true); + sideboardLockButton->setState(false); + sideboardLockButton->setEnabled(true); } TabGame::TabGame(TabSupervisor *_tabSupervisor, GameReplay *_replay) - : Tab(_tabSupervisor), - hostId(-1), - localPlayerId(-1), - spectator(true), - gameStateKnown(false), - resuming(false), - currentPhase(-1), - activeCard(0), - gameClosed(false), - replay(_replay), - currentReplayStep(0) + : Tab(_tabSupervisor), + hostId(-1), + localPlayerId(-1), + spectator(true), + gameStateKnown(false), + resuming(false), + currentPhase(-1), + activeCard(0), + gameClosed(false), + replay(_replay), + currentReplayStep(0) { - setAttribute(Qt::WA_DeleteOnClose); - - gameInfo.CopyFrom(replay->game_info()); - gameInfo.set_spectators_omniscient(true); - - // Create list: event number -> time [ms] - // Distribute simultaneous events evenly across 1 second. - int lastEventTimestamp = -1; - const int eventCount = replay->event_list_size(); - for (int i = 0; i < eventCount; ++i) { - int j = i + 1; - while ((j < eventCount) && (replay->event_list(j).seconds_elapsed() == lastEventTimestamp)) - ++j; - - const int numberEventsThisSecond = j - i; - for (int k = 0; k < numberEventsThisSecond; ++k) - replayTimeline.append(replay->event_list(i + k).seconds_elapsed() * 1000 + (int) ((qreal) k / (qreal) numberEventsThisSecond * 1000)); - - if (j < eventCount) - lastEventTimestamp = replay->event_list(j).seconds_elapsed(); - i += numberEventsThisSecond - 1; - } - - phasesToolbar = new PhasesToolbar; - - scene = new GameScene(phasesToolbar, this); - gameView = new GameView(scene); - gameView->hide(); - - cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); - playerListWidget = new PlayerListWidget(0, 0, this); - playerListWidget->setFocusPolicy(Qt::NoFocus); - - timeElapsedLabel = new QLabel; - timeElapsedLabel->setAlignment(Qt::AlignCenter); - messageLog = new MessageLogWidget(tabSupervisor, this); - connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); - connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayLabel = 0; + setAttribute(Qt::WA_DeleteOnClose); + + gameInfo.CopyFrom(replay->game_info()); + gameInfo.set_spectators_omniscient(true); + + // Create list: event number -> time [ms] + // Distribute simultaneous events evenly across 1 second. + int lastEventTimestamp = -1; + const int eventCount = replay->event_list_size(); + for (int i = 0; i < eventCount; ++i) { + int j = i + 1; + while ((j < eventCount) && (replay->event_list(j).seconds_elapsed() == lastEventTimestamp)) + ++j; + + const int numberEventsThisSecond = j - i; + for (int k = 0; k < numberEventsThisSecond; ++k) + replayTimeline.append(replay->event_list(i + k).seconds_elapsed() * 1000 + (int) ((qreal) k / (qreal) numberEventsThisSecond * 1000)); + + if (j < eventCount) + lastEventTimestamp = replay->event_list(j).seconds_elapsed(); + i += numberEventsThisSecond - 1; + } + + phasesToolbar = new PhasesToolbar; + + scene = new GameScene(phasesToolbar, this); + gameView = new GameView(scene); + gameView->hide(); + + cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); + playerListWidget = new PlayerListWidget(0, 0, this); + playerListWidget->setFocusPolicy(Qt::NoFocus); + + timeElapsedLabel = new QLabel; + timeElapsedLabel->setAlignment(Qt::AlignCenter); + messageLog = new MessageLogWidget(tabSupervisor, this); + connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); + connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayLabel = 0; - deckViewContainerLayout = new QVBoxLayout; + deckViewContainerLayout = new QVBoxLayout; - QVBoxLayout *messageLogLayout = new QVBoxLayout; - messageLogLayout->addWidget(timeElapsedLabel); - messageLogLayout->addWidget(messageLog); - - QWidget *messageLogLayoutWidget = new QWidget; - messageLogLayoutWidget->setLayout(messageLogLayout); - - timelineWidget = new ReplayTimelineWidget; - timelineWidget->setTimeline(replayTimeline); - connect(timelineWidget, SIGNAL(processNextEvent()), this, SLOT(replayNextEvent())); - connect(timelineWidget, SIGNAL(replayFinished()), this, SLOT(replayFinished())); - - replayToStartButton = new QToolButton; - replayToStartButton->setIconSize(QSize(32, 32)); - replayToStartButton->setIcon(QIcon(":/resources/replay_tostart.svg")); - connect(replayToStartButton, SIGNAL(clicked()), this, SLOT(replayToStartButtonClicked())); - replayStartButton = new QToolButton; - replayStartButton->setIconSize(QSize(32, 32)); - replayStartButton->setIcon(QIcon(":/resources/replay_start.svg")); - connect(replayStartButton, SIGNAL(clicked()), this, SLOT(replayStartButtonClicked())); - replayPauseButton = new QToolButton; - replayPauseButton->setIconSize(QSize(32, 32)); - replayPauseButton->setEnabled(false); - replayPauseButton->setIcon(QIcon(":/resources/replay_pause.svg")); - connect(replayPauseButton, SIGNAL(clicked()), this, SLOT(replayPauseButtonClicked())); - replayStopButton = new QToolButton; - replayStopButton->setIconSize(QSize(32, 32)); - replayStopButton->setEnabled(false); - replayStopButton->setIcon(QIcon(":/resources/replay_stop.svg")); - connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayStopButtonClicked())); - replayFastForwardButton = new QToolButton; - replayFastForwardButton->setIconSize(QSize(32, 32)); - replayFastForwardButton->setEnabled(false); - replayFastForwardButton->setIcon(QIcon(":/resources/replay_fastforward.svg")); - replayFastForwardButton->setCheckable(true); - connect(replayFastForwardButton, SIGNAL(toggled(bool)), this, SLOT(replayFastForwardButtonToggled(bool))); - replayToEndButton = new QToolButton; - replayToEndButton->setIconSize(QSize(32, 32)); - replayToEndButton->setIcon(QIcon(":/resources/replay_toend.svg")); - connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayToEndButtonClicked())); - - splitter = new QSplitter(Qt::Vertical); - splitter->addWidget(cardInfo); - splitter->addWidget(playerListWidget); - splitter->addWidget(messageLogLayoutWidget); + QVBoxLayout *messageLogLayout = new QVBoxLayout; + messageLogLayout->addWidget(timeElapsedLabel); + messageLogLayout->addWidget(messageLog); + + QWidget *messageLogLayoutWidget = new QWidget; + messageLogLayoutWidget->setLayout(messageLogLayout); + + timelineWidget = new ReplayTimelineWidget; + timelineWidget->setTimeline(replayTimeline); + connect(timelineWidget, SIGNAL(processNextEvent()), this, SLOT(replayNextEvent())); + connect(timelineWidget, SIGNAL(replayFinished()), this, SLOT(replayFinished())); + + replayToStartButton = new QToolButton; + replayToStartButton->setIconSize(QSize(32, 32)); + replayToStartButton->setIcon(QIcon(":/resources/replay_tostart.svg")); + connect(replayToStartButton, SIGNAL(clicked()), this, SLOT(replayToStartButtonClicked())); + replayStartButton = new QToolButton; + replayStartButton->setIconSize(QSize(32, 32)); + replayStartButton->setIcon(QIcon(":/resources/replay_start.svg")); + connect(replayStartButton, SIGNAL(clicked()), this, SLOT(replayStartButtonClicked())); + replayPauseButton = new QToolButton; + replayPauseButton->setIconSize(QSize(32, 32)); + replayPauseButton->setEnabled(false); + replayPauseButton->setIcon(QIcon(":/resources/replay_pause.svg")); + connect(replayPauseButton, SIGNAL(clicked()), this, SLOT(replayPauseButtonClicked())); + replayStopButton = new QToolButton; + replayStopButton->setIconSize(QSize(32, 32)); + replayStopButton->setEnabled(false); + replayStopButton->setIcon(QIcon(":/resources/replay_stop.svg")); + connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayStopButtonClicked())); + replayFastForwardButton = new QToolButton; + replayFastForwardButton->setIconSize(QSize(32, 32)); + replayFastForwardButton->setEnabled(false); + replayFastForwardButton->setIcon(QIcon(":/resources/replay_fastforward.svg")); + replayFastForwardButton->setCheckable(true); + connect(replayFastForwardButton, SIGNAL(toggled(bool)), this, SLOT(replayFastForwardButtonToggled(bool))); + replayToEndButton = new QToolButton; + replayToEndButton->setIconSize(QSize(32, 32)); + replayToEndButton->setIcon(QIcon(":/resources/replay_toend.svg")); + connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayToEndButtonClicked())); + + splitter = new QSplitter(Qt::Vertical); + splitter->addWidget(cardInfo); + splitter->addWidget(playerListWidget); + splitter->addWidget(messageLogLayoutWidget); - mainLayout = new QHBoxLayout; - mainLayout->addWidget(gameView, 10); - mainLayout->addLayout(deckViewContainerLayout, 10); - mainLayout->addWidget(splitter); - - QHBoxLayout *replayControlLayout = new QHBoxLayout; - replayControlLayout->addWidget(timelineWidget, 10); - replayControlLayout->addWidget(replayToStartButton); - replayControlLayout->addWidget(replayStartButton); - replayControlLayout->addWidget(replayPauseButton); - replayControlLayout->addWidget(replayStopButton); - replayControlLayout->addWidget(replayFastForwardButton); - replayControlLayout->addWidget(replayToEndButton); - - QVBoxLayout *superMainLayout = new QVBoxLayout; - superMainLayout->addLayout(mainLayout); - superMainLayout->addLayout(replayControlLayout); - - aNextPhase = 0; - aNextTurn = 0; - aRemoveLocalArrows = 0; - aGameInfo = 0; - aConcede = 0; - aLeaveGame = 0; - aCloseReplay = new QAction(this); - connect(aCloseReplay, SIGNAL(triggered()), this, SLOT(actLeaveGame())); - - phasesMenu = 0; - gameMenu = new QMenu(this); - gameMenu->addAction(aCloseReplay); - addTabMenu(gameMenu); - - retranslateUi(); - setLayout(superMainLayout); + mainLayout = new QHBoxLayout; + mainLayout->addWidget(gameView, 10); + mainLayout->addLayout(deckViewContainerLayout, 10); + mainLayout->addWidget(splitter); + + QHBoxLayout *replayControlLayout = new QHBoxLayout; + replayControlLayout->addWidget(timelineWidget, 10); + replayControlLayout->addWidget(replayToStartButton); + replayControlLayout->addWidget(replayStartButton); + replayControlLayout->addWidget(replayPauseButton); + replayControlLayout->addWidget(replayStopButton); + replayControlLayout->addWidget(replayFastForwardButton); + replayControlLayout->addWidget(replayToEndButton); + + QVBoxLayout *superMainLayout = new QVBoxLayout; + superMainLayout->addLayout(mainLayout); + superMainLayout->addLayout(replayControlLayout); + + aNextPhase = 0; + aNextTurn = 0; + aRemoveLocalArrows = 0; + aGameInfo = 0; + aConcede = 0; + aLeaveGame = 0; + aCloseReplay = new QAction(this); + connect(aCloseReplay, SIGNAL(triggered()), this, SLOT(actLeaveGame())); + + phasesMenu = 0; + gameMenu = new QMenu(this); + gameMenu->addAction(aCloseReplay); + addTabMenu(gameMenu); + + retranslateUi(); + setLayout(superMainLayout); - splitter->restoreState(settingsCache->getTabGameSplitterSizes()); - - messageLog->logReplayStarted(gameInfo.game_id()); + splitter->restoreState(settingsCache->getTabGameSplitterSizes()); + + messageLog->logReplayStarted(gameInfo.game_id()); } TabGame::TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes) - : Tab(_tabSupervisor), - clients(_clients), - gameInfo(event.game_info()), - roomGameTypes(_roomGameTypes), - hostId(event.host_id()), - localPlayerId(event.player_id()), - spectator(event.spectator()), - gameStateKnown(false), - resuming(event.resuming()), - currentPhase(-1), - activeCard(0), - gameClosed(false), - replay(0) + : Tab(_tabSupervisor), + clients(_clients), + gameInfo(event.game_info()), + roomGameTypes(_roomGameTypes), + hostId(event.host_id()), + localPlayerId(event.player_id()), + spectator(event.spectator()), + gameStateKnown(false), + resuming(event.resuming()), + currentPhase(-1), + activeCard(0), + gameClosed(false), + replay(0) { - gameInfo.set_started(false); - - gameTimer = new QTimer(this); - gameTimer->setInterval(1000); - connect(gameTimer, SIGNAL(timeout()), this, SLOT(incrementGameTime())); - gameTimer->start(); - - phasesToolbar = new PhasesToolbar; - connect(phasesToolbar, SIGNAL(sendGameCommand(const ::google::protobuf::Message &, int)), this, SLOT(sendGameCommand(const ::google::protobuf::Message &, int))); - - scene = new GameScene(phasesToolbar, this); - gameView = new GameView(scene); - gameView->hide(); - - cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); - playerListWidget = new PlayerListWidget(tabSupervisor, clients.first(), this); - playerListWidget->setFocusPolicy(Qt::NoFocus); - connect(playerListWidget, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - - timeElapsedLabel = new QLabel; - timeElapsedLabel->setAlignment(Qt::AlignCenter); - messageLog = new MessageLogWidget(tabSupervisor, this); - connect(messageLog, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); - connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayLabel = new QLabel; - sayEdit = new QLineEdit; - sayLabel->setBuddy(sayEdit); + gameInfo.set_started(false); + + gameTimer = new QTimer(this); + gameTimer->setInterval(1000); + connect(gameTimer, SIGNAL(timeout()), this, SLOT(incrementGameTime())); + gameTimer->start(); + + phasesToolbar = new PhasesToolbar; + connect(phasesToolbar, SIGNAL(sendGameCommand(const ::google::protobuf::Message &, int)), this, SLOT(sendGameCommand(const ::google::protobuf::Message &, int))); + + scene = new GameScene(phasesToolbar, this); + gameView = new GameView(scene); + gameView->hide(); + + cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); + playerListWidget = new PlayerListWidget(tabSupervisor, clients.first(), this); + playerListWidget->setFocusPolicy(Qt::NoFocus); + connect(playerListWidget, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + + timeElapsedLabel = new QLabel; + timeElapsedLabel->setAlignment(Qt::AlignCenter); + messageLog = new MessageLogWidget(tabSupervisor, this); + connect(messageLog, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); + connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayLabel = new QLabel; + sayEdit = new QLineEdit; + sayLabel->setBuddy(sayEdit); - QHBoxLayout *hLayout = new QHBoxLayout; - hLayout->addWidget(sayLabel); - hLayout->addWidget(sayEdit); - - deckViewContainerLayout = new QVBoxLayout; + QHBoxLayout *hLayout = new QHBoxLayout; + hLayout->addWidget(sayLabel); + hLayout->addWidget(sayEdit); + + deckViewContainerLayout = new QVBoxLayout; - QVBoxLayout *messageLogLayout = new QVBoxLayout; - messageLogLayout->addWidget(timeElapsedLabel); - messageLogLayout->addWidget(messageLog); - messageLogLayout->addLayout(hLayout); - - QWidget *messageLogLayoutWidget = new QWidget; - messageLogLayoutWidget->setLayout(messageLogLayout); - - splitter = new QSplitter(Qt::Vertical); - splitter->addWidget(cardInfo); - splitter->addWidget(playerListWidget); - splitter->addWidget(messageLogLayoutWidget); + QVBoxLayout *messageLogLayout = new QVBoxLayout; + messageLogLayout->addWidget(timeElapsedLabel); + messageLogLayout->addWidget(messageLog); + messageLogLayout->addLayout(hLayout); + + QWidget *messageLogLayoutWidget = new QWidget; + messageLogLayoutWidget->setLayout(messageLogLayout); + + splitter = new QSplitter(Qt::Vertical); + splitter->addWidget(cardInfo); + splitter->addWidget(playerListWidget); + splitter->addWidget(messageLogLayoutWidget); - mainLayout = new QHBoxLayout; - mainLayout->addWidget(gameView, 10); - mainLayout->addLayout(deckViewContainerLayout, 10); - mainLayout->addWidget(splitter); - - if (spectator && !gameInfo.spectators_can_chat() && tabSupervisor->getAdminLocked()) { - sayLabel->hide(); - sayEdit->hide(); - } - connect(tabSupervisor, SIGNAL(adminLockChanged(bool)), this, SLOT(adminLockChanged(bool))); - connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(actSay())); + mainLayout = new QHBoxLayout; + mainLayout->addWidget(gameView, 10); + mainLayout->addLayout(deckViewContainerLayout, 10); + mainLayout->addWidget(splitter); + + if (spectator && !gameInfo.spectators_can_chat() && tabSupervisor->getAdminLocked()) { + sayLabel->hide(); + sayEdit->hide(); + } + connect(tabSupervisor, SIGNAL(adminLockChanged(bool)), this, SLOT(adminLockChanged(bool))); + connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(actSay())); - // Menu actions - aNextPhase = new QAction(this); - connect(aNextPhase, SIGNAL(triggered()), this, SLOT(actNextPhase())); - aNextTurn = new QAction(this); - connect(aNextTurn, SIGNAL(triggered()), this, SLOT(actNextTurn())); - aRemoveLocalArrows = new QAction(this); - connect(aRemoveLocalArrows, SIGNAL(triggered()), this, SLOT(actRemoveLocalArrows())); - aGameInfo = new QAction(this); - connect(aGameInfo, SIGNAL(triggered()), this, SLOT(actGameInfo())); - aConcede = new QAction(this); - connect(aConcede, SIGNAL(triggered()), this, SLOT(actConcede())); - aLeaveGame = new QAction(this); - connect(aLeaveGame, SIGNAL(triggered()), this, SLOT(actLeaveGame())); - aCloseReplay = 0; - - phasesMenu = new QMenu(this); - for (int i = 0; i < phasesToolbar->phaseCount(); ++i) { - QAction *temp = new QAction(QString(), this); - connect(temp, SIGNAL(triggered()), this, SLOT(actPhaseAction())); - switch (i) { - case 0: temp->setShortcut(tr("F5")); break; - case 2: temp->setShortcut(tr("F6")); break; - case 3: temp->setShortcut(tr("F7")); break; - case 4: temp->setShortcut(tr("F8")); break; - case 9: temp->setShortcut(tr("F9")); break; - case 10: temp->setShortcut(tr("F10")); break; - default: ; - } - phasesMenu->addAction(temp); - phaseActions.append(temp); - } - phasesMenu->addSeparator(); - phasesMenu->addAction(aNextPhase); - - gameMenu = new QMenu(this); - playersSeparator = gameMenu->addSeparator(); - gameMenu->addMenu(phasesMenu); - gameMenu->addAction(aNextTurn); - gameMenu->addSeparator(); - gameMenu->addAction(aRemoveLocalArrows); - gameMenu->addSeparator(); - gameMenu->addAction(aGameInfo); - gameMenu->addAction(aConcede); - gameMenu->addAction(aLeaveGame); - addTabMenu(gameMenu); - - retranslateUi(); - setLayout(mainLayout); + // Menu actions + aNextPhase = new QAction(this); + connect(aNextPhase, SIGNAL(triggered()), this, SLOT(actNextPhase())); + aNextTurn = new QAction(this); + connect(aNextTurn, SIGNAL(triggered()), this, SLOT(actNextTurn())); + aRemoveLocalArrows = new QAction(this); + connect(aRemoveLocalArrows, SIGNAL(triggered()), this, SLOT(actRemoveLocalArrows())); + aGameInfo = new QAction(this); + connect(aGameInfo, SIGNAL(triggered()), this, SLOT(actGameInfo())); + aConcede = new QAction(this); + connect(aConcede, SIGNAL(triggered()), this, SLOT(actConcede())); + aLeaveGame = new QAction(this); + connect(aLeaveGame, SIGNAL(triggered()), this, SLOT(actLeaveGame())); + aCloseReplay = 0; + + phasesMenu = new QMenu(this); + for (int i = 0; i < phasesToolbar->phaseCount(); ++i) { + QAction *temp = new QAction(QString(), this); + connect(temp, SIGNAL(triggered()), this, SLOT(actPhaseAction())); + switch (i) { + case 0: temp->setShortcut(tr("F5")); break; + case 2: temp->setShortcut(tr("F6")); break; + case 3: temp->setShortcut(tr("F7")); break; + case 4: temp->setShortcut(tr("F8")); break; + case 9: temp->setShortcut(tr("F9")); break; + case 10: temp->setShortcut(tr("F10")); break; + default: ; + } + phasesMenu->addAction(temp); + phaseActions.append(temp); + } + phasesMenu->addSeparator(); + phasesMenu->addAction(aNextPhase); + + gameMenu = new QMenu(this); + playersSeparator = gameMenu->addSeparator(); + gameMenu->addMenu(phasesMenu); + gameMenu->addAction(aNextTurn); + gameMenu->addSeparator(); + gameMenu->addAction(aRemoveLocalArrows); + gameMenu->addSeparator(); + gameMenu->addAction(aGameInfo); + gameMenu->addAction(aConcede); + gameMenu->addAction(aLeaveGame); + addTabMenu(gameMenu); + + retranslateUi(); + setLayout(mainLayout); - splitter->restoreState(settingsCache->getTabGameSplitterSizes()); - - messageLog->logGameJoined(gameInfo.game_id()); + splitter->restoreState(settingsCache->getTabGameSplitterSizes()); + + messageLog->logGameJoined(gameInfo.game_id()); } TabGame::~TabGame() { - delete replay; - settingsCache->setTabGameSplitterSizes(splitter->saveState()); + delete replay; + settingsCache->setTabGameSplitterSizes(splitter->saveState()); - QMapIterator i(players); - while (i.hasNext()) - delete i.next().value(); - players.clear(); - - delete deckViewContainerLayout; - - emit gameClosing(this); + QMapIterator i(players); + while (i.hasNext()) + delete i.next().value(); + players.clear(); + + delete deckViewContainerLayout; + + emit gameClosing(this); } void TabGame::retranslateUi() { - if (phasesMenu) { - for (int i = 0; i < phaseActions.size(); ++i) - phaseActions[i]->setText(phasesToolbar->getLongPhaseName(i)); - phasesMenu->setTitle(tr("&Phases")); - } - - gameMenu->setTitle(tr("&Game")); - if (aNextPhase) { - aNextPhase->setText(tr("Next &phase")); - aNextPhase->setShortcut(tr("Ctrl+Space")); - } - if (aNextTurn) { - aNextTurn->setText(tr("Next &turn")); - aNextTurn->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); - } - if (aRemoveLocalArrows) { - aRemoveLocalArrows->setText(tr("&Remove all local arrows")); - aRemoveLocalArrows->setShortcut(tr("Ctrl+R")); - } - if (aGameInfo) - aGameInfo->setText(tr("Game &information")); - if (aConcede) { - aConcede->setText(tr("&Concede")); - aConcede->setShortcut(tr("F2")); - } - if (aLeaveGame) { - aLeaveGame->setText(tr("&Leave game")); - aLeaveGame->setShortcut(tr("Ctrl+Q")); - } - if (aCloseReplay) { - aCloseReplay->setText(tr("C&lose replay")); - aCloseReplay->setShortcut(tr("Ctrl+Q")); - } - - if (sayLabel) - sayLabel->setText(tr("&Say:")); - cardInfo->retranslateUi(); + if (phasesMenu) { + for (int i = 0; i < phaseActions.size(); ++i) + phaseActions[i]->setText(phasesToolbar->getLongPhaseName(i)); + phasesMenu->setTitle(tr("&Phases")); + } + + gameMenu->setTitle(tr("&Game")); + if (aNextPhase) { + aNextPhase->setText(tr("Next &phase")); + aNextPhase->setShortcut(tr("Ctrl+Space")); + } + if (aNextTurn) { + aNextTurn->setText(tr("Next &turn")); + aNextTurn->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); + } + if (aRemoveLocalArrows) { + aRemoveLocalArrows->setText(tr("&Remove all local arrows")); + aRemoveLocalArrows->setShortcut(tr("Ctrl+R")); + } + if (aGameInfo) + aGameInfo->setText(tr("Game &information")); + if (aConcede) { + aConcede->setText(tr("&Concede")); + aConcede->setShortcut(tr("F2")); + } + if (aLeaveGame) { + aLeaveGame->setText(tr("&Leave game")); + aLeaveGame->setShortcut(tr("Ctrl+Q")); + } + if (aCloseReplay) { + aCloseReplay->setText(tr("C&lose replay")); + aCloseReplay->setShortcut(tr("Ctrl+Q")); + } + + if (sayLabel) + sayLabel->setText(tr("&Say:")); + cardInfo->retranslateUi(); - QMapIterator i(players); - while (i.hasNext()) - i.next().value()->retranslateUi(); - QMapIterator j(deckViewContainers); - while (j.hasNext()) - j.next().value()->retranslateUi(); - - scene->retranslateUi(); + QMapIterator i(players); + while (i.hasNext()) + i.next().value()->retranslateUi(); + QMapIterator j(deckViewContainers); + while (j.hasNext()) + j.next().value()->retranslateUi(); + + scene->retranslateUi(); } void TabGame::closeRequest() { - actLeaveGame(); + actLeaveGame(); } void TabGame::replayNextEvent() { - processGameEventContainer(replay->event_list(timelineWidget->getCurrentEvent()), 0); + processGameEventContainer(replay->event_list(timelineWidget->getCurrentEvent()), 0); } void TabGame::replayFinished() { - replayStartButton->setEnabled(true); - replayPauseButton->setEnabled(false); - replayStopButton->setEnabled(false); - replayFastForwardButton->setEnabled(false); + replayStartButton->setEnabled(true); + replayPauseButton->setEnabled(false); + replayStopButton->setEnabled(false); + replayFastForwardButton->setEnabled(false); } void TabGame::replayToStartButtonClicked() { - // XXX + // XXX } void TabGame::replayStartButtonClicked() { - replayStartButton->setEnabled(false); - replayPauseButton->setEnabled(true); - replayStopButton->setEnabled(true); - replayFastForwardButton->setEnabled(true); - - timelineWidget->startReplay(); + replayStartButton->setEnabled(false); + replayPauseButton->setEnabled(true); + replayStopButton->setEnabled(true); + replayFastForwardButton->setEnabled(true); + + timelineWidget->startReplay(); } void TabGame::replayPauseButtonClicked() { - replayStartButton->setEnabled(true); - replayPauseButton->setEnabled(false); - replayFastForwardButton->setEnabled(false); - - timelineWidget->stopReplay(); + replayStartButton->setEnabled(true); + replayPauseButton->setEnabled(false); + replayFastForwardButton->setEnabled(false); + + timelineWidget->stopReplay(); } void TabGame::replayStopButtonClicked() { - replayStartButton->setEnabled(true); - replayPauseButton->setEnabled(false); - replayStopButton->setEnabled(false); - replayFastForwardButton->setEnabled(false); - - timelineWidget->stopReplay(); - // XXX to start + replayStartButton->setEnabled(true); + replayPauseButton->setEnabled(false); + replayStopButton->setEnabled(false); + replayFastForwardButton->setEnabled(false); + + timelineWidget->stopReplay(); + // XXX to start } void TabGame::replayFastForwardButtonToggled(bool checked) { - timelineWidget->setTimeScaleFactor(checked ? 10.0 : 1.0); + timelineWidget->setTimeScaleFactor(checked ? 10.0 : 1.0); } void TabGame::replayToEndButtonClicked() { - // XXX + // XXX } void TabGame::incrementGameTime() { - int seconds = ++secondsElapsed; - int minutes = seconds / 60; - seconds -= minutes * 60; - int hours = minutes / 60; - minutes -= hours * 60; - - timeElapsedLabel->setText(QString::number(hours).rightJustified(2, '0') + ":" + QString::number(minutes).rightJustified(2, '0') + ":" + QString::number(seconds).rightJustified(2, '0')); + int seconds = ++secondsElapsed; + int minutes = seconds / 60; + seconds -= minutes * 60; + int hours = minutes / 60; + minutes -= hours * 60; + + timeElapsedLabel->setText(QString::number(hours).rightJustified(2, '0') + ":" + QString::number(minutes).rightJustified(2, '0') + ":" + QString::number(seconds).rightJustified(2, '0')); } void TabGame::adminLockChanged(bool lock) { - bool v = !(spectator && !gameInfo.spectators_can_chat() && lock); - sayLabel->setVisible(v); - sayEdit->setVisible(v); + bool v = !(spectator && !gameInfo.spectators_can_chat() && lock); + sayLabel->setVisible(v); + sayEdit->setVisible(v); } void TabGame::actGameInfo() { - DlgCreateGame dlg(gameInfo, roomGameTypes); - dlg.exec(); + DlgCreateGame dlg(gameInfo, roomGameTypes); + dlg.exec(); } void TabGame::actConcede() { - if (QMessageBox::question(this, tr("Concede"), tr("Are you sure you want to concede this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) - return; + if (QMessageBox::question(this, tr("Concede"), tr("Are you sure you want to concede this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) + return; - sendGameCommand(Command_Concede()); + sendGameCommand(Command_Concede()); } void TabGame::actLeaveGame() { - if (!gameClosed) { - if (!spectator) - if (QMessageBox::question(this, tr("Leave game"), tr("Are you sure you want to leave this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) - return; - - if (!replay) - sendGameCommand(Command_LeaveGame()); - } - deleteLater(); + if (!gameClosed) { + if (!spectator) + if (QMessageBox::question(this, tr("Leave game"), tr("Are you sure you want to leave this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) + return; + + if (!replay) + sendGameCommand(Command_LeaveGame()); + } + deleteLater(); } void TabGame::actSay() { - if (!sayEdit->text().isEmpty()) { - Command_GameSay cmd; - cmd.set_message(sayEdit->text().toStdString()); - sendGameCommand(cmd); - sayEdit->clear(); - } + if (!sayEdit->text().isEmpty()) { + Command_GameSay cmd; + cmd.set_message(sayEdit->text().toStdString()); + sendGameCommand(cmd); + sayEdit->clear(); + } } void TabGame::actPhaseAction() { - int phase = phaseActions.indexOf(static_cast(sender())); - Command_SetActivePhase cmd; - cmd.set_phase(phase); - sendGameCommand(cmd); + int phase = phaseActions.indexOf(static_cast(sender())); + Command_SetActivePhase cmd; + cmd.set_phase(phase); + sendGameCommand(cmd); } void TabGame::actNextPhase() { - int phase = currentPhase; - if (++phase >= phasesToolbar->phaseCount()) - phase = 0; - Command_SetActivePhase cmd; - cmd.set_phase(phase); - sendGameCommand(cmd); + int phase = currentPhase; + if (++phase >= phasesToolbar->phaseCount()) + phase = 0; + Command_SetActivePhase cmd; + cmd.set_phase(phase); + sendGameCommand(cmd); } void TabGame::actNextTurn() { - sendGameCommand(Command_NextTurn()); + sendGameCommand(Command_NextTurn()); } void TabGame::actRemoveLocalArrows() { - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) { - Player *player = playerIterator.next().value(); - if (!player->getLocal()) - continue; - QMapIterator arrowIterator(player->getArrows()); - while (arrowIterator.hasNext()) { - ArrowItem *a = arrowIterator.next().value(); - Command_DeleteArrow cmd; - cmd.set_arrow_id(a->getId()); - sendGameCommand(cmd); - } - } + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) { + Player *player = playerIterator.next().value(); + if (!player->getLocal()) + continue; + QMapIterator arrowIterator(player->getArrows()); + while (arrowIterator.hasNext()) { + ArrowItem *a = arrowIterator.next().value(); + Command_DeleteArrow cmd; + cmd.set_arrow_id(a->getId()); + sendGameCommand(cmd); + } + } } Player *TabGame::addPlayer(int playerId, const ServerInfo_User &info) { - bool local = ((clients.size() > 1) || (playerId == localPlayerId)); - Player *newPlayer = new Player(info, playerId, local, this); - connect(newPlayer, SIGNAL(openDeckEditor(const DeckLoader *)), this, SIGNAL(openDeckEditor(const DeckLoader *))); - scene->addPlayer(newPlayer); + bool local = ((clients.size() > 1) || (playerId == localPlayerId)); + Player *newPlayer = new Player(info, playerId, local, this); + connect(newPlayer, SIGNAL(openDeckEditor(const DeckLoader *)), this, SIGNAL(openDeckEditor(const DeckLoader *))); + scene->addPlayer(newPlayer); - connect(newPlayer, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); - messageLog->connectToPlayer(newPlayer); - - if (local && !spectator) { - if (clients.size() == 1) - newPlayer->setShortcutsActive(); - - DeckViewContainer *deckView = new DeckViewContainer(playerId, this); - connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); - deckViewContainers.insert(playerId, deckView); - deckViewContainerLayout->addWidget(deckView); - } + connect(newPlayer, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); + messageLog->connectToPlayer(newPlayer); + + if (local && !spectator) { + if (clients.size() == 1) + newPlayer->setShortcutsActive(); + + DeckViewContainer *deckView = new DeckViewContainer(playerId, this); + connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); + deckViewContainers.insert(playerId, deckView); + deckViewContainerLayout->addWidget(deckView); + } - gameMenu->insertMenu(playersSeparator, newPlayer->getPlayerMenu()); - - players.insert(playerId, newPlayer); - emit playerAdded(newPlayer); + gameMenu->insertMenu(playersSeparator, newPlayer->getPlayerMenu()); + + players.insert(playerId, newPlayer); + emit playerAdded(newPlayer); - return newPlayer; + return newPlayer; } void TabGame::processGameEventContainer(const GameEventContainer &cont, AbstractClient *client) { - const GameEventContext &context = cont.context(); - messageLog->containerProcessingStarted(context); - const int eventListSize = cont.event_list_size(); - for (int i = 0; i < eventListSize; ++i) { - const GameEvent &event = cont.event_list(i); - const int playerId = event.player_id(); - const GameEvent::GameEventType eventType = static_cast(getPbExtension(event)); - if (spectators.contains(playerId)) { - switch (eventType) { - case GameEvent::GAME_SAY: eventSpectatorSay(event.GetExtension(Event_GameSay::ext), playerId, context); break; - case GameEvent::LEAVE: eventSpectatorLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; - default: { - qDebug() << "unhandled spectator game event"; - break; - } - } - } else { - if ((clients.size() > 1) && (playerId != -1)) - if (clients.at(playerId) != client) - continue; - - switch (eventType) { - case GameEvent::GAME_STATE_CHANGED: eventGameStateChanged(event.GetExtension(Event_GameStateChanged::ext), playerId, context); break; - case GameEvent::PLAYER_PROPERTIES_CHANGED: eventPlayerPropertiesChanged(event.GetExtension(Event_PlayerPropertiesChanged::ext), playerId, context); break; - case GameEvent::JOIN: eventJoin(event.GetExtension(Event_Join::ext), playerId, context); break; - case GameEvent::LEAVE: eventLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; - case GameEvent::KICKED: eventKicked(event.GetExtension(Event_Kicked::ext), playerId, context); break; - case GameEvent::GAME_HOST_CHANGED: eventGameHostChanged(event.GetExtension(Event_GameHostChanged::ext), playerId, context); break; - case GameEvent::GAME_CLOSED: eventGameClosed(event.GetExtension(Event_GameClosed::ext), playerId, context); break; - case GameEvent::SET_ACTIVE_PLAYER: eventSetActivePlayer(event.GetExtension(Event_SetActivePlayer::ext), playerId, context); break; - case GameEvent::SET_ACTIVE_PHASE: eventSetActivePhase(event.GetExtension(Event_SetActivePhase::ext), playerId, context); break; - - default: { - Player *player = players.value(playerId, 0); - if (!player) { - qDebug() << "unhandled game event: invalid player id"; - break; - } - player->processGameEvent(eventType, event, context); - emit userEvent(); - } - } - } - } - messageLog->containerProcessingDone(); + const GameEventContext &context = cont.context(); + messageLog->containerProcessingStarted(context); + const int eventListSize = cont.event_list_size(); + for (int i = 0; i < eventListSize; ++i) { + const GameEvent &event = cont.event_list(i); + const int playerId = event.player_id(); + const GameEvent::GameEventType eventType = static_cast(getPbExtension(event)); + if (spectators.contains(playerId)) { + switch (eventType) { + case GameEvent::GAME_SAY: eventSpectatorSay(event.GetExtension(Event_GameSay::ext), playerId, context); break; + case GameEvent::LEAVE: eventSpectatorLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; + default: { + qDebug() << "unhandled spectator game event"; + break; + } + } + } else { + if ((clients.size() > 1) && (playerId != -1)) + if (clients.at(playerId) != client) + continue; + + switch (eventType) { + case GameEvent::GAME_STATE_CHANGED: eventGameStateChanged(event.GetExtension(Event_GameStateChanged::ext), playerId, context); break; + case GameEvent::PLAYER_PROPERTIES_CHANGED: eventPlayerPropertiesChanged(event.GetExtension(Event_PlayerPropertiesChanged::ext), playerId, context); break; + case GameEvent::JOIN: eventJoin(event.GetExtension(Event_Join::ext), playerId, context); break; + case GameEvent::LEAVE: eventLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; + case GameEvent::KICKED: eventKicked(event.GetExtension(Event_Kicked::ext), playerId, context); break; + case GameEvent::GAME_HOST_CHANGED: eventGameHostChanged(event.GetExtension(Event_GameHostChanged::ext), playerId, context); break; + case GameEvent::GAME_CLOSED: eventGameClosed(event.GetExtension(Event_GameClosed::ext), playerId, context); break; + case GameEvent::SET_ACTIVE_PLAYER: eventSetActivePlayer(event.GetExtension(Event_SetActivePlayer::ext), playerId, context); break; + case GameEvent::SET_ACTIVE_PHASE: eventSetActivePhase(event.GetExtension(Event_SetActivePhase::ext), playerId, context); break; + + default: { + Player *player = players.value(playerId, 0); + if (!player) { + qDebug() << "unhandled game event: invalid player id"; + break; + } + player->processGameEvent(eventType, event, context); + emit userEvent(); + } + } + } + } + messageLog->containerProcessingDone(); } AbstractClient *TabGame::getClientForPlayer(int playerId) const { - if (clients.size() > 1) { - if (playerId == -1) - playerId = getActiveLocalPlayer()->getId(); + if (clients.size() > 1) { + if (playerId == -1) + playerId = getActiveLocalPlayer()->getId(); - return clients.at(playerId); - } else if (clients.isEmpty()) - return 0; - else - return clients.first(); + return clients.at(playerId); + } else if (clients.isEmpty()) + return 0; + else + return clients.first(); } void TabGame::sendGameCommand(PendingCommand *pend, int playerId) { - AbstractClient *client = getClientForPlayer(playerId); - if (!client) - return; - client->sendCommand(pend); + AbstractClient *client = getClientForPlayer(playerId); + if (!client) + return; + client->sendCommand(pend); } void TabGame::sendGameCommand(const google::protobuf::Message &command, int playerId) { - AbstractClient *client = getClientForPlayer(playerId); - if (!client) - return; - client->sendCommand(prepareGameCommand(command)); + AbstractClient *client = getClientForPlayer(playerId); + if (!client) + return; + client->sendCommand(prepareGameCommand(command)); } PendingCommand *TabGame::prepareGameCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - cont.set_game_id(gameInfo.game_id()); - GameCommand *c = cont.add_game_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + cont.set_game_id(gameInfo.game_id()); + GameCommand *c = cont.add_game_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *TabGame::prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList) { - CommandContainer cont; - cont.set_game_id(gameInfo.game_id()); - for (int i = 0; i < cmdList.size(); ++i) { - GameCommand *c = cont.add_game_command(); - c->GetReflection()->MutableMessage(c, cmdList[i]->GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(*cmdList[i]); - delete cmdList[i]; - } - return new PendingCommand(cont); + CommandContainer cont; + cont.set_game_id(gameInfo.game_id()); + for (int i = 0; i < cmdList.size(); ++i) { + GameCommand *c = cont.add_game_command(); + c->GetReflection()->MutableMessage(c, cmdList[i]->GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(*cmdList[i]); + delete cmdList[i]; + } + return new PendingCommand(cont); } void TabGame::startGame(bool resuming) { - currentPhase = -1; + currentPhase = -1; - QMapIterator i(deckViewContainers); - while (i.hasNext()) { - i.next(); - i.value()->setReadyStart(false); - i.value()->hide(); - } - mainLayout->removeItem(deckViewContainerLayout); - - if (!resuming) { - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) - playerIterator.next().value()->setConceded(false); - } + QMapIterator i(deckViewContainers); + while (i.hasNext()) { + i.next(); + i.value()->setReadyStart(false); + i.value()->hide(); + } + mainLayout->removeItem(deckViewContainerLayout); + + if (!resuming) { + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) + playerIterator.next().value()->setConceded(false); + } - playerListWidget->setGameStarted(true, resuming); - gameInfo.set_started(true); - static_cast(gameView->scene())->rearrange(); - gameView->show(); + playerListWidget->setGameStarted(true, resuming); + gameInfo.set_started(true); + static_cast(gameView->scene())->rearrange(); + gameView->show(); } void TabGame::stopGame() { - currentPhase = -1; - activePlayer = -1; - - QMapIterator i(deckViewContainers); - while (i.hasNext()) { - i.next(); - i.value()->show(); - } - mainLayout->insertLayout(1, deckViewContainerLayout, 10); + currentPhase = -1; + activePlayer = -1; + + QMapIterator i(deckViewContainers); + while (i.hasNext()) { + i.next(); + i.value()->show(); + } + mainLayout->insertLayout(1, deckViewContainerLayout, 10); - playerListWidget->setActivePlayer(-1); - playerListWidget->setGameStarted(false, false); - gameInfo.set_started(false); - gameView->hide(); + playerListWidget->setActivePlayer(-1); + playerListWidget->setGameStarted(false, false); + gameInfo.set_started(false); + gameView->hide(); } void TabGame::closeGame() { - gameInfo.set_started(false); - gameClosed = true; - - gameMenu->clear(); - gameMenu->addAction(aLeaveGame); + gameInfo.set_started(false); + gameClosed = true; + + gameMenu->clear(); + gameMenu->addAction(aLeaveGame); } void TabGame::eventSpectatorSay(const Event_GameSay &event, int eventPlayerId, const GameEventContext & /*context*/) { - const ServerInfo_User &userInfo = spectators.value(eventPlayerId); - messageLog->logSpectatorSay(QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), QString::fromStdString(event.message())); + const ServerInfo_User &userInfo = spectators.value(eventPlayerId); + messageLog->logSpectatorSay(QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), QString::fromStdString(event.message())); } void TabGame::eventSpectatorLeave(const Event_Leave & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) { - messageLog->logLeaveSpectator(QString::fromStdString(spectators.value(eventPlayerId).name())); - playerListWidget->removePlayer(eventPlayerId); - spectators.remove(eventPlayerId); - - emit userEvent(); + messageLog->logLeaveSpectator(QString::fromStdString(spectators.value(eventPlayerId).name())); + playerListWidget->removePlayer(eventPlayerId); + spectators.remove(eventPlayerId); + + emit userEvent(); } void TabGame::eventGameStateChanged(const Event_GameStateChanged &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - const int playerListSize = event.player_list_size(); - for (int i = 0; i < playerListSize; ++i) { - const ServerInfo_Player &playerInfo = event.player_list(i); - const ServerInfo_PlayerProperties &prop = playerInfo.properties(); - const int playerId = prop.player_id(); - if (prop.spectator()) { - if (!spectators.contains(playerId)) { - spectators.insert(playerId, prop.user_info()); - playerListWidget->addPlayer(prop); - } - } else { - Player *player = players.value(playerId, 0); - if (!player) { - player = addPlayer(playerId, prop.user_info()); - playerListWidget->addPlayer(prop); - } - player->processPlayerInfo(playerInfo); - if (player->getLocal()) { - DeckViewContainer *deckViewContainer = deckViewContainers.value(playerId); - if (playerInfo.has_deck_list()) { - DeckLoader newDeck(QString::fromStdString(playerInfo.deck_list())); - db->cacheCardPixmaps(newDeck.getCardList()); - deckViewContainer->setDeck(newDeck); - player->setDeck(newDeck); - } - deckViewContainer->setReadyStart(prop.ready_start()); - deckViewContainer->setSideboardLocked(prop.sideboard_locked()); - } - } - } - for (int i = 0; i < playerListSize; ++i) { - const ServerInfo_Player &playerInfo = event.player_list(i); - const ServerInfo_PlayerProperties &prop = playerInfo.properties(); - if (!prop.spectator()) { - Player *player = players.value(prop.player_id(), 0); - if (!player) - continue; - player->processCardAttachment(playerInfo); - } - } - - secondsElapsed = event.seconds_elapsed(); - - if (event.game_started() && !gameInfo.started()) { - startGame(!gameStateKnown); - if (gameStateKnown) - messageLog->logGameStart(); - setActivePlayer(event.active_player_id()); - setActivePhase(event.active_phase()); - } else if (!event.game_started() && gameInfo.started()) { - stopGame(); - scene->clearViews(); - } - gameStateKnown = true; - emit userEvent(); + const int playerListSize = event.player_list_size(); + for (int i = 0; i < playerListSize; ++i) { + const ServerInfo_Player &playerInfo = event.player_list(i); + const ServerInfo_PlayerProperties &prop = playerInfo.properties(); + const int playerId = prop.player_id(); + if (prop.spectator()) { + if (!spectators.contains(playerId)) { + spectators.insert(playerId, prop.user_info()); + playerListWidget->addPlayer(prop); + } + } else { + Player *player = players.value(playerId, 0); + if (!player) { + player = addPlayer(playerId, prop.user_info()); + playerListWidget->addPlayer(prop); + } + player->processPlayerInfo(playerInfo); + if (player->getLocal()) { + DeckViewContainer *deckViewContainer = deckViewContainers.value(playerId); + if (playerInfo.has_deck_list()) { + DeckLoader newDeck(QString::fromStdString(playerInfo.deck_list())); + db->cacheCardPixmaps(newDeck.getCardList()); + deckViewContainer->setDeck(newDeck); + player->setDeck(newDeck); + } + deckViewContainer->setReadyStart(prop.ready_start()); + deckViewContainer->setSideboardLocked(prop.sideboard_locked()); + } + } + } + for (int i = 0; i < playerListSize; ++i) { + const ServerInfo_Player &playerInfo = event.player_list(i); + const ServerInfo_PlayerProperties &prop = playerInfo.properties(); + if (!prop.spectator()) { + Player *player = players.value(prop.player_id(), 0); + if (!player) + continue; + player->processCardAttachment(playerInfo); + } + } + + secondsElapsed = event.seconds_elapsed(); + + if (event.game_started() && !gameInfo.started()) { + startGame(!gameStateKnown); + if (gameStateKnown) + messageLog->logGameStart(); + setActivePlayer(event.active_player_id()); + setActivePhase(event.active_phase()); + } else if (!event.game_started() && gameInfo.started()) { + stopGame(); + scene->clearViews(); + } + gameStateKnown = true; + emit userEvent(); } void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context) { - Player *player = players.value(eventPlayerId, 0); - if (!player) - return; - const ServerInfo_PlayerProperties &prop = event.player_properties(); - playerListWidget->updatePlayerProperties(prop, eventPlayerId); - - const GameEventContext::ContextType contextType = static_cast(getPbExtension(context)); - switch (contextType) { - case GameEventContext::READY_START: { - bool ready = prop.ready_start(); - if (player->getLocal()) - deckViewContainers.value(player->getId())->setReadyStart(ready); - if (ready) - messageLog->logReadyStart(player); - else - messageLog->logNotReadyStart(player); - break; - } - case GameEventContext::CONCEDE: { - messageLog->logConcede(player); - player->setConceded(true); - - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) - playerIterator.next().value()->updateZones(); - - break; - } - case GameEventContext::DECK_SELECT: { - messageLog->logDeckSelect(player, QString::fromStdString(context.GetExtension(Context_DeckSelect::ext).deck_hash())); - break; - } - case GameEventContext::SET_SIDEBOARD_LOCK: { - if (player->getLocal()) - deckViewContainers.value(player->getId())->setSideboardLocked(prop.sideboard_locked()); - messageLog->logSetSideboardLock(player, prop.sideboard_locked()); - break; - } - case GameEventContext::CONNECTION_STATE_CHANGED: { - messageLog->logConnectionStateChanged(player, prop.ping_seconds() != -1); - break; - } - default: ; - } + Player *player = players.value(eventPlayerId, 0); + if (!player) + return; + const ServerInfo_PlayerProperties &prop = event.player_properties(); + playerListWidget->updatePlayerProperties(prop, eventPlayerId); + + const GameEventContext::ContextType contextType = static_cast(getPbExtension(context)); + switch (contextType) { + case GameEventContext::READY_START: { + bool ready = prop.ready_start(); + if (player->getLocal()) + deckViewContainers.value(player->getId())->setReadyStart(ready); + if (ready) + messageLog->logReadyStart(player); + else + messageLog->logNotReadyStart(player); + break; + } + case GameEventContext::CONCEDE: { + messageLog->logConcede(player); + player->setConceded(true); + + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) + playerIterator.next().value()->updateZones(); + + break; + } + case GameEventContext::DECK_SELECT: { + messageLog->logDeckSelect(player, QString::fromStdString(context.GetExtension(Context_DeckSelect::ext).deck_hash())); + break; + } + case GameEventContext::SET_SIDEBOARD_LOCK: { + if (player->getLocal()) + deckViewContainers.value(player->getId())->setSideboardLocked(prop.sideboard_locked()); + messageLog->logSetSideboardLock(player, prop.sideboard_locked()); + break; + } + case GameEventContext::CONNECTION_STATE_CHANGED: { + messageLog->logConnectionStateChanged(player, prop.ping_seconds() != -1); + break; + } + default: ; + } } void TabGame::eventJoin(const Event_Join &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - const ServerInfo_PlayerProperties &playerInfo = event.player_properties(); - const int playerId = playerInfo.player_id(); - if (players.contains(playerId)) - return; - if (playerInfo.spectator()) { - spectators.insert(playerId, playerInfo.user_info()); - messageLog->logJoinSpectator(QString::fromStdString(playerInfo.user_info().name())); - } else { - Player *newPlayer = addPlayer(playerId, playerInfo.user_info()); - messageLog->logJoin(newPlayer); - } - playerListWidget->addPlayer(playerInfo); - emit userEvent(); + const ServerInfo_PlayerProperties &playerInfo = event.player_properties(); + const int playerId = playerInfo.player_id(); + if (players.contains(playerId)) + return; + if (playerInfo.spectator()) { + spectators.insert(playerId, playerInfo.user_info()); + messageLog->logJoinSpectator(QString::fromStdString(playerInfo.user_info().name())); + } else { + Player *newPlayer = addPlayer(playerId, playerInfo.user_info()); + messageLog->logJoin(newPlayer); + } + playerListWidget->addPlayer(playerInfo); + emit userEvent(); } void TabGame::eventLeave(const Event_Leave & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) { - Player *player = players.value(eventPlayerId, 0); - if (!player) - return; - - messageLog->logLeave(player); - playerListWidget->removePlayer(eventPlayerId); - players.remove(eventPlayerId); - emit playerRemoved(player); - player->clear(); - player->deleteLater(); - - // Rearrange all remaining zones so that attachment relationship updates take place - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) - playerIterator.next().value()->updateZones(); - - emit userEvent(); + Player *player = players.value(eventPlayerId, 0); + if (!player) + return; + + messageLog->logLeave(player); + playerListWidget->removePlayer(eventPlayerId); + players.remove(eventPlayerId); + emit playerRemoved(player); + player->clear(); + player->deleteLater(); + + // Rearrange all remaining zones so that attachment relationship updates take place + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) + playerIterator.next().value()->updateZones(); + + emit userEvent(); } void TabGame::eventKicked(const Event_Kicked & /*event*/, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - closeGame(); - messageLog->logKicked(); - emit userEvent(); + closeGame(); + messageLog->logKicked(); + emit userEvent(); } void TabGame::eventGameHostChanged(const Event_GameHostChanged & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) { - hostId = eventPlayerId; + hostId = eventPlayerId; } void TabGame::eventGameClosed(const Event_GameClosed & /*event*/, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - closeGame(); - messageLog->logGameClosed(); - emit userEvent(); + closeGame(); + messageLog->logGameClosed(); + emit userEvent(); } Player *TabGame::setActivePlayer(int id) { - Player *player = players.value(id, 0); - if (!player) - return 0; - activePlayer = id; - playerListWidget->setActivePlayer(id); - QMapIterator i(players); - while (i.hasNext()) { - i.next(); - if (i.value() == player) { - i.value()->setActive(true); - if (clients.size() > 1) - i.value()->setShortcutsActive(); - } else { - i.value()->setActive(false); - if (clients.size() > 1) - i.value()->setShortcutsInactive(); - } - } - currentPhase = -1; - emit userEvent(); - return player; + Player *player = players.value(id, 0); + if (!player) + return 0; + activePlayer = id; + playerListWidget->setActivePlayer(id); + QMapIterator i(players); + while (i.hasNext()) { + i.next(); + if (i.value() == player) { + i.value()->setActive(true); + if (clients.size() > 1) + i.value()->setShortcutsActive(); + } else { + i.value()->setActive(false); + if (clients.size() > 1) + i.value()->setShortcutsInactive(); + } + } + currentPhase = -1; + emit userEvent(); + return player; } void TabGame::eventSetActivePlayer(const Event_SetActivePlayer &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - Player *player = setActivePlayer(event.active_player_id()); - if (!player) - return; - messageLog->logSetActivePlayer(player); - emit userEvent(); + Player *player = setActivePlayer(event.active_player_id()); + if (!player) + return; + messageLog->logSetActivePlayer(player); + emit userEvent(); } void TabGame::setActivePhase(int phase) { - if (currentPhase != phase) { - currentPhase = phase; - phasesToolbar->setActivePhase(phase); - } + if (currentPhase != phase) { + currentPhase = phase; + phasesToolbar->setActivePhase(phase); + } } void TabGame::eventSetActivePhase(const Event_SetActivePhase &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - const int phase = event.phase(); - if (currentPhase != phase) - messageLog->logSetActivePhase(phase); - setActivePhase(phase); - emit userEvent(); + const int phase = event.phase(); + if (currentPhase != phase) + messageLog->logSetActivePhase(phase); + setActivePhase(phase); + emit userEvent(); } void TabGame::newCardAdded(AbstractCardItem *card) { - connect(card, SIGNAL(hovered(AbstractCardItem *)), cardInfo, SLOT(setCard(AbstractCardItem *))); - connect(card, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(card, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - connect(card, SIGNAL(updateCardMenu(AbstractCardItem *)), this, SLOT(updateCardMenu(AbstractCardItem *))); + connect(card, SIGNAL(hovered(AbstractCardItem *)), cardInfo, SLOT(setCard(AbstractCardItem *))); + connect(card, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(card, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + connect(card, SIGNAL(updateCardMenu(AbstractCardItem *)), this, SLOT(updateCardMenu(AbstractCardItem *))); } CardItem *TabGame::getCard(int playerId, const QString &zoneName, int cardId) const { - Player *player = players.value(playerId, 0); - if (!player) - return 0; - - CardZone *zone = player->getZones().value(zoneName, 0); - if (!zone) - return 0; - - return zone->getCard(cardId, QString()); + Player *player = players.value(playerId, 0); + if (!player) + return 0; + + CardZone *zone = player->getZones().value(zoneName, 0); + if (!zone) + return 0; + + return zone->getCard(cardId, QString()); } QString TabGame::getTabText() const { - if (replay) - return tr("Replay %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); - else - return tr("Game %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); + if (replay) + return tr("Replay %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); + else + return tr("Game %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); } Player *TabGame::getActiveLocalPlayer() const { - Player *active = players.value(activePlayer, 0); - if (active) - if (active->getLocal()) - return active; - - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) { - Player *temp = playerIterator.next().value(); - if (temp->getLocal()) - return temp; - } - - return 0; + Player *active = players.value(activePlayer, 0); + if (active) + if (active->getLocal()) + return active; + + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) { + Player *temp = playerIterator.next().value(); + if (temp->getLocal()) + return temp; + } + + return 0; } void TabGame::updateCardMenu(AbstractCardItem *card) { - Player *p; - if ((clients.size() > 1) || !players.contains(localPlayerId)) - p = card->getOwner(); - else - p = players.value(localPlayerId); - p->updateCardMenu(static_cast(card)); + Player *p; + if ((clients.size() > 1) || !players.contains(localPlayerId)) + p = card->getOwner(); + else + p = players.value(localPlayerId); + p->updateCardMenu(static_cast(card)); } diff --git a/cockatrice/src/tab_game.h b/cockatrice/src/tab_game.h index f511ef69..50f77e1a 100644 --- a/cockatrice/src/tab_game.h +++ b/cockatrice/src/tab_game.h @@ -56,170 +56,170 @@ class ServerInfo_User; class PendingCommand; class ToggleButton : public QPushButton { - Q_OBJECT + Q_OBJECT private: - bool state; + bool state; signals: - void stateChanged(); + void stateChanged(); public: - ToggleButton(QWidget *parent = 0); - bool getState() const { return state; } - void setState(bool _state); + ToggleButton(QWidget *parent = 0); + bool getState() const { return state; } + void setState(bool _state); protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent *event); }; class DeckViewContainer : public QWidget { - Q_OBJECT + Q_OBJECT private: - QPushButton *loadLocalButton, *loadRemoteButton; - ToggleButton *readyStartButton, *sideboardLockButton; - DeckView *deckView; - int playerId; + QPushButton *loadLocalButton, *loadRemoteButton; + ToggleButton *readyStartButton, *sideboardLockButton; + DeckView *deckView; + int playerId; private slots: - void loadLocalDeck(); - void loadRemoteDeck(); - void readyStart(); - void deckSelectFinished(const Response &r); - void sideboardPlanChanged(); - void sideboardLockButtonClicked(); - void updateSideboardLockButtonText(); + void loadLocalDeck(); + void loadRemoteDeck(); + void readyStart(); + void deckSelectFinished(const Response &r); + void sideboardPlanChanged(); + void sideboardLockButtonClicked(); + void updateSideboardLockButtonText(); signals: - void newCardAdded(AbstractCardItem *card); + void newCardAdded(AbstractCardItem *card); public: - DeckViewContainer(int _playerId, TabGame *parent = 0); - void retranslateUi(); - void setButtonsVisible(bool _visible); - void setReadyStart(bool ready); - void setSideboardLocked(bool locked); - void setDeck(const DeckLoader &deck); + DeckViewContainer(int _playerId, TabGame *parent = 0); + void retranslateUi(); + void setButtonsVisible(bool _visible); + void setReadyStart(bool ready); + void setSideboardLocked(bool locked); + void setDeck(const DeckLoader &deck); }; class TabGame : public Tab { - Q_OBJECT + Q_OBJECT private: - QTimer *gameTimer; - int secondsElapsed; - QList clients; - ServerInfo_Game gameInfo; - QMap roomGameTypes; - int hostId; - int localPlayerId; - bool spectator; - QMap players; - QMap spectators; - bool gameStateKnown; - bool resuming; - QStringList phasesList; - int currentPhase; - int activePlayer; - CardItem *activeCard; - bool gameClosed; - - // Replay related members - GameReplay *replay; - int currentReplayStep; - QList replayTimeline; - ReplayTimelineWidget *timelineWidget; - QToolButton *replayToStartButton, *replayStartButton, *replayPauseButton, *replayStopButton, *replayFastForwardButton, *replayToEndButton; - - QSplitter *splitter; - CardInfoWidget *cardInfo; - PlayerListWidget *playerListWidget; - QLabel *timeElapsedLabel; - MessageLogWidget *messageLog; - QLabel *sayLabel; - QLineEdit *sayEdit; - PhasesToolbar *phasesToolbar; - GameScene *scene; - GameView *gameView; - QMap deckViewContainers; - QVBoxLayout *deckViewContainerLayout; - QHBoxLayout *mainLayout; - ZoneViewLayout *zoneLayout; - QAction *playersSeparator; - QMenu *gameMenu; - QMenu *phasesMenu; - QAction *aGameInfo, *aConcede, *aLeaveGame, *aCloseReplay, *aNextPhase, *aNextTurn, *aRemoveLocalArrows; - QList phaseActions; + QTimer *gameTimer; + int secondsElapsed; + QList clients; + ServerInfo_Game gameInfo; + QMap roomGameTypes; + int hostId; + int localPlayerId; + bool spectator; + QMap players; + QMap spectators; + bool gameStateKnown; + bool resuming; + QStringList phasesList; + int currentPhase; + int activePlayer; + CardItem *activeCard; + bool gameClosed; + + // Replay related members + GameReplay *replay; + int currentReplayStep; + QList replayTimeline; + ReplayTimelineWidget *timelineWidget; + QToolButton *replayToStartButton, *replayStartButton, *replayPauseButton, *replayStopButton, *replayFastForwardButton, *replayToEndButton; + + QSplitter *splitter; + CardInfoWidget *cardInfo; + PlayerListWidget *playerListWidget; + QLabel *timeElapsedLabel; + MessageLogWidget *messageLog; + QLabel *sayLabel; + QLineEdit *sayEdit; + PhasesToolbar *phasesToolbar; + GameScene *scene; + GameView *gameView; + QMap deckViewContainers; + QVBoxLayout *deckViewContainerLayout; + QHBoxLayout *mainLayout; + ZoneViewLayout *zoneLayout; + QAction *playersSeparator; + QMenu *gameMenu; + QMenu *phasesMenu; + QAction *aGameInfo, *aConcede, *aLeaveGame, *aCloseReplay, *aNextPhase, *aNextTurn, *aRemoveLocalArrows; + QList phaseActions; - Player *addPlayer(int playerId, const ServerInfo_User &info); + Player *addPlayer(int playerId, const ServerInfo_User &info); - void startGame(bool resuming); - void stopGame(); - void closeGame(); + void startGame(bool resuming); + void stopGame(); + void closeGame(); - void eventSpectatorSay(const Event_GameSay &event, int eventPlayerId, const GameEventContext &context); - void eventSpectatorLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); - - void eventGameStateChanged(const Event_GameStateChanged &event, int eventPlayerId, const GameEventContext &context); - void eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context); - void eventJoin(const Event_Join &event, int eventPlayerId, const GameEventContext &context); - void eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); - void eventKicked(const Event_Kicked &event, int eventPlayerId, const GameEventContext &context); - void eventGameHostChanged(const Event_GameHostChanged &event, int eventPlayerId, const GameEventContext &context); - void eventGameClosed(const Event_GameClosed &event, int eventPlayerId, const GameEventContext &context); - Player *setActivePlayer(int id); - void eventSetActivePlayer(const Event_SetActivePlayer &event, int eventPlayerId, const GameEventContext &context); - void setActivePhase(int phase); - void eventSetActivePhase(const Event_SetActivePhase &event, int eventPlayerId, const GameEventContext &context); - void eventPing(const Event_Ping &event, int eventPlayerId, const GameEventContext &context); + void eventSpectatorSay(const Event_GameSay &event, int eventPlayerId, const GameEventContext &context); + void eventSpectatorLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); + + void eventGameStateChanged(const Event_GameStateChanged &event, int eventPlayerId, const GameEventContext &context); + void eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context); + void eventJoin(const Event_Join &event, int eventPlayerId, const GameEventContext &context); + void eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); + void eventKicked(const Event_Kicked &event, int eventPlayerId, const GameEventContext &context); + void eventGameHostChanged(const Event_GameHostChanged &event, int eventPlayerId, const GameEventContext &context); + void eventGameClosed(const Event_GameClosed &event, int eventPlayerId, const GameEventContext &context); + Player *setActivePlayer(int id); + void eventSetActivePlayer(const Event_SetActivePlayer &event, int eventPlayerId, const GameEventContext &context); + void setActivePhase(int phase); + void eventSetActivePhase(const Event_SetActivePhase &event, int eventPlayerId, const GameEventContext &context); + void eventPing(const Event_Ping &event, int eventPlayerId, const GameEventContext &context); signals: - void gameClosing(TabGame *tab); - void playerAdded(Player *player); - void playerRemoved(Player *player); - void containerProcessingStarted(const GameEventContext &context); - void containerProcessingDone(); - void openMessageDialog(const QString &userName, bool focus); - void openDeckEditor(const DeckLoader *deck); + void gameClosing(TabGame *tab); + void playerAdded(Player *player); + void playerRemoved(Player *player); + void containerProcessingStarted(const GameEventContext &context); + void containerProcessingDone(); + void openMessageDialog(const QString &userName, bool focus); + void openDeckEditor(const DeckLoader *deck); private slots: - void replayNextEvent(); - void replayFinished(); - void replayToStartButtonClicked(); - void replayStartButtonClicked(); - void replayPauseButtonClicked(); - void replayStopButtonClicked(); - void replayFastForwardButtonToggled(bool checked); - void replayToEndButtonClicked(); - - void incrementGameTime(); - void adminLockChanged(bool lock); - void newCardAdded(AbstractCardItem *card); - void updateCardMenu(AbstractCardItem *card); - - void actGameInfo(); - void actConcede(); - void actLeaveGame(); - void actRemoveLocalArrows(); - void actSay(); - void actPhaseAction(); - void actNextPhase(); - void actNextTurn(); + void replayNextEvent(); + void replayFinished(); + void replayToStartButtonClicked(); + void replayStartButtonClicked(); + void replayPauseButtonClicked(); + void replayStopButtonClicked(); + void replayFastForwardButtonToggled(bool checked); + void replayToEndButtonClicked(); + + void incrementGameTime(); + void adminLockChanged(bool lock); + void newCardAdded(AbstractCardItem *card); + void updateCardMenu(AbstractCardItem *card); + + void actGameInfo(); + void actConcede(); + void actLeaveGame(); + void actRemoveLocalArrows(); + void actSay(); + void actPhaseAction(); + void actNextPhase(); + void actNextTurn(); public: - TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes); - TabGame(TabSupervisor *_tabSupervisor, GameReplay *replay); - ~TabGame(); - void retranslateUi(); - void closeRequest(); - const QMap &getPlayers() const { return players; } - CardItem *getCard(int playerId, const QString &zoneName, int cardId) const; - bool isHost() const { return hostId == localPlayerId; } - int getGameId() const { return gameInfo.game_id(); } - QString getTabText() const; - bool getSpectator() const { return spectator; } - bool getSpectatorsSeeEverything() const { return gameInfo.spectators_omniscient(); } - Player *getActiveLocalPlayer() const; - AbstractClient *getClientForPlayer(int playerId) const; - - void setActiveCard(CardItem *_card) { activeCard = _card; } - CardItem *getActiveCard() const { return activeCard; } + TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes); + TabGame(TabSupervisor *_tabSupervisor, GameReplay *replay); + ~TabGame(); + void retranslateUi(); + void closeRequest(); + const QMap &getPlayers() const { return players; } + CardItem *getCard(int playerId, const QString &zoneName, int cardId) const; + bool isHost() const { return hostId == localPlayerId; } + int getGameId() const { return gameInfo.game_id(); } + QString getTabText() const; + bool getSpectator() const { return spectator; } + bool getSpectatorsSeeEverything() const { return gameInfo.spectators_omniscient(); } + Player *getActiveLocalPlayer() const; + AbstractClient *getClientForPlayer(int playerId) const; + + void setActiveCard(CardItem *_card) { activeCard = _card; } + CardItem *getActiveCard() const { return activeCard; } - void processGameEventContainer(const GameEventContainer &cont, AbstractClient *client); - PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); - PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); + void processGameEventContainer(const GameEventContainer &cont, AbstractClient *client); + PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); + PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); public slots: - void sendGameCommand(PendingCommand *pend, int playerId = -1); - void sendGameCommand(const ::google::protobuf::Message &command, int playerId = -1); + void sendGameCommand(PendingCommand *pend, int playerId = -1); + void sendGameCommand(const ::google::protobuf::Message &command, int playerId = -1); }; #endif diff --git a/cockatrice/src/tab_message.cpp b/cockatrice/src/tab_message.cpp index cfc5c050..80a56154 100644 --- a/cockatrice/src/tab_message.cpp +++ b/cockatrice/src/tab_message.cpp @@ -13,100 +13,100 @@ #include "pb/serverinfo_user.pb.h" TabMessage::TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo) - : Tab(_tabSupervisor), client(_client), ownUserInfo(new ServerInfo_User(_ownUserInfo)), otherUserInfo(new ServerInfo_User(_otherUserInfo)), userOnline(true) + : Tab(_tabSupervisor), client(_client), ownUserInfo(new ServerInfo_User(_ownUserInfo)), otherUserInfo(new ServerInfo_User(_otherUserInfo)), userOnline(true) { - chatView = new ChatView(tabSupervisor, 0, true); - connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayEdit = new QLineEdit; - connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(chatView); - vbox->addWidget(sayEdit); - - aLeave = new QAction(this); - connect(aLeave, SIGNAL(triggered()), this, SLOT(actLeave())); + chatView = new ChatView(tabSupervisor, 0, true); + connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayEdit = new QLineEdit; + connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(chatView); + vbox->addWidget(sayEdit); + + aLeave = new QAction(this); + connect(aLeave, SIGNAL(triggered()), this, SLOT(actLeave())); - messageMenu = new QMenu(this); - messageMenu->addAction(aLeave); - addTabMenu(messageMenu); + messageMenu = new QMenu(this); + messageMenu->addAction(aLeave); + addTabMenu(messageMenu); - retranslateUi(); - setLayout(vbox); + retranslateUi(); + setLayout(vbox); } TabMessage::~TabMessage() { - emit talkClosing(this); - delete ownUserInfo; - delete otherUserInfo; + emit talkClosing(this); + delete ownUserInfo; + delete otherUserInfo; } void TabMessage::retranslateUi() { - messageMenu->setTitle(tr("Personal &talk")); - aLeave->setText(tr("&Leave")); + messageMenu->setTitle(tr("Personal &talk")); + aLeave->setText(tr("&Leave")); } QString TabMessage::getUserName() const { - return QString::fromStdString(otherUserInfo->name()); + return QString::fromStdString(otherUserInfo->name()); } QString TabMessage::getTabText() const { - return tr("Talking to %1").arg(QString::fromStdString(otherUserInfo->name())); + return tr("Talking to %1").arg(QString::fromStdString(otherUserInfo->name())); } void TabMessage::closeRequest() { - actLeave(); + actLeave(); } void TabMessage::sendMessage() { - if (sayEdit->text().isEmpty() || !userOnline) - return; - - Command_Message cmd; - cmd.set_user_name(otherUserInfo->name()); - cmd.set_message(sayEdit->text().toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(messageSent(const Response &))); - client->sendCommand(pend); - - sayEdit->clear(); + if (sayEdit->text().isEmpty() || !userOnline) + return; + + Command_Message cmd; + cmd.set_user_name(otherUserInfo->name()); + cmd.set_message(sayEdit->text().toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(messageSent(const Response &))); + client->sendCommand(pend); + + sayEdit->clear(); } void TabMessage::messageSent(const Response &response) { - if (response.response_code() == Response::RespInIgnoreList) - chatView->appendMessage(tr("This user is ignoring you.")); + if (response.response_code() == Response::RespInIgnoreList) + chatView->appendMessage(tr("This user is ignoring you.")); } void TabMessage::actLeave() { - deleteLater(); + deleteLater(); } void TabMessage::processUserMessageEvent(const Event_UserMessage &event) { - const UserLevelFlags userLevel(event.sender_name() == otherUserInfo->name() ? otherUserInfo->user_level() : ownUserInfo->user_level()); - chatView->appendMessage(QString::fromStdString(event.message()), QString::fromStdString(event.sender_name()), userLevel); - emit userEvent(); + const UserLevelFlags userLevel(event.sender_name() == otherUserInfo->name() ? otherUserInfo->user_level() : ownUserInfo->user_level()); + chatView->appendMessage(QString::fromStdString(event.message()), QString::fromStdString(event.sender_name()), userLevel); + emit userEvent(); } void TabMessage::processUserLeft() { - chatView->appendMessage(tr("%1 has left the server.").arg(QString::fromStdString(otherUserInfo->name()))); - userOnline = false; + chatView->appendMessage(tr("%1 has left the server.").arg(QString::fromStdString(otherUserInfo->name()))); + userOnline = false; } void TabMessage::processUserJoined(const ServerInfo_User &_userInfo) { - chatView->appendMessage(tr("%1 has joined the server.").arg(QString::fromStdString(otherUserInfo->name()))); - userOnline = true; - *otherUserInfo = _userInfo; + chatView->appendMessage(tr("%1 has joined the server.").arg(QString::fromStdString(otherUserInfo->name()))); + userOnline = true; + *otherUserInfo = _userInfo; } diff --git a/cockatrice/src/tab_message.h b/cockatrice/src/tab_message.h index 08307fff..b8f98959 100644 --- a/cockatrice/src/tab_message.h +++ b/cockatrice/src/tab_message.h @@ -11,35 +11,35 @@ class Response; class ServerInfo_User; class TabMessage : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - QMenu *messageMenu; - ServerInfo_User *ownUserInfo; - ServerInfo_User *otherUserInfo; - bool userOnline; - - ChatView *chatView; - QLineEdit *sayEdit; + AbstractClient *client; + QMenu *messageMenu; + ServerInfo_User *ownUserInfo; + ServerInfo_User *otherUserInfo; + bool userOnline; + + ChatView *chatView; + QLineEdit *sayEdit; - QAction *aLeave; + QAction *aLeave; signals: - void talkClosing(TabMessage *tab); + void talkClosing(TabMessage *tab); private slots: - void sendMessage(); - void actLeave(); - void messageSent(const Response &response); + void sendMessage(); + void actLeave(); + void messageSent(const Response &response); public: - TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo); - ~TabMessage(); - void retranslateUi(); - void closeRequest(); - QString getUserName() const; - QString getTabText() const; + TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo); + ~TabMessage(); + void retranslateUi(); + void closeRequest(); + QString getUserName() const; + QString getTabText() const; - void processUserMessageEvent(const Event_UserMessage &event); - void processUserLeft(); - void processUserJoined(const ServerInfo_User &_userInfo); + void processUserMessageEvent(const Event_UserMessage &event); + void processUserLeft(); + void processUserJoined(const ServerInfo_User &_userInfo); }; #endif diff --git a/cockatrice/src/tab_replays.cpp b/cockatrice/src/tab_replays.cpp index 27fbce94..92b0be08 100644 --- a/cockatrice/src/tab_replays.cpp +++ b/cockatrice/src/tab_replays.cpp @@ -25,248 +25,248 @@ #include "pb/event_replay_added.pb.h" TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) - : Tab(_tabSupervisor), client(_client) + : Tab(_tabSupervisor), client(_client) { - localDirModel = new QFileSystemModel(this); - localDirModel->setRootPath(settingsCache->getReplaysPath()); - localDirModel->sort(0, Qt::AscendingOrder); - - localDirView = new QTreeView; - localDirView->setModel(localDirModel); - localDirView->setColumnHidden(1, true); - localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); - localDirView->setSortingEnabled(true); - localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); - localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); - - leftToolBar = new QToolBar; - leftToolBar->setOrientation(Qt::Horizontal); - leftToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *leftToolBarLayout = new QHBoxLayout; - leftToolBarLayout->addStretch(); - leftToolBarLayout->addWidget(leftToolBar); - leftToolBarLayout->addStretch(); + localDirModel = new QFileSystemModel(this); + localDirModel->setRootPath(settingsCache->getReplaysPath()); + localDirModel->sort(0, Qt::AscendingOrder); + + localDirView = new QTreeView; + localDirView->setModel(localDirModel); + localDirView->setColumnHidden(1, true); + localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); + localDirView->setSortingEnabled(true); + localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); + localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); + + leftToolBar = new QToolBar; + leftToolBar->setOrientation(Qt::Horizontal); + leftToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *leftToolBarLayout = new QHBoxLayout; + leftToolBarLayout->addStretch(); + leftToolBarLayout->addWidget(leftToolBar); + leftToolBarLayout->addStretch(); - QVBoxLayout *leftVbox = new QVBoxLayout; - leftVbox->addWidget(localDirView); - leftVbox->addLayout(leftToolBarLayout); - leftGroupBox = new QGroupBox; - leftGroupBox->setLayout(leftVbox); - - rightToolBar = new QToolBar; - rightToolBar->setOrientation(Qt::Horizontal); - rightToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *rightToolBarLayout = new QHBoxLayout; - rightToolBarLayout->addStretch(); - rightToolBarLayout->addWidget(rightToolBar); - rightToolBarLayout->addStretch(); + QVBoxLayout *leftVbox = new QVBoxLayout; + leftVbox->addWidget(localDirView); + leftVbox->addLayout(leftToolBarLayout); + leftGroupBox = new QGroupBox; + leftGroupBox->setLayout(leftVbox); + + rightToolBar = new QToolBar; + rightToolBar->setOrientation(Qt::Horizontal); + rightToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *rightToolBarLayout = new QHBoxLayout; + rightToolBarLayout->addStretch(); + rightToolBarLayout->addWidget(rightToolBar); + rightToolBarLayout->addStretch(); - serverDirView = new RemoteReplayList_TreeWidget(client); + serverDirView = new RemoteReplayList_TreeWidget(client); - QVBoxLayout *rightVbox = new QVBoxLayout; - rightVbox->addWidget(serverDirView); - rightVbox->addLayout(rightToolBarLayout); - rightGroupBox = new QGroupBox; - rightGroupBox->setLayout(rightVbox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addWidget(leftGroupBox); - hbox->addWidget(rightGroupBox); - - aOpenLocalReplay = new QAction(this); - aOpenLocalReplay->setIcon(QIcon(":/resources/icon_view.svg")); - connect(aOpenLocalReplay, SIGNAL(triggered()), this, SLOT(actOpenLocalReplay())); - aDeleteLocalReplay = new QAction(this); - aDeleteLocalReplay->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteLocalReplay, SIGNAL(triggered()), this, SLOT(actDeleteLocalReplay())); - aOpenRemoteReplay = new QAction(this); - aOpenRemoteReplay->setIcon(QIcon(":/resources/icon_view.svg")); - connect(aOpenRemoteReplay, SIGNAL(triggered()), this, SLOT(actOpenRemoteReplay())); - aDownload = new QAction(this); - aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); - connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); - aKeep = new QAction(this); - aKeep->setIcon(QIcon(":/resources/lock.svg")); - connect(aKeep, SIGNAL(triggered()), this, SLOT(actKeepRemoteReplay())); - aDeleteRemoteReplay = new QAction(this); - aDeleteRemoteReplay->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteRemoteReplay, SIGNAL(triggered()), this, SLOT(actDeleteRemoteReplay())); - - leftToolBar->addAction(aOpenLocalReplay); - leftToolBar->addAction(aDeleteLocalReplay); - rightToolBar->addAction(aOpenRemoteReplay); - rightToolBar->addAction(aDownload); - rightToolBar->addAction(aKeep); - rightToolBar->addAction(aDeleteRemoteReplay); - - retranslateUi(); - setLayout(hbox); - - connect(client, SIGNAL(replayAddedEventReceived(const Event_ReplayAdded &)), this, SLOT(replayAddedEventReceived(const Event_ReplayAdded &))); + QVBoxLayout *rightVbox = new QVBoxLayout; + rightVbox->addWidget(serverDirView); + rightVbox->addLayout(rightToolBarLayout); + rightGroupBox = new QGroupBox; + rightGroupBox->setLayout(rightVbox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(leftGroupBox); + hbox->addWidget(rightGroupBox); + + aOpenLocalReplay = new QAction(this); + aOpenLocalReplay->setIcon(QIcon(":/resources/icon_view.svg")); + connect(aOpenLocalReplay, SIGNAL(triggered()), this, SLOT(actOpenLocalReplay())); + aDeleteLocalReplay = new QAction(this); + aDeleteLocalReplay->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteLocalReplay, SIGNAL(triggered()), this, SLOT(actDeleteLocalReplay())); + aOpenRemoteReplay = new QAction(this); + aOpenRemoteReplay->setIcon(QIcon(":/resources/icon_view.svg")); + connect(aOpenRemoteReplay, SIGNAL(triggered()), this, SLOT(actOpenRemoteReplay())); + aDownload = new QAction(this); + aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); + connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); + aKeep = new QAction(this); + aKeep->setIcon(QIcon(":/resources/lock.svg")); + connect(aKeep, SIGNAL(triggered()), this, SLOT(actKeepRemoteReplay())); + aDeleteRemoteReplay = new QAction(this); + aDeleteRemoteReplay->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteRemoteReplay, SIGNAL(triggered()), this, SLOT(actDeleteRemoteReplay())); + + leftToolBar->addAction(aOpenLocalReplay); + leftToolBar->addAction(aDeleteLocalReplay); + rightToolBar->addAction(aOpenRemoteReplay); + rightToolBar->addAction(aDownload); + rightToolBar->addAction(aKeep); + rightToolBar->addAction(aDeleteRemoteReplay); + + retranslateUi(); + setLayout(hbox); + + connect(client, SIGNAL(replayAddedEventReceived(const Event_ReplayAdded &)), this, SLOT(replayAddedEventReceived(const Event_ReplayAdded &))); } void TabReplays::retranslateUi() { - leftGroupBox->setTitle(tr("Local file system")); - rightGroupBox->setTitle(tr("Server replay storage")); - - aOpenLocalReplay->setText(tr("Watch replay")); - aDeleteLocalReplay->setText(tr("Delete")); - aOpenRemoteReplay->setText(tr("Watch replay")); - aDownload->setText(tr("Download replay")); - aKeep->setText(tr("Toggle expiration lock")); - aDeleteLocalReplay->setText(tr("Delete")); + leftGroupBox->setTitle(tr("Local file system")); + rightGroupBox->setTitle(tr("Server replay storage")); + + aOpenLocalReplay->setText(tr("Watch replay")); + aDeleteLocalReplay->setText(tr("Delete")); + aOpenRemoteReplay->setText(tr("Watch replay")); + aDownload->setText(tr("Download replay")); + aKeep->setText(tr("Toggle expiration lock")); + aDeleteLocalReplay->setText(tr("Delete")); } void TabReplays::actOpenLocalReplay() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (localDirModel->isDir(curLeft)) - return; - QString filePath = localDirModel->filePath(curLeft); - - QFile f(filePath); - if (!f.open(QIODevice::ReadOnly)) - return; - QByteArray data = f.readAll(); - f.close(); - - GameReplay *replay = new GameReplay; - replay->ParseFromArray(data.data(), data.size()); - - emit openReplay(replay); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (localDirModel->isDir(curLeft)) + return; + QString filePath = localDirModel->filePath(curLeft); + + QFile f(filePath); + if (!f.open(QIODevice::ReadOnly)) + return; + QByteArray data = f.readAll(); + f.close(); + + GameReplay *replay = new GameReplay; + replay->ParseFromArray(data.data(), data.size()); + + emit openReplay(replay); } void TabReplays::actDeleteLocalReplay() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - localDirModel->remove(curLeft); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + localDirModel->remove(curLeft); } void TabReplays::actOpenRemoteReplay() { - ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); - if (!curRight) - return; - - Command_ReplayDownload cmd; - cmd.set_replay_id(curRight->replay_id()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteReplayFinished(const Response &))); - client->sendCommand(pend); + ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); + if (!curRight) + return; + + Command_ReplayDownload cmd; + cmd.set_replay_id(curRight->replay_id()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteReplayFinished(const Response &))); + client->sendCommand(pend); } void TabReplays::openRemoteReplayFinished(const Response &r) { - if (r.response_code() != Response::RespOk) - return; - - const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); - GameReplay *replay = new GameReplay; - replay->ParseFromString(resp.replay_data()); - - emit openReplay(replay); + if (r.response_code() != Response::RespOk) + return; + + const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); + GameReplay *replay = new GameReplay; + replay->ParseFromString(resp.replay_data()); + + emit openReplay(replay); } void TabReplays::actDownload() { - QString filePath; - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (!curLeft.isValid()) - filePath = localDirModel->rootPath(); - else { - while (!localDirModel->isDir(curLeft)) - curLeft = curLeft.parent(); - filePath = localDirModel->filePath(curLeft); - } + QString filePath; + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (!curLeft.isValid()) + filePath = localDirModel->rootPath(); + else { + while (!localDirModel->isDir(curLeft)) + curLeft = curLeft.parent(); + filePath = localDirModel->filePath(curLeft); + } - ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); - if (!curRight) - return; - filePath += QString("/replay_%1.cor").arg(curRight->replay_id()); - - Command_ReplayDownload cmd; - cmd.set_replay_id(curRight->replay_id()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - pend->setExtraData(filePath); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); - client->sendCommand(pend); + ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); + if (!curRight) + return; + filePath += QString("/replay_%1.cor").arg(curRight->replay_id()); + + Command_ReplayDownload cmd; + cmd.set_replay_id(curRight->replay_id()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + pend->setExtraData(filePath); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); + client->sendCommand(pend); } void TabReplays::downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData) { - if (r.response_code() != Response::RespOk) - return; - - const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); - QString filePath = extraData.toString(); - - const std::string &data = resp.replay_data(); - QFile f(filePath); - f.open(QIODevice::WriteOnly); - f.write((const char *) data.data(), data.size()); - f.close(); + if (r.response_code() != Response::RespOk) + return; + + const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); + QString filePath = extraData.toString(); + + const std::string &data = resp.replay_data(); + QFile f(filePath); + f.open(QIODevice::WriteOnly); + f.write((const char *) data.data(), data.size()); + f.close(); } void TabReplays::actKeepRemoteReplay() { - ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); - if (!curRight) - return; - - Command_ReplayModifyMatch cmd; - cmd.set_game_id(curRight->game_id()); - cmd.set_do_not_hide(!curRight->do_not_hide()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(keepRemoteReplayFinished(Response, CommandContainer))); - client->sendCommand(pend); + ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); + if (!curRight) + return; + + Command_ReplayModifyMatch cmd; + cmd.set_game_id(curRight->game_id()); + cmd.set_do_not_hide(!curRight->do_not_hide()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(keepRemoteReplayFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabReplays::keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Command_ReplayModifyMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext); - - ServerInfo_ReplayMatch temp; - temp.set_do_not_hide(cmd.do_not_hide()); - - serverDirView->updateMatchInfo(cmd.game_id(), temp); + if (r.response_code() != Response::RespOk) + return; + + const Command_ReplayModifyMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext); + + ServerInfo_ReplayMatch temp; + temp.set_do_not_hide(cmd.do_not_hide()); + + serverDirView->updateMatchInfo(cmd.game_id(), temp); } void TabReplays::actDeleteRemoteReplay() { - ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); - if (!curRight) - return; - if (QMessageBox::warning(this, tr("Delete remote replay"), tr("Are you sure you want to delete the replay of game %1?").arg(curRight->game_id()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - Command_ReplayDeleteMatch cmd; - cmd.set_game_id(curRight->game_id()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteRemoteReplayFinished(Response, CommandContainer))); - client->sendCommand(pend); + ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); + if (!curRight) + return; + if (QMessageBox::warning(this, tr("Delete remote replay"), tr("Are you sure you want to delete the replay of game %1?").arg(curRight->game_id()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + Command_ReplayDeleteMatch cmd; + cmd.set_game_id(curRight->game_id()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteRemoteReplayFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabReplays::deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Command_ReplayDeleteMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext); - serverDirView->removeMatchInfo(cmd.game_id()); + if (r.response_code() != Response::RespOk) + return; + + const Command_ReplayDeleteMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext); + serverDirView->removeMatchInfo(cmd.game_id()); } void TabReplays::replayAddedEventReceived(const Event_ReplayAdded &event) { - serverDirView->addMatchInfo(event.match_info()); + serverDirView->addMatchInfo(event.match_info()); } diff --git a/cockatrice/src/tab_replays.h b/cockatrice/src/tab_replays.h index dd3e3b0e..99f1c6f4 100644 --- a/cockatrice/src/tab_replays.h +++ b/cockatrice/src/tab_replays.h @@ -15,40 +15,40 @@ class Event_ReplayAdded; class CommandContainer; class TabReplays : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - QTreeView *localDirView; - QFileSystemModel *localDirModel; - QToolBar *leftToolBar, *rightToolBar; - RemoteReplayList_TreeWidget *serverDirView; - QGroupBox *leftGroupBox, *rightGroupBox; - - QAction *aOpenLocalReplay, *aDeleteLocalReplay, *aOpenRemoteReplay, *aDownload, *aKeep, *aDeleteRemoteReplay; + AbstractClient *client; + QTreeView *localDirView; + QFileSystemModel *localDirModel; + QToolBar *leftToolBar, *rightToolBar; + RemoteReplayList_TreeWidget *serverDirView; + QGroupBox *leftGroupBox, *rightGroupBox; + + QAction *aOpenLocalReplay, *aDeleteLocalReplay, *aOpenRemoteReplay, *aDownload, *aKeep, *aDeleteRemoteReplay; private slots: - void actOpenLocalReplay(); - - void actDeleteLocalReplay(); - - void actOpenRemoteReplay(); - void openRemoteReplayFinished(const Response &r); - - void actDownload(); - void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); - - void actKeepRemoteReplay(); - void keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); - - void actDeleteRemoteReplay(); - void deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); - - void replayAddedEventReceived(const Event_ReplayAdded &event); + void actOpenLocalReplay(); + + void actDeleteLocalReplay(); + + void actOpenRemoteReplay(); + void openRemoteReplayFinished(const Response &r); + + void actDownload(); + void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); + + void actKeepRemoteReplay(); + void keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); + + void actDeleteRemoteReplay(); + void deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); + + void replayAddedEventReceived(const Event_ReplayAdded &event); signals: - void openReplay(GameReplay *replay); + void openReplay(GameReplay *replay); public: - TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client); - void retranslateUi(); - QString getTabText() const { return tr("Game replays"); } + TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client); + void retranslateUi(); + QString getTabText() const { return tr("Game replays"); } }; #endif diff --git a/cockatrice/src/tab_room.cpp b/cockatrice/src/tab_room.cpp index 04ceb338..79673e0f 100644 --- a/cockatrice/src/tab_room.cpp +++ b/cockatrice/src/tab_room.cpp @@ -28,195 +28,195 @@ #include "pending_command.h" TabRoom::TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info) - : Tab(_tabSupervisor), client(_client), roomId(info.room_id()), roomName(QString::fromStdString(info.name())), ownUser(_ownUser) + : Tab(_tabSupervisor), client(_client), roomId(info.room_id()), roomName(QString::fromStdString(info.name())), ownUser(_ownUser) { - const int gameTypeListSize = info.gametype_list_size(); - for (int i = 0; i < gameTypeListSize; ++i) - gameTypes.insert(info.gametype_list(i).game_type_id(), QString::fromStdString(info.gametype_list(i).description())); - - QMap tempMap; - tempMap.insert(info.room_id(), gameTypes); - gameSelector = new GameSelector(client, tabSupervisor, this, QMap(), tempMap); - userList = new UserList(tabSupervisor, client, UserList::RoomList); - connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - - chatView = new ChatView(tabSupervisor, 0, true); - connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayLabel = new QLabel; - sayEdit = new QLineEdit; - sayLabel->setBuddy(sayEdit); - connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); - - QMenu *chatSettingsMenu = new QMenu(this); - aIgnoreUnregisteredUsers = chatSettingsMenu->addAction(QString()); - aIgnoreUnregisteredUsers->setCheckable(true); - connect(aIgnoreUnregisteredUsers, SIGNAL(triggered()), this, SLOT(actIgnoreUnregisteredUsers())); - connect(settingsCache, SIGNAL(ignoreUnregisteredUsersChanged()), this, SLOT(ignoreUnregisteredUsersChanged())); - QToolButton *chatSettingsButton = new QToolButton; - chatSettingsButton->setIcon(QIcon(":/resources/icon_settings.svg")); - chatSettingsButton->setMenu(chatSettingsMenu); - chatSettingsButton->setPopupMode(QToolButton::InstantPopup); - - QHBoxLayout *sayHbox = new QHBoxLayout; - sayHbox->addWidget(sayLabel); - sayHbox->addWidget(sayEdit); - sayHbox->addWidget(chatSettingsButton); - - QVBoxLayout *chatVbox = new QVBoxLayout; - chatVbox->addWidget(chatView); - chatVbox->addLayout(sayHbox); - - chatGroupBox = new QGroupBox; - chatGroupBox->setLayout(chatVbox); - - QSplitter *splitter = new QSplitter(Qt::Vertical); - splitter->addWidget(gameSelector); - splitter->addWidget(chatGroupBox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addWidget(splitter, 3); - hbox->addWidget(userList, 1); - - aLeaveRoom = new QAction(this); - connect(aLeaveRoom, SIGNAL(triggered()), this, SLOT(actLeaveRoom())); + const int gameTypeListSize = info.gametype_list_size(); + for (int i = 0; i < gameTypeListSize; ++i) + gameTypes.insert(info.gametype_list(i).game_type_id(), QString::fromStdString(info.gametype_list(i).description())); + + QMap tempMap; + tempMap.insert(info.room_id(), gameTypes); + gameSelector = new GameSelector(client, tabSupervisor, this, QMap(), tempMap); + userList = new UserList(tabSupervisor, client, UserList::RoomList); + connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + + chatView = new ChatView(tabSupervisor, 0, true); + connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayLabel = new QLabel; + sayEdit = new QLineEdit; + sayLabel->setBuddy(sayEdit); + connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); + + QMenu *chatSettingsMenu = new QMenu(this); + aIgnoreUnregisteredUsers = chatSettingsMenu->addAction(QString()); + aIgnoreUnregisteredUsers->setCheckable(true); + connect(aIgnoreUnregisteredUsers, SIGNAL(triggered()), this, SLOT(actIgnoreUnregisteredUsers())); + connect(settingsCache, SIGNAL(ignoreUnregisteredUsersChanged()), this, SLOT(ignoreUnregisteredUsersChanged())); + QToolButton *chatSettingsButton = new QToolButton; + chatSettingsButton->setIcon(QIcon(":/resources/icon_settings.svg")); + chatSettingsButton->setMenu(chatSettingsMenu); + chatSettingsButton->setPopupMode(QToolButton::InstantPopup); + + QHBoxLayout *sayHbox = new QHBoxLayout; + sayHbox->addWidget(sayLabel); + sayHbox->addWidget(sayEdit); + sayHbox->addWidget(chatSettingsButton); + + QVBoxLayout *chatVbox = new QVBoxLayout; + chatVbox->addWidget(chatView); + chatVbox->addLayout(sayHbox); + + chatGroupBox = new QGroupBox; + chatGroupBox->setLayout(chatVbox); + + QSplitter *splitter = new QSplitter(Qt::Vertical); + splitter->addWidget(gameSelector); + splitter->addWidget(chatGroupBox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(splitter, 3); + hbox->addWidget(userList, 1); + + aLeaveRoom = new QAction(this); + connect(aLeaveRoom, SIGNAL(triggered()), this, SLOT(actLeaveRoom())); - roomMenu = new QMenu(this); - roomMenu->addAction(aLeaveRoom); - addTabMenu(roomMenu); + roomMenu = new QMenu(this); + roomMenu->addAction(aLeaveRoom); + addTabMenu(roomMenu); - retranslateUi(); - setLayout(hbox); - - const int userListSize = info.user_list_size(); - for (int i = 0; i < userListSize; ++i) - userList->processUserInfo(info.user_list(i), true); - userList->sortItems(); - - const int gameListSize = info.game_list_size(); - for (int i = 0; i < gameListSize; ++i) - gameSelector->processGameInfo(info.game_list(i)); + retranslateUi(); + setLayout(hbox); + + const int userListSize = info.user_list_size(); + for (int i = 0; i < userListSize; ++i) + userList->processUserInfo(info.user_list(i), true); + userList->sortItems(); + + const int gameListSize = info.game_list_size(); + for (int i = 0; i < gameListSize; ++i) + gameSelector->processGameInfo(info.game_list(i)); } TabRoom::~TabRoom() { - emit roomClosing(this); + emit roomClosing(this); } void TabRoom::retranslateUi() { gameSelector->retranslateUi(); - chatView->retranslateUi(); - userList->retranslateUi(); - sayLabel->setText(tr("&Say:")); - chatGroupBox->setTitle(tr("Chat")); - roomMenu->setTitle(tr("&Room")); - aLeaveRoom->setText(tr("&Leave room")); - aIgnoreUnregisteredUsers->setText(tr("&Ignore unregistered users in chat")); + chatView->retranslateUi(); + userList->retranslateUi(); + sayLabel->setText(tr("&Say:")); + chatGroupBox->setTitle(tr("Chat")); + roomMenu->setTitle(tr("&Room")); + aLeaveRoom->setText(tr("&Leave room")); + aIgnoreUnregisteredUsers->setText(tr("&Ignore unregistered users in chat")); } void TabRoom::closeRequest() { - actLeaveRoom(); + actLeaveRoom(); } QString TabRoom::sanitizeHtml(QString dirty) const { - return dirty - .replace("&", "&") - .replace("<", "<") - .replace(">", ">"); + return dirty + .replace("&", "&") + .replace("<", "<") + .replace(">", ">"); } void TabRoom::sendMessage() { - if (sayEdit->text().isEmpty()) - return; - - Command_RoomSay cmd; - cmd.set_message(sayEdit->text().toStdString()); - - PendingCommand *pend = prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(sayFinished(const Response &))); - sendRoomCommand(pend); - sayEdit->clear(); + if (sayEdit->text().isEmpty()) + return; + + Command_RoomSay cmd; + cmd.set_message(sayEdit->text().toStdString()); + + PendingCommand *pend = prepareRoomCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(sayFinished(const Response &))); + sendRoomCommand(pend); + sayEdit->clear(); } void TabRoom::sayFinished(const Response &response) { - if (response.response_code() == Response::RespChatFlood) - chatView->appendMessage(tr("You are flooding the chat. Please wait a couple of seconds.")); + if (response.response_code() == Response::RespChatFlood) + chatView->appendMessage(tr("You are flooding the chat. Please wait a couple of seconds.")); } void TabRoom::actLeaveRoom() { - sendRoomCommand(prepareRoomCommand(Command_LeaveRoom())); - deleteLater(); + sendRoomCommand(prepareRoomCommand(Command_LeaveRoom())); + deleteLater(); } void TabRoom::actIgnoreUnregisteredUsers() { - aIgnoreUnregisteredUsers->setChecked(!aIgnoreUnregisteredUsers->isChecked()); - settingsCache->setIgnoreUnregisteredUsers(!settingsCache->getIgnoreUnregisteredUsers()); + aIgnoreUnregisteredUsers->setChecked(!aIgnoreUnregisteredUsers->isChecked()); + settingsCache->setIgnoreUnregisteredUsers(!settingsCache->getIgnoreUnregisteredUsers()); } void TabRoom::ignoreUnregisteredUsersChanged() { - aIgnoreUnregisteredUsers->setChecked(settingsCache->getIgnoreUnregisteredUsers()); + aIgnoreUnregisteredUsers->setChecked(settingsCache->getIgnoreUnregisteredUsers()); } void TabRoom::processRoomEvent(const RoomEvent &event) { - switch (static_cast(getPbExtension(event))) { - case RoomEvent::LIST_GAMES: processListGamesEvent(event.GetExtension(Event_ListGames::ext)); break; - case RoomEvent::JOIN_ROOM: processJoinRoomEvent(event.GetExtension(Event_JoinRoom::ext)); break; - case RoomEvent::LEAVE_ROOM: processLeaveRoomEvent(event.GetExtension(Event_LeaveRoom::ext)); break; - case RoomEvent::ROOM_SAY: processRoomSayEvent(event.GetExtension(Event_RoomSay::ext)); break; - default: ; - } + switch (static_cast(getPbExtension(event))) { + case RoomEvent::LIST_GAMES: processListGamesEvent(event.GetExtension(Event_ListGames::ext)); break; + case RoomEvent::JOIN_ROOM: processJoinRoomEvent(event.GetExtension(Event_JoinRoom::ext)); break; + case RoomEvent::LEAVE_ROOM: processLeaveRoomEvent(event.GetExtension(Event_LeaveRoom::ext)); break; + case RoomEvent::ROOM_SAY: processRoomSayEvent(event.GetExtension(Event_RoomSay::ext)); break; + default: ; + } } void TabRoom::processListGamesEvent(const Event_ListGames &event) { - const int gameListSize = event.game_list_size(); - for (int i = 0; i < gameListSize; ++i) - gameSelector->processGameInfo(event.game_list(i)); + const int gameListSize = event.game_list_size(); + for (int i = 0; i < gameListSize; ++i) + gameSelector->processGameInfo(event.game_list(i)); } void TabRoom::processJoinRoomEvent(const Event_JoinRoom &event) { - userList->processUserInfo(event.user_info(), true); - userList->sortItems(); + userList->processUserInfo(event.user_info(), true); + userList->sortItems(); } void TabRoom::processLeaveRoomEvent(const Event_LeaveRoom &event) { - userList->deleteUser(QString::fromStdString(event.name())); + userList->deleteUser(QString::fromStdString(event.name())); } void TabRoom::processRoomSayEvent(const Event_RoomSay &event) { - QString senderName = QString::fromStdString(event.name()); - if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(senderName)) - return; - UserListTWI *twi = userList->getUsers().value(senderName); - UserLevelFlags userLevel; - if (twi) { - userLevel = UserLevelFlags(twi->getUserInfo().user_level()); - if (settingsCache->getIgnoreUnregisteredUsers() && !userLevel.testFlag(ServerInfo_User::IsRegistered)) - return; - } - chatView->appendMessage(QString::fromStdString(event.message()), senderName, userLevel); - emit userEvent(false); + QString senderName = QString::fromStdString(event.name()); + if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(senderName)) + return; + UserListTWI *twi = userList->getUsers().value(senderName); + UserLevelFlags userLevel; + if (twi) { + userLevel = UserLevelFlags(twi->getUserInfo().user_level()); + if (settingsCache->getIgnoreUnregisteredUsers() && !userLevel.testFlag(ServerInfo_User::IsRegistered)) + return; + } + chatView->appendMessage(QString::fromStdString(event.message()), senderName, userLevel); + emit userEvent(false); } PendingCommand *TabRoom::prepareRoomCommand(const ::google::protobuf::Message &cmd) { - return client->prepareRoomCommand(cmd, roomId); + return client->prepareRoomCommand(cmd, roomId); } void TabRoom::sendRoomCommand(PendingCommand *pend) { - client->sendCommand(pend); + client->sendCommand(pend); } diff --git a/cockatrice/src/tab_room.h b/cockatrice/src/tab_room.h index 752a4672..ada3aca8 100644 --- a/cockatrice/src/tab_room.h +++ b/cockatrice/src/tab_room.h @@ -26,53 +26,53 @@ class PendingCommand; class ServerInfo_User; class TabRoom : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - int roomId; - QString roomName; - ServerInfo_User *ownUser; - QMap gameTypes; - - GameSelector *gameSelector; - UserList *userList; - ChatView *chatView; - QLabel *sayLabel; - QLineEdit *sayEdit; - QGroupBox *chatGroupBox; - - QMenu *roomMenu; - QAction *aLeaveRoom; - QAction *aIgnoreUnregisteredUsers; - QString sanitizeHtml(QString dirty) const; + AbstractClient *client; + int roomId; + QString roomName; + ServerInfo_User *ownUser; + QMap gameTypes; + + GameSelector *gameSelector; + UserList *userList; + ChatView *chatView; + QLabel *sayLabel; + QLineEdit *sayEdit; + QGroupBox *chatGroupBox; + + QMenu *roomMenu; + QAction *aLeaveRoom; + QAction *aIgnoreUnregisteredUsers; + QString sanitizeHtml(QString dirty) const; signals: - void roomClosing(TabRoom *tab); - void openMessageDialog(const QString &userName, bool focus); + void roomClosing(TabRoom *tab); + void openMessageDialog(const QString &userName, bool focus); private slots: - void sendMessage(); - void sayFinished(const Response &response); - void actLeaveRoom(); - void actIgnoreUnregisteredUsers(); - void ignoreUnregisteredUsersChanged(); - - void processListGamesEvent(const Event_ListGames &event); - void processJoinRoomEvent(const Event_JoinRoom &event); - void processLeaveRoomEvent(const Event_LeaveRoom &event); - void processRoomSayEvent(const Event_RoomSay &event); + void sendMessage(); + void sayFinished(const Response &response); + void actLeaveRoom(); + void actIgnoreUnregisteredUsers(); + void ignoreUnregisteredUsersChanged(); + + void processListGamesEvent(const Event_ListGames &event); + void processJoinRoomEvent(const Event_JoinRoom &event); + void processLeaveRoomEvent(const Event_LeaveRoom &event); + void processRoomSayEvent(const Event_RoomSay &event); public: - TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info); - ~TabRoom(); - void retranslateUi(); - void closeRequest(); - void processRoomEvent(const RoomEvent &event); - int getRoomId() const { return roomId; } - const QMap &getGameTypes() const { return gameTypes; } - QString getChannelName() const { return roomName; } - QString getTabText() const { return roomName; } - const ServerInfo_User *getUserInfo() const { return ownUser; } + TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info); + ~TabRoom(); + void retranslateUi(); + void closeRequest(); + void processRoomEvent(const RoomEvent &event); + int getRoomId() const { return roomId; } + const QMap &getGameTypes() const { return gameTypes; } + QString getChannelName() const { return roomName; } + QString getTabText() const { return roomName; } + const ServerInfo_User *getUserInfo() const { return ownUser; } - PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd); - void sendRoomCommand(PendingCommand *pend); + PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd); + void sendRoomCommand(PendingCommand *pend); }; #endif diff --git a/cockatrice/src/tab_server.cpp b/cockatrice/src/tab_server.cpp index 0ad57ccd..a8e89af5 100644 --- a/cockatrice/src/tab_server.cpp +++ b/cockatrice/src/tab_server.cpp @@ -22,140 +22,140 @@ #include "pb/response_join_room.pb.h" RoomSelector::RoomSelector(AbstractClient *_client, QWidget *parent) - : QGroupBox(parent), client(_client) + : QGroupBox(parent), client(_client) { - roomList = new QTreeWidget; - roomList->setRootIsDecorated(false); - roomList->setColumnCount(4); - roomList->header()->setStretchLastSection(false); - roomList->header()->setResizeMode(0, QHeaderView::ResizeToContents); - roomList->header()->setResizeMode(1, QHeaderView::Stretch); - roomList->header()->setResizeMode(2, QHeaderView::ResizeToContents); - roomList->header()->setResizeMode(3, QHeaderView::ResizeToContents); - - joinButton = new QPushButton; - connect(joinButton, SIGNAL(clicked()), this, SLOT(joinClicked())); - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addStretch(); - buttonLayout->addWidget(joinButton); - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(roomList); - vbox->addLayout(buttonLayout); - - retranslateUi(); - setLayout(vbox); - - connect(client, SIGNAL(listRoomsEventReceived(const Event_ListRooms &)), this, SLOT(processListRoomsEvent(const Event_ListRooms &))); - client->sendCommand(client->prepareSessionCommand(Command_ListRooms())); + roomList = new QTreeWidget; + roomList->setRootIsDecorated(false); + roomList->setColumnCount(4); + roomList->header()->setStretchLastSection(false); + roomList->header()->setResizeMode(0, QHeaderView::ResizeToContents); + roomList->header()->setResizeMode(1, QHeaderView::Stretch); + roomList->header()->setResizeMode(2, QHeaderView::ResizeToContents); + roomList->header()->setResizeMode(3, QHeaderView::ResizeToContents); + + joinButton = new QPushButton; + connect(joinButton, SIGNAL(clicked()), this, SLOT(joinClicked())); + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addStretch(); + buttonLayout->addWidget(joinButton); + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(roomList); + vbox->addLayout(buttonLayout); + + retranslateUi(); + setLayout(vbox); + + connect(client, SIGNAL(listRoomsEventReceived(const Event_ListRooms &)), this, SLOT(processListRoomsEvent(const Event_ListRooms &))); + client->sendCommand(client->prepareSessionCommand(Command_ListRooms())); } void RoomSelector::retranslateUi() { - setTitle(tr("Rooms")); - joinButton->setText(tr("Joi&n")); + setTitle(tr("Rooms")); + joinButton->setText(tr("Joi&n")); - QTreeWidgetItem *header = roomList->headerItem(); - header->setText(0, tr("Room")); - header->setText(1, tr("Description")); - header->setText(2, tr("Players")); - header->setText(3, tr("Games")); - header->setTextAlignment(2, Qt::AlignRight); - header->setTextAlignment(3, Qt::AlignRight); + QTreeWidgetItem *header = roomList->headerItem(); + header->setText(0, tr("Room")); + header->setText(1, tr("Description")); + header->setText(2, tr("Players")); + header->setText(3, tr("Games")); + header->setTextAlignment(2, Qt::AlignRight); + header->setTextAlignment(3, Qt::AlignRight); } void RoomSelector::processListRoomsEvent(const Event_ListRooms &event) { - const int roomListSize = event.room_list_size(); - for (int i = 0; i < roomListSize; ++i) { - const ServerInfo_Room &room = event.room_list(i); - - for (int j = 0; j < roomList->topLevelItemCount(); ++j) { - QTreeWidgetItem *twi = roomList->topLevelItem(j); - if (twi->data(0, Qt::UserRole).toInt() == room.room_id()) { - if (room.has_name()) - twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); - if (room.has_description()) - twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); - if (room.has_player_count()) - twi->setData(2, Qt::DisplayRole, room.player_count()); - if (room.has_game_count()) - twi->setData(3, Qt::DisplayRole, room.game_count()); - return; - } - } - QTreeWidgetItem *twi = new QTreeWidgetItem; - twi->setData(0, Qt::UserRole, room.room_id()); - if (room.has_name()) - twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); - if (room.has_description()) - twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); - twi->setData(2, Qt::DisplayRole, room.player_count()); - twi->setData(3, Qt::DisplayRole, room.game_count()); - twi->setTextAlignment(2, Qt::AlignRight); - twi->setTextAlignment(3, Qt::AlignRight); - - roomList->addTopLevelItem(twi); - if (room.has_auto_join()) - if (room.auto_join()) - joinRoom(room.room_id(), false); - } + const int roomListSize = event.room_list_size(); + for (int i = 0; i < roomListSize; ++i) { + const ServerInfo_Room &room = event.room_list(i); + + for (int j = 0; j < roomList->topLevelItemCount(); ++j) { + QTreeWidgetItem *twi = roomList->topLevelItem(j); + if (twi->data(0, Qt::UserRole).toInt() == room.room_id()) { + if (room.has_name()) + twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); + if (room.has_description()) + twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); + if (room.has_player_count()) + twi->setData(2, Qt::DisplayRole, room.player_count()); + if (room.has_game_count()) + twi->setData(3, Qt::DisplayRole, room.game_count()); + return; + } + } + QTreeWidgetItem *twi = new QTreeWidgetItem; + twi->setData(0, Qt::UserRole, room.room_id()); + if (room.has_name()) + twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); + if (room.has_description()) + twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); + twi->setData(2, Qt::DisplayRole, room.player_count()); + twi->setData(3, Qt::DisplayRole, room.game_count()); + twi->setTextAlignment(2, Qt::AlignRight); + twi->setTextAlignment(3, Qt::AlignRight); + + roomList->addTopLevelItem(twi); + if (room.has_auto_join()) + if (room.auto_join()) + joinRoom(room.room_id(), false); + } } void RoomSelector::joinRoom(int id, bool setCurrent) { - Command_JoinRoom cmd; - cmd.set_room_id(id); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - pend->setExtraData(setCurrent); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(joinFinished(Response, CommandContainer, QVariant))); - - client->sendCommand(pend); + Command_JoinRoom cmd; + cmd.set_room_id(id); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + pend->setExtraData(setCurrent); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(joinFinished(Response, CommandContainer, QVariant))); + + client->sendCommand(pend); } void RoomSelector::joinClicked() { - QTreeWidgetItem *twi = roomList->currentItem(); - if (!twi) - return; - - joinRoom(twi->data(0, Qt::UserRole).toInt(), true); + QTreeWidgetItem *twi = roomList->currentItem(); + if (!twi) + return; + + joinRoom(twi->data(0, Qt::UserRole).toInt(), true); } void RoomSelector::joinFinished(const Response &r, const CommandContainer & /*commandContainer*/, const QVariant &extraData) { - if (r.response_code() != Response::RespOk) - return; - const Response_JoinRoom &resp = r.GetExtension(Response_JoinRoom::ext); - - emit roomJoined(resp.room_info(), extraData.toBool()); + if (r.response_code() != Response::RespOk) + return; + const Response_JoinRoom &resp = r.GetExtension(Response_JoinRoom::ext); + + emit roomJoined(resp.room_info(), extraData.toBool()); } TabServer::TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent) - : Tab(_tabSupervisor, parent), client(_client) + : Tab(_tabSupervisor, parent), client(_client) { - roomSelector = new RoomSelector(client); - serverInfoBox = new QTextBrowser; - serverInfoBox->setOpenExternalLinks(true); - - connect(roomSelector, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SIGNAL(roomJoined(const ServerInfo_Room &, bool))); - - connect(client, SIGNAL(serverMessageEventReceived(const Event_ServerMessage &)), this, SLOT(processServerMessageEvent(const Event_ServerMessage &))); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(roomSelector); - vbox->addWidget(serverInfoBox); - - setLayout(vbox); + roomSelector = new RoomSelector(client); + serverInfoBox = new QTextBrowser; + serverInfoBox->setOpenExternalLinks(true); + + connect(roomSelector, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SIGNAL(roomJoined(const ServerInfo_Room &, bool))); + + connect(client, SIGNAL(serverMessageEventReceived(const Event_ServerMessage &)), this, SLOT(processServerMessageEvent(const Event_ServerMessage &))); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(roomSelector); + vbox->addWidget(serverInfoBox); + + setLayout(vbox); } void TabServer::retranslateUi() { - roomSelector->retranslateUi(); + roomSelector->retranslateUi(); } void TabServer::processServerMessageEvent(const Event_ServerMessage &event) { - serverInfoBox->setHtml(QString::fromStdString(event.message())); - emit userEvent(); + serverInfoBox->setHtml(QString::fromStdString(event.message())); + emit userEvent(); } diff --git a/cockatrice/src/tab_server.h b/cockatrice/src/tab_server.h index f64e4871..a057660b 100644 --- a/cockatrice/src/tab_server.h +++ b/cockatrice/src/tab_server.h @@ -19,38 +19,38 @@ class ServerInfo_Room; class CommandContainer; class RoomSelector : public QGroupBox { - Q_OBJECT + Q_OBJECT private: - QTreeWidget *roomList; - QPushButton *joinButton; - AbstractClient *client; - - void joinRoom(int id, bool setCurrent); + QTreeWidget *roomList; + QPushButton *joinButton; + AbstractClient *client; + + void joinRoom(int id, bool setCurrent); private slots: - void processListRoomsEvent(const Event_ListRooms &event); - void joinClicked(); - void joinFinished(const Response &resp, const CommandContainer &commandContainer, const QVariant &extraData); + void processListRoomsEvent(const Event_ListRooms &event); + void joinClicked(); + void joinFinished(const Response &resp, const CommandContainer &commandContainer, const QVariant &extraData); signals: - void roomJoined(const ServerInfo_Room &info, bool setCurrent); + void roomJoined(const ServerInfo_Room &info, bool setCurrent); public: - RoomSelector(AbstractClient *_client, QWidget *parent = 0); - void retranslateUi(); + RoomSelector(AbstractClient *_client, QWidget *parent = 0); + void retranslateUi(); }; class TabServer : public Tab { - Q_OBJECT + Q_OBJECT signals: - void roomJoined(const ServerInfo_Room &info, bool setCurrent); + void roomJoined(const ServerInfo_Room &info, bool setCurrent); private slots: - void processServerMessageEvent(const Event_ServerMessage &event); + void processServerMessageEvent(const Event_ServerMessage &event); private: - AbstractClient *client; - RoomSelector *roomSelector; - QTextBrowser *serverInfoBox; + AbstractClient *client; + RoomSelector *roomSelector; + QTextBrowser *serverInfoBox; public: - TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent = 0); - void retranslateUi(); - QString getTabText() const { return tr("Server"); } + TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent = 0); + void retranslateUi(); + QString getTabText() const { return tr("Server"); } }; #endif diff --git a/cockatrice/src/tab_supervisor.cpp b/cockatrice/src/tab_supervisor.cpp index f5a06d67..e85efc6a 100644 --- a/cockatrice/src/tab_supervisor.cpp +++ b/cockatrice/src/tab_supervisor.cpp @@ -25,467 +25,467 @@ #include "pb/serverinfo_room.pb.h" CloseButton::CloseButton(QWidget *parent) - : QAbstractButton(parent) + : QAbstractButton(parent) { - setFocusPolicy(Qt::NoFocus); - setCursor(Qt::ArrowCursor); - resize(sizeHint()); + setFocusPolicy(Qt::NoFocus); + setCursor(Qt::ArrowCursor); + resize(sizeHint()); } QSize CloseButton::sizeHint() const { - ensurePolished(); - int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this); - int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this); - return QSize(width, height); + ensurePolished(); + int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this); + int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this); + return QSize(width, height); } void CloseButton::enterEvent(QEvent *event) { - update(); - QAbstractButton::enterEvent(event); + update(); + QAbstractButton::enterEvent(event); } void CloseButton::leaveEvent(QEvent *event) { - update(); - QAbstractButton::leaveEvent(event); + update(); + QAbstractButton::leaveEvent(event); } void CloseButton::paintEvent(QPaintEvent * /*event*/) { - QPainter p(this); - QStyleOption opt; - opt.init(this); - opt.state |= QStyle::State_AutoRaise; - if (isEnabled() && underMouse() && !isChecked() && !isDown()) - opt.state |= QStyle::State_Raised; - if (isChecked()) - opt.state |= QStyle::State_On; - if (isDown()) - opt.state |= QStyle::State_Sunken; - - if (const QTabBar *tb = qobject_cast(parent())) { - int index = tb->currentIndex(); - QTabBar::ButtonPosition position = (QTabBar::ButtonPosition) style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tb); - if (tb->tabButton(index, position) == this) - opt.state |= QStyle::State_Selected; - } - - style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this); + QPainter p(this); + QStyleOption opt; + opt.init(this); + opt.state |= QStyle::State_AutoRaise; + if (isEnabled() && underMouse() && !isChecked() && !isDown()) + opt.state |= QStyle::State_Raised; + if (isChecked()) + opt.state |= QStyle::State_On; + if (isDown()) + opt.state |= QStyle::State_Sunken; + + if (const QTabBar *tb = qobject_cast(parent())) { + int index = tb->currentIndex(); + QTabBar::ButtonPosition position = (QTabBar::ButtonPosition) style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tb); + if (tb->tabButton(index, position) == this) + opt.state |= QStyle::State_Selected; + } + + style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this); } TabSupervisor::TabSupervisor(AbstractClient *_client, QWidget *parent) - : QTabWidget(parent), userInfo(0), client(_client), tabUserLists(0), tabServer(0), tabDeckStorage(0), tabAdmin(0), tabReplays(0) + : QTabWidget(parent), userInfo(0), client(_client), tabUserLists(0), tabServer(0), tabDeckStorage(0), tabAdmin(0), tabReplays(0) { - tabChangedIcon = new QIcon(":/resources/icon_tab_changed.svg"); - setElideMode(Qt::ElideRight); - setMovable(true); - setIconSize(QSize(15, 15)); - connect(this, SIGNAL(currentChanged(int)), this, SLOT(updateCurrent(int))); + tabChangedIcon = new QIcon(":/resources/icon_tab_changed.svg"); + setElideMode(Qt::ElideRight); + setMovable(true); + setIconSize(QSize(15, 15)); + connect(this, SIGNAL(currentChanged(int)), this, SLOT(updateCurrent(int))); - connect(client, SIGNAL(roomEventReceived(const RoomEvent &)), this, SLOT(processRoomEvent(const RoomEvent &))); - connect(client, SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); - connect(client, SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(gameJoined(const Event_GameJoined &))); - connect(client, SIGNAL(userMessageEventReceived(const Event_UserMessage &)), this, SLOT(processUserMessageEvent(const Event_UserMessage &))); - connect(client, SIGNAL(maxPingTime(int, int)), this, SLOT(updatePingTime(int, int))); - - retranslateUi(); + connect(client, SIGNAL(roomEventReceived(const RoomEvent &)), this, SLOT(processRoomEvent(const RoomEvent &))); + connect(client, SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); + connect(client, SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(gameJoined(const Event_GameJoined &))); + connect(client, SIGNAL(userMessageEventReceived(const Event_UserMessage &)), this, SLOT(processUserMessageEvent(const Event_UserMessage &))); + connect(client, SIGNAL(maxPingTime(int, int)), this, SLOT(updatePingTime(int, int))); + + retranslateUi(); } TabSupervisor::~TabSupervisor() { - stop(); - delete tabChangedIcon; + stop(); + delete tabChangedIcon; } void TabSupervisor::retranslateUi() { - QList tabs; - tabs.append(tabServer); - tabs.append(tabReplays); - tabs.append(tabDeckStorage); - tabs.append(tabAdmin); - tabs.append(tabUserLists); - QMapIterator roomIterator(roomTabs); - while (roomIterator.hasNext()) - tabs.append(roomIterator.next().value()); - QMapIterator gameIterator(gameTabs); - while (gameIterator.hasNext()) - tabs.append(gameIterator.next().value()); - QListIterator replayIterator(replayTabs); - while (replayIterator.hasNext()) - tabs.append(replayIterator.next()); - QListIterator deckEditorIterator(deckEditorTabs); - while (deckEditorIterator.hasNext()) - tabs.append(deckEditorIterator.next()); - QMapIterator messageIterator(messageTabs); - while (messageIterator.hasNext()) - tabs.append(messageIterator.next().value()); - - for (int i = 0; i < tabs.size(); ++i) - if (tabs[i]) { - setTabText(indexOf(tabs[i]), tabs[i]->getTabText()); - tabs[i]->retranslateUi(); - } + QList tabs; + tabs.append(tabServer); + tabs.append(tabReplays); + tabs.append(tabDeckStorage); + tabs.append(tabAdmin); + tabs.append(tabUserLists); + QMapIterator roomIterator(roomTabs); + while (roomIterator.hasNext()) + tabs.append(roomIterator.next().value()); + QMapIterator gameIterator(gameTabs); + while (gameIterator.hasNext()) + tabs.append(gameIterator.next().value()); + QListIterator replayIterator(replayTabs); + while (replayIterator.hasNext()) + tabs.append(replayIterator.next()); + QListIterator deckEditorIterator(deckEditorTabs); + while (deckEditorIterator.hasNext()) + tabs.append(deckEditorIterator.next()); + QMapIterator messageIterator(messageTabs); + while (messageIterator.hasNext()) + tabs.append(messageIterator.next().value()); + + for (int i = 0; i < tabs.size(); ++i) + if (tabs[i]) { + setTabText(indexOf(tabs[i]), tabs[i]->getTabText()); + tabs[i]->retranslateUi(); + } } AbstractClient *TabSupervisor::getClient() const { - return localClients.isEmpty() ? client : localClients.first(); + return localClients.isEmpty() ? client : localClients.first(); } int TabSupervisor::myAddTab(Tab *tab) { - connect(tab, SIGNAL(userEvent(bool)), this, SLOT(tabUserEvent(bool))); - connect(tab, SIGNAL(tabTextChanged(Tab *, QString)), this, SLOT(updateTabText(Tab *, QString))); - return addTab(tab, tab->getTabText()); + connect(tab, SIGNAL(userEvent(bool)), this, SLOT(tabUserEvent(bool))); + connect(tab, SIGNAL(tabTextChanged(Tab *, QString)), this, SLOT(updateTabText(Tab *, QString))); + return addTab(tab, tab->getTabText()); } void TabSupervisor::start(const ServerInfo_User &_userInfo) { - userInfo = new ServerInfo_User(_userInfo); - - tabServer = new TabServer(this, client); - connect(tabServer, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SLOT(addRoomTab(const ServerInfo_Room &, bool))); - myAddTab(tabServer); - - tabUserLists = new TabUserLists(this, client, *userInfo); - connect(tabUserLists, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); - connect(tabUserLists, SIGNAL(userJoined(ServerInfo_User)), this, SLOT(processUserJoined(ServerInfo_User))); - connect(tabUserLists, SIGNAL(userLeft(const QString &)), this, SLOT(processUserLeft(const QString &))); - myAddTab(tabUserLists); - - updatePingTime(0, -1); - - if (userInfo->user_level() & ServerInfo_User::IsRegistered) { - tabDeckStorage = new TabDeckStorage(this, client); - connect(tabDeckStorage, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); - myAddTab(tabDeckStorage); - - tabReplays = new TabReplays(this, client); - connect(tabReplays, SIGNAL(openReplay(GameReplay *)), this, SLOT(openReplay(GameReplay *))); - myAddTab(tabReplays); - } else { - tabDeckStorage = 0; - tabReplays = 0; - } - - if (userInfo->user_level() & ServerInfo_User::IsModerator) { - tabAdmin = new TabAdmin(this, client, (userInfo->user_level() & ServerInfo_User::IsAdmin)); - connect(tabAdmin, SIGNAL(adminLockChanged(bool)), this, SIGNAL(adminLockChanged(bool))); - myAddTab(tabAdmin); - } else - tabAdmin = 0; + userInfo = new ServerInfo_User(_userInfo); + + tabServer = new TabServer(this, client); + connect(tabServer, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SLOT(addRoomTab(const ServerInfo_Room &, bool))); + myAddTab(tabServer); + + tabUserLists = new TabUserLists(this, client, *userInfo); + connect(tabUserLists, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); + connect(tabUserLists, SIGNAL(userJoined(ServerInfo_User)), this, SLOT(processUserJoined(ServerInfo_User))); + connect(tabUserLists, SIGNAL(userLeft(const QString &)), this, SLOT(processUserLeft(const QString &))); + myAddTab(tabUserLists); + + updatePingTime(0, -1); + + if (userInfo->user_level() & ServerInfo_User::IsRegistered) { + tabDeckStorage = new TabDeckStorage(this, client); + connect(tabDeckStorage, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); + myAddTab(tabDeckStorage); + + tabReplays = new TabReplays(this, client); + connect(tabReplays, SIGNAL(openReplay(GameReplay *)), this, SLOT(openReplay(GameReplay *))); + myAddTab(tabReplays); + } else { + tabDeckStorage = 0; + tabReplays = 0; + } + + if (userInfo->user_level() & ServerInfo_User::IsModerator) { + tabAdmin = new TabAdmin(this, client, (userInfo->user_level() & ServerInfo_User::IsAdmin)); + connect(tabAdmin, SIGNAL(adminLockChanged(bool)), this, SIGNAL(adminLockChanged(bool))); + myAddTab(tabAdmin); + } else + tabAdmin = 0; - retranslateUi(); + retranslateUi(); } void TabSupervisor::startLocal(const QList &_clients) { - tabUserLists = 0; - tabDeckStorage = 0; - tabReplays = 0; - tabAdmin = 0; - userInfo = new ServerInfo_User; - localClients = _clients; - for (int i = 0; i < localClients.size(); ++i) - connect(localClients[i], SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); - connect(localClients.first(), SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(localGameJoined(const Event_GameJoined &))); + tabUserLists = 0; + tabDeckStorage = 0; + tabReplays = 0; + tabAdmin = 0; + userInfo = new ServerInfo_User; + localClients = _clients; + for (int i = 0; i < localClients.size(); ++i) + connect(localClients[i], SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); + connect(localClients.first(), SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(localGameJoined(const Event_GameJoined &))); } void TabSupervisor::stop() { - if ((!client) && localClients.isEmpty()) - return; - - if (!localClients.isEmpty()) { - for (int i = 0; i < localClients.size(); ++i) - localClients[i]->deleteLater(); - localClients.clear(); - - emit localGameEnded(); - } else { - if (tabUserLists) - tabUserLists->deleteLater(); - if (tabServer) - tabServer->deleteLater(); - if (tabDeckStorage) - tabDeckStorage->deleteLater(); - if (tabReplays) - tabReplays->deleteLater(); - if (tabAdmin) - tabAdmin->deleteLater(); - } - tabUserLists = 0; - tabServer = 0; - tabDeckStorage = 0; - tabReplays = 0; - tabAdmin = 0; - - QMapIterator roomIterator(roomTabs); - while (roomIterator.hasNext()) - roomIterator.next().value()->deleteLater(); - roomTabs.clear(); + if ((!client) && localClients.isEmpty()) + return; + + if (!localClients.isEmpty()) { + for (int i = 0; i < localClients.size(); ++i) + localClients[i]->deleteLater(); + localClients.clear(); + + emit localGameEnded(); + } else { + if (tabUserLists) + tabUserLists->deleteLater(); + if (tabServer) + tabServer->deleteLater(); + if (tabDeckStorage) + tabDeckStorage->deleteLater(); + if (tabReplays) + tabReplays->deleteLater(); + if (tabAdmin) + tabAdmin->deleteLater(); + } + tabUserLists = 0; + tabServer = 0; + tabDeckStorage = 0; + tabReplays = 0; + tabAdmin = 0; + + QMapIterator roomIterator(roomTabs); + while (roomIterator.hasNext()) + roomIterator.next().value()->deleteLater(); + roomTabs.clear(); - QMapIterator gameIterator(gameTabs); - while (gameIterator.hasNext()) - gameIterator.next().value()->deleteLater(); - gameTabs.clear(); + QMapIterator gameIterator(gameTabs); + while (gameIterator.hasNext()) + gameIterator.next().value()->deleteLater(); + gameTabs.clear(); - QListIterator replayIterator(replayTabs); - while (replayIterator.hasNext()) - replayIterator.next()->deleteLater(); - replayTabs.clear(); + QListIterator replayIterator(replayTabs); + while (replayIterator.hasNext()) + replayIterator.next()->deleteLater(); + replayTabs.clear(); - QMapIterator messageIterator(messageTabs); - while (messageIterator.hasNext()) - messageIterator.next().value()->deleteLater(); - messageTabs.clear(); - - delete userInfo; - userInfo = 0; + QMapIterator messageIterator(messageTabs); + while (messageIterator.hasNext()) + messageIterator.next().value()->deleteLater(); + messageTabs.clear(); + + delete userInfo; + userInfo = 0; } void TabSupervisor::updatePingTime(int value, int max) { - if (!tabServer) - return; - if (tabServer->getContentsChanged()) - return; - - setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max))); + if (!tabServer) + return; + if (tabServer->getContentsChanged()) + return; + + setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max))); } void TabSupervisor::closeButtonPressed() { - Tab *tab = static_cast(static_cast(sender())->property("tab").value()); - tab->closeRequest(); + Tab *tab = static_cast(static_cast(sender())->property("tab").value()); + tab->closeRequest(); } void TabSupervisor::addCloseButtonToTab(Tab *tab, int tabIndex) { - QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition) tabBar()->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tabBar()); - CloseButton *closeButton = new CloseButton; - connect(closeButton, SIGNAL(clicked()), this, SLOT(closeButtonPressed())); - closeButton->setProperty("tab", qVariantFromValue((QObject *) tab)); - tabBar()->setTabButton(tabIndex, closeSide, closeButton); + QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition) tabBar()->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tabBar()); + CloseButton *closeButton = new CloseButton; + connect(closeButton, SIGNAL(clicked()), this, SLOT(closeButtonPressed())); + closeButton->setProperty("tab", qVariantFromValue((QObject *) tab)); + tabBar()->setTabButton(tabIndex, closeSide, closeButton); } void TabSupervisor::gameJoined(const Event_GameJoined &event) { - QMap roomGameTypes; - TabRoom *room = roomTabs.value(event.game_info().room_id()); - if (room) - roomGameTypes = room->getGameTypes(); - else - for (int i = 0; i < event.game_types_size(); ++i) - roomGameTypes.insert(event.game_types(i).game_type_id(), QString::fromStdString(event.game_types(i).description())); - - TabGame *tab = new TabGame(this, QList() << client, event, roomGameTypes); - connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); - connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); - connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - gameTabs.insert(event.game_info().game_id(), tab); - setCurrentWidget(tab); + QMap roomGameTypes; + TabRoom *room = roomTabs.value(event.game_info().room_id()); + if (room) + roomGameTypes = room->getGameTypes(); + else + for (int i = 0; i < event.game_types_size(); ++i) + roomGameTypes.insert(event.game_types(i).game_type_id(), QString::fromStdString(event.game_types(i).description())); + + TabGame *tab = new TabGame(this, QList() << client, event, roomGameTypes); + connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); + connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); + connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + gameTabs.insert(event.game_info().game_id(), tab); + setCurrentWidget(tab); } void TabSupervisor::localGameJoined(const Event_GameJoined &event) { - TabGame *tab = new TabGame(this, localClients, event, QMap()); - connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); - connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - gameTabs.insert(event.game_info().game_id(), tab); - setCurrentWidget(tab); - - for (int i = 1; i < localClients.size(); ++i) { - Command_JoinGame cmd; - cmd.set_game_id(event.game_info().game_id()); - localClients[i]->sendCommand(localClients[i]->prepareRoomCommand(cmd, 0)); - } + TabGame *tab = new TabGame(this, localClients, event, QMap()); + connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); + connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + gameTabs.insert(event.game_info().game_id(), tab); + setCurrentWidget(tab); + + for (int i = 1; i < localClients.size(); ++i) { + Command_JoinGame cmd; + cmd.set_game_id(event.game_info().game_id()); + localClients[i]->sendCommand(localClients[i]->prepareRoomCommand(cmd, 0)); + } } void TabSupervisor::gameLeft(TabGame *tab) { - if (tab == currentWidget()) - emit setMenu(); + if (tab == currentWidget()) + emit setMenu(); - gameTabs.remove(tab->getGameId()); - removeTab(indexOf(tab)); - - if (!localClients.isEmpty()) - stop(); + gameTabs.remove(tab->getGameId()); + removeTab(indexOf(tab)); + + if (!localClients.isEmpty()) + stop(); } void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent) { - TabRoom *tab = new TabRoom(this, client, userInfo, info); - connect(tab, SIGNAL(roomClosing(TabRoom *)), this, SLOT(roomLeft(TabRoom *))); - connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - roomTabs.insert(info.room_id(), tab); - if (setCurrent) - setCurrentWidget(tab); + TabRoom *tab = new TabRoom(this, client, userInfo, info); + connect(tab, SIGNAL(roomClosing(TabRoom *)), this, SLOT(roomLeft(TabRoom *))); + connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + roomTabs.insert(info.room_id(), tab); + if (setCurrent) + setCurrentWidget(tab); } void TabSupervisor::roomLeft(TabRoom *tab) { - if (tab == currentWidget()) - emit setMenu(); - - roomTabs.remove(tab->getRoomId()); - removeTab(indexOf(tab)); + if (tab == currentWidget()) + emit setMenu(); + + roomTabs.remove(tab->getRoomId()); + removeTab(indexOf(tab)); } void TabSupervisor::openReplay(GameReplay *replay) { - TabGame *replayTab = new TabGame(this, replay); - connect(replayTab, SIGNAL(gameClosing(TabGame *)), this, SLOT(replayLeft(TabGame *))); - int tabIndex = myAddTab(replayTab); - addCloseButtonToTab(replayTab, tabIndex); - replayTabs.append(replayTab); - setCurrentWidget(replayTab); + TabGame *replayTab = new TabGame(this, replay); + connect(replayTab, SIGNAL(gameClosing(TabGame *)), this, SLOT(replayLeft(TabGame *))); + int tabIndex = myAddTab(replayTab); + addCloseButtonToTab(replayTab, tabIndex); + replayTabs.append(replayTab); + setCurrentWidget(replayTab); } void TabSupervisor::replayLeft(TabGame *tab) { - if (tab == currentWidget()) - emit setMenu(); - - replayTabs.removeAt(replayTabs.indexOf(tab)); + if (tab == currentWidget()) + emit setMenu(); + + replayTabs.removeAt(replayTabs.indexOf(tab)); } TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus) { - if (receiverName == QString::fromStdString(userInfo->name())) - return 0; - - ServerInfo_User otherUser; - UserListTWI *twi = tabUserLists->getAllUsersList()->getUsers().value(receiverName); - if (twi) - otherUser = twi->getUserInfo(); - else - otherUser.set_name(receiverName.toStdString()); - TabMessage *tab = new TabMessage(this, client, *userInfo, otherUser); - connect(tab, SIGNAL(talkClosing(TabMessage *)), this, SLOT(talkLeft(TabMessage *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - messageTabs.insert(receiverName, tab); - if (focus) - setCurrentWidget(tab); - return tab; + if (receiverName == QString::fromStdString(userInfo->name())) + return 0; + + ServerInfo_User otherUser; + UserListTWI *twi = tabUserLists->getAllUsersList()->getUsers().value(receiverName); + if (twi) + otherUser = twi->getUserInfo(); + else + otherUser.set_name(receiverName.toStdString()); + TabMessage *tab = new TabMessage(this, client, *userInfo, otherUser); + connect(tab, SIGNAL(talkClosing(TabMessage *)), this, SLOT(talkLeft(TabMessage *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + messageTabs.insert(receiverName, tab); + if (focus) + setCurrentWidget(tab); + return tab; } void TabSupervisor::talkLeft(TabMessage *tab) { - if (tab == currentWidget()) - emit setMenu(); + if (tab == currentWidget()) + emit setMenu(); - messageTabs.remove(tab->getUserName()); - removeTab(indexOf(tab)); + messageTabs.remove(tab->getUserName()); + removeTab(indexOf(tab)); } TabDeckEditor *TabSupervisor::addDeckEditorTab(const DeckLoader *deckToOpen) { - TabDeckEditor *tab = new TabDeckEditor(this); - if (deckToOpen) - tab->setDeck(new DeckLoader(*deckToOpen)); - connect(tab, SIGNAL(deckEditorClosing(TabDeckEditor *)), this, SLOT(deckEditorClosed(TabDeckEditor *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - deckEditorTabs.append(tab); - setCurrentWidget(tab); - return tab; + TabDeckEditor *tab = new TabDeckEditor(this); + if (deckToOpen) + tab->setDeck(new DeckLoader(*deckToOpen)); + connect(tab, SIGNAL(deckEditorClosing(TabDeckEditor *)), this, SLOT(deckEditorClosed(TabDeckEditor *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + deckEditorTabs.append(tab); + setCurrentWidget(tab); + return tab; } void TabSupervisor::deckEditorClosed(TabDeckEditor *tab) { - if (tab == currentWidget()) - emit setMenu(); - - deckEditorTabs.removeAt(deckEditorTabs.indexOf(tab)); - removeTab(indexOf(tab)); + if (tab == currentWidget()) + emit setMenu(); + + deckEditorTabs.removeAt(deckEditorTabs.indexOf(tab)); + removeTab(indexOf(tab)); } void TabSupervisor::tabUserEvent(bool globalEvent) { - Tab *tab = static_cast(sender()); - if (tab != currentWidget()) { - tab->setContentsChanged(true); - setTabIcon(indexOf(tab), *tabChangedIcon); - } - if (globalEvent && settingsCache->getNotificationsEnabled()) - QApplication::alert(this); + Tab *tab = static_cast(sender()); + if (tab != currentWidget()) { + tab->setContentsChanged(true); + setTabIcon(indexOf(tab), *tabChangedIcon); + } + if (globalEvent && settingsCache->getNotificationsEnabled()) + QApplication::alert(this); } void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText) { - setTabText(indexOf(tab), newTabText); + setTabText(indexOf(tab), newTabText); } void TabSupervisor::processRoomEvent(const RoomEvent &event) { - TabRoom *tab = roomTabs.value(event.room_id(), 0); - if (tab) - tab->processRoomEvent(event); + TabRoom *tab = roomTabs.value(event.room_id(), 0); + if (tab) + tab->processRoomEvent(event); } void TabSupervisor::processGameEventContainer(const GameEventContainer &cont) { - TabGame *tab = gameTabs.value(cont.game_id()); - if (tab) - tab->processGameEventContainer(cont, qobject_cast(sender())); - else - qDebug() << "gameEvent: invalid gameId"; + TabGame *tab = gameTabs.value(cont.game_id()); + if (tab) + tab->processGameEventContainer(cont, qobject_cast(sender())); + else + qDebug() << "gameEvent: invalid gameId"; } void TabSupervisor::processUserMessageEvent(const Event_UserMessage &event) { - TabMessage *tab = messageTabs.value(QString::fromStdString(event.sender_name())); - if (!tab) - tab = messageTabs.value(QString::fromStdString(event.receiver_name())); - if (!tab) - tab = addMessageTab(QString::fromStdString(event.sender_name()), false); - if (!tab) - return; - tab->processUserMessageEvent(event); + TabMessage *tab = messageTabs.value(QString::fromStdString(event.sender_name())); + if (!tab) + tab = messageTabs.value(QString::fromStdString(event.receiver_name())); + if (!tab) + tab = addMessageTab(QString::fromStdString(event.sender_name()), false); + if (!tab) + return; + tab->processUserMessageEvent(event); } void TabSupervisor::processUserLeft(const QString &userName) { - TabMessage *tab = messageTabs.value(userName); - if (tab) - tab->processUserLeft(); + TabMessage *tab = messageTabs.value(userName); + if (tab) + tab->processUserLeft(); } void TabSupervisor::processUserJoined(const ServerInfo_User &userInfo) { - TabMessage *tab = messageTabs.value(QString::fromStdString(userInfo.name())); - if (tab) - tab->processUserJoined(userInfo); + TabMessage *tab = messageTabs.value(QString::fromStdString(userInfo.name())); + if (tab) + tab->processUserJoined(userInfo); } void TabSupervisor::updateCurrent(int index) { - if (index != -1) { - Tab *tab = static_cast(widget(index)); - if (tab->getContentsChanged()) { - setTabIcon(index, QIcon()); - tab->setContentsChanged(false); - } - emit setMenu(static_cast(widget(index))->getTabMenus()); - } else - emit setMenu(); + if (index != -1) { + Tab *tab = static_cast(widget(index)); + if (tab->getContentsChanged()) { + setTabIcon(index, QIcon()); + tab->setContentsChanged(false); + } + emit setMenu(static_cast(widget(index))->getTabMenus()); + } else + emit setMenu(); } bool TabSupervisor::getAdminLocked() const { - if (!tabAdmin) - return true; - return tabAdmin->getLocked(); + if (!tabAdmin) + return true; + return tabAdmin->getLocked(); } diff --git a/cockatrice/src/tab_supervisor.h b/cockatrice/src/tab_supervisor.h index 70941e12..48af3c8a 100644 --- a/cockatrice/src/tab_supervisor.h +++ b/cockatrice/src/tab_supervisor.h @@ -28,76 +28,76 @@ class GameReplay; class DeckList; class CloseButton : public QAbstractButton { - Q_OBJECT + Q_OBJECT public: - CloseButton(QWidget *parent = 0); - QSize sizeHint() const; - inline QSize minimumSizeHint() const { return sizeHint(); } + CloseButton(QWidget *parent = 0); + QSize sizeHint() const; + inline QSize minimumSizeHint() const { return sizeHint(); } protected: - void enterEvent(QEvent *event); - void leaveEvent(QEvent *event); - void paintEvent(QPaintEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + void paintEvent(QPaintEvent *event); }; class TabSupervisor : public QTabWidget { - Q_OBJECT + Q_OBJECT private: - ServerInfo_User *userInfo; - QIcon *tabChangedIcon; - AbstractClient *client; - QList localClients; - TabServer *tabServer; - TabUserLists *tabUserLists; - TabDeckStorage *tabDeckStorage; - TabReplays *tabReplays; - TabAdmin *tabAdmin; - QMap roomTabs; - QMap gameTabs; - QList replayTabs; - QMap messageTabs; - QList deckEditorTabs; - int myAddTab(Tab *tab); - void addCloseButtonToTab(Tab *tab, int tabIndex); + ServerInfo_User *userInfo; + QIcon *tabChangedIcon; + AbstractClient *client; + QList localClients; + TabServer *tabServer; + TabUserLists *tabUserLists; + TabDeckStorage *tabDeckStorage; + TabReplays *tabReplays; + TabAdmin *tabAdmin; + QMap roomTabs; + QMap gameTabs; + QList replayTabs; + QMap messageTabs; + QList deckEditorTabs; + int myAddTab(Tab *tab); + void addCloseButtonToTab(Tab *tab, int tabIndex); public: - TabSupervisor(AbstractClient *_client, QWidget *parent = 0); - ~TabSupervisor(); - void retranslateUi(); - void start(const ServerInfo_User &userInfo); - void startLocal(const QList &_clients); - void stop(); - int getGameCount() const { return gameTabs.size(); } - TabUserLists *getUserListsTab() const { return tabUserLists; } - ServerInfo_User *getUserInfo() const { return userInfo; } - AbstractClient *getClient() const; - const QMap &getRoomTabs() const { return roomTabs; } - bool getAdminLocked() const; + TabSupervisor(AbstractClient *_client, QWidget *parent = 0); + ~TabSupervisor(); + void retranslateUi(); + void start(const ServerInfo_User &userInfo); + void startLocal(const QList &_clients); + void stop(); + int getGameCount() const { return gameTabs.size(); } + TabUserLists *getUserListsTab() const { return tabUserLists; } + ServerInfo_User *getUserInfo() const { return userInfo; } + AbstractClient *getClient() const; + const QMap &getRoomTabs() const { return roomTabs; } + bool getAdminLocked() const; signals: - void setMenu(const QList &newMenuList = QList()); - void localGameEnded(); - void adminLockChanged(bool lock); + void setMenu(const QList &newMenuList = QList()); + void localGameEnded(); + void adminLockChanged(bool lock); public slots: - TabDeckEditor *addDeckEditorTab(const DeckLoader *deckToOpen); - void openReplay(GameReplay *replay); + TabDeckEditor *addDeckEditorTab(const DeckLoader *deckToOpen); + void openReplay(GameReplay *replay); private slots: - void closeButtonPressed(); - void updateCurrent(int index); - void updatePingTime(int value, int max); - void gameJoined(const Event_GameJoined &event); - void localGameJoined(const Event_GameJoined &event); - void gameLeft(TabGame *tab); - void addRoomTab(const ServerInfo_Room &info, bool setCurrent); - void roomLeft(TabRoom *tab); - TabMessage *addMessageTab(const QString &userName, bool focus); - void replayLeft(TabGame *tab); - void processUserLeft(const QString &userName); - void processUserJoined(const ServerInfo_User &userInfo); - void talkLeft(TabMessage *tab); - void deckEditorClosed(TabDeckEditor *tab); - void tabUserEvent(bool globalEvent); - void updateTabText(Tab *tab, const QString &newTabText); - void processRoomEvent(const RoomEvent &event); - void processGameEventContainer(const GameEventContainer &cont); - void processUserMessageEvent(const Event_UserMessage &event); + void closeButtonPressed(); + void updateCurrent(int index); + void updatePingTime(int value, int max); + void gameJoined(const Event_GameJoined &event); + void localGameJoined(const Event_GameJoined &event); + void gameLeft(TabGame *tab); + void addRoomTab(const ServerInfo_Room &info, bool setCurrent); + void roomLeft(TabRoom *tab); + TabMessage *addMessageTab(const QString &userName, bool focus); + void replayLeft(TabGame *tab); + void processUserLeft(const QString &userName); + void processUserJoined(const ServerInfo_User &userInfo); + void talkLeft(TabMessage *tab); + void deckEditorClosed(TabDeckEditor *tab); + void tabUserEvent(bool globalEvent); + void updateTabText(Tab *tab, const QString &newTabText); + void processRoomEvent(const RoomEvent &event); + void processGameEventContainer(const GameEventContainer &cont); + void processUserMessageEvent(const Event_UserMessage &event); }; #endif diff --git a/cockatrice/src/tab_userlists.cpp b/cockatrice/src/tab_userlists.cpp index 4059a3e7..3ad1d96a 100644 --- a/cockatrice/src/tab_userlists.cpp +++ b/cockatrice/src/tab_userlists.cpp @@ -14,137 +14,137 @@ #include "pb/event_remove_from_list.pb.h" TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent) - : Tab(_tabSupervisor, parent), client(_client) + : Tab(_tabSupervisor, parent), client(_client) { - allUsersList = new UserList(_tabSupervisor, client, UserList::AllUsersList); - buddyList = new UserList(_tabSupervisor, client, UserList::BuddyList); - ignoreList = new UserList(_tabSupervisor, client, UserList::IgnoreList); - userInfoBox = new UserInfoBox(client, false); - userInfoBox->updateInfo(userInfo); - - connect(allUsersList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - connect(buddyList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - connect(ignoreList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - - connect(client, SIGNAL(userJoinedEventReceived(const Event_UserJoined &)), this, SLOT(processUserJoinedEvent(const Event_UserJoined &))); - connect(client, SIGNAL(userLeftEventReceived(const Event_UserLeft &)), this, SLOT(processUserLeftEvent(const Event_UserLeft &))); - connect(client, SIGNAL(buddyListReceived(const QList &)), this, SLOT(buddyListReceived(const QList &))); - connect(client, SIGNAL(ignoreListReceived(const QList &)), this, SLOT(ignoreListReceived(const QList &))); - connect(client, SIGNAL(addToListEventReceived(const Event_AddToList &)), this, SLOT(processAddToListEvent(const Event_AddToList &))); - connect(client, SIGNAL(removeFromListEventReceived(const Event_RemoveFromList &)), this, SLOT(processRemoveFromListEvent(const Event_RemoveFromList &))); - - PendingCommand *pend = client->prepareSessionCommand(Command_ListUsers()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processListUsersResponse(const Response &))); - client->sendCommand(pend); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(userInfoBox); - vbox->addWidget(allUsersList); - - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addWidget(buddyList); - mainLayout->addWidget(ignoreList); - mainLayout->addLayout(vbox); - - setLayout(mainLayout); + allUsersList = new UserList(_tabSupervisor, client, UserList::AllUsersList); + buddyList = new UserList(_tabSupervisor, client, UserList::BuddyList); + ignoreList = new UserList(_tabSupervisor, client, UserList::IgnoreList); + userInfoBox = new UserInfoBox(client, false); + userInfoBox->updateInfo(userInfo); + + connect(allUsersList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + connect(buddyList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + connect(ignoreList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + + connect(client, SIGNAL(userJoinedEventReceived(const Event_UserJoined &)), this, SLOT(processUserJoinedEvent(const Event_UserJoined &))); + connect(client, SIGNAL(userLeftEventReceived(const Event_UserLeft &)), this, SLOT(processUserLeftEvent(const Event_UserLeft &))); + connect(client, SIGNAL(buddyListReceived(const QList &)), this, SLOT(buddyListReceived(const QList &))); + connect(client, SIGNAL(ignoreListReceived(const QList &)), this, SLOT(ignoreListReceived(const QList &))); + connect(client, SIGNAL(addToListEventReceived(const Event_AddToList &)), this, SLOT(processAddToListEvent(const Event_AddToList &))); + connect(client, SIGNAL(removeFromListEventReceived(const Event_RemoveFromList &)), this, SLOT(processRemoveFromListEvent(const Event_RemoveFromList &))); + + PendingCommand *pend = client->prepareSessionCommand(Command_ListUsers()); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processListUsersResponse(const Response &))); + client->sendCommand(pend); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(userInfoBox); + vbox->addWidget(allUsersList); + + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addWidget(buddyList); + mainLayout->addWidget(ignoreList); + mainLayout->addLayout(vbox); + + setLayout(mainLayout); } void TabUserLists::retranslateUi() { - allUsersList->retranslateUi(); - buddyList->retranslateUi(); - ignoreList->retranslateUi(); - userInfoBox->retranslateUi(); + allUsersList->retranslateUi(); + buddyList->retranslateUi(); + ignoreList->retranslateUi(); + userInfoBox->retranslateUi(); } void TabUserLists::processListUsersResponse(const Response &response) { - const Response_ListUsers &resp = response.GetExtension(Response_ListUsers::ext); - - const int userListSize = resp.user_list_size(); - for (int i = 0; i < userListSize; ++i) { - const ServerInfo_User &info = resp.user_list(i); - const QString userName = QString::fromStdString(info.name()); - allUsersList->processUserInfo(info, true); - ignoreList->setUserOnline(userName, true); - buddyList->setUserOnline(userName, true); - } - - allUsersList->sortItems(); - ignoreList->sortItems(); - buddyList->sortItems(); + const Response_ListUsers &resp = response.GetExtension(Response_ListUsers::ext); + + const int userListSize = resp.user_list_size(); + for (int i = 0; i < userListSize; ++i) { + const ServerInfo_User &info = resp.user_list(i); + const QString userName = QString::fromStdString(info.name()); + allUsersList->processUserInfo(info, true); + ignoreList->setUserOnline(userName, true); + buddyList->setUserOnline(userName, true); + } + + allUsersList->sortItems(); + ignoreList->sortItems(); + buddyList->sortItems(); } void TabUserLists::processUserJoinedEvent(const Event_UserJoined &event) { - const ServerInfo_User &info = event.user_info(); - const QString userName = QString::fromStdString(info.name()); - - allUsersList->processUserInfo(info, true); - ignoreList->setUserOnline(userName, true); - buddyList->setUserOnline(userName, true); - - allUsersList->sortItems(); - ignoreList->sortItems(); - buddyList->sortItems(); - - emit userJoined(info); + const ServerInfo_User &info = event.user_info(); + const QString userName = QString::fromStdString(info.name()); + + allUsersList->processUserInfo(info, true); + ignoreList->setUserOnline(userName, true); + buddyList->setUserOnline(userName, true); + + allUsersList->sortItems(); + ignoreList->sortItems(); + buddyList->sortItems(); + + emit userJoined(info); } void TabUserLists::processUserLeftEvent(const Event_UserLeft &event) { - QString userName = QString::fromStdString(event.name()); - if (allUsersList->deleteUser(userName)) { - ignoreList->setUserOnline(userName, false); - buddyList->setUserOnline(userName, false); - ignoreList->sortItems(); - buddyList->sortItems(); - - emit userLeft(userName); - } + QString userName = QString::fromStdString(event.name()); + if (allUsersList->deleteUser(userName)) { + ignoreList->setUserOnline(userName, false); + buddyList->setUserOnline(userName, false); + ignoreList->sortItems(); + buddyList->sortItems(); + + emit userLeft(userName); + } } void TabUserLists::buddyListReceived(const QList &_buddyList) { - for (int i = 0; i < _buddyList.size(); ++i) - buddyList->processUserInfo(_buddyList[i], false); - buddyList->sortItems(); + for (int i = 0; i < _buddyList.size(); ++i) + buddyList->processUserInfo(_buddyList[i], false); + buddyList->sortItems(); } void TabUserLists::ignoreListReceived(const QList &_ignoreList) { - for (int i = 0; i < _ignoreList.size(); ++i) - ignoreList->processUserInfo(_ignoreList[i], false); - ignoreList->sortItems(); + for (int i = 0; i < _ignoreList.size(); ++i) + ignoreList->processUserInfo(_ignoreList[i], false); + ignoreList->sortItems(); } void TabUserLists::processAddToListEvent(const Event_AddToList &event) { - const ServerInfo_User &info = event.user_info(); - bool online = allUsersList->getUsers().contains(QString::fromStdString(info.name())); - QString list = QString::fromStdString(event.list_name()); - UserList *userList = 0; - if (list == "buddy") - userList = buddyList; - else if (list == "ignore") - userList = ignoreList; - if (!userList) - return; - - userList->processUserInfo(info, online); - userList->sortItems(); + const ServerInfo_User &info = event.user_info(); + bool online = allUsersList->getUsers().contains(QString::fromStdString(info.name())); + QString list = QString::fromStdString(event.list_name()); + UserList *userList = 0; + if (list == "buddy") + userList = buddyList; + else if (list == "ignore") + userList = ignoreList; + if (!userList) + return; + + userList->processUserInfo(info, online); + userList->sortItems(); } void TabUserLists::processRemoveFromListEvent(const Event_RemoveFromList &event) { - QString list = QString::fromStdString(event.list_name()); - QString user = QString::fromStdString(event.user_name()); - UserList *userList = 0; - if (list == "buddy") - userList = buddyList; - else if (list == "ignore") - userList = ignoreList; - if (!userList) - return; - userList->deleteUser(user); + QString list = QString::fromStdString(event.list_name()); + QString user = QString::fromStdString(event.user_name()); + UserList *userList = 0; + if (list == "buddy") + userList = buddyList; + else if (list == "ignore") + userList = ignoreList; + if (!userList) + return; + userList->deleteUser(user); } diff --git a/cockatrice/src/tab_userlists.h b/cockatrice/src/tab_userlists.h index 866ae579..90e25604 100644 --- a/cockatrice/src/tab_userlists.h +++ b/cockatrice/src/tab_userlists.h @@ -17,32 +17,32 @@ class Event_AddToList; class Event_RemoveFromList; class TabUserLists : public Tab { - Q_OBJECT + Q_OBJECT signals: - void openMessageDialog(const QString &userName, bool focus); - void userLeft(const QString &userName); - void userJoined(const ServerInfo_User &userInfo); + void openMessageDialog(const QString &userName, bool focus); + void userLeft(const QString &userName); + void userJoined(const ServerInfo_User &userInfo); private slots: - void processListUsersResponse(const Response &response); - void processUserJoinedEvent(const Event_UserJoined &event); - void processUserLeftEvent(const Event_UserLeft &event); - void buddyListReceived(const QList &_buddyList); - void ignoreListReceived(const QList &_ignoreList); - void processAddToListEvent(const Event_AddToList &event); - void processRemoveFromListEvent(const Event_RemoveFromList &event); + void processListUsersResponse(const Response &response); + void processUserJoinedEvent(const Event_UserJoined &event); + void processUserLeftEvent(const Event_UserLeft &event); + void buddyListReceived(const QList &_buddyList); + void ignoreListReceived(const QList &_ignoreList); + void processAddToListEvent(const Event_AddToList &event); + void processRemoveFromListEvent(const Event_RemoveFromList &event); private: - AbstractClient *client; - UserList *allUsersList; - UserList *buddyList; - UserList *ignoreList; - UserInfoBox *userInfoBox; + AbstractClient *client; + UserList *allUsersList; + UserList *buddyList; + UserList *ignoreList; + UserInfoBox *userInfoBox; public: - TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent = 0); - void retranslateUi(); - QString getTabText() const { return tr("User lists"); } - const UserList *getAllUsersList() const { return allUsersList; } - const UserList *getBuddyList() const { return buddyList; } - const UserList *getIgnoreList() const { return ignoreList; } + TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent = 0); + void retranslateUi(); + QString getTabText() const { return tr("User lists"); } + const UserList *getAllUsersList() const { return allUsersList; } + const UserList *getBuddyList() const { return buddyList; } + const UserList *getIgnoreList() const { return ignoreList; } }; #endif diff --git a/cockatrice/src/tablezone.cpp b/cockatrice/src/tablezone.cpp index 63c17a5f..49965929 100644 --- a/cockatrice/src/tablezone.cpp +++ b/cockatrice/src/tablezone.cpp @@ -14,306 +14,306 @@ #include "pb/command_set_card_attr.pb.h" TableZone::TableZone(Player *_p, QGraphicsItem *parent) - : SelectZone(_p, "table", true, false, true, parent), active(false) + : SelectZone(_p, "table", true, false, true, parent), active(false) { - connect(settingsCache, SIGNAL(tableBgPathChanged()), this, SLOT(updateBgPixmap())); - connect(settingsCache, SIGNAL(invertVerticalCoordinateChanged()), this, SLOT(reorganizeCards())); - updateBgPixmap(); + connect(settingsCache, SIGNAL(tableBgPathChanged()), this, SLOT(updateBgPixmap())); + connect(settingsCache, SIGNAL(invertVerticalCoordinateChanged()), this, SLOT(reorganizeCards())); + updateBgPixmap(); - height = 2 * boxLineWidth + 3 * (CARD_HEIGHT + 20) + 2 * paddingY; - width = minWidth + 2 * marginX + 2 * boxLineWidth; - currentMinimumWidth = minWidth; + height = 2 * boxLineWidth + 3 * (CARD_HEIGHT + 20) + 2 * paddingY; + width = minWidth + 2 * marginX + 2 * boxLineWidth; + currentMinimumWidth = minWidth; - setCacheMode(DeviceCoordinateCache); - setAcceptsHoverEvents(true); + setCacheMode(DeviceCoordinateCache); + setAcceptsHoverEvents(true); } void TableZone::updateBgPixmap() { - QString bgPath = settingsCache->getTableBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); - update(); + QString bgPath = settingsCache->getTableBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); + update(); } QRectF TableZone::boundingRect() const { - return QRectF(0, 0, width, height); + return QRectF(0, 0, width, height); } bool TableZone::isInverted() const { - return ((player->getMirrored() && !settingsCache->getInvertVerticalCoordinate()) || (!player->getMirrored() && settingsCache->getInvertVerticalCoordinate())); + return ((player->getMirrored() && !settingsCache->getInvertVerticalCoordinate()) || (!player->getMirrored() && settingsCache->getInvertVerticalCoordinate())); } void TableZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), QColor(0, 0, 100)); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); - painter->setPen(QColor(255, 255, 255, 40)); - qreal separatorY = 2 * (CARD_HEIGHT + 20 + paddingY) + boxLineWidth - paddingY / 2; - if (isInverted()) - separatorY = height - separatorY; - painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); - - if (active) { - QColor color1(255, 255, 255, 150); - QColor color2(255, 255, 255, 0); - QLinearGradient grad1(0, 0, 0, 1); - grad1.setCoordinateMode(QGradient::ObjectBoundingMode); - grad1.setColorAt(0, color1); - grad1.setColorAt(1, color2); - painter->fillRect(QRectF(0, 0, width, boxLineWidth), QBrush(grad1)); - - grad1.setFinalStop(1, 0); - painter->fillRect(QRectF(0, 0, boxLineWidth, height), QBrush(grad1)); - - grad1.setStart(0, 1); - grad1.setFinalStop(0, 0); - painter->fillRect(QRectF(0, height - boxLineWidth, width, boxLineWidth), QBrush(grad1)); - - grad1.setStart(1, 0); - painter->fillRect(QRectF(width - boxLineWidth, 0, boxLineWidth, height), QBrush(grad1)); - } + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), QColor(0, 0, 100)); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); + painter->setPen(QColor(255, 255, 255, 40)); + qreal separatorY = 2 * (CARD_HEIGHT + 20 + paddingY) + boxLineWidth - paddingY / 2; + if (isInverted()) + separatorY = height - separatorY; + painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); + + if (active) { + QColor color1(255, 255, 255, 150); + QColor color2(255, 255, 255, 0); + QLinearGradient grad1(0, 0, 0, 1); + grad1.setCoordinateMode(QGradient::ObjectBoundingMode); + grad1.setColorAt(0, color1); + grad1.setColorAt(1, color2); + painter->fillRect(QRectF(0, 0, width, boxLineWidth), QBrush(grad1)); + + grad1.setFinalStop(1, 0); + painter->fillRect(QRectF(0, 0, boxLineWidth, height), QBrush(grad1)); + + grad1.setStart(0, 1); + grad1.setFinalStop(0, 0); + painter->fillRect(QRectF(0, height - boxLineWidth, width, boxLineWidth), QBrush(grad1)); + + grad1.setStart(1, 0); + painter->fillRect(QRectF(width - boxLineWidth, 0, boxLineWidth, height), QBrush(grad1)); + } } void TableZone::addCardImpl(CardItem *card, int _x, int _y) { - cards.append(card); - card->setGridPoint(QPoint(_x, _y)); + cards.append(card); + card->setGridPoint(QPoint(_x, _y)); - card->setParentItem(this); - card->setVisible(true); - card->update(); + card->setParentItem(this); + card->setVisible(true); + card->update(); } void TableZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint) { - handleDropEventByGrid(dragItems, startZone, mapToGrid(dropPoint)); + handleDropEventByGrid(dragItems, startZone, mapToGrid(dropPoint)); } void TableZone::handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint) { - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(gridPoint.x()); - cmd.set_y(gridPoint.y()); - - for (int i = 0; i < dragItems.size(); ++i) { - CardToMove *ctm = cmd.mutable_cards_to_move()->add_card(); - ctm->set_card_id(dragItems[i]->getId()); - ctm->set_face_down(dragItems[i]->getFaceDown()); - ctm->set_pt(startZone->getName() == name ? std::string() : dragItems[i]->getItem()->getInfo()->getPowTough().toStdString()); - } - - startZone->getPlayer()->sendGameCommand(cmd); + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(gridPoint.x()); + cmd.set_y(gridPoint.y()); + + for (int i = 0; i < dragItems.size(); ++i) { + CardToMove *ctm = cmd.mutable_cards_to_move()->add_card(); + ctm->set_card_id(dragItems[i]->getId()); + ctm->set_face_down(dragItems[i]->getFaceDown()); + ctm->set_pt(startZone->getName() == name ? std::string() : dragItems[i]->getItem()->getInfo()->getPowTough().toStdString()); + } + + startZone->getPlayer()->sendGameCommand(cmd); } void TableZone::reorganizeCards() { - QList arrowsToUpdate; - - // Calculate table grid distortion so that the mapping functions work properly - QMap gridPointStackCount; - for (int i = 0; i < cards.size(); ++i) { - const QPoint &gridPoint = cards[i]->getGridPos(); - if (gridPoint.x() == -1) - continue; - - const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; - gridPointStackCount.insert(key, gridPointStackCount.value(key, 0) + 1); - } - gridPointWidth.clear(); - for (int i = 0; i < cards.size(); ++i) { - const QPoint &gridPoint = cards[i]->getGridPos(); - if (gridPoint.x() == -1) - continue; - - const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; - const int stackCount = gridPointStackCount.value(key, 0); - if (stackCount == 1) - gridPointWidth.insert(key, CARD_WIDTH * (1 + cards[i]->getAttachedCards().size() / 3.0)); - else - gridPointWidth.insert(key, CARD_WIDTH * (1 + (stackCount - 1) / 3.0)); - } - - for (int i = 0; i < cards.size(); ++i) { - QPoint gridPoint = cards[i]->getGridPos(); - if (gridPoint.x() == -1) - continue; - - QPointF mapPoint = mapFromGrid(gridPoint); - qreal x = mapPoint.x(); - qreal y = mapPoint.y(); - - int numberAttachedCards = cards[i]->getAttachedCards().size(); - qreal actualX = x + numberAttachedCards * CARD_WIDTH / 3.0; - qreal actualY = y; - if (numberAttachedCards) - actualY += 15; - - cards[i]->setPos(actualX, actualY); - cards[i]->setRealZValue((actualY + CARD_HEIGHT) * 100000 + (actualX + 1) * 100); - - QListIterator attachedCardIterator(cards[i]->getAttachedCards()); - int j = 0; - while (attachedCardIterator.hasNext()) { - ++j; - CardItem *attachedCard = attachedCardIterator.next(); - qreal childX = actualX - j * CARD_WIDTH / 3.0; - qreal childY = y + 5; - attachedCard->setPos(childX, childY); - attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100); + QList arrowsToUpdate; + + // Calculate table grid distortion so that the mapping functions work properly + QMap gridPointStackCount; + for (int i = 0; i < cards.size(); ++i) { + const QPoint &gridPoint = cards[i]->getGridPos(); + if (gridPoint.x() == -1) + continue; + + const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; + gridPointStackCount.insert(key, gridPointStackCount.value(key, 0) + 1); + } + gridPointWidth.clear(); + for (int i = 0; i < cards.size(); ++i) { + const QPoint &gridPoint = cards[i]->getGridPos(); + if (gridPoint.x() == -1) + continue; + + const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; + const int stackCount = gridPointStackCount.value(key, 0); + if (stackCount == 1) + gridPointWidth.insert(key, CARD_WIDTH * (1 + cards[i]->getAttachedCards().size() / 3.0)); + else + gridPointWidth.insert(key, CARD_WIDTH * (1 + (stackCount - 1) / 3.0)); + } + + for (int i = 0; i < cards.size(); ++i) { + QPoint gridPoint = cards[i]->getGridPos(); + if (gridPoint.x() == -1) + continue; + + QPointF mapPoint = mapFromGrid(gridPoint); + qreal x = mapPoint.x(); + qreal y = mapPoint.y(); + + int numberAttachedCards = cards[i]->getAttachedCards().size(); + qreal actualX = x + numberAttachedCards * CARD_WIDTH / 3.0; + qreal actualY = y; + if (numberAttachedCards) + actualY += 15; + + cards[i]->setPos(actualX, actualY); + cards[i]->setRealZValue((actualY + CARD_HEIGHT) * 100000 + (actualX + 1) * 100); + + QListIterator attachedCardIterator(cards[i]->getAttachedCards()); + int j = 0; + while (attachedCardIterator.hasNext()) { + ++j; + CardItem *attachedCard = attachedCardIterator.next(); + qreal childX = actualX - j * CARD_WIDTH / 3.0; + qreal childY = y + 5; + attachedCard->setPos(childX, childY); + attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100); - arrowsToUpdate.append(attachedCard->getArrowsFrom()); - arrowsToUpdate.append(attachedCard->getArrowsTo()); - } - - arrowsToUpdate.append(cards[i]->getArrowsFrom()); - arrowsToUpdate.append(cards[i]->getArrowsTo()); - } + arrowsToUpdate.append(attachedCard->getArrowsFrom()); + arrowsToUpdate.append(attachedCard->getArrowsTo()); + } + + arrowsToUpdate.append(cards[i]->getArrowsFrom()); + arrowsToUpdate.append(cards[i]->getArrowsTo()); + } - QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); - while (arrowIterator.hasNext()) - arrowIterator.next()->updatePath(); - - resizeToContents(); - update(); + QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); + while (arrowIterator.hasNext()) + arrowIterator.next()->updatePath(); + + resizeToContents(); + update(); } void TableZone::toggleTapped() { - QList selectedItems = scene()->selectedItems(); - bool tapAll = false; - for (int i = 0; i < selectedItems.size(); i++) - if (!qgraphicsitem_cast(selectedItems[i])->getTapped()) { - tapAll = true; - break; - } - QList< const ::google::protobuf::Message * > cmdList; - for (int i = 0; i < selectedItems.size(); i++) { - CardItem *temp = qgraphicsitem_cast(selectedItems[i]); - if (temp->getTapped() != tapAll) { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(name.toStdString()); - cmd->set_card_id(temp->getId()); - cmd->set_attribute(AttrTapped); - cmd->set_attr_value(tapAll ? "1" : "0"); - cmdList.append(cmd); - } - } - player->sendGameCommand(player->prepareGameCommand(cmdList)); + QList selectedItems = scene()->selectedItems(); + bool tapAll = false; + for (int i = 0; i < selectedItems.size(); i++) + if (!qgraphicsitem_cast(selectedItems[i])->getTapped()) { + tapAll = true; + break; + } + QList< const ::google::protobuf::Message * > cmdList; + for (int i = 0; i < selectedItems.size(); i++) { + CardItem *temp = qgraphicsitem_cast(selectedItems[i]); + if (temp->getTapped() != tapAll) { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(name.toStdString()); + cmd->set_card_id(temp->getId()); + cmd->set_attribute(AttrTapped); + cmd->set_attr_value(tapAll ? "1" : "0"); + cmdList.append(cmd); + } + } + player->sendGameCommand(player->prepareGameCommand(cmdList)); } CardItem *TableZone::takeCard(int position, int cardId, bool canResize) { - CardItem *result = CardZone::takeCard(position, cardId); - if (canResize) - resizeToContents(); - return result; + CardItem *result = CardZone::takeCard(position, cardId); + if (canResize) + resizeToContents(); + return result; } void TableZone::resizeToContents() { - int xMax = 0; - for (int i = 0; i < cards.size(); ++i) - if (cards[i]->pos().x() > xMax) - xMax = (int) cards[i]->pos().x(); - xMax += 2 * CARD_WIDTH; - if (xMax < minWidth) - xMax = minWidth; - currentMinimumWidth = xMax + 2 * marginX + 2 * boxLineWidth; - if (currentMinimumWidth != width) { - prepareGeometryChange(); - width = currentMinimumWidth; - emit sizeChanged(); - } + int xMax = 0; + for (int i = 0; i < cards.size(); ++i) + if (cards[i]->pos().x() > xMax) + xMax = (int) cards[i]->pos().x(); + xMax += 2 * CARD_WIDTH; + if (xMax < minWidth) + xMax = minWidth; + currentMinimumWidth = xMax + 2 * marginX + 2 * boxLineWidth; + if (currentMinimumWidth != width) { + prepareGeometryChange(); + width = currentMinimumWidth; + emit sizeChanged(); + } } CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const { - for (int i = 0; i < cards.size(); i++) - if (cards.at(i)->getGridPoint() == gridPoint) - return cards.at(i); - return 0; + for (int i = 0; i < cards.size(); i++) + if (cards.at(i)->getGridPoint() == gridPoint) + return cards.at(i); + return 0; } CardItem *TableZone::getCardFromCoords(const QPointF &point) const { - QPoint gridPoint = mapToGrid(point); - return getCardFromGrid(gridPoint); + QPoint gridPoint = mapToGrid(point); + return getCardFromGrid(gridPoint); } QPointF TableZone::mapFromGrid(QPoint gridPoint) const { - qreal x, y; - x = marginX + (gridPoint.x() % 3) * CARD_WIDTH / 3.0; - for (int i = 0; i < gridPoint.x() / 3; ++i) - x += gridPointWidth.value(gridPoint.y() * 1000 + i, CARD_WIDTH) + paddingX; - - if (isInverted()) - gridPoint.setY(2 - gridPoint.y()); - - y = boxLineWidth + gridPoint.y() * (CARD_HEIGHT + paddingY + 20) + (gridPoint.x() % 3) * 10; -/* - if (isInverted()) - y = height - CARD_HEIGHT - y; -*/ - return QPointF(x, y); + qreal x, y; + x = marginX + (gridPoint.x() % 3) * CARD_WIDTH / 3.0; + for (int i = 0; i < gridPoint.x() / 3; ++i) + x += gridPointWidth.value(gridPoint.y() * 1000 + i, CARD_WIDTH) + paddingX; + + if (isInverted()) + gridPoint.setY(2 - gridPoint.y()); + + y = boxLineWidth + gridPoint.y() * (CARD_HEIGHT + paddingY + 20) + (gridPoint.x() % 3) * 10; +/* + if (isInverted()) + y = height - CARD_HEIGHT - y; +*/ + return QPointF(x, y); } QPoint TableZone::mapToGrid(const QPointF &mapPoint) const { - qreal x = mapPoint.x() - marginX; - qreal y = mapPoint.y(); -/* if (isInverted()) - y = height - y; -*/ y -= boxLineWidth; - - if (x < 0) - x = 0; - else if (x > width - CARD_WIDTH - marginX) - x = width - CARD_WIDTH - marginX; - if (y < 0) - y = 0; - else if (y > height - CARD_HEIGHT) - y = height - CARD_HEIGHT; - - int resultY = round(y / (CARD_HEIGHT + paddingY + 20)); - if (isInverted()) - resultY = 2 - resultY; + qreal x = mapPoint.x() - marginX; + qreal y = mapPoint.y(); +/* if (isInverted()) + y = height - y; +*/ y -= boxLineWidth; + + if (x < 0) + x = 0; + else if (x > width - CARD_WIDTH - marginX) + x = width - CARD_WIDTH - marginX; + if (y < 0) + y = 0; + else if (y > height - CARD_HEIGHT) + y = height - CARD_HEIGHT; + + int resultY = round(y / (CARD_HEIGHT + paddingY + 20)); + if (isInverted()) + resultY = 2 - resultY; - int baseX = -1; - qreal oldTempX = 0, tempX = 0; - do { - ++baseX; - oldTempX = tempX; - tempX += gridPointWidth.value(resultY * 1000 + baseX, CARD_WIDTH) + paddingX; - } while (tempX < x + 1); - - qreal xdiff = x - oldTempX; - int resultX = baseX * 3 + qMin((int) floor(xdiff * 3 / CARD_WIDTH), 2); - return QPoint(resultX, resultY); + int baseX = -1; + qreal oldTempX = 0, tempX = 0; + do { + ++baseX; + oldTempX = tempX; + tempX += gridPointWidth.value(resultY * 1000 + baseX, CARD_WIDTH) + paddingX; + } while (tempX < x + 1); + + qreal xdiff = x - oldTempX; + int resultX = baseX * 3 + qMin((int) floor(xdiff * 3 / CARD_WIDTH), 2); + return QPoint(resultX, resultY); } QPointF TableZone::closestGridPoint(const QPointF &point) { - QPoint gridPoint = mapToGrid(point + QPoint(1, 1)); - gridPoint.setX((gridPoint.x() / 3) * 3); - if (getCardFromGrid(gridPoint)) - gridPoint.setX(gridPoint.x() + 1); - if (getCardFromGrid(gridPoint)) - gridPoint.setX(gridPoint.x() + 1); - return mapFromGrid(gridPoint); + QPoint gridPoint = mapToGrid(point + QPoint(1, 1)); + gridPoint.setX((gridPoint.x() / 3) * 3); + if (getCardFromGrid(gridPoint)) + gridPoint.setX(gridPoint.x() + 1); + if (getCardFromGrid(gridPoint)) + gridPoint.setX(gridPoint.x() + 1); + return mapFromGrid(gridPoint); } void TableZone::setWidth(qreal _width) { - prepareGeometryChange(); - width = _width; + prepareGeometryChange(); + width = _width; } diff --git a/cockatrice/src/tablezone.h b/cockatrice/src/tablezone.h index 44cca399..297f097f 100644 --- a/cockatrice/src/tablezone.h +++ b/cockatrice/src/tablezone.h @@ -5,46 +5,46 @@ #include "abstractcarditem.h" class TableZone : public SelectZone { - Q_OBJECT + Q_OBJECT signals: - void sizeChanged(); + void sizeChanged(); private: - static const int boxLineWidth = 10; - static const int paddingX = 35; - static const int paddingY = 10; - static const int marginX = 20; - static const int minWidth = 15 * CARD_WIDTH / 2; + static const int boxLineWidth = 10; + static const int paddingX = 35; + static const int paddingY = 10; + static const int marginX = 20; + static const int minWidth = 15 * CARD_WIDTH / 2; - QMap gridPointWidth; - int width, height; - int currentMinimumWidth; - QPixmap bgPixmap; - bool active; - bool isInverted() const; -private slots: - void updateBgPixmap(); + QMap gridPointWidth; + int width, height; + int currentMinimumWidth; + QPixmap bgPixmap; + bool active; + bool isInverted() const; +private slots: + void updateBgPixmap(); public slots: - void reorganizeCards(); + void reorganizeCards(); public: - TableZone(Player *_p, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void toggleTapped(); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - void handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint); - CardItem *getCardFromGrid(const QPoint &gridPoint) const; - CardItem *getCardFromCoords(const QPointF &point) const; - QPointF mapFromGrid(QPoint gridPoint) const; - QPoint mapToGrid(const QPointF &mapPoint) const; - QPointF closestGridPoint(const QPointF &point); - CardItem *takeCard(int position, int cardId, bool canResize = true); - void resizeToContents(); - int getMinimumWidth() const { return currentMinimumWidth; } - void setWidth(qreal _width); - qreal getWidth() const { return width; } - void setActive(bool _active) { active = _active; update(); } + TableZone(Player *_p, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void toggleTapped(); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + void handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint); + CardItem *getCardFromGrid(const QPoint &gridPoint) const; + CardItem *getCardFromCoords(const QPointF &point) const; + QPointF mapFromGrid(QPoint gridPoint) const; + QPoint mapToGrid(const QPointF &mapPoint) const; + QPointF closestGridPoint(const QPointF &point); + CardItem *takeCard(int position, int cardId, bool canResize = true); + void resizeToContents(); + int getMinimumWidth() const { return currentMinimumWidth; } + void setWidth(qreal _width); + qreal getWidth() const { return width; } + void setActive(bool _active) { active = _active; update(); } protected: - void addCardImpl(CardItem *card, int x, int y); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/user_context_menu.cpp b/cockatrice/src/user_context_menu.cpp index 657dc40b..eab48f47 100644 --- a/cockatrice/src/user_context_menu.cpp +++ b/cockatrice/src/user_context_menu.cpp @@ -18,181 +18,181 @@ #include "pb/response_get_user_info.pb.h" UserContextMenu::UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *parent, TabGame *_game) - : QObject(parent), client(_tabSupervisor->getClient()), tabSupervisor(_tabSupervisor), game(_game) + : QObject(parent), client(_tabSupervisor->getClient()), tabSupervisor(_tabSupervisor), game(_game) { - aUserName = new QAction(QString(), this); - aUserName->setEnabled(false); - aDetails = new QAction(QString(), this); - aChat = new QAction(QString(), this); - aShowGames = new QAction(QString(), this); - aAddToBuddyList = new QAction(QString(), this); - aRemoveFromBuddyList = new QAction(QString(), this); - aAddToIgnoreList = new QAction(QString(), this); - aRemoveFromIgnoreList = new QAction(QString(), this); - aKick = new QAction(QString(), this); - aBan = new QAction(QString(), this); - - retranslateUi(); + aUserName = new QAction(QString(), this); + aUserName->setEnabled(false); + aDetails = new QAction(QString(), this); + aChat = new QAction(QString(), this); + aShowGames = new QAction(QString(), this); + aAddToBuddyList = new QAction(QString(), this); + aRemoveFromBuddyList = new QAction(QString(), this); + aAddToIgnoreList = new QAction(QString(), this); + aRemoveFromIgnoreList = new QAction(QString(), this); + aKick = new QAction(QString(), this); + aBan = new QAction(QString(), this); + + retranslateUi(); } void UserContextMenu::retranslateUi() { - aDetails->setText(tr("User &details")); - aChat->setText(tr("Direct &chat")); - aShowGames->setText(tr("Show this user's &games")); - aAddToBuddyList->setText(tr("Add to &buddy list")); - aRemoveFromBuddyList->setText(tr("Remove from &buddy list")); - aAddToIgnoreList->setText(tr("Add to &ignore list")); - aRemoveFromIgnoreList->setText(tr("Remove from &ignore list")); - aKick->setText(tr("Kick from &game")); - aBan->setText(tr("Ban from &server")); + aDetails->setText(tr("User &details")); + aChat->setText(tr("Direct &chat")); + aShowGames->setText(tr("Show this user's &games")); + aAddToBuddyList->setText(tr("Add to &buddy list")); + aRemoveFromBuddyList->setText(tr("Remove from &buddy list")); + aAddToIgnoreList->setText(tr("Add to &ignore list")); + aRemoveFromIgnoreList->setText(tr("Remove from &ignore list")); + aKick->setText(tr("Kick from &game")); + aBan->setText(tr("Ban from &server")); } void UserContextMenu::gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer) { - const Response_GetGamesOfUser &response = resp.GetExtension(Response_GetGamesOfUser::ext); - const Command_GetGamesOfUser &cmd = commandContainer.session_command(0).GetExtension(Command_GetGamesOfUser::ext); - - QMap gameTypeMap; - QMap roomMap; - const int roomListSize = response.room_list_size(); - for (int i = 0; i < roomListSize; ++i) { - const ServerInfo_Room &roomInfo = response.room_list(i); - roomMap.insert(roomInfo.room_id(), QString::fromStdString(roomInfo.name())); - GameTypeMap tempMap; - const int gameTypeListSize = roomInfo.gametype_list_size(); - for (int j = 0; j < gameTypeListSize; ++j) { - const ServerInfo_GameType &gameTypeInfo = roomInfo.gametype_list(j); - tempMap.insert(gameTypeInfo.game_type_id(), QString::fromStdString(gameTypeInfo.description())); - } - gameTypeMap.insert(roomInfo.room_id(), tempMap); - } - - GameSelector *selector = new GameSelector(client, tabSupervisor, 0, roomMap, gameTypeMap); - const int gameListSize = response.game_list_size(); - for (int i = 0; i < gameListSize; ++i) - selector->processGameInfo(response.game_list(i)); - - selector->setWindowTitle(tr("%1's games").arg(QString::fromStdString(cmd.user_name()))); - selector->setAttribute(Qt::WA_DeleteOnClose); - selector->show(); + const Response_GetGamesOfUser &response = resp.GetExtension(Response_GetGamesOfUser::ext); + const Command_GetGamesOfUser &cmd = commandContainer.session_command(0).GetExtension(Command_GetGamesOfUser::ext); + + QMap gameTypeMap; + QMap roomMap; + const int roomListSize = response.room_list_size(); + for (int i = 0; i < roomListSize; ++i) { + const ServerInfo_Room &roomInfo = response.room_list(i); + roomMap.insert(roomInfo.room_id(), QString::fromStdString(roomInfo.name())); + GameTypeMap tempMap; + const int gameTypeListSize = roomInfo.gametype_list_size(); + for (int j = 0; j < gameTypeListSize; ++j) { + const ServerInfo_GameType &gameTypeInfo = roomInfo.gametype_list(j); + tempMap.insert(gameTypeInfo.game_type_id(), QString::fromStdString(gameTypeInfo.description())); + } + gameTypeMap.insert(roomInfo.room_id(), tempMap); + } + + GameSelector *selector = new GameSelector(client, tabSupervisor, 0, roomMap, gameTypeMap); + const int gameListSize = response.game_list_size(); + for (int i = 0; i < gameListSize; ++i) + selector->processGameInfo(response.game_list(i)); + + selector->setWindowTitle(tr("%1's games").arg(QString::fromStdString(cmd.user_name()))); + selector->setAttribute(Qt::WA_DeleteOnClose); + selector->show(); } void UserContextMenu::banUser_processUserInfoResponse(const Response &r) { - const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); - - // The dialog needs to be non-modal in order to not block the event queue of the client. - BanDialog *dlg = new BanDialog(response.user_info(), static_cast(parent())); - connect(dlg, SIGNAL(accepted()), this, SLOT(banUser_dialogFinished())); - dlg->show(); + const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); + + // The dialog needs to be non-modal in order to not block the event queue of the client. + BanDialog *dlg = new BanDialog(response.user_info(), static_cast(parent())); + connect(dlg, SIGNAL(accepted()), this, SLOT(banUser_dialogFinished())); + dlg->show(); } void UserContextMenu::banUser_dialogFinished() { - BanDialog *dlg = static_cast(sender()); - - Command_BanFromServer cmd; - cmd.set_user_name(dlg->getBanName().toStdString()); - cmd.set_address(dlg->getBanIP().toStdString()); - cmd.set_minutes(dlg->getMinutes()); - cmd.set_reason(dlg->getReason().toStdString()); - cmd.set_visible_reason(dlg->getVisibleReason().toStdString()); - - client->sendCommand(client->prepareModeratorCommand(cmd)); + BanDialog *dlg = static_cast(sender()); + + Command_BanFromServer cmd; + cmd.set_user_name(dlg->getBanName().toStdString()); + cmd.set_address(dlg->getBanIP().toStdString()); + cmd.set_minutes(dlg->getMinutes()); + cmd.set_reason(dlg->getReason().toStdString()); + cmd.set_visible_reason(dlg->getVisibleReason().toStdString()); + + client->sendCommand(client->prepareModeratorCommand(cmd)); } void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, int playerId) { - aUserName->setText(userName); - - QMenu *menu = new QMenu(static_cast(parent())); - menu->addAction(aUserName); - menu->addSeparator(); - menu->addAction(aDetails); - menu->addAction(aShowGames); - menu->addAction(aChat); - if (userLevel.testFlag(ServerInfo_User::IsRegistered) && (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsRegistered)) { - menu->addSeparator(); - if (tabSupervisor->getUserListsTab()->getBuddyList()->getUsers().contains(userName)) - menu->addAction(aRemoveFromBuddyList); - else - menu->addAction(aAddToBuddyList); - if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(userName)) - menu->addAction(aRemoveFromIgnoreList); - else - menu->addAction(aAddToIgnoreList); - } - if (game && (game->isHost() || !tabSupervisor->getAdminLocked())) { - menu->addSeparator(); - menu->addAction(aKick); - } - if (!tabSupervisor->getAdminLocked()) { - menu->addSeparator(); - menu->addAction(aBan); - } - bool anotherUser = userName != QString::fromStdString(tabSupervisor->getUserInfo()->name()); - aChat->setEnabled(anotherUser); - aShowGames->setEnabled(anotherUser); - aAddToBuddyList->setEnabled(anotherUser); - aRemoveFromBuddyList->setEnabled(anotherUser); - aAddToIgnoreList->setEnabled(anotherUser); - aRemoveFromIgnoreList->setEnabled(anotherUser); - aKick->setEnabled(anotherUser); - aBan->setEnabled(anotherUser); - - QAction *actionClicked = menu->exec(pos); - if (actionClicked == aDetails) { - UserInfoBox *infoWidget = new UserInfoBox(client, true, static_cast(parent()), Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); - infoWidget->setAttribute(Qt::WA_DeleteOnClose); - infoWidget->updateInfo(userName); - } else if (actionClicked == aChat) - emit openMessageDialog(userName, true); - else if (actionClicked == aShowGames) { - Command_GetGamesOfUser cmd; - cmd.set_user_name(userName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(gamesOfUserReceived(Response, CommandContainer))); - - client->sendCommand(pend); - } else if (actionClicked == aAddToBuddyList) { - Command_AddToList cmd; - cmd.set_list("buddy"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aRemoveFromBuddyList) { - Command_RemoveFromList cmd; - cmd.set_list("buddy"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aAddToIgnoreList) { - Command_AddToList cmd; - cmd.set_list("ignore"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aRemoveFromIgnoreList) { - Command_RemoveFromList cmd; - cmd.set_list("ignore"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aKick) { - Command_KickFromGame cmd; - cmd.set_player_id(playerId); - game->sendGameCommand(cmd); - } else if (actionClicked == aBan) { - Command_GetUserInfo cmd; - cmd.set_user_name(userName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(banUser_processUserInfoResponse(Response))); - - client->sendCommand(pend); - } - - delete menu; + aUserName->setText(userName); + + QMenu *menu = new QMenu(static_cast(parent())); + menu->addAction(aUserName); + menu->addSeparator(); + menu->addAction(aDetails); + menu->addAction(aShowGames); + menu->addAction(aChat); + if (userLevel.testFlag(ServerInfo_User::IsRegistered) && (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsRegistered)) { + menu->addSeparator(); + if (tabSupervisor->getUserListsTab()->getBuddyList()->getUsers().contains(userName)) + menu->addAction(aRemoveFromBuddyList); + else + menu->addAction(aAddToBuddyList); + if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(userName)) + menu->addAction(aRemoveFromIgnoreList); + else + menu->addAction(aAddToIgnoreList); + } + if (game && (game->isHost() || !tabSupervisor->getAdminLocked())) { + menu->addSeparator(); + menu->addAction(aKick); + } + if (!tabSupervisor->getAdminLocked()) { + menu->addSeparator(); + menu->addAction(aBan); + } + bool anotherUser = userName != QString::fromStdString(tabSupervisor->getUserInfo()->name()); + aChat->setEnabled(anotherUser); + aShowGames->setEnabled(anotherUser); + aAddToBuddyList->setEnabled(anotherUser); + aRemoveFromBuddyList->setEnabled(anotherUser); + aAddToIgnoreList->setEnabled(anotherUser); + aRemoveFromIgnoreList->setEnabled(anotherUser); + aKick->setEnabled(anotherUser); + aBan->setEnabled(anotherUser); + + QAction *actionClicked = menu->exec(pos); + if (actionClicked == aDetails) { + UserInfoBox *infoWidget = new UserInfoBox(client, true, static_cast(parent()), Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); + infoWidget->setAttribute(Qt::WA_DeleteOnClose); + infoWidget->updateInfo(userName); + } else if (actionClicked == aChat) + emit openMessageDialog(userName, true); + else if (actionClicked == aShowGames) { + Command_GetGamesOfUser cmd; + cmd.set_user_name(userName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(gamesOfUserReceived(Response, CommandContainer))); + + client->sendCommand(pend); + } else if (actionClicked == aAddToBuddyList) { + Command_AddToList cmd; + cmd.set_list("buddy"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aRemoveFromBuddyList) { + Command_RemoveFromList cmd; + cmd.set_list("buddy"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aAddToIgnoreList) { + Command_AddToList cmd; + cmd.set_list("ignore"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aRemoveFromIgnoreList) { + Command_RemoveFromList cmd; + cmd.set_list("ignore"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aKick) { + Command_KickFromGame cmd; + cmd.set_player_id(playerId); + game->sendGameCommand(cmd); + } else if (actionClicked == aBan) { + Command_GetUserInfo cmd; + cmd.set_user_name(userName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(banUser_processUserInfoResponse(Response))); + + client->sendCommand(pend); + } + + delete menu; } diff --git a/cockatrice/src/user_context_menu.h b/cockatrice/src/user_context_menu.h index 7634b962..8e6708b0 100644 --- a/cockatrice/src/user_context_menu.h +++ b/cockatrice/src/user_context_menu.h @@ -13,30 +13,30 @@ class Response; class AbstractClient; class UserContextMenu : public QObject { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - const TabSupervisor *tabSupervisor; - TabGame *game; - - QAction *aUserName; - QAction *aDetails; - QAction *aShowGames; - QAction *aChat; - QAction *aAddToBuddyList, *aRemoveFromBuddyList; - QAction *aAddToIgnoreList, *aRemoveFromIgnoreList; - QAction *aKick; - QAction *aBan; + AbstractClient *client; + const TabSupervisor *tabSupervisor; + TabGame *game; + + QAction *aUserName; + QAction *aDetails; + QAction *aShowGames; + QAction *aChat; + QAction *aAddToBuddyList, *aRemoveFromBuddyList; + QAction *aAddToIgnoreList, *aRemoveFromIgnoreList; + QAction *aKick; + QAction *aBan; signals: - void openMessageDialog(const QString &userName, bool focus); + void openMessageDialog(const QString &userName, bool focus); private slots: - void banUser_processUserInfoResponse(const Response &resp); - void banUser_dialogFinished(); - void gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer); + void banUser_processUserInfoResponse(const Response &resp); + void banUser_dialogFinished(); + void gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer); public: - UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *_parent, TabGame *_game = 0); - void retranslateUi(); - void showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, int playerId = -1); + UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *_parent, TabGame *_game = 0); + void retranslateUi(); + void showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, int playerId = -1); }; #endif diff --git a/cockatrice/src/userinfobox.cpp b/cockatrice/src/userinfobox.cpp index 79d64afa..855cd748 100644 --- a/cockatrice/src/userinfobox.cpp +++ b/cockatrice/src/userinfobox.cpp @@ -9,93 +9,93 @@ #include "pb/response_get_user_info.pb.h" UserInfoBox::UserInfoBox(AbstractClient *_client, bool _fullInfo, QWidget *parent, Qt::WindowFlags flags) - : QWidget(parent, flags), client(_client), fullInfo(_fullInfo) + : QWidget(parent, flags), client(_client), fullInfo(_fullInfo) { - avatarLabel = new QLabel; - nameLabel = new QLabel; - QFont nameFont = nameLabel->font(); - nameFont.setBold(true); - nameFont.setPointSize(nameFont.pointSize() * 1.5); - nameLabel->setFont(nameFont); - realNameLabel1 = new QLabel; - realNameLabel2 = new QLabel; - genderLabel1 = new QLabel; - genderLabel2 = new QLabel; - countryLabel1 = new QLabel; - countryLabel2 = new QLabel; - userLevelLabel1 = new QLabel; - userLevelLabel2 = new QLabel; - userLevelLabel3 = new QLabel; - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(avatarLabel, 0, 0, 1, 3, Qt::AlignCenter); - mainLayout->addWidget(nameLabel, 1, 0, 1, 3); - mainLayout->addWidget(realNameLabel1, 2, 0, 1, 1); - mainLayout->addWidget(realNameLabel2, 2, 1, 1, 2); - mainLayout->addWidget(genderLabel1, 3, 0, 1, 1); - mainLayout->addWidget(genderLabel2, 3, 1, 1, 2); - mainLayout->addWidget(countryLabel1, 4, 0, 1, 1); - mainLayout->addWidget(countryLabel2, 4, 1, 1, 2); - mainLayout->addWidget(userLevelLabel1, 5, 0, 1, 1); - mainLayout->addWidget(userLevelLabel2, 5, 1, 1, 1); - mainLayout->addWidget(userLevelLabel3, 5, 2, 1, 1); - mainLayout->setColumnStretch(2, 10); - - setWindowTitle(tr("User information")); - setLayout(mainLayout); - retranslateUi(); + avatarLabel = new QLabel; + nameLabel = new QLabel; + QFont nameFont = nameLabel->font(); + nameFont.setBold(true); + nameFont.setPointSize(nameFont.pointSize() * 1.5); + nameLabel->setFont(nameFont); + realNameLabel1 = new QLabel; + realNameLabel2 = new QLabel; + genderLabel1 = new QLabel; + genderLabel2 = new QLabel; + countryLabel1 = new QLabel; + countryLabel2 = new QLabel; + userLevelLabel1 = new QLabel; + userLevelLabel2 = new QLabel; + userLevelLabel3 = new QLabel; + + QGridLayout *mainLayout = new QGridLayout; + mainLayout->addWidget(avatarLabel, 0, 0, 1, 3, Qt::AlignCenter); + mainLayout->addWidget(nameLabel, 1, 0, 1, 3); + mainLayout->addWidget(realNameLabel1, 2, 0, 1, 1); + mainLayout->addWidget(realNameLabel2, 2, 1, 1, 2); + mainLayout->addWidget(genderLabel1, 3, 0, 1, 1); + mainLayout->addWidget(genderLabel2, 3, 1, 1, 2); + mainLayout->addWidget(countryLabel1, 4, 0, 1, 1); + mainLayout->addWidget(countryLabel2, 4, 1, 1, 2); + mainLayout->addWidget(userLevelLabel1, 5, 0, 1, 1); + mainLayout->addWidget(userLevelLabel2, 5, 1, 1, 1); + mainLayout->addWidget(userLevelLabel3, 5, 2, 1, 1); + mainLayout->setColumnStretch(2, 10); + + setWindowTitle(tr("User information")); + setLayout(mainLayout); + retranslateUi(); } void UserInfoBox::retranslateUi() { - realNameLabel1->setText(tr("Real name:")); - genderLabel1->setText(tr("Gender:")); - countryLabel1->setText(tr("Location:")); - userLevelLabel1->setText(tr("User level:")); + realNameLabel1->setText(tr("Real name:")); + genderLabel1->setText(tr("Gender:")); + countryLabel1->setText(tr("Location:")); + userLevelLabel1->setText(tr("User level:")); } void UserInfoBox::updateInfo(const ServerInfo_User &user) { - const UserLevelFlags userLevel(user.user_level()); - - QPixmap avatarPixmap; - const std::string bmp = user.avatar_bmp(); - if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) - avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel); - avatarLabel->setPixmap(avatarPixmap); - - nameLabel->setText(QString::fromStdString(user.name())); - realNameLabel2->setText(QString::fromStdString(user.real_name())); - genderLabel2->setPixmap(GenderPixmapGenerator::generatePixmap(15, user.gender())); - countryLabel2->setPixmap(CountryPixmapGenerator::generatePixmap(15, QString::fromStdString(user.country()))); - userLevelLabel2->setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel)); - QString userLevelText; - if (userLevel.testFlag(ServerInfo_User::IsAdmin)) - userLevelText = tr("Administrator"); - else if (userLevel.testFlag(ServerInfo_User::IsModerator)) - userLevelText = tr("Moderator"); - else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) - userLevelText = tr("Registered user"); - else - userLevelText = tr("Unregistered user"); - userLevelLabel3->setText(userLevelText); + const UserLevelFlags userLevel(user.user_level()); + + QPixmap avatarPixmap; + const std::string bmp = user.avatar_bmp(); + if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) + avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel); + avatarLabel->setPixmap(avatarPixmap); + + nameLabel->setText(QString::fromStdString(user.name())); + realNameLabel2->setText(QString::fromStdString(user.real_name())); + genderLabel2->setPixmap(GenderPixmapGenerator::generatePixmap(15, user.gender())); + countryLabel2->setPixmap(CountryPixmapGenerator::generatePixmap(15, QString::fromStdString(user.country()))); + userLevelLabel2->setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel)); + QString userLevelText; + if (userLevel.testFlag(ServerInfo_User::IsAdmin)) + userLevelText = tr("Administrator"); + else if (userLevel.testFlag(ServerInfo_User::IsModerator)) + userLevelText = tr("Moderator"); + else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) + userLevelText = tr("Registered user"); + else + userLevelText = tr("Unregistered user"); + userLevelLabel3->setText(userLevelText); } void UserInfoBox::updateInfo(const QString &userName) { - Command_GetUserInfo cmd; - cmd.set_user_name(userName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processResponse(const Response &))); - - client->sendCommand(pend); + Command_GetUserInfo cmd; + cmd.set_user_name(userName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processResponse(const Response &))); + + client->sendCommand(pend); } void UserInfoBox::processResponse(const Response &r) { - const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); - updateInfo(response.user_info()); - setFixedSize(sizeHint()); - show(); + const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); + updateInfo(response.user_info()); + setFixedSize(sizeHint()); + show(); } diff --git a/cockatrice/src/userinfobox.h b/cockatrice/src/userinfobox.h index 186ca8ff..5c47c4a2 100644 --- a/cockatrice/src/userinfobox.h +++ b/cockatrice/src/userinfobox.h @@ -9,19 +9,19 @@ class AbstractClient; class Response; class UserInfoBox : public QWidget { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - bool fullInfo; - QLabel *avatarLabel, *nameLabel, *realNameLabel1, *realNameLabel2, *genderLabel1, *genderLabel2, *countryLabel1, *countryLabel2, *userLevelLabel1, *userLevelLabel2, *userLevelLabel3; + AbstractClient *client; + bool fullInfo; + QLabel *avatarLabel, *nameLabel, *realNameLabel1, *realNameLabel2, *genderLabel1, *genderLabel2, *countryLabel1, *countryLabel2, *userLevelLabel1, *userLevelLabel2, *userLevelLabel3; public: - UserInfoBox(AbstractClient *_client, bool fullInfo, QWidget *parent = 0, Qt::WindowFlags flags = 0); - void retranslateUi(); + UserInfoBox(AbstractClient *_client, bool fullInfo, QWidget *parent = 0, Qt::WindowFlags flags = 0); + void retranslateUi(); private slots: - void processResponse(const Response &r); + void processResponse(const Response &r); public slots: - void updateInfo(const ServerInfo_User &user); - void updateInfo(const QString &userName); + void updateInfo(const ServerInfo_User &user); + void updateInfo(const QString &userName); }; #endif diff --git a/cockatrice/src/userlist.cpp b/cockatrice/src/userlist.cpp index 205418f0..562d395b 100644 --- a/cockatrice/src/userlist.cpp +++ b/cockatrice/src/userlist.cpp @@ -27,291 +27,291 @@ #include "pb/response_get_user_info.pb.h" BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - setAttribute(Qt::WA_DeleteOnClose); - - nameBanCheckBox = new QCheckBox(tr("ban &user name")); - nameBanCheckBox->setChecked(true); - nameBanEdit = new QLineEdit(QString::fromStdString(info.name())); - ipBanCheckBox = new QCheckBox(tr("ban &IP address")); - ipBanCheckBox->setChecked(true); - ipBanEdit = new QLineEdit(QString::fromStdString(info.address())); - QGridLayout *banTypeGrid = new QGridLayout; - banTypeGrid->addWidget(nameBanCheckBox, 0, 0); - banTypeGrid->addWidget(nameBanEdit, 0, 1); - banTypeGrid->addWidget(ipBanCheckBox, 1, 0); - banTypeGrid->addWidget(ipBanEdit, 1, 1); - QGroupBox *banTypeGroupBox = new QGroupBox(tr("Ban type")); - banTypeGroupBox->setLayout(banTypeGrid); - - permanentRadio = new QRadioButton(tr("&permanent ban")); - temporaryRadio = new QRadioButton(tr("&temporary ban")); - temporaryRadio->setChecked(true); - connect(temporaryRadio, SIGNAL(toggled(bool)), this, SLOT(enableTemporaryEdits(bool))); - daysLabel = new QLabel(tr("&Days:")); - daysEdit = new QSpinBox; - daysEdit->setMinimum(0); - daysEdit->setValue(0); - daysEdit->setMaximum(10000); - daysLabel->setBuddy(daysEdit); - hoursLabel = new QLabel(tr("&Hours:")); - hoursEdit = new QSpinBox; - hoursEdit->setMinimum(0); - hoursEdit->setValue(0); - hoursEdit->setMaximum(24); - hoursLabel->setBuddy(hoursEdit); - minutesLabel = new QLabel(tr("&Minutes:")); - minutesEdit = new QSpinBox; - minutesEdit->setMinimum(0); - minutesEdit->setValue(5); - minutesEdit->setMaximum(60); - minutesLabel->setBuddy(minutesEdit); - QGridLayout *durationLayout = new QGridLayout; - durationLayout->addWidget(permanentRadio, 0, 0, 1, 6); - durationLayout->addWidget(temporaryRadio, 1, 0, 1, 6); - durationLayout->addWidget(daysLabel, 2, 0); - durationLayout->addWidget(daysEdit, 2, 1); - durationLayout->addWidget(hoursLabel, 2, 2); - durationLayout->addWidget(hoursEdit, 2, 3); - durationLayout->addWidget(minutesLabel, 2, 4); - durationLayout->addWidget(minutesEdit, 2, 5); - QGroupBox *durationGroupBox = new QGroupBox(tr("Duration of the ban")); - durationGroupBox->setLayout(durationLayout); - - QLabel *reasonLabel = new QLabel(tr("Please enter the reason for the ban.\nThis is only saved for moderators and cannot be seen by the banned person.")); - reasonEdit = new QPlainTextEdit; - - QLabel *visibleReasonLabel = new QLabel(tr("Please enter the reason for the ban that will be visible to the banned person.")); - visibleReasonEdit = new QPlainTextEdit; - - QPushButton *okButton = new QPushButton(tr("&OK")); - okButton->setAutoDefault(true); - connect(okButton, SIGNAL(clicked()), this, SLOT(okClicked())); - QPushButton *cancelButton = new QPushButton(tr("&Cancel")); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); - - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addStretch(); - buttonLayout->addWidget(okButton); - buttonLayout->addWidget(cancelButton); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(banTypeGroupBox); - vbox->addWidget(durationGroupBox); - vbox->addWidget(reasonLabel); - vbox->addWidget(reasonEdit); - vbox->addWidget(visibleReasonLabel); - vbox->addWidget(visibleReasonEdit); - vbox->addLayout(buttonLayout); - - setLayout(vbox); - setWindowTitle(tr("Ban user from server")); + setAttribute(Qt::WA_DeleteOnClose); + + nameBanCheckBox = new QCheckBox(tr("ban &user name")); + nameBanCheckBox->setChecked(true); + nameBanEdit = new QLineEdit(QString::fromStdString(info.name())); + ipBanCheckBox = new QCheckBox(tr("ban &IP address")); + ipBanCheckBox->setChecked(true); + ipBanEdit = new QLineEdit(QString::fromStdString(info.address())); + QGridLayout *banTypeGrid = new QGridLayout; + banTypeGrid->addWidget(nameBanCheckBox, 0, 0); + banTypeGrid->addWidget(nameBanEdit, 0, 1); + banTypeGrid->addWidget(ipBanCheckBox, 1, 0); + banTypeGrid->addWidget(ipBanEdit, 1, 1); + QGroupBox *banTypeGroupBox = new QGroupBox(tr("Ban type")); + banTypeGroupBox->setLayout(banTypeGrid); + + permanentRadio = new QRadioButton(tr("&permanent ban")); + temporaryRadio = new QRadioButton(tr("&temporary ban")); + temporaryRadio->setChecked(true); + connect(temporaryRadio, SIGNAL(toggled(bool)), this, SLOT(enableTemporaryEdits(bool))); + daysLabel = new QLabel(tr("&Days:")); + daysEdit = new QSpinBox; + daysEdit->setMinimum(0); + daysEdit->setValue(0); + daysEdit->setMaximum(10000); + daysLabel->setBuddy(daysEdit); + hoursLabel = new QLabel(tr("&Hours:")); + hoursEdit = new QSpinBox; + hoursEdit->setMinimum(0); + hoursEdit->setValue(0); + hoursEdit->setMaximum(24); + hoursLabel->setBuddy(hoursEdit); + minutesLabel = new QLabel(tr("&Minutes:")); + minutesEdit = new QSpinBox; + minutesEdit->setMinimum(0); + minutesEdit->setValue(5); + minutesEdit->setMaximum(60); + minutesLabel->setBuddy(minutesEdit); + QGridLayout *durationLayout = new QGridLayout; + durationLayout->addWidget(permanentRadio, 0, 0, 1, 6); + durationLayout->addWidget(temporaryRadio, 1, 0, 1, 6); + durationLayout->addWidget(daysLabel, 2, 0); + durationLayout->addWidget(daysEdit, 2, 1); + durationLayout->addWidget(hoursLabel, 2, 2); + durationLayout->addWidget(hoursEdit, 2, 3); + durationLayout->addWidget(minutesLabel, 2, 4); + durationLayout->addWidget(minutesEdit, 2, 5); + QGroupBox *durationGroupBox = new QGroupBox(tr("Duration of the ban")); + durationGroupBox->setLayout(durationLayout); + + QLabel *reasonLabel = new QLabel(tr("Please enter the reason for the ban.\nThis is only saved for moderators and cannot be seen by the banned person.")); + reasonEdit = new QPlainTextEdit; + + QLabel *visibleReasonLabel = new QLabel(tr("Please enter the reason for the ban that will be visible to the banned person.")); + visibleReasonEdit = new QPlainTextEdit; + + QPushButton *okButton = new QPushButton(tr("&OK")); + okButton->setAutoDefault(true); + connect(okButton, SIGNAL(clicked()), this, SLOT(okClicked())); + QPushButton *cancelButton = new QPushButton(tr("&Cancel")); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addStretch(); + buttonLayout->addWidget(okButton); + buttonLayout->addWidget(cancelButton); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(banTypeGroupBox); + vbox->addWidget(durationGroupBox); + vbox->addWidget(reasonLabel); + vbox->addWidget(reasonEdit); + vbox->addWidget(visibleReasonLabel); + vbox->addWidget(visibleReasonEdit); + vbox->addLayout(buttonLayout); + + setLayout(vbox); + setWindowTitle(tr("Ban user from server")); } void BanDialog::okClicked() { - if (!nameBanCheckBox->isChecked() && !ipBanCheckBox->isChecked()) { - QMessageBox::critical(this, tr("Error"), tr("You have to select a name-based or IP-based ban, or both.")); - return; - } - accept(); + if (!nameBanCheckBox->isChecked() && !ipBanCheckBox->isChecked()) { + QMessageBox::critical(this, tr("Error"), tr("You have to select a name-based or IP-based ban, or both.")); + return; + } + accept(); } void BanDialog::enableTemporaryEdits(bool enabled) { - daysLabel->setEnabled(enabled); - daysEdit->setEnabled(enabled); - hoursLabel->setEnabled(enabled); - hoursEdit->setEnabled(enabled); - minutesLabel->setEnabled(enabled); - minutesEdit->setEnabled(enabled); + daysLabel->setEnabled(enabled); + daysEdit->setEnabled(enabled); + hoursLabel->setEnabled(enabled); + hoursEdit->setEnabled(enabled); + minutesLabel->setEnabled(enabled); + minutesEdit->setEnabled(enabled); } QString BanDialog::getBanName() const { - return nameBanCheckBox->isChecked() ? nameBanEdit->text() : QString(); + return nameBanCheckBox->isChecked() ? nameBanEdit->text() : QString(); } QString BanDialog::getBanIP() const { - return ipBanCheckBox->isChecked() ? ipBanEdit->text() : QString(); + return ipBanCheckBox->isChecked() ? ipBanEdit->text() : QString(); } int BanDialog::getMinutes() const { - return permanentRadio->isChecked() ? 0 : (daysEdit->value() * 24 * 60 + hoursEdit->value() * 60 + minutesEdit->value()); + return permanentRadio->isChecked() ? 0 : (daysEdit->value() * 24 * 60 + hoursEdit->value() * 60 + minutesEdit->value()); } QString BanDialog::getReason() const { - return reasonEdit->toPlainText(); + return reasonEdit->toPlainText(); } QString BanDialog::getVisibleReason() const { - return visibleReasonEdit->toPlainText(); + return visibleReasonEdit->toPlainText(); } UserListItemDelegate::UserListItemDelegate(QObject *const parent) - : QStyledItemDelegate(parent) + : QStyledItemDelegate(parent) { } bool UserListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { - if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { - QMouseEvent *const mouseEvent = static_cast(event); - if (mouseEvent->button() == Qt::RightButton) { - static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); - return true; - } - } - return QStyledItemDelegate::editorEvent(event, model, option, index); + if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { + QMouseEvent *const mouseEvent = static_cast(event); + if (mouseEvent->button() == Qt::RightButton) { + static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); + return true; + } + } + return QStyledItemDelegate::editorEvent(event, model, option, index); } UserListTWI::UserListTWI(const ServerInfo_User &_userInfo) - : QTreeWidgetItem(Type) + : QTreeWidgetItem(Type) { - setUserInfo(_userInfo); + setUserInfo(_userInfo); } void UserListTWI::setUserInfo(const ServerInfo_User &_userInfo) { - userInfo = _userInfo; + userInfo = _userInfo; - setData(0, Qt::UserRole, userInfo.user_level()); - setIcon(0, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(userInfo.user_level())))); - setIcon(1, QIcon(CountryPixmapGenerator::generatePixmap(12, QString::fromStdString(userInfo.country())))); - setData(2, Qt::UserRole, QString::fromStdString(userInfo.name())); - setData(2, Qt::DisplayRole, QString::fromStdString(userInfo.name())); + setData(0, Qt::UserRole, userInfo.user_level()); + setIcon(0, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(userInfo.user_level())))); + setIcon(1, QIcon(CountryPixmapGenerator::generatePixmap(12, QString::fromStdString(userInfo.country())))); + setData(2, Qt::UserRole, QString::fromStdString(userInfo.name())); + setData(2, Qt::DisplayRole, QString::fromStdString(userInfo.name())); } void UserListTWI::setOnline(bool online) { - setData(0, Qt::UserRole + 1, online); - setData(2, Qt::ForegroundRole, online ? QBrush() : QBrush(Qt::gray)); + setData(0, Qt::UserRole + 1, online); + setData(2, Qt::ForegroundRole, online ? QBrush() : QBrush(Qt::gray)); } bool UserListTWI::operator<(const QTreeWidgetItem &other) const { - // Sort by online/offline - if (data(0, Qt::UserRole + 1) != other.data(0, Qt::UserRole + 1)) - return data(0, Qt::UserRole + 1).toBool(); - - // Sort by user level - if (data(0, Qt::UserRole) != other.data(0, Qt::UserRole)) - return data(0, Qt::UserRole).toInt() > other.data(0, Qt::UserRole).toInt(); - - // Sort by name - return QString::localeAwareCompare(data(2, Qt::UserRole).toString(), other.data(2, Qt::UserRole).toString()) < 0; + // Sort by online/offline + if (data(0, Qt::UserRole + 1) != other.data(0, Qt::UserRole + 1)) + return data(0, Qt::UserRole + 1).toBool(); + + // Sort by user level + if (data(0, Qt::UserRole) != other.data(0, Qt::UserRole)) + return data(0, Qt::UserRole).toInt() > other.data(0, Qt::UserRole).toInt(); + + // Sort by name + return QString::localeAwareCompare(data(2, Qt::UserRole).toString(), other.data(2, Qt::UserRole).toString()) < 0; } UserList::UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserListType _type, QWidget *parent) - : QGroupBox(parent), tabSupervisor(_tabSupervisor), client(_client), type(_type), onlineCount(0) + : QGroupBox(parent), tabSupervisor(_tabSupervisor), client(_client), type(_type), onlineCount(0) { - itemDelegate = new UserListItemDelegate(this); - userContextMenu = new UserContextMenu(tabSupervisor, this); - connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - - userTree = new QTreeWidget; - userTree->setColumnCount(3); - userTree->header()->setResizeMode(QHeaderView::ResizeToContents); - userTree->setHeaderHidden(true); - userTree->setRootIsDecorated(false); - userTree->setIconSize(QSize(20, 12)); - userTree->setItemDelegate(itemDelegate); - userTree->setAlternatingRowColors(true); - connect(userTree, SIGNAL(itemActivated(QTreeWidgetItem *, int)), this, SLOT(userClicked(QTreeWidgetItem *, int))); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(userTree); - - setLayout(vbox); - - retranslateUi(); + itemDelegate = new UserListItemDelegate(this); + userContextMenu = new UserContextMenu(tabSupervisor, this); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + + userTree = new QTreeWidget; + userTree->setColumnCount(3); + userTree->header()->setResizeMode(QHeaderView::ResizeToContents); + userTree->setHeaderHidden(true); + userTree->setRootIsDecorated(false); + userTree->setIconSize(QSize(20, 12)); + userTree->setItemDelegate(itemDelegate); + userTree->setAlternatingRowColors(true); + connect(userTree, SIGNAL(itemActivated(QTreeWidgetItem *, int)), this, SLOT(userClicked(QTreeWidgetItem *, int))); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(userTree); + + setLayout(vbox); + + retranslateUi(); } void UserList::retranslateUi() { - userContextMenu->retranslateUi(); - switch (type) { - case AllUsersList: titleStr = tr("Users online: %1"); break; - case RoomList: titleStr = tr("Users in this room: %1"); break; - case BuddyList: titleStr = tr("Buddies online: %1 / %2"); break; - case IgnoreList: titleStr = tr("Ignored users online: %1 / %2"); break; - } - updateCount(); + userContextMenu->retranslateUi(); + switch (type) { + case AllUsersList: titleStr = tr("Users online: %1"); break; + case RoomList: titleStr = tr("Users in this room: %1"); break; + case BuddyList: titleStr = tr("Buddies online: %1 / %2"); break; + case IgnoreList: titleStr = tr("Ignored users online: %1 / %2"); break; + } + updateCount(); } void UserList::processUserInfo(const ServerInfo_User &user, bool online) { - const QString userName = QString::fromStdString(user.name()); - UserListTWI *item = users.value(userName); - if (item) - item->setUserInfo(user); - else { - item = new UserListTWI(user); - users.insert(userName, item); - userTree->addTopLevelItem(item); - if (online) - ++onlineCount; - updateCount(); - } - item->setOnline(online); + const QString userName = QString::fromStdString(user.name()); + UserListTWI *item = users.value(userName); + if (item) + item->setUserInfo(user); + else { + item = new UserListTWI(user); + users.insert(userName, item); + userTree->addTopLevelItem(item); + if (online) + ++onlineCount; + updateCount(); + } + item->setOnline(online); } bool UserList::deleteUser(const QString &userName) { - UserListTWI *twi = users.value(userName); - if (twi) { - users.remove(userName); - userTree->takeTopLevelItem(userTree->indexOfTopLevelItem(twi)); - if (twi->data(0, Qt::UserRole + 1).toBool()) - --onlineCount; - delete twi; - updateCount(); - return true; - } - - return false; + UserListTWI *twi = users.value(userName); + if (twi) { + users.remove(userName); + userTree->takeTopLevelItem(userTree->indexOfTopLevelItem(twi)); + if (twi->data(0, Qt::UserRole + 1).toBool()) + --onlineCount; + delete twi; + updateCount(); + return true; + } + + return false; } void UserList::setUserOnline(const QString &userName, bool online) { - UserListTWI *twi = users.value(userName); - if (!twi) - return; - - twi->setOnline(online); - if (online) - ++onlineCount; - else - --onlineCount; - updateCount(); + UserListTWI *twi = users.value(userName); + if (!twi) + return; + + twi->setOnline(online); + if (online) + ++onlineCount; + else + --onlineCount; + updateCount(); } void UserList::updateCount() { - QString str = titleStr; - if ((type == BuddyList) || (type == IgnoreList)) - str = str.arg(onlineCount); - setTitle(str.arg(userTree->topLevelItemCount())); + QString str = titleStr; + if ((type == BuddyList) || (type == IgnoreList)) + str = str.arg(onlineCount); + setTitle(str.arg(userTree->topLevelItemCount())); } void UserList::userClicked(QTreeWidgetItem *item, int /*column*/) { - emit openMessageDialog(item->data(2, Qt::UserRole).toString(), true); + emit openMessageDialog(item->data(2, Qt::UserRole).toString(), true); } void UserList::showContextMenu(const QPoint &pos, const QModelIndex &index) { - const ServerInfo_User &userInfo = static_cast(userTree->topLevelItem(index.row()))->getUserInfo(); - - userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level())); + const ServerInfo_User &userInfo = static_cast(userTree->topLevelItem(index.row()))->getUserInfo(); + + userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level())); } void UserList::sortItems() { - userTree->sortItems(1, Qt::AscendingOrder); + userTree->sortItems(1, Qt::AscendingOrder); } diff --git a/cockatrice/src/userlist.h b/cockatrice/src/userlist.h index 001db621..fc043b1d 100644 --- a/cockatrice/src/userlist.h +++ b/cockatrice/src/userlist.h @@ -21,75 +21,75 @@ class CommandContainer; class UserContextMenu; class BanDialog : public QDialog { - Q_OBJECT + Q_OBJECT private: - QLabel *daysLabel, *hoursLabel, *minutesLabel; - QCheckBox *nameBanCheckBox, *ipBanCheckBox; - QLineEdit *nameBanEdit, *ipBanEdit; - QSpinBox *daysEdit, *hoursEdit, *minutesEdit; - QRadioButton *permanentRadio, *temporaryRadio; - QPlainTextEdit *reasonEdit, *visibleReasonEdit; + QLabel *daysLabel, *hoursLabel, *minutesLabel; + QCheckBox *nameBanCheckBox, *ipBanCheckBox; + QLineEdit *nameBanEdit, *ipBanEdit; + QSpinBox *daysEdit, *hoursEdit, *minutesEdit; + QRadioButton *permanentRadio, *temporaryRadio; + QPlainTextEdit *reasonEdit, *visibleReasonEdit; private slots: - void okClicked(); - void enableTemporaryEdits(bool enabled); + void okClicked(); + void enableTemporaryEdits(bool enabled); public: - BanDialog(const ServerInfo_User &info, QWidget *parent = 0); - QString getBanName() const; - QString getBanIP() const; - int getMinutes() const; - QString getReason() const; - QString getVisibleReason() const; + BanDialog(const ServerInfo_User &info, QWidget *parent = 0); + QString getBanName() const; + QString getBanIP() const; + int getMinutes() const; + QString getReason() const; + QString getVisibleReason() const; }; class UserListItemDelegate : public QStyledItemDelegate { public: - UserListItemDelegate(QObject *const parent); - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); + UserListItemDelegate(QObject *const parent); + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; class UserListTWI : public QTreeWidgetItem { private: - ServerInfo_User userInfo; + ServerInfo_User userInfo; public: - UserListTWI(const ServerInfo_User &_userInfo); - const ServerInfo_User &getUserInfo() const { return userInfo; } - void setUserInfo(const ServerInfo_User &_userInfo); - void setOnline(bool online); - bool operator<(const QTreeWidgetItem &other) const; + UserListTWI(const ServerInfo_User &_userInfo); + const ServerInfo_User &getUserInfo() const { return userInfo; } + void setUserInfo(const ServerInfo_User &_userInfo); + void setOnline(bool online); + bool operator<(const QTreeWidgetItem &other) const; }; class UserList : public QGroupBox { - Q_OBJECT + Q_OBJECT public: - enum UserListType { AllUsersList, RoomList, BuddyList, IgnoreList }; + enum UserListType { AllUsersList, RoomList, BuddyList, IgnoreList }; private: - QMap users; - TabSupervisor *tabSupervisor; - AbstractClient *client; - UserListType type; - QTreeWidget *userTree; - UserListItemDelegate *itemDelegate; - UserContextMenu *userContextMenu; - int onlineCount; - QString titleStr; - void updateCount(); + QMap users; + TabSupervisor *tabSupervisor; + AbstractClient *client; + UserListType type; + QTreeWidget *userTree; + UserListItemDelegate *itemDelegate; + UserContextMenu *userContextMenu; + int onlineCount; + QString titleStr; + void updateCount(); private slots: - void userClicked(QTreeWidgetItem *item, int column); + void userClicked(QTreeWidgetItem *item, int column); signals: - void openMessageDialog(const QString &userName, bool focus); - void addBuddy(const QString &userName); - void removeBuddy(const QString &userName); - void addIgnore(const QString &userName); - void removeIgnore(const QString &userName); + void openMessageDialog(const QString &userName, bool focus); + void addBuddy(const QString &userName); + void removeBuddy(const QString &userName); + void addIgnore(const QString &userName); + void removeIgnore(const QString &userName); public: - UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserListType _type, QWidget *parent = 0); - void retranslateUi(); - void processUserInfo(const ServerInfo_User &user, bool online); - bool deleteUser(const QString &userName); - void setUserOnline(const QString &userName, bool online); - const QMap &getUsers() const { return users; } - void showContextMenu(const QPoint &pos, const QModelIndex &index); - void sortItems(); + UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserListType _type, QWidget *parent = 0); + void retranslateUi(); + void processUserInfo(const ServerInfo_User &user, bool online); + bool deleteUser(const QString &userName); + void setUserOnline(const QString &userName, bool online); + const QMap &getUsers() const { return users; } + void showContextMenu(const QPoint &pos, const QModelIndex &index); + void sortItems(); }; #endif diff --git a/cockatrice/src/window_main.cpp b/cockatrice/src/window_main.cpp index f3d20e19..f5dc2684 100644 --- a/cockatrice/src/window_main.cpp +++ b/cockatrice/src/window_main.cpp @@ -52,369 +52,369 @@ const QString MainWindow::appName = "Cockatrice"; void MainWindow::updateTabMenu(const QList &newMenuList) { - for (int i = 0; i < tabMenus.size(); ++i) - menuBar()->removeAction(tabMenus[i]->menuAction()); - tabMenus = newMenuList; - for (int i = 0; i < tabMenus.size(); ++i) - menuBar()->insertMenu(helpMenu->menuAction(), tabMenus[i]); + for (int i = 0; i < tabMenus.size(); ++i) + menuBar()->removeAction(tabMenus[i]->menuAction()); + tabMenus = newMenuList; + for (int i = 0; i < tabMenus.size(); ++i) + menuBar()->insertMenu(helpMenu->menuAction(), tabMenus[i]); } void MainWindow::processConnectionClosedEvent(const Event_ConnectionClosed &event) { - client->disconnectFromServer(); - QString reasonStr; - switch (event.reason()) { - case Event_ConnectionClosed::TOO_MANY_CONNECTIONS: reasonStr = tr("There are too many concurrent connections from your address."); break; - case Event_ConnectionClosed::BANNED: { - reasonStr = tr("Banned by moderator"); - if (event.has_end_time()) - reasonStr.append("\n" + tr("Expected end time: %1").arg(QDateTime::fromTime_t(event.end_time()).toString())); - else - reasonStr.append("\n" + tr("This ban lasts indefinitely.")); - if (event.has_reason_str()) - reasonStr.append("\n\n" + QString::fromStdString(event.reason_str())); - break; - } - case Event_ConnectionClosed::SERVER_SHUTDOWN: reasonStr = tr("Scheduled server shutdown."); break; - case Event_ConnectionClosed::USERNAMEINVALID: reasonStr = tr("Invalid username."); break; - default: reasonStr = QString::fromStdString(event.reason_str()); - } - QMessageBox::critical(this, tr("Connection closed"), tr("The server has terminated your connection.\nReason: %1").arg(reasonStr)); + client->disconnectFromServer(); + QString reasonStr; + switch (event.reason()) { + case Event_ConnectionClosed::TOO_MANY_CONNECTIONS: reasonStr = tr("There are too many concurrent connections from your address."); break; + case Event_ConnectionClosed::BANNED: { + reasonStr = tr("Banned by moderator"); + if (event.has_end_time()) + reasonStr.append("\n" + tr("Expected end time: %1").arg(QDateTime::fromTime_t(event.end_time()).toString())); + else + reasonStr.append("\n" + tr("This ban lasts indefinitely.")); + if (event.has_reason_str()) + reasonStr.append("\n\n" + QString::fromStdString(event.reason_str())); + break; + } + case Event_ConnectionClosed::SERVER_SHUTDOWN: reasonStr = tr("Scheduled server shutdown."); break; + case Event_ConnectionClosed::USERNAMEINVALID: reasonStr = tr("Invalid username."); break; + default: reasonStr = QString::fromStdString(event.reason_str()); + } + QMessageBox::critical(this, tr("Connection closed"), tr("The server has terminated your connection.\nReason: %1").arg(reasonStr)); } void MainWindow::processServerShutdownEvent(const Event_ServerShutdown &event) { - QMessageBox::information(this, tr("Scheduled server shutdown"), tr("The server is going to be restarted in %n minute(s).\nAll running games will be lost.\nReason for shutdown: %1", "", event.minutes()).arg(QString::fromStdString(event.reason()))); + QMessageBox::information(this, tr("Scheduled server shutdown"), tr("The server is going to be restarted in %n minute(s).\nAll running games will be lost.\nReason for shutdown: %1", "", event.minutes()).arg(QString::fromStdString(event.reason()))); } void MainWindow::statusChanged(ClientStatus _status) { - setClientStatusTitle(); - switch (_status) { - case StatusConnecting: - break; - case StatusDisconnected: - tabSupervisor->stop(); - aSinglePlayer->setEnabled(true); - aConnect->setEnabled(true); - aDisconnect->setEnabled(false); - break; - case StatusLoggingIn: - aSinglePlayer->setEnabled(false); - aConnect->setEnabled(false); - aDisconnect->setEnabled(true); - break; - case StatusLoggedIn: - break; - default: - break; - } + setClientStatusTitle(); + switch (_status) { + case StatusConnecting: + break; + case StatusDisconnected: + tabSupervisor->stop(); + aSinglePlayer->setEnabled(true); + aConnect->setEnabled(true); + aDisconnect->setEnabled(false); + break; + case StatusLoggingIn: + aSinglePlayer->setEnabled(false); + aConnect->setEnabled(false); + aDisconnect->setEnabled(true); + break; + case StatusLoggedIn: + break; + default: + break; + } } void MainWindow::userInfoReceived(const ServerInfo_User &info) { - tabSupervisor->start(info); + tabSupervisor->start(info); } // Actions void MainWindow::actConnect() { - DlgConnect dlg(this); - if (dlg.exec()) - client->connectToServer(dlg.getHost(), dlg.getPort(), dlg.getPlayerName(), dlg.getPassword()); + DlgConnect dlg(this); + if (dlg.exec()) + client->connectToServer(dlg.getHost(), dlg.getPort(), dlg.getPlayerName(), dlg.getPassword()); } void MainWindow::actDisconnect() { - client->disconnectFromServer(); + client->disconnectFromServer(); } void MainWindow::actSinglePlayer() { - bool ok; - int numberPlayers = QInputDialog::getInt(this, tr("Number of players"), tr("Please enter the number of players."), 2, 1, 8, 1, &ok); - if (!ok) - return; - - aConnect->setEnabled(false); - aSinglePlayer->setEnabled(false); - - localServer = new LocalServer(this); - LocalServerInterface *mainLsi = localServer->newConnection(); - LocalClient *mainClient = new LocalClient(mainLsi, tr("Player %1").arg(1), this); - QList localClients; - localClients.append(mainClient); - - for (int i = 0; i < numberPlayers - 1; ++i) { - LocalServerInterface *slaveLsi = localServer->newConnection(); - LocalClient *slaveClient = new LocalClient(slaveLsi, tr("Player %1").arg(i + 2), this); - localClients.append(slaveClient); - } - tabSupervisor->startLocal(localClients); - - Command_CreateGame createCommand; - createCommand.set_max_players(numberPlayers); - mainClient->sendCommand(mainClient->prepareRoomCommand(createCommand, 0)); + bool ok; + int numberPlayers = QInputDialog::getInt(this, tr("Number of players"), tr("Please enter the number of players."), 2, 1, 8, 1, &ok); + if (!ok) + return; + + aConnect->setEnabled(false); + aSinglePlayer->setEnabled(false); + + localServer = new LocalServer(this); + LocalServerInterface *mainLsi = localServer->newConnection(); + LocalClient *mainClient = new LocalClient(mainLsi, tr("Player %1").arg(1), this); + QList localClients; + localClients.append(mainClient); + + for (int i = 0; i < numberPlayers - 1; ++i) { + LocalServerInterface *slaveLsi = localServer->newConnection(); + LocalClient *slaveClient = new LocalClient(slaveLsi, tr("Player %1").arg(i + 2), this); + localClients.append(slaveClient); + } + tabSupervisor->startLocal(localClients); + + Command_CreateGame createCommand; + createCommand.set_max_players(numberPlayers); + mainClient->sendCommand(mainClient->prepareRoomCommand(createCommand, 0)); } void MainWindow::actWatchReplay() { - QFileDialog dlg(this, tr("Load replay")); - dlg.setDirectory(settingsCache->getReplaysPath()); - dlg.setNameFilters(QStringList() << QObject::tr("Cockatrice replays (*.cor)")); - if (!dlg.exec()) - return; - - QString fileName = dlg.selectedFiles().at(0); - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly)) - return; - QByteArray buf = file.readAll(); - file.close(); - - GameReplay *replay = new GameReplay; - replay->ParseFromArray(buf.data(), buf.size()); - - tabSupervisor->openReplay(replay); + QFileDialog dlg(this, tr("Load replay")); + dlg.setDirectory(settingsCache->getReplaysPath()); + dlg.setNameFilters(QStringList() << QObject::tr("Cockatrice replays (*.cor)")); + if (!dlg.exec()) + return; + + QString fileName = dlg.selectedFiles().at(0); + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly)) + return; + QByteArray buf = file.readAll(); + file.close(); + + GameReplay *replay = new GameReplay; + replay->ParseFromArray(buf.data(), buf.size()); + + tabSupervisor->openReplay(replay); } void MainWindow::localGameEnded() { - delete localServer; - localServer = 0; - - aConnect->setEnabled(true); - aSinglePlayer->setEnabled(true); + delete localServer; + localServer = 0; + + aConnect->setEnabled(true); + aSinglePlayer->setEnabled(true); } void MainWindow::actDeckEditor() { - tabSupervisor->addDeckEditorTab(0); + tabSupervisor->addDeckEditorTab(0); } void MainWindow::actFullScreen(bool checked) { - if (checked) - setWindowState(windowState() | Qt::WindowFullScreen); - else - setWindowState(windowState() & ~Qt::WindowFullScreen); + if (checked) + setWindowState(windowState() | Qt::WindowFullScreen); + else + setWindowState(windowState() & ~Qt::WindowFullScreen); } void MainWindow::actSettings() { - DlgSettings dlg(this); - dlg.exec(); + DlgSettings dlg(this); + dlg.exec(); } void MainWindow::actExit() { - close(); + close(); } void MainWindow::actAbout() { - QMessageBox::about(this, tr("About Cockatrice"), QString( - "Cockatrice
" - + tr("Version %1").arg(VERSION_STRING) - + "


" + tr("Authors:") + "
Max-Wilhelm Bruker
Marcus Schütz

" - + "" + tr("Translators:") + "
" - + tr("Spanish:") + " Víctor Martínez
" - + tr("Portugese (Portugal):") + " Milton Gonçalves
" - + tr("Portugese (Brazil):") + " Thiago Queiroz
" - + tr("French:") + " Yannick Hammer, Arnaud Faes
" - + tr("Japanese:") + " Nagase Task
" - + tr("Russian:") + " Alexander Davidov
" -// + tr("Czech:") + " Ondřej Trhoň
" -// + tr("Slovak:") + " Ganjalf Rendy
" - + tr("Italian:") + " Luigi Sciolla
" - + tr("Swedish:") + " Jessica Dahl
" - )); + QMessageBox::about(this, tr("About Cockatrice"), QString( + "Cockatrice
" + + tr("Version %1").arg(VERSION_STRING) + + "


" + tr("Authors:") + "
Max-Wilhelm Bruker
Marcus Schütz

" + + "" + tr("Translators:") + "
" + + tr("Spanish:") + " Víctor Martínez
" + + tr("Portugese (Portugal):") + " Milton Gonçalves
" + + tr("Portugese (Brazil):") + " Thiago Queiroz
" + + tr("French:") + " Yannick Hammer, Arnaud Faes
" + + tr("Japanese:") + " Nagase Task
" + + tr("Russian:") + " Alexander Davidov
" +// + tr("Czech:") + " Ondřej Trhoň
" +// + tr("Slovak:") + " Ganjalf Rendy
" + + tr("Italian:") + " Luigi Sciolla
" + + tr("Swedish:") + " Jessica Dahl
" + )); } void MainWindow::serverTimeout() { - QMessageBox::critical(this, tr("Error"), tr("Server timeout")); + QMessageBox::critical(this, tr("Error"), tr("Server timeout")); } void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime) { - switch (r) { - case Response::RespWrongPassword: - QMessageBox::critical(this, tr("Error"), tr("Invalid login data.")); - break; - case Response::RespWouldOverwriteOldSession: - QMessageBox::critical(this, tr("Error"), tr("There is already an active session using this user name.\nPlease close that session first and re-login.")); - break; - case Response::RespUserIsBanned: { - QString bannedStr; - if (endTime) - bannedStr = tr("You are banned until %1.").arg(QDateTime::fromTime_t(endTime).toString()); - else - bannedStr = tr("You are banned indefinitely."); - if (!reasonStr.isEmpty()) - bannedStr.append("\n\n" + reasonStr); - - QMessageBox::critical(this, tr("Error"), bannedStr); - break; - } - case Response::RespUsernameInvalid: - QMessageBox::critical(this, tr("Error"), tr("Invalid username.")); - break; - default: - QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast(r))); - } + switch (r) { + case Response::RespWrongPassword: + QMessageBox::critical(this, tr("Error"), tr("Invalid login data.")); + break; + case Response::RespWouldOverwriteOldSession: + QMessageBox::critical(this, tr("Error"), tr("There is already an active session using this user name.\nPlease close that session first and re-login.")); + break; + case Response::RespUserIsBanned: { + QString bannedStr; + if (endTime) + bannedStr = tr("You are banned until %1.").arg(QDateTime::fromTime_t(endTime).toString()); + else + bannedStr = tr("You are banned indefinitely."); + if (!reasonStr.isEmpty()) + bannedStr.append("\n\n" + reasonStr); + + QMessageBox::critical(this, tr("Error"), bannedStr); + break; + } + case Response::RespUsernameInvalid: + QMessageBox::critical(this, tr("Error"), tr("Invalid username.")); + break; + default: + QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast(r))); + } } void MainWindow::socketError(const QString &errorStr) { - QMessageBox::critical(this, tr("Error"), tr("Socket error: %1").arg(errorStr)); + QMessageBox::critical(this, tr("Error"), tr("Socket error: %1").arg(errorStr)); } void MainWindow::protocolVersionMismatch(int localVersion, int remoteVersion) { - if (localVersion > remoteVersion) - QMessageBox::critical(this, tr("Error"), tr("You are trying to connect to an obsolete server. Please downgrade your Cockatrice version or connect to a suitable server.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); - else - QMessageBox::critical(this, tr("Error"), tr("Your Cockatrice client is obsolete. Please update your Cockatrice version.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); + if (localVersion > remoteVersion) + QMessageBox::critical(this, tr("Error"), tr("You are trying to connect to an obsolete server. Please downgrade your Cockatrice version or connect to a suitable server.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); + else + QMessageBox::critical(this, tr("Error"), tr("Your Cockatrice client is obsolete. Please update your Cockatrice version.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); } void MainWindow::setClientStatusTitle() { - switch (client->getStatus()) { - case StatusConnecting: setWindowTitle(appName + " - " + tr("Connecting to %1...").arg(client->peerName())); break; - case StatusDisconnected: setWindowTitle(appName + " - " + tr("Disconnected")); break; - case StatusLoggingIn: setWindowTitle(appName + " - " + tr("Connected, logging in at %1").arg(client->peerName())); break; - case StatusLoggedIn: setWindowTitle(appName + " - " + tr("Logged in at %1").arg(client->peerName())); break; - default: setWindowTitle(appName); - } + switch (client->getStatus()) { + case StatusConnecting: setWindowTitle(appName + " - " + tr("Connecting to %1...").arg(client->peerName())); break; + case StatusDisconnected: setWindowTitle(appName + " - " + tr("Disconnected")); break; + case StatusLoggingIn: setWindowTitle(appName + " - " + tr("Connected, logging in at %1").arg(client->peerName())); break; + case StatusLoggedIn: setWindowTitle(appName + " - " + tr("Logged in at %1").arg(client->peerName())); break; + default: setWindowTitle(appName); + } } void MainWindow::retranslateUi() { - setClientStatusTitle(); - - aConnect->setText(tr("&Connect...")); - aDisconnect->setText(tr("&Disconnect")); - aSinglePlayer->setText(tr("Start &local game...")); - aWatchReplay->setText(tr("&Watch replay...")); - aDeckEditor->setText(tr("&Deck editor")); - aFullScreen->setText(tr("&Full screen")); - aFullScreen->setShortcut(tr("Ctrl+F")); - aSettings->setText(tr("&Settings...")); - aExit->setText(tr("&Exit")); - - cockatriceMenu->setTitle(tr("&Cockatrice")); - - aAbout->setText(tr("&About Cockatrice")); - helpMenu->setTitle(tr("&Help")); - - tabSupervisor->retranslateUi(); + setClientStatusTitle(); + + aConnect->setText(tr("&Connect...")); + aDisconnect->setText(tr("&Disconnect")); + aSinglePlayer->setText(tr("Start &local game...")); + aWatchReplay->setText(tr("&Watch replay...")); + aDeckEditor->setText(tr("&Deck editor")); + aFullScreen->setText(tr("&Full screen")); + aFullScreen->setShortcut(tr("Ctrl+F")); + aSettings->setText(tr("&Settings...")); + aExit->setText(tr("&Exit")); + + cockatriceMenu->setTitle(tr("&Cockatrice")); + + aAbout->setText(tr("&About Cockatrice")); + helpMenu->setTitle(tr("&Help")); + + tabSupervisor->retranslateUi(); } void MainWindow::createActions() { - aConnect = new QAction(this); - connect(aConnect, SIGNAL(triggered()), this, SLOT(actConnect())); - aDisconnect = new QAction(this); - aDisconnect->setEnabled(false); - connect(aDisconnect, SIGNAL(triggered()), this, SLOT(actDisconnect())); - aSinglePlayer = new QAction(this); - connect(aSinglePlayer, SIGNAL(triggered()), this, SLOT(actSinglePlayer())); - aWatchReplay = new QAction(this); - connect(aWatchReplay, SIGNAL(triggered()), this, SLOT(actWatchReplay())); - aDeckEditor = new QAction(this); - connect(aDeckEditor, SIGNAL(triggered()), this, SLOT(actDeckEditor())); - aFullScreen = new QAction(this); - aFullScreen->setCheckable(true); - connect(aFullScreen, SIGNAL(toggled(bool)), this, SLOT(actFullScreen(bool))); - aSettings = new QAction(this); - connect(aSettings, SIGNAL(triggered()), this, SLOT(actSettings())); - aExit = new QAction(this); - connect(aExit, SIGNAL(triggered()), this, SLOT(actExit())); - - aAbout = new QAction(this); - connect(aAbout, SIGNAL(triggered()), this, SLOT(actAbout())); + aConnect = new QAction(this); + connect(aConnect, SIGNAL(triggered()), this, SLOT(actConnect())); + aDisconnect = new QAction(this); + aDisconnect->setEnabled(false); + connect(aDisconnect, SIGNAL(triggered()), this, SLOT(actDisconnect())); + aSinglePlayer = new QAction(this); + connect(aSinglePlayer, SIGNAL(triggered()), this, SLOT(actSinglePlayer())); + aWatchReplay = new QAction(this); + connect(aWatchReplay, SIGNAL(triggered()), this, SLOT(actWatchReplay())); + aDeckEditor = new QAction(this); + connect(aDeckEditor, SIGNAL(triggered()), this, SLOT(actDeckEditor())); + aFullScreen = new QAction(this); + aFullScreen->setCheckable(true); + connect(aFullScreen, SIGNAL(toggled(bool)), this, SLOT(actFullScreen(bool))); + aSettings = new QAction(this); + connect(aSettings, SIGNAL(triggered()), this, SLOT(actSettings())); + aExit = new QAction(this); + connect(aExit, SIGNAL(triggered()), this, SLOT(actExit())); + + aAbout = new QAction(this); + connect(aAbout, SIGNAL(triggered()), this, SLOT(actAbout())); } void MainWindow::createMenus() { - cockatriceMenu = menuBar()->addMenu(QString()); - cockatriceMenu->addAction(aConnect); - cockatriceMenu->addAction(aDisconnect); - cockatriceMenu->addAction(aSinglePlayer); - cockatriceMenu->addAction(aWatchReplay); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aDeckEditor); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aFullScreen); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aSettings); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aExit); - - helpMenu = menuBar()->addMenu(QString()); - helpMenu->addAction(aAbout); + cockatriceMenu = menuBar()->addMenu(QString()); + cockatriceMenu->addAction(aConnect); + cockatriceMenu->addAction(aDisconnect); + cockatriceMenu->addAction(aSinglePlayer); + cockatriceMenu->addAction(aWatchReplay); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aDeckEditor); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aFullScreen); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aSettings); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aExit); + + helpMenu = menuBar()->addMenu(QString()); + helpMenu->addAction(aAbout); } MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), localServer(0) + : QMainWindow(parent), localServer(0) { - QPixmapCache::setCacheLimit(200000); + QPixmapCache::setCacheLimit(200000); - client = new RemoteClient; - connect(client, SIGNAL(connectionClosedEventReceived(const Event_ConnectionClosed &)), this, SLOT(processConnectionClosedEvent(const Event_ConnectionClosed &))); - connect(client, SIGNAL(serverShutdownEventReceived(const Event_ServerShutdown &)), this, SLOT(processServerShutdownEvent(const Event_ServerShutdown &))); - connect(client, SIGNAL(loginError(Response::ResponseCode, QString, quint32)), this, SLOT(loginError(Response::ResponseCode, QString, quint32))); - connect(client, SIGNAL(socketError(const QString &)), this, SLOT(socketError(const QString &))); - connect(client, SIGNAL(serverTimeout()), this, SLOT(serverTimeout())); - connect(client, SIGNAL(statusChanged(ClientStatus)), this, SLOT(statusChanged(ClientStatus))); - connect(client, SIGNAL(protocolVersionMismatch(int, int)), this, SLOT(protocolVersionMismatch(int, int))); - connect(client, SIGNAL(userInfoChanged(const ServerInfo_User &)), this, SLOT(userInfoReceived(const ServerInfo_User &)), Qt::BlockingQueuedConnection); - - clientThread = new QThread(this); - client->moveToThread(clientThread); - clientThread->start(); + client = new RemoteClient; + connect(client, SIGNAL(connectionClosedEventReceived(const Event_ConnectionClosed &)), this, SLOT(processConnectionClosedEvent(const Event_ConnectionClosed &))); + connect(client, SIGNAL(serverShutdownEventReceived(const Event_ServerShutdown &)), this, SLOT(processServerShutdownEvent(const Event_ServerShutdown &))); + connect(client, SIGNAL(loginError(Response::ResponseCode, QString, quint32)), this, SLOT(loginError(Response::ResponseCode, QString, quint32))); + connect(client, SIGNAL(socketError(const QString &)), this, SLOT(socketError(const QString &))); + connect(client, SIGNAL(serverTimeout()), this, SLOT(serverTimeout())); + connect(client, SIGNAL(statusChanged(ClientStatus)), this, SLOT(statusChanged(ClientStatus))); + connect(client, SIGNAL(protocolVersionMismatch(int, int)), this, SLOT(protocolVersionMismatch(int, int))); + connect(client, SIGNAL(userInfoChanged(const ServerInfo_User &)), this, SLOT(userInfoReceived(const ServerInfo_User &)), Qt::BlockingQueuedConnection); + + clientThread = new QThread(this); + client->moveToThread(clientThread); + clientThread->start(); - createActions(); - createMenus(); - - tabSupervisor = new TabSupervisor(client); - connect(tabSupervisor, SIGNAL(setMenu(QList)), this, SLOT(updateTabMenu(QList))); - connect(tabSupervisor, SIGNAL(localGameEnded()), this, SLOT(localGameEnded())); - tabSupervisor->addDeckEditorTab(0); - - setCentralWidget(tabSupervisor); + createActions(); + createMenus(); + + tabSupervisor = new TabSupervisor(client); + connect(tabSupervisor, SIGNAL(setMenu(QList)), this, SLOT(updateTabMenu(QList))); + connect(tabSupervisor, SIGNAL(localGameEnded()), this, SLOT(localGameEnded())); + tabSupervisor->addDeckEditorTab(0); + + setCentralWidget(tabSupervisor); - retranslateUi(); - - resize(900, 700); - restoreGeometry(settingsCache->getMainWindowGeometry()); - aFullScreen->setChecked(windowState() & Qt::WindowFullScreen); + retranslateUi(); + + resize(900, 700); + restoreGeometry(settingsCache->getMainWindowGeometry()); + aFullScreen->setChecked(windowState() & Qt::WindowFullScreen); } MainWindow::~MainWindow() { - client->deleteLater(); - clientThread->wait(); + client->deleteLater(); + clientThread->wait(); } void MainWindow::closeEvent(QCloseEvent *event) { - if (tabSupervisor->getGameCount()) { - if (QMessageBox::question(this, tr("Are you sure?"), tr("There are still open games. Are you sure you want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { - event->ignore(); - return; - } - } - event->accept(); - settingsCache->setMainWindowGeometry(saveGeometry()); - delete tabSupervisor; + if (tabSupervisor->getGameCount()) { + if (QMessageBox::question(this, tr("Are you sure?"), tr("There are still open games. Are you sure you want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { + event->ignore(); + return; + } + } + event->accept(); + settingsCache->setMainWindowGeometry(saveGeometry()); + delete tabSupervisor; } void MainWindow::changeEvent(QEvent *event) { - if (event->type() == QEvent::LanguageChange) - retranslateUi(); - QMainWindow::changeEvent(event); + if (event->type() == QEvent::LanguageChange) + retranslateUi(); + QMainWindow::changeEvent(event); } diff --git a/cockatrice/src/window_main.h b/cockatrice/src/window_main.h index e8b42a6a..07ad1d71 100644 --- a/cockatrice/src/window_main.h +++ b/cockatrice/src/window_main.h @@ -32,51 +32,51 @@ class ServerInfo_User; class QThread; class MainWindow : public QMainWindow { - Q_OBJECT + Q_OBJECT private slots: - void updateTabMenu(const QList &newMenuList); - void statusChanged(ClientStatus _status); - void processConnectionClosedEvent(const Event_ConnectionClosed &event); - void processServerShutdownEvent(const Event_ServerShutdown &event); - void serverTimeout(); - void loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime); - void socketError(const QString &errorStr); - void protocolVersionMismatch(int localVersion, int remoteVersion); - void userInfoReceived(const ServerInfo_User &userInfo); - void localGameEnded(); + void updateTabMenu(const QList &newMenuList); + void statusChanged(ClientStatus _status); + void processConnectionClosedEvent(const Event_ConnectionClosed &event); + void processServerShutdownEvent(const Event_ServerShutdown &event); + void serverTimeout(); + void loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime); + void socketError(const QString &errorStr); + void protocolVersionMismatch(int localVersion, int remoteVersion); + void userInfoReceived(const ServerInfo_User &userInfo); + void localGameEnded(); - void actConnect(); - void actDisconnect(); - void actSinglePlayer(); - void actWatchReplay(); - void actDeckEditor(); - void actFullScreen(bool checked); - void actSettings(); - void actExit(); - - void actAbout(); + void actConnect(); + void actDisconnect(); + void actSinglePlayer(); + void actWatchReplay(); + void actDeckEditor(); + void actFullScreen(bool checked); + void actSettings(); + void actExit(); + + void actAbout(); private: - static const QString appName; - void setClientStatusTitle(); - void retranslateUi(); - void createActions(); - void createMenus(); - QList tabMenus; - QMenu *cockatriceMenu, *helpMenu; - QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit, - *aAbout; - TabSupervisor *tabSupervisor; + static const QString appName; + void setClientStatusTitle(); + void retranslateUi(); + void createActions(); + void createMenus(); + QList tabMenus; + QMenu *cockatriceMenu, *helpMenu; + QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit, + *aAbout; + TabSupervisor *tabSupervisor; - RemoteClient *client; - QThread *clientThread; - - LocalServer *localServer; + RemoteClient *client; + QThread *clientThread; + + LocalServer *localServer; public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); + MainWindow(QWidget *parent = 0); + ~MainWindow(); protected: - void closeEvent(QCloseEvent *event); - void changeEvent(QEvent *event); + void closeEvent(QCloseEvent *event); + void changeEvent(QEvent *event); }; #endif diff --git a/cockatrice/src/window_sets.cpp b/cockatrice/src/window_sets.cpp index dd6bcd8a..668b36e0 100644 --- a/cockatrice/src/window_sets.cpp +++ b/cockatrice/src/window_sets.cpp @@ -5,29 +5,29 @@ #include WndSets::WndSets(QWidget *parent) - : QMainWindow(parent) + : QMainWindow(parent) { - model = new SetsModel(db, this); - view = new QTreeView; - view->setModel(model); - view->setAlternatingRowColors(true); - view->setUniformRowHeights(true); - view->setAllColumnsShowFocus(true); + model = new SetsModel(db, this); + view = new QTreeView; + view->setModel(model); + view->setAlternatingRowColors(true); + view->setUniformRowHeights(true); + view->setAllColumnsShowFocus(true); - view->setDragEnabled(true); - view->setAcceptDrops(true); - view->setDropIndicatorShown(true); - view->setDragDropMode(QAbstractItemView::InternalMove); + view->setDragEnabled(true); + view->setAcceptDrops(true); + view->setDropIndicatorShown(true); + view->setDragDropMode(QAbstractItemView::InternalMove); - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addWidget(view); + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addWidget(view); - QWidget *centralWidget = new QWidget; - centralWidget->setLayout(mainLayout); - setCentralWidget(centralWidget); + QWidget *centralWidget = new QWidget; + centralWidget->setLayout(mainLayout); + setCentralWidget(centralWidget); - setWindowTitle(tr("Edit sets")); - resize(400, 400); + setWindowTitle(tr("Edit sets")); + resize(400, 400); } WndSets::~WndSets() diff --git a/cockatrice/src/window_sets.h b/cockatrice/src/window_sets.h index 4c10d249..ce7cb622 100644 --- a/cockatrice/src/window_sets.h +++ b/cockatrice/src/window_sets.h @@ -8,13 +8,13 @@ class QTreeView; class CardDatabase; class WndSets : public QMainWindow { - Q_OBJECT + Q_OBJECT private: - SetsModel *model; - QTreeView *view; + SetsModel *model; + QTreeView *view; public: - WndSets(QWidget *parent = 0); - ~WndSets(); + WndSets(QWidget *parent = 0); + ~WndSets(); }; #endif diff --git a/cockatrice/src/zoneviewwidget.cpp b/cockatrice/src/zoneviewwidget.cpp index 580624e7..9fd13272 100644 --- a/cockatrice/src/zoneviewwidget.cpp +++ b/cockatrice/src/zoneviewwidget.cpp @@ -19,197 +19,197 @@ #include "pb/command_shuffle.pb.h" TitleLabel::TitleLabel() - : QGraphicsWidget(), text(" ") + : QGraphicsWidget(), text(" ") { - setAcceptHoverEvents(true); + setAcceptHoverEvents(true); } void TitleLabel::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush windowBrush = palette().window(); - windowBrush.setColor(windowBrush.color().darker(150)); - painter->fillRect(boundingRect(), windowBrush); - painter->drawText(boundingRect(), Qt::AlignLeft | Qt::AlignVCenter, text); + QBrush windowBrush = palette().window(); + windowBrush.setColor(windowBrush.color().darker(150)); + painter->fillRect(boundingRect(), windowBrush); + painter->drawText(boundingRect(), Qt::AlignLeft | Qt::AlignVCenter, text); } QSizeF TitleLabel::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { - QFont f; - QFontMetrics fm(f); - if (which == Qt::MaximumSize) - return QSizeF(constraint.width(), fm.size(Qt::TextSingleLine, text).height() + 10); - else - return fm.size(Qt::TextSingleLine, text) + QSizeF(10, 10); + QFont f; + QFontMetrics fm(f); + if (which == Qt::MaximumSize) + return QSizeF(constraint.width(), fm.size(Qt::TextSingleLine, text).height() + 10); + else + return fm.size(Qt::TextSingleLine, text) + QSizeF(10, 10); } void TitleLabel::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - buttonDownPos = static_cast(scene())->getViewTransform().inverted().map(event->pos()); - event->accept(); - } else - event->ignore(); + if (event->button() == Qt::LeftButton) { + buttonDownPos = static_cast(scene())->getViewTransform().inverted().map(event->pos()); + event->accept(); + } else + event->ignore(); } void TitleLabel::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - emit mouseMoved(event->scenePos() - buttonDownPos); + emit mouseMoved(event->scenePos() - buttonDownPos); } ZoneViewWidget::ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards, bool _revealZone, bool _writeableRevealZone, const QList &cardList) - : QGraphicsWidget(0, Qt::Tool | Qt::FramelessWindowHint), player(_player) + : QGraphicsWidget(0, Qt::Tool | Qt::FramelessWindowHint), player(_player) { - setAcceptHoverEvents(true); - setAttribute(Qt::WA_DeleteOnClose); - setZValue(2000000006); - setFlag(ItemIgnoresTransformations); - - QGraphicsLinearLayout *hbox = new QGraphicsLinearLayout(Qt::Horizontal); - titleLabel = new TitleLabel; - connect(titleLabel, SIGNAL(mouseMoved(QPointF)), this, SLOT(moveWidget(QPointF))); - closeButton = new QPushButton("X"); - connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); - closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - QGraphicsProxyWidget *closeButtonProxy = new QGraphicsProxyWidget; - closeButtonProxy->setWidget(closeButton); - - hbox->addItem(titleLabel); - hbox->addItem(closeButtonProxy); - QGraphicsLinearLayout *vbox = new QGraphicsLinearLayout(Qt::Vertical); - - vbox->addItem(hbox); - - if (numberCards < 0) { - sortByNameCheckBox = new QCheckBox; - QGraphicsProxyWidget *sortByNameProxy = new QGraphicsProxyWidget; - sortByNameProxy->setWidget(sortByNameCheckBox); - vbox->addItem(sortByNameProxy); + setAcceptHoverEvents(true); + setAttribute(Qt::WA_DeleteOnClose); + setZValue(2000000006); + setFlag(ItemIgnoresTransformations); + + QGraphicsLinearLayout *hbox = new QGraphicsLinearLayout(Qt::Horizontal); + titleLabel = new TitleLabel; + connect(titleLabel, SIGNAL(mouseMoved(QPointF)), this, SLOT(moveWidget(QPointF))); + closeButton = new QPushButton("X"); + connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); + closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + QGraphicsProxyWidget *closeButtonProxy = new QGraphicsProxyWidget; + closeButtonProxy->setWidget(closeButton); + + hbox->addItem(titleLabel); + hbox->addItem(closeButtonProxy); + QGraphicsLinearLayout *vbox = new QGraphicsLinearLayout(Qt::Vertical); + + vbox->addItem(hbox); + + if (numberCards < 0) { + sortByNameCheckBox = new QCheckBox; + QGraphicsProxyWidget *sortByNameProxy = new QGraphicsProxyWidget; + sortByNameProxy->setWidget(sortByNameCheckBox); + vbox->addItem(sortByNameProxy); - sortByTypeCheckBox = new QCheckBox; - QGraphicsProxyWidget *sortByTypeProxy = new QGraphicsProxyWidget; - sortByTypeProxy->setWidget(sortByTypeCheckBox); - vbox->addItem(sortByTypeProxy); - } else { - sortByNameCheckBox = 0; - sortByTypeCheckBox = 0; - } - - if (_origZone->getIsShufflable() && (numberCards == -1)) { - shuffleCheckBox = new QCheckBox; - shuffleCheckBox->setChecked(true); - QGraphicsProxyWidget *shuffleProxy = new QGraphicsProxyWidget; - shuffleProxy->setWidget(shuffleCheckBox); - vbox->addItem(shuffleProxy); - } else - shuffleCheckBox = 0; - - extraHeight = vbox->sizeHint(Qt::PreferredSize).height(); - resize(150, 150); - - QGraphicsLinearLayout *zoneHBox = new QGraphicsLinearLayout(Qt::Horizontal); - - zoneContainer = new QGraphicsWidget(this); - zoneContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - zoneContainer->setFlag(QGraphicsItem::ItemClipsChildrenToShape); - zoneHBox->addItem(zoneContainer); - - scrollBar = new QScrollBar(Qt::Vertical); - scrollBar->setMinimum(0); - scrollBar->setSingleStep(50); - connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(handleScrollBarChange(int))); - QGraphicsProxyWidget *scrollBarProxy = new QGraphicsProxyWidget; - scrollBarProxy->setWidget(scrollBar); - zoneHBox->addItem(scrollBarProxy); - - vbox->addItem(zoneHBox); - - zone = new ZoneViewZone(player, _origZone, numberCards, _revealZone, _writeableRevealZone, zoneContainer); - connect(zone, SIGNAL(wheelEventReceived(QGraphicsSceneWheelEvent *)), this, SLOT(handleWheelEvent(QGraphicsSceneWheelEvent *))); - - if (sortByNameCheckBox) { - connect(sortByNameCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByName(int))); - connect(sortByTypeCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByType(int))); - sortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); - sortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); - } + sortByTypeCheckBox = new QCheckBox; + QGraphicsProxyWidget *sortByTypeProxy = new QGraphicsProxyWidget; + sortByTypeProxy->setWidget(sortByTypeCheckBox); + vbox->addItem(sortByTypeProxy); + } else { + sortByNameCheckBox = 0; + sortByTypeCheckBox = 0; + } + + if (_origZone->getIsShufflable() && (numberCards == -1)) { + shuffleCheckBox = new QCheckBox; + shuffleCheckBox->setChecked(true); + QGraphicsProxyWidget *shuffleProxy = new QGraphicsProxyWidget; + shuffleProxy->setWidget(shuffleCheckBox); + vbox->addItem(shuffleProxy); + } else + shuffleCheckBox = 0; + + extraHeight = vbox->sizeHint(Qt::PreferredSize).height(); + resize(150, 150); + + QGraphicsLinearLayout *zoneHBox = new QGraphicsLinearLayout(Qt::Horizontal); + + zoneContainer = new QGraphicsWidget(this); + zoneContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + zoneContainer->setFlag(QGraphicsItem::ItemClipsChildrenToShape); + zoneHBox->addItem(zoneContainer); + + scrollBar = new QScrollBar(Qt::Vertical); + scrollBar->setMinimum(0); + scrollBar->setSingleStep(50); + connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(handleScrollBarChange(int))); + QGraphicsProxyWidget *scrollBarProxy = new QGraphicsProxyWidget; + scrollBarProxy->setWidget(scrollBar); + zoneHBox->addItem(scrollBarProxy); + + vbox->addItem(zoneHBox); + + zone = new ZoneViewZone(player, _origZone, numberCards, _revealZone, _writeableRevealZone, zoneContainer); + connect(zone, SIGNAL(wheelEventReceived(QGraphicsSceneWheelEvent *)), this, SLOT(handleWheelEvent(QGraphicsSceneWheelEvent *))); + + if (sortByNameCheckBox) { + connect(sortByNameCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByName(int))); + connect(sortByTypeCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByType(int))); + sortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); + sortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); + } - retranslateUi(); - setLayout(vbox); - - connect(zone, SIGNAL(optimumRectChanged()), this, SLOT(resizeToZoneContents())); - connect(zone, SIGNAL(beingDeleted()), this, SLOT(zoneDeleted())); - zone->initializeCards(cardList); + retranslateUi(); + setLayout(vbox); + + connect(zone, SIGNAL(optimumRectChanged()), this, SLOT(resizeToZoneContents())); + connect(zone, SIGNAL(beingDeleted()), this, SLOT(zoneDeleted())); + zone->initializeCards(cardList); } void ZoneViewWidget::retranslateUi() { - titleLabel->setText(zone->getTranslatedName(false, CaseNominative)); - if (sortByNameCheckBox) - sortByNameCheckBox->setText(tr("sort by name")); - if (sortByTypeCheckBox) - sortByTypeCheckBox->setText(tr("sort by type")); - if (shuffleCheckBox) - shuffleCheckBox->setText(tr("shuffle when closing")); + titleLabel->setText(zone->getTranslatedName(false, CaseNominative)); + if (sortByNameCheckBox) + sortByNameCheckBox->setText(tr("sort by name")); + if (sortByTypeCheckBox) + sortByTypeCheckBox->setText(tr("sort by type")); + if (shuffleCheckBox) + shuffleCheckBox->setText(tr("shuffle when closing")); } void ZoneViewWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - painter->fillRect(boundingRect(), palette().color(QPalette::Window)); - QGraphicsWidget::paint(painter, option, widget); + painter->fillRect(boundingRect(), palette().color(QPalette::Window)); + QGraphicsWidget::paint(painter, option, widget); } void ZoneViewWidget::moveWidget(QPointF scenePos) { - setPos(scenePos); + setPos(scenePos); } void ZoneViewWidget::resizeToZoneContents() { - QRectF zoneRect = zone->getOptimumRect(); - qreal totalZoneHeight = zoneRect.height(); - if (zoneRect.height() > 500) - zoneRect.setHeight(500); - QSizeF newSize(qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), zoneRect.width() + scrollBar->width() + 10), zoneRect.height() + extraHeight + 10); - setMaximumSize(newSize); - resize(newSize); - - zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight)); - scrollBar->setMaximum(totalZoneHeight - zoneRect.height()); - - if (layout()) - layout()->invalidate(); + QRectF zoneRect = zone->getOptimumRect(); + qreal totalZoneHeight = zoneRect.height(); + if (zoneRect.height() > 500) + zoneRect.setHeight(500); + QSizeF newSize(qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), zoneRect.width() + scrollBar->width() + 10), zoneRect.height() + extraHeight + 10); + setMaximumSize(newSize); + resize(newSize); + + zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight)); + scrollBar->setMaximum(totalZoneHeight - zoneRect.height()); + + if (layout()) + layout()->invalidate(); } void ZoneViewWidget::handleWheelEvent(QGraphicsSceneWheelEvent *event) { - QWheelEvent wheelEvent(QPoint(), event->delta(), event->buttons(), event->modifiers(), event->orientation()); - scrollBar->event(&wheelEvent); + QWheelEvent wheelEvent(QPoint(), event->delta(), event->buttons(), event->modifiers(), event->orientation()); + scrollBar->event(&wheelEvent); } void ZoneViewWidget::handleScrollBarChange(int value) { - zone->setY(-value); + zone->setY(-value); } void ZoneViewWidget::closeEvent(QCloseEvent *event) { - disconnect(zone, SIGNAL(beingDeleted()), this, 0); - if (zone->getNumberCards() != -2) { - Command_StopDumpZone cmd; - cmd.set_player_id(player->getId()); - cmd.set_zone_name(zone->getName().toStdString()); - player->sendGameCommand(cmd); - } - if (shuffleCheckBox) - if (shuffleCheckBox->isChecked()) - player->sendGameCommand(Command_Shuffle()); - emit closePressed(this); - deleteLater(); - event->accept(); + disconnect(zone, SIGNAL(beingDeleted()), this, 0); + if (zone->getNumberCards() != -2) { + Command_StopDumpZone cmd; + cmd.set_player_id(player->getId()); + cmd.set_zone_name(zone->getName().toStdString()); + player->sendGameCommand(cmd); + } + if (shuffleCheckBox) + if (shuffleCheckBox->isChecked()) + player->sendGameCommand(Command_Shuffle()); + emit closePressed(this); + deleteLater(); + event->accept(); } void ZoneViewWidget::zoneDeleted() { - emit closePressed(this); - deleteLater(); + emit closePressed(this); + deleteLater(); } diff --git a/cockatrice/src/zoneviewwidget.h b/cockatrice/src/zoneviewwidget.h index 5148ba74..2c89a571 100644 --- a/cockatrice/src/zoneviewwidget.h +++ b/cockatrice/src/zoneviewwidget.h @@ -17,50 +17,50 @@ class QGraphicsSceneMouseEvent; class QGraphicsSceneWheelEvent; class TitleLabel : public QGraphicsWidget { - Q_OBJECT + Q_OBJECT private: - QString text; - QPointF buttonDownPos; + QString text; + QPointF buttonDownPos; public: - TitleLabel(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); - void setText(const QString &_text) { text = _text; update(); } + TitleLabel(); + void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); + void setText(const QString &_text) { text = _text; update(); } signals: - void mouseMoved(QPointF scenePos); + void mouseMoved(QPointF scenePos); protected: - QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint) const; - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint) const; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); }; class ZoneViewWidget : public QGraphicsWidget { - Q_OBJECT + Q_OBJECT private: - ZoneViewZone *zone; - QGraphicsWidget *zoneContainer; - - TitleLabel *titleLabel; - QPushButton *closeButton; - QScrollBar *scrollBar; - QCheckBox *sortByNameCheckBox, *sortByTypeCheckBox, *shuffleCheckBox; - - int extraHeight; - Player *player; + ZoneViewZone *zone; + QGraphicsWidget *zoneContainer; + + TitleLabel *titleLabel; + QPushButton *closeButton; + QScrollBar *scrollBar; + QCheckBox *sortByNameCheckBox, *sortByTypeCheckBox, *shuffleCheckBox; + + int extraHeight; + Player *player; signals: - void closePressed(ZoneViewWidget *zv); + void closePressed(ZoneViewWidget *zv); private slots: - void resizeToZoneContents(); - void handleWheelEvent(QGraphicsSceneWheelEvent *event); - void handleScrollBarChange(int value); - void zoneDeleted(); - void moveWidget(QPointF scenePos); + void resizeToZoneContents(); + void handleWheelEvent(QGraphicsSceneWheelEvent *event); + void handleScrollBarChange(int value); + void zoneDeleted(); + void moveWidget(QPointF scenePos); public: - ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards = 0, bool _revealZone = false, bool _writeableRevealZone = false, const QList &cardList = QList()); - ZoneViewZone *getZone() const { return zone; } - void retranslateUi(); + ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards = 0, bool _revealZone = false, bool _writeableRevealZone = false, const QList &cardList = QList()); + ZoneViewZone *getZone() const { return zone; } + void retranslateUi(); protected: - void closeEvent(QCloseEvent *event); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void closeEvent(QCloseEvent *event); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif diff --git a/cockatrice/src/zoneviewzone.cpp b/cockatrice/src/zoneviewzone.cpp index cfa1dda2..c42dfd0e 100644 --- a/cockatrice/src/zoneviewzone.cpp +++ b/cockatrice/src/zoneviewzone.cpp @@ -12,23 +12,23 @@ #include "pending_command.h" ZoneViewZone::ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards, bool _revealZone, bool _writeableRevealZone, QGraphicsItem *parent) - : SelectZone(_p, _origZone->getName(), false, false, true, parent, true), bRect(QRectF()), minRows(0), numberCards(_numberCards), origZone(_origZone), revealZone(_revealZone), writeableRevealZone(_writeableRevealZone), sortByName(false), sortByType(false) + : SelectZone(_p, _origZone->getName(), false, false, true, parent, true), bRect(QRectF()), minRows(0), numberCards(_numberCards), origZone(_origZone), revealZone(_revealZone), writeableRevealZone(_writeableRevealZone), sortByName(false), sortByType(false) { - if (!(revealZone && !writeableRevealZone)) - origZone->setView(this); + if (!(revealZone && !writeableRevealZone)) + origZone->setView(this); } ZoneViewZone::~ZoneViewZone() { - emit beingDeleted(); - qDebug("ZoneViewZone destructor"); - if (!(revealZone && !writeableRevealZone)) - origZone->setView(NULL); + emit beingDeleted(); + qDebug("ZoneViewZone destructor"); + if (!(revealZone && !writeableRevealZone)) + origZone->setView(NULL); } QRectF ZoneViewZone::boundingRect() const { - return bRect; + return bRect; } void ZoneViewZone::paint(QPainter */*painter*/, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) @@ -37,154 +37,154 @@ void ZoneViewZone::paint(QPainter */*painter*/, const QStyleOptionGraphicsItem * void ZoneViewZone::initializeCards(const QList &cardList) { - if (!cardList.isEmpty()) { - for (int i = 0; i < cardList.size(); ++i) - addCard(new CardItem(player, QString::fromStdString(cardList[i]->name()), cardList[i]->id(), revealZone, this), false, i); - reorganizeCards(); - } else if (!origZone->contentsKnown()) { - Command_DumpZone cmd; - cmd.set_player_id(player->getId()); - cmd.set_zone_name(name.toStdString()); - cmd.set_number_cards(numberCards); - - PendingCommand *pend = player->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(zoneDumpReceived(const Response &))); - player->sendGameCommand(pend); - } else { - const CardList &c = origZone->getCards(); - int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); - for (int i = 0; i < number; i++) { - CardItem *card = c.at(i); - addCard(new CardItem(player, card->getName(), card->getId(), revealZone, this), false, i); - } - reorganizeCards(); - } + if (!cardList.isEmpty()) { + for (int i = 0; i < cardList.size(); ++i) + addCard(new CardItem(player, QString::fromStdString(cardList[i]->name()), cardList[i]->id(), revealZone, this), false, i); + reorganizeCards(); + } else if (!origZone->contentsKnown()) { + Command_DumpZone cmd; + cmd.set_player_id(player->getId()); + cmd.set_zone_name(name.toStdString()); + cmd.set_number_cards(numberCards); + + PendingCommand *pend = player->prepareGameCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(zoneDumpReceived(const Response &))); + player->sendGameCommand(pend); + } else { + const CardList &c = origZone->getCards(); + int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); + for (int i = 0; i < number; i++) { + CardItem *card = c.at(i); + addCard(new CardItem(player, card->getName(), card->getId(), revealZone, this), false, i); + } + reorganizeCards(); + } } void ZoneViewZone::zoneDumpReceived(const Response &r) { - const Response_DumpZone &resp = r.GetExtension(Response_DumpZone::ext); - const int respCardListSize = resp.zone_info().card_list_size(); - for (int i = 0; i < respCardListSize; ++i) { - const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i); - CardItem *card = new CardItem(player, QString::fromStdString(cardInfo.name()), cardInfo.id(), revealZone, this); - addCard(card, false, i); - } - - reorganizeCards(); + const Response_DumpZone &resp = r.GetExtension(Response_DumpZone::ext); + const int respCardListSize = resp.zone_info().card_list_size(); + for (int i = 0; i < respCardListSize; ++i) { + const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i); + CardItem *card = new CardItem(player, QString::fromStdString(cardInfo.name()), cardInfo.id(), revealZone, this); + addCard(card, false, i); + } + + reorganizeCards(); } // Because of boundingRect(), this function must not be called before the zone was added to a scene. void ZoneViewZone::reorganizeCards() { - int cardCount = cards.size(); - if (!origZone->contentsKnown()) - for (int i = 0; i < cardCount; ++i) - cards[i]->setId(i); + int cardCount = cards.size(); + if (!origZone->contentsKnown()) + for (int i = 0; i < cardCount; ++i) + cards[i]->setId(i); - int cols = floor(sqrt((double) cardCount / 2)); - if (cols > 7) - cols = 7; - int rows = ceil((double) cardCount / cols); - if (rows < 1) - rows = 1; - if (minRows == 0) - minRows = rows; - else if (rows < minRows) { - rows = minRows; - cols = ceil((double) cardCount / minRows); - } - if (cols < 2) - cols = 2; - - qDebug() << "reorganizeCards: rows=" << rows << "cols=" << cols; + int cols = floor(sqrt((double) cardCount / 2)); + if (cols > 7) + cols = 7; + int rows = ceil((double) cardCount / cols); + if (rows < 1) + rows = 1; + if (minRows == 0) + minRows = rows; + else if (rows < minRows) { + rows = minRows; + cols = ceil((double) cardCount / minRows); + } + if (cols < 2) + cols = 2; + + qDebug() << "reorganizeCards: rows=" << rows << "cols=" << cols; - CardList cardsToDisplay(cards); - if (sortByName || sortByType) - cardsToDisplay.sort((sortByName ? CardList::SortByName : 0) | (sortByType ? CardList::SortByType : 0)); - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cardsToDisplay.at(i); - qreal x = (i / rows) * CARD_WIDTH; - qreal y = (i % rows) * CARD_HEIGHT / 3; - c->setPos(x + 5, y + 5); - c->setRealZValue(i); - } + CardList cardsToDisplay(cards); + if (sortByName || sortByType) + cardsToDisplay.sort((sortByName ? CardList::SortByName : 0) | (sortByType ? CardList::SortByType : 0)); + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cardsToDisplay.at(i); + qreal x = (i / rows) * CARD_WIDTH; + qreal y = (i % rows) * CARD_HEIGHT / 3; + c->setPos(x + 5, y + 5); + c->setRealZValue(i); + } - optimumRect = QRectF(0, 0, qMax(cols, 3) * CARD_WIDTH + 10, ((rows - 1) * CARD_HEIGHT) / 3 + CARD_HEIGHT + 10); - updateGeometry(); - emit optimumRectChanged(); + optimumRect = QRectF(0, 0, qMax(cols, 3) * CARD_WIDTH + 10, ((rows - 1) * CARD_HEIGHT) / 3 + CARD_HEIGHT + 10); + updateGeometry(); + emit optimumRectChanged(); } void ZoneViewZone::setSortByName(int _sortByName) { - sortByName = _sortByName; - reorganizeCards(); + sortByName = _sortByName; + reorganizeCards(); } void ZoneViewZone::setSortByType(int _sortByType) { - sortByType = _sortByType; - reorganizeCards(); + sortByType = _sortByType; + reorganizeCards(); } void ZoneViewZone::addCardImpl(CardItem *card, int x, int /*y*/) { - cards.insert(x, card); - card->setParentItem(this); - card->update(); + cards.insert(x, card); + card->setParentItem(this); + card->update(); } void ZoneViewZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) { - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(0); - cmd.set_y(0); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(0); + cmd.set_y(0); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - player->sendGameCommand(cmd); + player->sendGameCommand(cmd); } void ZoneViewZone::removeCard(int position) { - if (position >= cards.size()) - return; + if (position >= cards.size()) + return; - CardItem *card = cards.takeAt(position); - card->deleteLater(); - reorganizeCards(); + CardItem *card = cards.takeAt(position); + card->deleteLater(); + reorganizeCards(); } void ZoneViewZone::setGeometry(const QRectF &rect) { - prepareGeometryChange(); - setPos(rect.x(), rect.y()); - bRect = QRectF(0, 0, rect.width(), rect.height()); + prepareGeometryChange(); + setPos(rect.x(), rect.y()); + bRect = QRectF(0, 0, rect.width(), rect.height()); } QSizeF ZoneViewZone::sizeHint(Qt::SizeHint /*which*/, const QSizeF & /*constraint*/) const { - return optimumRect.size(); + return optimumRect.size(); } void ZoneViewZone::setWriteableRevealZone(bool _writeableRevealZone) { - if (writeableRevealZone && !_writeableRevealZone) - origZone->setView(this); - else if (!writeableRevealZone && _writeableRevealZone) - origZone->setView(NULL); - - writeableRevealZone = _writeableRevealZone; - + if (writeableRevealZone && !_writeableRevealZone) + origZone->setView(this); + else if (!writeableRevealZone && _writeableRevealZone) + origZone->setView(NULL); + + writeableRevealZone = _writeableRevealZone; + } void ZoneViewZone::wheelEvent(QGraphicsSceneWheelEvent *event) { - emit wheelEventReceived(event); + emit wheelEventReceived(event); } diff --git a/cockatrice/src/zoneviewzone.h b/cockatrice/src/zoneviewzone.h index 25850e38..727148a8 100644 --- a/cockatrice/src/zoneviewzone.h +++ b/cockatrice/src/zoneviewzone.h @@ -10,41 +10,41 @@ class ServerInfo_Card; class QGraphicsSceneWheelEvent; class ZoneViewZone : public SelectZone, public QGraphicsLayoutItem { - Q_OBJECT + Q_OBJECT private: - QRectF bRect, optimumRect; - int minRows, numberCards; - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - CardZone *origZone; - bool revealZone, writeableRevealZone; - bool sortByName, sortByType; + QRectF bRect, optimumRect; + int minRows, numberCards; + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + CardZone *origZone; + bool revealZone, writeableRevealZone; + bool sortByName, sortByType; public: - ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards = -1, bool _revealZone = false, bool _writeableRevealZone = false, QGraphicsItem *parent = 0); - ~ZoneViewZone(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); - void initializeCards(const QList &cardList = QList()); - void removeCard(int position); - int getNumberCards() const { return numberCards; } - void setGeometry(const QRectF &rect); - QRectF getOptimumRect() const { return optimumRect; } - bool getRevealZone() const { return revealZone; } - bool getWriteableRevealZone() const { return writeableRevealZone; } - void setWriteableRevealZone(bool _writeableRevealZone); + ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards = -1, bool _revealZone = false, bool _writeableRevealZone = false, QGraphicsItem *parent = 0); + ~ZoneViewZone(); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); + void initializeCards(const QList &cardList = QList()); + void removeCard(int position); + int getNumberCards() const { return numberCards; } + void setGeometry(const QRectF &rect); + QRectF getOptimumRect() const { return optimumRect; } + bool getRevealZone() const { return revealZone; } + bool getWriteableRevealZone() const { return writeableRevealZone; } + void setWriteableRevealZone(bool _writeableRevealZone); public slots: - void setSortByName(int _sortByName); - void setSortByType(int _sortByType); + void setSortByName(int _sortByName); + void setSortByType(int _sortByType); private slots: - void zoneDumpReceived(const Response &r); + void zoneDumpReceived(const Response &r); signals: - void beingDeleted(); - void optimumRectChanged(); - void wheelEventReceived(QGraphicsSceneWheelEvent *event); + void beingDeleted(); + void optimumRectChanged(); + void wheelEventReceived(QGraphicsSceneWheelEvent *event); protected: - void addCardImpl(CardItem *card, int x, int y); - QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; - void wheelEvent(QGraphicsSceneWheelEvent *event); + void addCardImpl(CardItem *card, int x, int y); + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; + void wheelEvent(QGraphicsSceneWheelEvent *event); }; #endif From e366bd7a71b8dd5011935f34272dbaca7f273f87 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Fri, 14 Feb 2014 13:58:54 -0500 Subject: [PATCH 09/10] Fixed for Linux - pushing to test on OS X --- common/CMakeLists.txt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 51ce1650..38413187 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -48,5 +48,8 @@ INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) add_library(cockatrice_common ${common_SOURCES} ${common_HEADERS_MOC}) -target_link_libraries(cockatrice_common cockatrice_protocol) - +if (UNIX) + target_link_libraries(cockatrice_common cockatrice_protocol pthread) +else (UNIX) + target_link_libraries(cockatrice_common cockatrice_protocol) +endif (UNIX) From b93317cc17d5ada0a6c2d882bf500d925d61f462 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Fri, 14 Feb 2014 14:14:10 -0500 Subject: [PATCH 10/10] OS X still works with pthread fix - added explanation --- common/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 38413187..3a8031b1 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -48,6 +48,7 @@ INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) add_library(cockatrice_common ${common_SOURCES} ${common_HEADERS_MOC}) +# Without this check, Linux will put -pthread out of order in link.txt and build will fail if (UNIX) target_link_libraries(cockatrice_common cockatrice_protocol pthread) else (UNIX)