lobby_moc.cpp 15 KB

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