lobby_moc.cpp 14 KB

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