lobby_moc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /*
  2. * lobby_moc.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "main.h"
  12. #include "lobby_moc.h"
  13. #include "ui_lobby_moc.h"
  14. #include "lobbyroomrequest_moc.h"
  15. #include "../mainwindow_moc.h"
  16. #include "../modManager/cmodlist.h"
  17. #include "../../lib/CConfigHandler.h"
  18. enum GameMode
  19. {
  20. NEW_GAME = 0, LOAD_GAME = 1
  21. };
  22. enum ModResolutionRoles
  23. {
  24. ModNameRole = Qt::UserRole + 1,
  25. ModEnableRole,
  26. ModResolvableRole
  27. };
  28. Lobby::Lobby(QWidget *parent) :
  29. QWidget(parent),
  30. ui(new Ui::Lobby)
  31. {
  32. ui->setupUi(this);
  33. connect(&socketLobby, SIGNAL(text(QString)), ui->chatWidget, SLOT(sysMessage(QString)));
  34. connect(&socketLobby, SIGNAL(receive(QString)), this, SLOT(dispatchMessage(QString)));
  35. connect(&socketLobby, SIGNAL(disconnect()), this, SLOT(onDisconnected()));
  36. connect(ui->chatWidget, SIGNAL(messageSent(QString)), this, SLOT(onMessageSent(QString)));
  37. connect(ui->chatWidget, SIGNAL(channelSwitch(QString)), this, SLOT(onChannelSwitch(QString)));
  38. QString hostString("%1:%2");
  39. hostString = hostString.arg(QString::fromStdString(settings["launcher"]["lobbyUrl"].String()));
  40. hostString = hostString.arg(settings["launcher"]["lobbyPort"].Integer());
  41. ui->serverEdit->setText(hostString);
  42. ui->userEdit->setText(QString::fromStdString(settings["launcher"]["lobbyUsername"].String()));
  43. ui->kickButton->setVisible(false);
  44. }
  45. void Lobby::changeEvent(QEvent *event)
  46. {
  47. if(event->type() == QEvent::LanguageChange)
  48. {
  49. ui->retranslateUi(this);
  50. }
  51. QWidget::changeEvent(event);
  52. }
  53. Lobby::~Lobby()
  54. {
  55. delete ui;
  56. }
  57. QMap<QString, QString> Lobby::buildModsMap() const
  58. {
  59. QMap<QString, QString> result;
  60. QObject * mainWindow = qApp->activeWindow();
  61. if(!mainWindow)
  62. mainWindow = parent();
  63. if(!mainWindow)
  64. return result; //probably something is really wrong here
  65. while(mainWindow->parent())
  66. mainWindow = mainWindow->parent();
  67. const auto & modlist = qobject_cast<MainWindow*>(mainWindow)->getModList();
  68. for(auto & modname : modlist.getModList())
  69. {
  70. auto mod = modlist.getMod(modname);
  71. if(mod.isEnabled())
  72. {
  73. result[modname] = mod.getValue("version").toString();
  74. }
  75. }
  76. return result;
  77. }
  78. bool Lobby::isModAvailable(const QString & modName, const QString & modVersion) const
  79. {
  80. QObject * mainWindow = qApp->activeWindow();
  81. while(mainWindow->parent())
  82. mainWindow = mainWindow->parent();
  83. const auto & modlist = qobject_cast<MainWindow*>(mainWindow)->getModList();
  84. if(!modlist.hasMod(modName))
  85. return false;
  86. auto mod = modlist.getMod(modName);
  87. return (mod.isInstalled () || mod.isAvailable()) && (mod.getValue("version") == modVersion);
  88. }
  89. void Lobby::serverCommand(const ServerCommand & command) try
  90. {
  91. //initialize variables outside of switch block
  92. const QString statusPlaceholder("%1 %2\n");
  93. const auto & args = command.arguments;
  94. int amount;
  95. int tagPoint;
  96. QString joinStr;
  97. switch(command.command)
  98. {
  99. case SRVERROR:
  100. protocolAssert(args.size());
  101. ui->chatWidget->chatMessage("System error", args[0], true);
  102. if(authentificationStatus == AuthStatus::AUTH_NONE)
  103. authentificationStatus = AuthStatus::AUTH_ERROR;
  104. break;
  105. case CREATED:
  106. protocolAssert(args.size());
  107. hostSession = args[0];
  108. session = args[0];
  109. ui->chatWidget->setSession(session);
  110. break;
  111. case SESSIONS:
  112. protocolAssert(args.size());
  113. amount = args[0].toInt();
  114. protocolAssert(amount * 4 == (args.size() - 1));
  115. ui->sessionsTable->setRowCount(amount);
  116. tagPoint = 1;
  117. for(int i = 0; i < amount; ++i)
  118. {
  119. QTableWidgetItem * sessionNameItem = new QTableWidgetItem(args[tagPoint++]);
  120. ui->sessionsTable->setItem(i, 0, sessionNameItem);
  121. int playersJoined = args[tagPoint++].toInt();
  122. int playersTotal = args[tagPoint++].toInt();
  123. QTableWidgetItem * sessionPlayerItem = new QTableWidgetItem(QString("%1/%2").arg(playersJoined).arg(playersTotal));
  124. ui->sessionsTable->setItem(i, 1, sessionPlayerItem);
  125. QTableWidgetItem * sessionProtectedItem = new QTableWidgetItem();
  126. bool isPrivate = (args[tagPoint++] == "True");
  127. sessionProtectedItem->setData(Qt::UserRole, isPrivate);
  128. if(isPrivate)
  129. sessionProtectedItem->setIcon(QIcon("icons:room-private.png"));
  130. ui->sessionsTable->setItem(i, 2, sessionProtectedItem);
  131. }
  132. break;
  133. case JOINED:
  134. case KICKED:
  135. protocolAssert(args.size() == 2);
  136. if(args[1] == username)
  137. {
  138. hostModsMap.clear();
  139. session = "";
  140. ui->chatWidget->setSession(session);
  141. ui->buttonReady->setText("Ready");
  142. ui->optNewGame->setChecked(true);
  143. session = args[0];
  144. ui->chatWidget->setSession(session);
  145. bool isHost = command.command == JOINED && hostSession == session;
  146. ui->optNewGame->setEnabled(isHost);
  147. ui->optLoadGame->setEnabled(isHost);
  148. ui->stackedWidget->setCurrentWidget(command.command == JOINED ? ui->roomPage : ui->sessionsPage);
  149. }
  150. else
  151. {
  152. joinStr = (command.command == JOINED ? "%1 joined to the session %2" : "%1 left session %2");
  153. ui->chatWidget->sysMessage(joinStr.arg(args[1], args[0]));
  154. }
  155. break;
  156. case MODS: {
  157. protocolAssert(args.size() > 0);
  158. amount = args[0].toInt();
  159. protocolAssert(amount * 2 == (args.size() - 1));
  160. tagPoint = 1;
  161. for(int i = 0; i < amount; ++i, tagPoint += 2)
  162. hostModsMap[args[tagPoint]] = args[tagPoint + 1];
  163. updateMods();
  164. break;
  165. }
  166. case CLIENTMODS: {
  167. protocolAssert(args.size() >= 1);
  168. auto & clientModsMap = clientsModsMap[args[0]];
  169. amount = args[1].toInt();
  170. protocolAssert(amount * 2 == (args.size() - 2));
  171. tagPoint = 2;
  172. for(int i = 0; i < amount; ++i, tagPoint += 2)
  173. clientModsMap[args[tagPoint]] = args[tagPoint + 1];
  174. break;
  175. }
  176. case STATUS:
  177. protocolAssert(args.size() > 0);
  178. amount = args[0].toInt();
  179. protocolAssert(amount * 2 == (args.size() - 1));
  180. tagPoint = 1;
  181. ui->playersList->clear();
  182. for(int i = 0; i < amount; ++i, tagPoint += 2)
  183. {
  184. if(args[tagPoint + 1] == "True")
  185. ui->playersList->addItem(new QListWidgetItem(QIcon("icons:mod-enabled.png"), args[tagPoint]));
  186. else
  187. ui->playersList->addItem(new QListWidgetItem(QIcon("icons:mod-disabled.png"), args[tagPoint]));
  188. if(args[tagPoint] == username)
  189. {
  190. if(args[tagPoint + 1] == "True")
  191. ui->buttonReady->setText("Not ready");
  192. else
  193. ui->buttonReady->setText("Ready");
  194. }
  195. }
  196. break;
  197. case START: {
  198. protocolAssert(args.size() == 1);
  199. //actually start game
  200. gameArgs << "--lobby";
  201. gameArgs << "--lobby-address" << serverUrl;
  202. gameArgs << "--lobby-port" << QString::number(serverPort);
  203. gameArgs << "--lobby-username" << username;
  204. gameArgs << "--lobby-gamemode" << QString::number(isLoadGameMode);
  205. gameArgs << "--uuid" << args[0];
  206. startGame(gameArgs);
  207. break;
  208. }
  209. case HOST: {
  210. protocolAssert(args.size() == 2);
  211. gameArgs << "--lobby-host";
  212. gameArgs << "--lobby-uuid" << args[0];
  213. gameArgs << "--lobby-connections" << args[1];
  214. break;
  215. }
  216. case CHAT: {
  217. protocolAssert(args.size() > 1);
  218. QString msg;
  219. for(int i = 1; i < args.size(); ++i)
  220. msg += args[i];
  221. ui->chatWidget->chatMessage(args[0], msg);
  222. break;
  223. }
  224. case CHATCHANNEL: {
  225. protocolAssert(args.size() > 2);
  226. QString msg;
  227. for(int i = 2; i < args.size(); ++i)
  228. msg += args[i];
  229. ui->chatWidget->chatMessage(args[0], args[1], msg);
  230. break;
  231. }
  232. case CHANNEL: {
  233. protocolAssert(args.size() == 1);
  234. ui->chatWidget->setChannel(args[0]);
  235. break;
  236. }
  237. case HEALTH: {
  238. socketLobby.send(ProtocolStrings[ALIVE]);
  239. break;
  240. }
  241. case USERS: {
  242. protocolAssert(args.size() > 0);
  243. amount = args[0].toInt();
  244. protocolAssert(amount == (args.size() - 1));
  245. ui->chatWidget->clearUsers();
  246. for(int i = 0; i < amount; ++i)
  247. {
  248. ui->chatWidget->addUser(args[i + 1]);
  249. }
  250. break;
  251. }
  252. case GAMEMODE: {
  253. protocolAssert(args.size() == 1);
  254. isLoadGameMode = args[0].toInt();
  255. if(isLoadGameMode)
  256. ui->optLoadGame->setChecked(true);
  257. else
  258. ui->optNewGame->setChecked(true);
  259. break;
  260. }
  261. default:
  262. ui->chatWidget->sysMessage("Unknown server command");
  263. }
  264. if(authentificationStatus == AuthStatus::AUTH_ERROR)
  265. {
  266. socketLobby.disconnectServer();
  267. }
  268. else
  269. {
  270. authentificationStatus = AuthStatus::AUTH_OK;
  271. ui->newButton->setEnabled(true);
  272. }
  273. }
  274. catch(const ProtocolError & e)
  275. {
  276. ui->chatWidget->chatMessage("System error", e.what(), true);
  277. }
  278. void Lobby::dispatchMessage(QString txt) try
  279. {
  280. if(txt.isEmpty())
  281. return;
  282. QStringList parseTags = txt.split(":>>");
  283. protocolAssert(parseTags.size() > 1 && parseTags[0].isEmpty() && !parseTags[1].isEmpty());
  284. for(int c = 1; c < parseTags.size(); ++c)
  285. {
  286. QStringList parseArgs = parseTags[c].split(":");
  287. protocolAssert(parseArgs.size() > 1);
  288. auto ctype = ProtocolStrings.key(parseArgs[0]);
  289. parseArgs.pop_front();
  290. ServerCommand cmd(ctype, parseArgs);
  291. serverCommand(cmd);
  292. }
  293. }
  294. catch(const ProtocolError & e)
  295. {
  296. ui->chatWidget->chatMessage("System error", e.what(), true);
  297. }
  298. void Lobby::onDisconnected()
  299. {
  300. authentificationStatus = AuthStatus::AUTH_NONE;
  301. session = "";
  302. ui->chatWidget->setSession(session);
  303. ui->chatWidget->setChannel("global");
  304. ui->stackedWidget->setCurrentWidget(ui->sessionsPage);
  305. ui->connectButton->setChecked(false);
  306. ui->serverEdit->setEnabled(true);
  307. ui->userEdit->setEnabled(true);
  308. ui->newButton->setEnabled(false);
  309. ui->joinButton->setEnabled(false);
  310. ui->sessionsTable->setRowCount(0);
  311. }
  312. void Lobby::protocolAssert(bool expr)
  313. {
  314. if(!expr)
  315. throw ProtocolError("Protocol error");
  316. }
  317. void Lobby::on_connectButton_toggled(bool checked)
  318. {
  319. if(checked)
  320. {
  321. ui->connectButton->setText(tr("Disconnect"));
  322. authentificationStatus = AuthStatus::AUTH_NONE;
  323. username = ui->userEdit->text();
  324. ui->chatWidget->setUsername(username);
  325. const int connectionTimeout = settings["launcher"]["connectionTimeout"].Integer();
  326. auto serverStrings = ui->serverEdit->text().split(":");
  327. if(serverStrings.size() != 2)
  328. {
  329. QMessageBox::critical(this, "Connection error", "Server address must have the format URL:port");
  330. return;
  331. }
  332. serverUrl = serverStrings[0];
  333. serverPort = serverStrings[1].toInt();
  334. Settings node = settings.write["launcher"];
  335. node["lobbyUrl"].String() = serverUrl.toStdString();
  336. node["lobbyPort"].Integer() = serverPort;
  337. node["lobbyUsername"].String() = username.toStdString();
  338. ui->serverEdit->setEnabled(false);
  339. ui->userEdit->setEnabled(false);
  340. ui->chatWidget->sysMessage("Connecting to " + serverUrl + ":" + QString::number(serverPort));
  341. //show text immediately
  342. ui->chatWidget->repaint();
  343. qApp->processEvents();
  344. socketLobby.connectServer(serverUrl, serverPort, username, connectionTimeout);
  345. }
  346. else
  347. {
  348. ui->connectButton->setText(tr("Connect"));
  349. ui->serverEdit->setEnabled(true);
  350. ui->userEdit->setEnabled(true);
  351. ui->chatWidget->clearUsers();
  352. hostModsMap.clear();
  353. updateMods();
  354. socketLobby.disconnectServer();
  355. }
  356. }
  357. void Lobby::updateMods()
  358. {
  359. ui->modsList->clear();
  360. if(hostModsMap.empty())
  361. return;
  362. auto createModListWidget = [](const QIcon & icon, const QString & label, const QString & name, bool enableFlag, bool resolveFlag)
  363. {
  364. auto * lw = new QListWidgetItem(icon, label);
  365. lw->setData(ModResolutionRoles::ModNameRole, name);
  366. lw->setData(ModResolutionRoles::ModEnableRole, enableFlag);
  367. lw->setData(ModResolutionRoles::ModResolvableRole, resolveFlag);
  368. return lw;
  369. };
  370. auto enabledMods = buildModsMap();
  371. for(const auto & mod : hostModsMap.keys())
  372. {
  373. auto & modValue = hostModsMap[mod];
  374. auto modName = QString("%1 (v%2)").arg(mod, modValue);
  375. if(enabledMods.contains(mod))
  376. {
  377. if(enabledMods[mod] == modValue)
  378. enabledMods.remove(mod); //mod fully matches, remove from list
  379. else
  380. {
  381. //mod version mismatch
  382. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-update.png"), modName, mod, true, false));
  383. }
  384. }
  385. else if(isModAvailable(mod, modValue))
  386. {
  387. //mod is available and needs to be enabled
  388. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-enabled.png"), modName, mod, true, true));
  389. }
  390. else
  391. {
  392. //mod is not available and needs to be installed
  393. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-delete.png"), modName, mod, true, false));
  394. }
  395. }
  396. for(const auto & remainMod : enabledMods.keys())
  397. {
  398. auto modName = QString("%1 (v%2)").arg(remainMod, enabledMods[remainMod]);
  399. //mod needs to be disabled
  400. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-disabled.png"), modName, remainMod, false, true));
  401. }
  402. if(!ui->modsList->count())
  403. {
  404. ui->buttonResolve->setEnabled(false);
  405. ui->modsList->addItem(tr("No issues detected"));
  406. }
  407. else
  408. {
  409. ui->buttonResolve->setEnabled(true);
  410. }
  411. }
  412. void Lobby::on_newButton_clicked()
  413. {
  414. new LobbyRoomRequest(socketLobby, "", buildModsMap(), this);
  415. }
  416. void Lobby::on_joinButton_clicked()
  417. {
  418. auto * item = ui->sessionsTable->item(ui->sessionsTable->currentRow(), 0);
  419. if(item)
  420. {
  421. auto isPrivate = ui->sessionsTable->item(ui->sessionsTable->currentRow(), 2)->data(Qt::UserRole).toBool();
  422. if(isPrivate)
  423. new LobbyRoomRequest(socketLobby, item->text(), buildModsMap(), this);
  424. else
  425. socketLobby.requestJoinSession(item->text(), "", buildModsMap());
  426. }
  427. }
  428. void Lobby::on_buttonLeave_clicked()
  429. {
  430. socketLobby.requestLeaveSession(session);
  431. }
  432. void Lobby::on_buttonReady_clicked()
  433. {
  434. if(ui->buttonReady->text() == "Ready")
  435. ui->buttonReady->setText("Not ready");
  436. else
  437. ui->buttonReady->setText("Ready");
  438. socketLobby.requestReadySession(session);
  439. }
  440. void Lobby::on_sessionsTable_itemSelectionChanged()
  441. {
  442. auto selection = ui->sessionsTable->selectedItems();
  443. ui->joinButton->setEnabled(!selection.empty());
  444. }
  445. void Lobby::on_playersList_currentRowChanged(int currentRow)
  446. {
  447. ui->kickButton->setVisible(ui->playersList->currentItem()
  448. && currentRow > 0
  449. && ui->playersList->currentItem()->text() != username);
  450. }
  451. void Lobby::on_kickButton_clicked()
  452. {
  453. if(ui->playersList->currentItem() && ui->playersList->currentItem()->text() != username)
  454. socketLobby.send(ProtocolStrings[KICK].arg(ui->playersList->currentItem()->text()));
  455. }
  456. void Lobby::on_buttonResolve_clicked()
  457. {
  458. QStringList toEnableList;
  459. QStringList toDisableList;
  460. auto items = ui->modsList->selectedItems();
  461. if(items.empty())
  462. {
  463. for(int i = 0; i < ui->modsList->count(); ++i)
  464. items.push_back(ui->modsList->item(i));
  465. }
  466. for(auto * item : items)
  467. {
  468. auto modName = item->data(ModResolutionRoles::ModNameRole);
  469. if(modName.isNull())
  470. continue;
  471. bool modToEnable = item->data(ModResolutionRoles::ModEnableRole).toBool();
  472. bool modToResolve = item->data(ModResolutionRoles::ModResolvableRole).toBool();
  473. if(!modToResolve)
  474. continue;
  475. if(modToEnable)
  476. toEnableList << modName.toString();
  477. else
  478. toDisableList << modName.toString();
  479. }
  480. //disabling first, then enabling
  481. for(auto & mod : toDisableList)
  482. emit disableMod(mod);
  483. for(auto & mod : toEnableList)
  484. emit enableMod(mod);
  485. }
  486. void Lobby::on_optNewGame_toggled(bool checked)
  487. {
  488. if(checked)
  489. {
  490. if(isLoadGameMode)
  491. socketLobby.send(ProtocolStrings[HOSTMODE].arg(GameMode::NEW_GAME));
  492. }
  493. }
  494. void Lobby::on_optLoadGame_toggled(bool checked)
  495. {
  496. if(checked)
  497. {
  498. if(!isLoadGameMode)
  499. socketLobby.send(ProtocolStrings[HOSTMODE].arg(GameMode::LOAD_GAME));
  500. }
  501. }
  502. void Lobby::onMessageSent(QString message)
  503. {
  504. socketLobby.send(ProtocolStrings[MESSAGE].arg(message));
  505. }
  506. void Lobby::onChannelSwitch(QString channel)
  507. {
  508. socketLobby.send(ProtocolStrings[SETCHANNEL].arg(channel));
  509. }