lobby_moc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. namesCompleter.setModel(ui->listUsers->model());
  40. namesCompleter.setCompletionMode(QCompleter::InlineCompletion);
  41. ui->serverEdit->setText(hostString);
  42. ui->userEdit->setText(QString::fromStdString(settings["launcher"]["lobbyUsername"].String()));
  43. ui->kickButton->setVisible(false);
  44. ui->messageEdit->setCompleter(&namesCompleter);
  45. }
  46. void Lobby::changeEvent(QEvent *event)
  47. {
  48. if(event->type() == QEvent::LanguageChange)
  49. {
  50. ui->retranslateUi(this);
  51. }
  52. QWidget::changeEvent(event);
  53. }
  54. Lobby::~Lobby()
  55. {
  56. delete ui;
  57. }
  58. QMap<QString, QString> Lobby::buildModsMap() const
  59. {
  60. QMap<QString, QString> result;
  61. QObject * mainWindow = qApp->activeWindow();
  62. if(!mainWindow)
  63. mainWindow = parent();
  64. if(!mainWindow)
  65. return result; //probably something is really wrong here
  66. while(mainWindow->parent())
  67. mainWindow = mainWindow->parent();
  68. const auto & modlist = qobject_cast<MainWindow*>(mainWindow)->getModList();
  69. for(auto & modname : modlist.getModList())
  70. {
  71. auto mod = modlist.getMod(modname);
  72. if(mod.isEnabled())
  73. {
  74. result[modname] = mod.getValue("version").toString();
  75. }
  76. }
  77. return result;
  78. }
  79. bool Lobby::isModAvailable(const QString & modName, const QString & modVersion) const
  80. {
  81. QObject * mainWindow = qApp->activeWindow();
  82. while(mainWindow->parent())
  83. mainWindow = mainWindow->parent();
  84. const auto & modlist = qobject_cast<MainWindow*>(mainWindow)->getModList();
  85. if(!modlist.hasMod(modName))
  86. return false;
  87. auto mod = modlist.getMod(modName);
  88. return (mod.isInstalled () || mod.isAvailable()) && (mod.getValue("version") == modVersion);
  89. }
  90. void Lobby::serverCommand(const ServerCommand & command) try
  91. {
  92. //initialize variables outside of switch block
  93. const QString statusPlaceholder("%1 %2\n");
  94. const auto & args = command.arguments;
  95. int amount, tagPoint;
  96. QString joinStr;
  97. switch(command.command)
  98. {
  99. case SRVERROR:
  100. protocolAssert(args.size());
  101. 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. sysMessage("new session started");
  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. session = "";
  137. joinStr = (command.command == JOINED ? "%1 joined to the session %2" : "%1 left session %2");
  138. if(args[1] == username)
  139. {
  140. hostModsMap.clear();
  141. ui->buttonReady->setText("Ready");
  142. ui->optNewGame->setChecked(true);
  143. sysMessage(joinStr.arg("you", args[0]));
  144. session = args[0];
  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. 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. chatMessage(args[0], msg);
  218. break;
  219. }
  220. case HEALTH: {
  221. socketLobby.send(ProtocolStrings[ALIVE]);
  222. break;
  223. }
  224. case USERS: {
  225. protocolAssert(args.size() > 0);
  226. amount = args[0].toInt();
  227. protocolAssert(amount == (args.size() - 1));
  228. ui->listUsers->clear();
  229. for(int i = 0; i < amount; ++i)
  230. {
  231. ui->listUsers->addItem(new QListWidgetItem("@" + args[i + 1]));
  232. }
  233. break;
  234. }
  235. case GAMEMODE: {
  236. protocolAssert(args.size() == 1);
  237. isLoadGameMode = args[0].toInt();
  238. if(isLoadGameMode)
  239. ui->optLoadGame->setChecked(true);
  240. else
  241. ui->optNewGame->setChecked(true);
  242. break;
  243. }
  244. default:
  245. sysMessage("Unknown server command");
  246. }
  247. if(authentificationStatus == AuthStatus::AUTH_ERROR)
  248. {
  249. socketLobby.disconnectServer();
  250. }
  251. else
  252. {
  253. authentificationStatus = AuthStatus::AUTH_OK;
  254. ui->newButton->setEnabled(true);
  255. }
  256. }
  257. catch(const ProtocolError & e)
  258. {
  259. chatMessage("System error", e.what(), true);
  260. }
  261. void Lobby::dispatchMessage(QString txt) try
  262. {
  263. if(txt.isEmpty())
  264. return;
  265. QStringList parseTags = txt.split(":>>");
  266. protocolAssert(parseTags.size() > 1 && parseTags[0].isEmpty() && !parseTags[1].isEmpty());
  267. for(int c = 1; c < parseTags.size(); ++c)
  268. {
  269. QStringList parseArgs = parseTags[c].split(":");
  270. protocolAssert(parseArgs.size() > 1);
  271. auto ctype = ProtocolStrings.key(parseArgs[0]);
  272. parseArgs.pop_front();
  273. ServerCommand cmd(ctype, parseArgs);
  274. serverCommand(cmd);
  275. }
  276. }
  277. catch(const ProtocolError & e)
  278. {
  279. chatMessage("System error", e.what(), true);
  280. }
  281. void Lobby::onDisconnected()
  282. {
  283. authentificationStatus = AuthStatus::AUTH_NONE;
  284. session = "";
  285. ui->stackedWidget->setCurrentWidget(ui->sessionsPage);
  286. ui->connectButton->setChecked(false);
  287. ui->serverEdit->setEnabled(true);
  288. ui->userEdit->setEnabled(true);
  289. ui->newButton->setEnabled(false);
  290. ui->joinButton->setEnabled(false);
  291. ui->sessionsTable->setRowCount(0);
  292. }
  293. void Lobby::chatMessage(QString title, QString body, bool isSystem)
  294. {
  295. QTextCharFormat fmtBody, fmtTitle;
  296. fmtTitle.setFontWeight(QFont::Bold);
  297. if(isSystem)
  298. fmtBody.setFontWeight(QFont::DemiBold);
  299. QTextCursor curs(ui->chat->document());
  300. curs.movePosition(QTextCursor::End);
  301. curs.insertText(title + ": ", fmtTitle);
  302. curs.insertText(body + "\n", fmtBody);
  303. if(ui->chat->verticalScrollBar()->maximum() - ui->chat->verticalScrollBar()->value() > 32)
  304. {
  305. ui->chat->ensureCursorVisible();
  306. ui->chat->verticalScrollBar()->setValue(ui->chat->verticalScrollBar()->maximum());
  307. }
  308. }
  309. void Lobby::sysMessage(QString body)
  310. {
  311. chatMessage("System", body, true);
  312. }
  313. void Lobby::protocolAssert(bool expr)
  314. {
  315. if(!expr)
  316. throw ProtocolError("Protocol error");
  317. }
  318. void Lobby::on_messageEdit_returnPressed()
  319. {
  320. socketLobby.send(ProtocolStrings[MESSAGE].arg(ui->messageEdit->text()));
  321. ui->messageEdit->clear();
  322. }
  323. void Lobby::on_connectButton_toggled(bool checked)
  324. {
  325. if(checked)
  326. {
  327. ui->connectButton->setText(tr("Disconnect"));
  328. authentificationStatus = AuthStatus::AUTH_NONE;
  329. username = ui->userEdit->text();
  330. const int connectionTimeout = settings["launcher"]["connectionTimeout"].Integer();
  331. auto serverStrings = ui->serverEdit->text().split(":");
  332. if(serverStrings.size() != 2)
  333. {
  334. QMessageBox::critical(this, "Connection error", "Server address must have the format URL:port");
  335. return;
  336. }
  337. serverUrl = serverStrings[0];
  338. serverPort = serverStrings[1].toInt();
  339. Settings node = settings.write["launcher"];
  340. node["lobbyUrl"].String() = serverUrl.toStdString();
  341. node["lobbyPort"].Integer() = serverPort;
  342. node["lobbyUsername"].String() = username.toStdString();
  343. ui->serverEdit->setEnabled(false);
  344. ui->userEdit->setEnabled(false);
  345. sysMessage("Connecting to " + serverUrl + ":" + QString::number(serverPort));
  346. //show text immediately
  347. ui->chat->repaint();
  348. qApp->processEvents();
  349. socketLobby.connectServer(serverUrl, serverPort, username, connectionTimeout);
  350. }
  351. else
  352. {
  353. ui->connectButton->setText(tr("Connect"));
  354. ui->serverEdit->setEnabled(true);
  355. ui->userEdit->setEnabled(true);
  356. ui->listUsers->clear();
  357. hostModsMap.clear();
  358. updateMods();
  359. socketLobby.disconnectServer();
  360. }
  361. }
  362. void Lobby::updateMods()
  363. {
  364. ui->modsList->clear();
  365. if(hostModsMap.empty())
  366. return;
  367. auto createModListWidget = [](const QIcon & icon, const QString & label, const QString & name, bool enableFlag, bool resolveFlag)
  368. {
  369. auto * lw = new QListWidgetItem(icon, label);
  370. lw->setData(ModResolutionRoles::ModNameRole, name);
  371. lw->setData(ModResolutionRoles::ModEnableRole, enableFlag);
  372. lw->setData(ModResolutionRoles::ModResolvableRole, resolveFlag);
  373. return lw;
  374. };
  375. auto enabledMods = buildModsMap();
  376. for(const auto & mod : hostModsMap.keys())
  377. {
  378. auto & modValue = hostModsMap[mod];
  379. auto modName = QString("%1 (v%2)").arg(mod, modValue);
  380. if(enabledMods.contains(mod))
  381. {
  382. if(enabledMods[mod] == modValue)
  383. enabledMods.remove(mod); //mod fully matches, remove from list
  384. else
  385. {
  386. //mod version mismatch
  387. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-update.png"), modName, mod, true, false));
  388. }
  389. }
  390. else if(isModAvailable(mod, modValue))
  391. {
  392. //mod is available and needs to be enabled
  393. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-enabled.png"), modName, mod, true, true));
  394. }
  395. else
  396. {
  397. //mod is not available and needs to be installed
  398. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-delete.png"), modName, mod, true, false));
  399. }
  400. }
  401. for(const auto & remainMod : enabledMods.keys())
  402. {
  403. auto modName = QString("%1 (v%2)").arg(remainMod, enabledMods[remainMod]);
  404. //mod needs to be disabled
  405. ui->modsList->addItem(createModListWidget(QIcon("icons:mod-disabled.png"), modName, remainMod, false, true));
  406. }
  407. if(!ui->modsList->count())
  408. {
  409. ui->buttonResolve->setEnabled(false);
  410. ui->modsList->addItem(tr("No issues detected"));
  411. }
  412. else
  413. {
  414. ui->buttonResolve->setEnabled(true);
  415. }
  416. }
  417. void Lobby::on_newButton_clicked()
  418. {
  419. new LobbyRoomRequest(socketLobby, "", buildModsMap(), this);
  420. }
  421. void Lobby::on_joinButton_clicked()
  422. {
  423. auto * item = ui->sessionsTable->item(ui->sessionsTable->currentRow(), 0);
  424. if(item)
  425. {
  426. auto isPrivate = ui->sessionsTable->item(ui->sessionsTable->currentRow(), 2)->data(Qt::UserRole).toBool();
  427. if(isPrivate)
  428. new LobbyRoomRequest(socketLobby, item->text(), buildModsMap(), this);
  429. else
  430. socketLobby.requestJoinSession(item->text(), "", buildModsMap());
  431. }
  432. }
  433. void Lobby::on_buttonLeave_clicked()
  434. {
  435. socketLobby.requestLeaveSession(session);
  436. }
  437. void Lobby::on_buttonReady_clicked()
  438. {
  439. if(ui->buttonReady->text() == "Ready")
  440. ui->buttonReady->setText("Not ready");
  441. else
  442. ui->buttonReady->setText("Ready");
  443. socketLobby.requestReadySession(session);
  444. }
  445. void Lobby::on_sessionsTable_itemSelectionChanged()
  446. {
  447. auto selection = ui->sessionsTable->selectedItems();
  448. ui->joinButton->setEnabled(!selection.empty());
  449. }
  450. void Lobby::on_playersList_currentRowChanged(int currentRow)
  451. {
  452. ui->kickButton->setVisible(ui->playersList->currentItem()
  453. && currentRow > 0
  454. && ui->playersList->currentItem()->text() != username);
  455. }
  456. void Lobby::on_kickButton_clicked()
  457. {
  458. if(ui->playersList->currentItem() && ui->playersList->currentItem()->text() != username)
  459. socketLobby.send(ProtocolStrings[KICK].arg(ui->playersList->currentItem()->text()));
  460. }
  461. void Lobby::on_buttonResolve_clicked()
  462. {
  463. QStringList toEnableList, toDisableList;
  464. for(auto * item : ui->modsList->selectedItems())
  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::on_chatSwither_clicked()
  501. {
  502. isGlobalChat = session.isEmpty() ? true : !isGlobalChat;
  503. ui->chatSwither->setText(isGlobalChat ? tr("Global chat") : tr("Room chat"));
  504. }