lobby_moc.cpp 15 KB

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