Debian Codegraph @

src/network/networkconnection.cpp

raw symbols SCIP
1 /***************************************************************************
2 * Copyright (C) 2009 by The qGo Project *
3 * *
4 * This file is part of qGo. *
5 * *
6 * qGo is free software: you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, see <http://www.gnu.org/licenses/> *
18 * or write to the Free Software Foundation, Inc., *
19 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
20 ***************************************************************************/
21
22
23 #ifdef LATENCY
24 #include <sys/time.h>
25 #endif //LATENCY
26 #include "defines.h"
27 #include "networkconnection.h"
28 #include "consoledispatch.h"
29 #include "boarddispatch.h"
30 #include "talk.h"
31 #include "gamedialog.h"
32 #include "room.h"
33 #include "playergamelistings.h"
34 #include "connectionwidget.h" //don't like so much
35 #include "matchnegotiationstate.h"
36
37 #define FRIENDWATCH_NOTIFY_DEFAULT 1
38
39 NetworkConnection::NetworkConnection(ConnectionCredentials credentials) :
40 default_room(0), console_dispatch(0), qsocket(0)
41 {
42 firstonReadyCall = 1;
43 mainwindowroom = 0;
44 friendwatch_notify_default = FRIENDWATCH_NOTIFY_DEFAULT;
45
46 connectingDialog = 0;
47 match_negotiation_state = new MatchNegotiationState();
48
49 connectionType = credentials.type;
50 hostname = credentials.hostName;
51 port = credentials.port;
52 username = credentials.userName;
53 password = credentials.password;
54
55 ourListing = NULL;
56 }
57
58 bool NetworkConnection::openConnection(const QString & host, const unsigned short port, bool not_main_connection)
59 {
60 qsocket = new QTcpSocket(); //try with no parent passed for now
61 if(!qsocket)
62 return 0;
63 //connect signals
64
65 //connect(qsocket, hostFound()), OnHostFound()));
66 connect(qsocket, &QTcpSocket::connected, this, &NetworkConnection::OnConnected);
67 connect(qsocket, &QTcpSocket::readyRead, this, &NetworkConnection::OnReadyRead);
68 connect(qsocket, &QTcpSocket::disconnected, this, &NetworkConnection::OnConnectionClosed);
69 connect(qsocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &NetworkConnection::OnError);
70
71 if(qsocket->state() != QTcpSocket::UnconnectedState)
72 {
73 qDebug("Called openConnection while in state %d", qsocket->isValid());
74 return 0;
75 }
76 //remove asserts later
77 Q_ASSERT(host != 0);
78 Q_ASSERT(port != 0);
79
80 if(!not_main_connection)
81 drawPleaseWait();
82
83 qDebug("Connecting to %s %d...\n", host.toLatin1().constData(), port);
84 // assume info.host is clean
85 qsocket->connectToHost(host, (quint16) port);
86
87 /* If dispatch does not have a UI, the thing that sets the UI
88 * will setupRoomAndConsole */
89 /* Tricky now without dispatches... who sets up the UI?
90 * there's always a mainwindow... but maybe things aren't setup? */
91
92 /* connectionInfo as a message with those pointers is probably a bad idea */
93 return (qsocket->state() != QTcpSocket::UnconnectedState);
94 }
95
96 int NetworkConnection::write(const char * packet, unsigned int size)
97 {
98 return qsocket->write(packet, size);
99 }
100
101 void NetworkConnection::writeZeroPaddedString(char * dst, const QString & src, int size)
102 {
103 int i;
104 Q_ASSERT(src.length() <= size);
105 for(i = 0; i < src.length(); i++)
106 dst[i] = src.toLatin1().constData()[i];
107 for(i = src.length(); i < size; i++)
108 dst[i] = 0x00;
109 }
110
111 int NetworkConnection::checkForOpenBoards(void)
112 {
113 BoardDispatch * boarddispatch;
114 QMap<unsigned int, class BoardDispatch *>::iterator i;
115 for(i = boardDispatchMap.begin(); i != boardDispatchMap.end(); i++)
116 {
117 boarddispatch = i.value();
118 if(!boarddispatch->canClose())
119 return -1;
120 }
121 return 0;
122 }
123
124 void NetworkConnection::closeConnection(bool send_disconnect)
125 {
126 if(!qsocket) //when can this happen? this function shouldn't be
127 //called if we get here!!!
128 return;
129
130 /* FIXME We also need to close any open dispatches,
131 * boards etc., for instance if there was an error.
132 * Clearing lists and such would be good to.
133 * there's a MainWindow::connexionClosed that does
134 * good stuff we should move into somewhere
135 * nearby., also what about onError?*/
136 if(connectingDialog)
137 {
138 connectingDialog->deleteLater();
139 connectingDialog = 0;
140 }
141 if(qsocket->state() != QTcpSocket::UnconnectedState)
142 {
143 if(send_disconnect)
144 {
145 if(console_dispatch)
146 console_dispatch->recvText("Disconnecting...\n");
147 qDebug("Disconnecting...");
148 sendDisconnect(); //legit?
149 }
150 // Close it.
151 qsocket->close();
152
153 // Closing succeeded, return message
154 if (qsocket->state() == QTcpSocket::UnconnectedState)
155 {
156 //authState = LOGIN;
157 //sendTextToApp("Connection closed.\n");
158 }
159 }
160 // Not yet closed? Data will be written and then slot OnDelayClosedFinish() called
161
162 //delete qsocket;
163 qsocket->deleteLater(); //for safety
164 qsocket = 0;
165 onClose();
166
167 return;
168 }
169
170 void NetworkConnection::onClose(void)
171 {
172 /* This is from old netdispatch, fix me */
173 //RoomDispatch * room;
174 /* This needs to close all open dispatches */
175 /*room = connection->getDefaultRoomDispatch();
176 if(room)
177 {
178 connection->setDefaultRoomDispatch(0);
179 delete room;
180 //FIXME mainwindowroom = 0;
181 }*/
182 tearDownRoomAndConsole();
183 }
184
185 NetworkConnection::~NetworkConnection()
186 {
187 //feels a little sparse so far... this should probably be super close FIXME
188 //qDebug("Destroying connection\n");
189 //closeConnection(); //specific impl already calls this
190 /* Not sure where to delete qsocket. Possible OnDelayClosedFinish() thing. */
191 //delete qsocket;
192 //In case these still exist
193 //probably unnecessary?
194 delete match_negotiation_state;
195 }
196
197 void NetworkConnection::setConsoleDispatch(class ConsoleDispatch * c)
198 {
199 console_dispatch = c;
200 }
201
202 QTime NetworkConnection::gd_checkMainTime(TimeSystem s, const QTime & t)
203 {
204 if(s == canadian)
205 {
206 // int seconds = (t.minute() * 60) + t.second();
207 if(t.second())
208 {
209 // seconds = (t.minute() * 60);
210 return QTime(0, t.minute(), 0);
211 }
212 }
213 return t;
214 }
215
216 PlayerListing * NetworkConnection::getPlayerListingFromFriendWatchListing(FriendWatchListing & f)
217 {
218 if(!default_room)
219 return NULL;
220 else
221 {
222 if(playerTrackingByID())
223 {
224 if(f.id == 0)
225 {
226 PlayerListing * p = default_room->getPlayerListing(f.name);
227 f.id = p->id;
228 return p;
229 }
230 else
231 return default_room->getPlayerListing(f.id);
232 }
233 else
234 return default_room->getPlayerListing(f.name);
235 }
236 }
237
238 /* This will often be overridden by the specific connection but
239 * otherwise this will handle local lists. There's also the
240 * possibility of a sync option? But that's almost useless */
241 /* As far as I can tell IGS has no support for on server lists,
242 * so that will be the first add */
243 /* Note that these can't be called if the listing already has
244 * the bit set and server side friends lists will have a
245 * separate interface */
246 void NetworkConnection::addFriend(PlayerListing * player)
247 {
248 if(player->friendWatchType == PlayerListing::blocked)
249 removeBlock(player);
250 else if(player->friendWatchType == PlayerListing::watched)
251 removeWatch(player);
252 player->friendWatchType = PlayerListing::friended;
253 //FIXME presumably they're not already on the list because
254 //the popup checked that in constructing the popup menu but...
255 friendedList.push_back(new FriendWatchListing(player->name, friendwatch_notify_default));
256 emit playerListingReceived(player);
257 }
258
259 void NetworkConnection::removeFriend(PlayerListing * player)
260 {
261 player->friendWatchType = PlayerListing::none;
262 std::vector<FriendWatchListing * >::iterator i;
263 for(i = friendedList.begin(); i != friendedList.end(); i++)
264 {
265 if((*i)->name == player->name)
266 {
267 delete *i;
268 friendedList.erase(i);
269 break;
270 }
271 }
272 emit playerListingReceived(player);
273 }
274
275 void NetworkConnection::addWatch(PlayerListing * player)
276 {
277 if(player->friendWatchType == PlayerListing::friended)
278 removeFriend(player);
279 else if(player->friendWatchType == PlayerListing::blocked)
280 removeBlock(player);
281 player->friendWatchType = PlayerListing::watched;
282 watchedList.push_back(new FriendWatchListing(player->name, friendwatch_notify_default));
283 emit playerListingReceived(player);
284 }
285
286 void NetworkConnection::removeWatch(PlayerListing * player)
287 {
288 player->friendWatchType = PlayerListing::none;
289 std::vector<FriendWatchListing * >::iterator i;
290 for(i = watchedList.begin(); i != watchedList.end(); i++)
291 {
292 if((*i)->name == player->name)
293 {
294 delete *i;
295 watchedList.erase(i);
296 break;
297 }
298 }
299 emit playerListingReceived(player);
300 }
301
302 void NetworkConnection::addBlock(PlayerListing * player)
303 {
304 if(player->friendWatchType == PlayerListing::friended)
305 removeFriend(player);
306 else if(player->friendWatchType == PlayerListing::watched)
307 removeWatch(player);
308 player->friendWatchType = PlayerListing::blocked;
309 blockedList.push_back(new FriendWatchListing(player->name));
310 }
311
312 void NetworkConnection::removeBlock(PlayerListing * player)
313 {
314 player->friendWatchType = PlayerListing::none;
315 std::vector<FriendWatchListing * >::iterator i;
316 for(i = blockedList.begin(); i != blockedList.end(); i++)
317 {
318 if((*i)->name == player->name)
319 {
320 delete *i;
321 blockedList.erase(i);
322 break;
323 }
324 }
325 }
326
327 /* This function checks the local lists for a name and sets
328 * appropriate flags. We may also have it do notifications.
329 * Other protocol types can override it to, for instance
330 * do nothing or just notify, assuming the flags are
331 * set when the player is received, rather than looking them
332 * up */
333 /* Another issue: recvPlayerListing is used to change
334 * the status of a player, as in which room they're in
335 * we don't want it to say "signed on" every time with
336 * that. So we probably need to have an online flag
337 * on the friends listing to see if we've already flagged
338 * them FIXME */
339 void NetworkConnection::getAndSetFriendWatchType(PlayerListing * player)
340 {
341 std::vector<FriendWatchListing * >::iterator i;
342
343 for(i = friendedList.begin(); i != friendedList.end(); i++)
344 {
345 if((*i)->name == player->name)
346 {
347 if(!(*i)->online)
348 {
349 (*i)->online = true;
350 player->friendWatchType = PlayerListing::friended;
351 /* We may want to put this somewhere else or have it be dialog
352 * with options, like talk or match. We might also want
353 * to block all notifies while one is in a game FIXME
354 * Also, these messages should be nonblocking !?!?!!!!! FIXME*/
355 /* And actually, its a big enough deal, i.e., we might want console
356 * messages, game blocks, etc., that it makes sense to have some separate
357 * class for it that handles the notifications... a notification class... */
358 #ifdef FIXME
359 if((*i)->notify)
360 QMessageBox::information(0, tr("Signed on"), tr("%1 has signed on").arg(player.name));
361 #endif //FIXME
362 }
363 else if(!player->online)
364 {
365 (*i)->online = false;
366 //they are disconnecting
367 }
368 return;
369 }
370 }
371 for(i = watchedList.begin(); i != watchedList.end(); i++)
372 {
373 if((*i)->name == player->name)
374 {
375 player->friendWatchType = PlayerListing::watched;
376 return;
377 }
378 }
379 for(i = blockedList.begin(); i != blockedList.end(); i++)
380 {
381 if((*i)->name == player->name)
382 {
383 player->friendWatchType = PlayerListing::blocked;
384 return;
385 }
386 }
387 player->friendWatchType = PlayerListing::none;
388 return;
389 }
390
391 void NetworkConnection::checkGameWatched(const GameListing *game)
392 {
393 std::vector<FriendWatchListing * >::iterator i;
394 for(i = watchedList.begin(); i != watchedList.end(); i++)
395 {
396 if((*i)->name == game->white_name() || (*i)->name == game->black_name())
397 {
398 //notifies too often!!! FIXME
399 if((*i)->notify)
400 QMessageBox::information(0, tr("Match Started!"), tr("Match has started between %1 and %2").arg(game->white_name()).arg(game->black_name()));
401 return;
402 }
403 }
404 }
405
406 void NetworkConnection::drawPleaseWait(void)
407 {
408 QPushButton * cancelConnecting;
409
410 connectingDialog = new QMessageBox(QMessageBox::NoIcon, tr("Please wait"), tr("Connecting..."));
411 //connectingDialog->setWindowTitle();
412 //connectingDialog->setText();
413 cancelConnecting = connectingDialog->addButton(QMessageBox::Cancel);
414 connect(cancelConnecting, &QPushButton::clicked, this, &NetworkConnection::slot_cancelConnecting);
415 connectingDialog->show();
416 connectingDialog->setMinimumSize(180, 100);
417 }
418
419 void NetworkConnection::slot_cancelConnecting(void)
420 {
421 userCanceled();
422 connectingDialog->deleteLater();
423 connectingDialog = 0;
424 }
425
426 void NetworkConnection::OnConnected()
427 {
428 }
429
430 void NetworkConnection::onAuthenticationNegotiated(void)
431 {
432 setupRoomAndConsole();
433 console_dispatch->recvText(QString("Connected")); //peerAddress returns 0 for some reason FIXME
434 //console_dispatch->recvText(QString("Connected to ") + qsocket->peerAddress().toString() + " " + QString::number(qsocket->peerPort()));
435 }
436
437 void NetworkConnection::onReady(void)
438 {
439 emit ready();
440 }
441
442 void NetworkConnection::OnReadyRead()
443 {
444 handlePendingData();
445 }
446
447 void NetworkConnection::OnConnectionClosed()
448 {
449 /* Without networkdispatch, this now needs to do something
450 * except FIXME only if there's actually been an error. like
451 * if we change servers and get disconnected, versus if we
452 * disconnect ourself.*/
453
454 // read last data that could be in the buffer WHY??
455 //OnReadyRead();
456 //authState = LOGIN;
457 //sendTextToApp("Connection closed by foreign host.\n");
458 /* I'm not yet sure what the best procedure is, but
459 * presumably this handler occurs when we disconnect
460 * or when there's an error. So we'll have it delete
461 * the main room which can then, upon deletion, notify
462 * the mainwindow_server code to delete the netdispatch
463 * which we'll delete the network connection... if
464 * there is one */
465 //if(default_room_dispatch)
466 // delete default_room_dispatch;
467 }
468
469 /*
470 // Connection was closed from application, but delayed
471 void IGSConnection::OnDelayedCloseFinish()
472 {
473 qDebug("DELAY CLOSED FINISHED");
474
475 authState = LOGIN;
476 sendTextToApp("Connection closed.\n");
477 }
478 */
479
480 void NetworkConnection::setState(ConnectionState newState)
481 {
482 connectionState = newState;
483 if((newState == Connected) && connectingDialog)
484 {
485 connectingDialog->deleteLater();
486 connectingDialog = NULL;
487 }
488 emit stateChanged(newState);
489 }
490
491 void NetworkConnection::OnError(QAbstractSocket::SocketError i)
492 {
493 /* FIXME These should pop up information boxes as
494 * well as somehow prevent the even attempted sending
495 * of other msgs? perhaps? like disconnect msgs?*/
496 qDebug() << "NetworkConnection::OnError() : TCP socket error: " << qsocket->errorString();
497 if(console_dispatch)
498 console_dispatch->recvText("TCP socket error: " + qsocket->errorString());
499 switch (i)
500 {
501 case QTcpSocket::ConnectionRefusedError:
502 setState(ConnectionRefused);
503 break;
504 case QTcpSocket::HostNotFoundError:
505 setState(HostNotFound);
506 break;
507 case QTcpSocket::SocketTimeoutError:
508 setState(SockTimeout);
509 break;
510 case QTcpSocket::RemoteHostClosedError:
511 setState(ProtocolError);
512 break;
513 default:
514 setState(UnknownError);
515 break;
516 }
517
518 if(connectingDialog)
519 {
520 connectingDialog->deleteLater();
521 connectingDialog = 0;
522 }
523 //sendTextToApp("ERROR - Connection closed.\n"+ qsocket->errorString() );
524 //OnReadyRead();
525 /* We need to toggle the connection flag, close things up, etc.. */
526
527 /* FIXME, we need to also notify the board dispatches, etc., not just ignore it, it should close everything and prevent
528 * those board window, do you want to resign messages */
529 if(connectionWidget) //mainwindow can ignore if loginDialog is open
530 connectionWidget->onConnectionError();
531 }
532
533 void NetworkConnection::setupRoomAndConsole(void)
534 {
535 mainwindowroom = new Room(this);
536 mainwindowroom->setConnection(this);
537 /* Two calls are needed beacause Room has a two step
538 * initialization process that should be merged
539 * in the constructor FIXME */
540 setDefaultRoom(mainwindowroom);
541
542 console_dispatch = new ConsoleDispatch(this);
543 setConsoleDispatch(console_dispatch);
544
545 loadfriendswatches();
546 }
547
548 void NetworkConnection::tearDownRoomAndConsole(void)
549 {
550 savefriendswatches();
551 QMap<unsigned int, class BoardDispatch *>::iterator i;
552 for(i = boardDispatchMap.begin(); i != boardDispatchMap.end(); i++)
553 {
554 (i.value())->setConnection(NULL);
555 }
556 boardDispatchMap.clear();
557 gameDialogMap.clear(); // FIXME probably unnecessary
558
559 if(mainwindowroom)
560 {
561 delete mainwindowroom;
562 mainwindowroom = 0;
563 }
564 if(console_dispatch)
565 {
566 delete console_dispatch;
567 console_dispatch = 0;
568 }
569 }
570
571 /* Edit friends/watches list window is created when needed.
572 * but we might consider having it always existing and then
573 * show hide it? That's ugly though. But like these functions
574 * should probably be part of a friendsfan class instead of
575 * the network connection awkward but perhaps minor FIXME */
576 void NetworkConnection::loadfriendswatches(void)
577 {
578 QSettings settings;
579 int size, i;
580 if(!supportsFriendList())
581 {
582 size = settings.beginReadArray("FRIENDEDLIST");
583 for (i = 0; i < size; ++i)
584 {
585 settings.setArrayIndex(i);
586 friendedList.push_back(new FriendWatchListing(
587 settings.value("name").toString(),
588 settings.value("notify").toBool()));
589 }
590 settings.endArray();
591 }
592 if(!supportsWatchList())
593 {
594 size = settings.beginReadArray("WATCHEDLIST");
595 for (i = 0; i < size; ++i)
596 {
597 settings.setArrayIndex(i);
598 watchedList.push_back(new FriendWatchListing(
599 settings.value("name").toString(),
600 settings.value("notify").toBool()));
601 }
602 settings.endArray();
603 }
604 if(!supportsBlockList())
605 {
606 size = settings.beginReadArray("BLOCKEDLIST");
607 for (i = 0; i < size; ++i)
608 {
609 settings.setArrayIndex(i);
610 blockedList.push_back(new FriendWatchListing(
611 settings.value("name").toString()));
612 }
613 settings.endArray();
614 }
615 }
616
617 void NetworkConnection::savefriendswatches(void)
618 {
619 QSettings settings;
620 int index;
621 if(!supportsFriendList())
622 {
623 settings.beginWriteArray("FRIENDEDLIST");
624 std::vector<FriendWatchListing * >::iterator i;
625 index = 0;
626 for (i = friendedList.begin(); i != friendedList.end(); i++)
627 {
628 settings.setArrayIndex(index);
629 settings.setValue("name", (*i)->name);
630 settings.setValue("notify", (*i)->notify);
631 delete (*i);
632 index++;
633 }
634 settings.endArray();
635 }
636 if(!supportsWatchList())
637 {
638 settings.beginWriteArray("WATCHEDLIST");
639 std::vector<FriendWatchListing * >::iterator i;
640 index = 0;
641 for (i = watchedList.begin(); i != watchedList.end(); i++)
642 {
643 settings.setArrayIndex(index);
644 settings.setValue("name", (*i)->name);
645 settings.setValue("notify", (*i)->notify);
646 delete (*i);
647 index++;
648 }
649 settings.endArray();
650 }
651 if(!supportsBlockList())
652 {
653 settings.beginWriteArray("BLOCKEDLIST");
654 std::vector<FriendWatchListing * >::iterator i;
655 index = 0;
656 for (i = blockedList.begin(); i != blockedList.end(); i++)
657 {
658 settings.setArrayIndex(index);
659 settings.setValue("name", (*i)->name);
660 delete (*i);
661 index++;
662 }
663 settings.endArray();
664 }
665 }
666
667 /* Problem if messages come out of order */
668 void NetworkConnection::latencyOnSend(void)
669 {
670 #ifdef LATENCY
671 gettimeofday(&latencyLast, NULL);
672 #endif //LATENCY
673 }
674
675 void NetworkConnection::latencyOnRecv(void)
676 {
677 #ifdef LATENCY
678 unsigned long ms;
679 struct timeval tv;
680 gettimeofday(&tv, NULL);
681 ms = (tv.tv_sec - latencyLast.tv_sec) * 1000;
682 ms += (tv.tv_usec - latencyLast.tv_usec);
683 latencyAverage += ms;
684 latencyAverage /= 2;
685 #endif //LATENCY
686 }
687
688 void NetworkConnection::sendConsoleText(const char * text)
689 {
690 //FIXME issue
691 if(console_dispatch)
692 console_dispatch->sendText(text);
693 }
694
695 /* I was thinking about breakng up the seeks and rooms by room dispatch, etc.
696 * originally, but if we're getting rid of the dispatches and we haven't
697 * yet seen anymore interesting use for a room dispatch then, we'll just
698 * let the network connection handle it for now. */
699 /* Also, I'm not in a hurry to have the sub connections calling mainwindow
700 * functions, but it is global and it is awkward to call recvRoomListing within
701 * the subconnection FIXME */
702 void NetworkConnection::recvRoomListing(class RoomListing * r)
703 {
704 if(connectionWidget)
705 connectionWidget->recvRoomListing(*r, true);
706 else
707 delete r;
708 }
709
710 void NetworkConnection::recvChannelListing(class ChannelListing * r)
711 {
712 if(connectionWidget)
713 connectionWidget->recvChannelListing(*r, true);
714 else
715 delete r;
716 }
717
718 void NetworkConnection::changeChannel(const QString & s)
719 {
720 if(connectionWidget)
721 connectionWidget->changeChannel(s);
722 }
723
724 void NetworkConnection::recvSeekCondition(class SeekCondition * s)
725 {
726 if(connectionWidget)
727 connectionWidget->recvSeekCondition(s);
728 else
729 delete s;
730 }
731
732 void NetworkConnection::recvSeekCancel(void)
733 {
734 if(connectionWidget)
735 connectionWidget->recvSeekCancel();
736 }
737
738 void NetworkConnection::recvSeekPlayer(QString player, QString condition)
739 {
740 if(connectionWidget)
741 connectionWidget->recvSeekPlayer(player, condition);
742 }
743
744 const PlayerListing * NetworkConnection::getOurListing(void)
745 {
746 if (ourListing == NULL)
747 ourListing = getDefaultRoom()->getPlayerListing(getUsername());
748 return ourListing;
749 }
750
751 /* FIXME These are really more like netdispatch type functions, but the registries
752 * are on the connection right now. We might want to move them though at
753 * some point if that does seem to make more sense in terms of the namespace. */
754 BoardDispatch * NetworkConnection::getBoardDispatch(unsigned int game_id)
755 {
756 BoardDispatch * result = getIfBoardDispatch(game_id);
757 if (result == NULL)
758 {
759 result = this->getDefaultRoom()->getNewBoardDispatch(game_id);
760 boardDispatchMap.insert(game_id, result);
761 }
762 return result;
763 }
764
765 BoardDispatch * NetworkConnection::getIfBoardDispatch(unsigned int game_id)
766 {
767 QMap <unsigned int, BoardDispatch *>::const_iterator i = boardDispatchMap.find(game_id);
768 if(i == boardDispatchMap.end())
769 return NULL;
770 else
771 return i.value();
772 }
773
774 void NetworkConnection::closeBoardDispatch(unsigned int game_id)
775 {
776 QMap <unsigned int, BoardDispatch *>::iterator i = boardDispatchMap.find(game_id);
777 if(i == boardDispatchMap.end())
778 return;
779
780 delete i.value();
781 boardDispatchMap.erase(i);
782 }
783
784 int NetworkConnection::getBoardDispatches(void)
785 {
786 return boardDispatchMap.count();
787 }
788
789 GameDialog * NetworkConnection::getGameDialog(const PlayerListing * opponent)
790 {
791 QMap <const PlayerListing *, GameDialog *>::const_iterator i = gameDialogMap.find(opponent);
792 if(i == gameDialogMap.end())
793 {
794 // Create if it does not exist
795 GameDialog * newDialog = new GameDialog(this, opponent);
796 gameDialogMap.insert(opponent, newDialog);
797 return newDialog;
798 }
799 else
800 return i.value();
801 }
802
803 GameDialog * NetworkConnection::getIfGameDialog(const PlayerListing * opponent)
804 {
805 QMap <const PlayerListing *, GameDialog *>::const_iterator i = gameDialogMap.find(opponent);
806 if(i == gameDialogMap.end())
807 return NULL;
808 else
809 return i.value();
810 }
811
812 void NetworkConnection::closeGameDialog(const PlayerListing * opponent)
813 {
814 QMap <const PlayerListing *, GameDialog *>::iterator i = gameDialogMap.find(opponent);
815 if(i == gameDialogMap.end())
816 return;
817
818 i.value()->deleteLater();
819 gameDialogMap.erase(i);
820 }
821
822 MatchRequest * NetworkConnection::getAndCloseGameDialog(const PlayerListing * opponent)
823 {
824 GameDialog * gd = getIfGameDialog(opponent);
825 MatchRequest * new_mr = 0;
826 if(gd)
827 {
828 MatchRequest * mr = gd->getMatchRequest();
829 new_mr = new MatchRequest(*mr);
830 closeGameDialog(opponent);
831 }
832 else
833 qDebug("Couldn't find gamedialog for opponent: %s", opponent->name.toLatin1().constData());
834 return new_mr;
835 }