CMainMenu.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. /*
  2. * CMainMenu.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 "CMainMenu.h"
  12. #include "CCampaignScreen.h"
  13. #include "CreditsScreen.h"
  14. #include "CHighScoreScreen.h"
  15. #include "../lobby/CBonusSelection.h"
  16. #include "../lobby/CSelectionBase.h"
  17. #include "../lobby/CLobbyScreen.h"
  18. #include "../gui/CursorHandler.h"
  19. #include "../windows/GUIClasses.h"
  20. #include "../gui/CGuiHandler.h"
  21. #include "../gui/ShortcutHandler.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../render/Canvas.h"
  25. #include "../serverLobby/LobbyWindow.h"
  26. #include "../widgets/CComponent.h"
  27. #include "../widgets/Buttons.h"
  28. #include "../widgets/MiscWidgets.h"
  29. #include "../widgets/ObjectLists.h"
  30. #include "../widgets/TextControls.h"
  31. #include "../windows/InfoWindows.h"
  32. #include "../CServerHandler.h"
  33. #include "../CGameInfo.h"
  34. #include "../CMusicHandler.h"
  35. #include "../CVideoHandler.h"
  36. #include "../CPlayerInterface.h"
  37. #include "../Client.h"
  38. #include "../CMT.h"
  39. #include "../../CCallback.h"
  40. #include "../../lib/CGeneralTextHandler.h"
  41. #include "../../lib/JsonNode.h"
  42. #include "../../lib/campaign/CampaignHandler.h"
  43. #include "../../lib/serializer/Connection.h"
  44. #include "../../lib/serializer/CTypeList.h"
  45. #include "../../lib/filesystem/Filesystem.h"
  46. #include "../../lib/filesystem/CCompressedStream.h"
  47. #include "../../lib/mapping/CMapInfo.h"
  48. #include "../../lib/modding/CModHandler.h"
  49. #include "../../lib/VCMIDirs.h"
  50. #include "../../lib/CStopWatch.h"
  51. #include "../../lib/CThreadHelper.h"
  52. #include "../../lib/CConfigHandler.h"
  53. #include "../../lib/GameConstants.h"
  54. #include "../../lib/CRandomGenerator.h"
  55. #include "../../lib/CondSh.h"
  56. #if defined(SINGLE_PROCESS_APP) && defined(VCMI_ANDROID)
  57. #include "../../server/CVCMIServer.h"
  58. #include <SDL.h>
  59. #endif
  60. std::shared_ptr<CMainMenu> CMM;
  61. ISelectionScreenInfo * SEL;
  62. static void do_quit()
  63. {
  64. GH.dispatchMainThread([]()
  65. {
  66. handleQuit(false);
  67. });
  68. }
  69. CMenuScreen::CMenuScreen(const JsonNode & configNode)
  70. : CWindowObject(BORDERED), config(configNode)
  71. {
  72. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  73. background = std::make_shared<CPicture>(ImagePath::fromJson(config["background"]));
  74. if(config["scalable"].Bool())
  75. background->scaleTo(GH.screenDimensions());
  76. pos = background->center();
  77. for(const JsonNode & node : config["items"].Vector())
  78. menuNameToEntry.push_back(node["name"].String());
  79. for(const JsonNode & node : config["images"].Vector())
  80. images.push_back(CMainMenu::createPicture(node));
  81. //Hardcoded entry
  82. menuNameToEntry.push_back("credits");
  83. tabs = std::make_shared<CTabbedInt>(std::bind(&CMenuScreen::createTab, this, _1));
  84. if(config["video"].isNull())
  85. tabs->setRedrawParent(true);
  86. }
  87. std::shared_ptr<CIntObject> CMenuScreen::createTab(size_t index)
  88. {
  89. if(config["items"].Vector().size() == index)
  90. return std::make_shared<CreditsScreen>(this->pos);
  91. else
  92. return std::make_shared<CMenuEntry>(this, config["items"].Vector()[index]);
  93. }
  94. void CMenuScreen::show(Canvas & to)
  95. {
  96. if(!config["video"].isNull())
  97. {
  98. // redraw order: background -> video -> buttons and pictures
  99. background->redraw();
  100. CCS->videoh->update((int)config["video"]["x"].Float() + pos.x, (int)config["video"]["y"].Float() + pos.y, to.getInternalSurface(), true, false);
  101. tabs->redraw();
  102. }
  103. CIntObject::show(to);
  104. }
  105. void CMenuScreen::activate()
  106. {
  107. CCS->musich->playMusic(AudioPath::builtin("Music/MainMenu"), true, true);
  108. if(!config["video"].isNull())
  109. CCS->videoh->open(VideoPath::fromJson(config["video"]["name"]));
  110. CIntObject::activate();
  111. }
  112. void CMenuScreen::deactivate()
  113. {
  114. if(!config["video"].isNull())
  115. CCS->videoh->close();
  116. CIntObject::deactivate();
  117. }
  118. void CMenuScreen::switchToTab(size_t index)
  119. {
  120. tabs->setActive(index);
  121. }
  122. void CMenuScreen::switchToTab(std::string name)
  123. {
  124. switchToTab(vstd::find_pos(menuNameToEntry, name));
  125. }
  126. size_t CMenuScreen::getActiveTab() const
  127. {
  128. return tabs->getActive();
  129. }
  130. //funciton for std::string -> std::function conversion for main menu
  131. static std::function<void()> genCommand(CMenuScreen * menu, std::vector<std::string> menuType, const std::string & string)
  132. {
  133. static const std::vector<std::string> commandType = {"to", "campaigns", "start", "load", "exit", "highscores"};
  134. static const std::vector<std::string> gameType = {"single", "multi", "campaign", "tutorial"};
  135. std::list<std::string> commands;
  136. boost::split(commands, string, boost::is_any_of("\t "));
  137. if(!commands.empty())
  138. {
  139. size_t index = std::find(commandType.begin(), commandType.end(), commands.front()) - commandType.begin();
  140. commands.pop_front();
  141. if(index > 3 || !commands.empty())
  142. {
  143. switch(index)
  144. {
  145. case 0: //to - switch to another tab, if such tab exists
  146. {
  147. size_t index2 = std::find(menuType.begin(), menuType.end(), commands.front()) - menuType.begin();
  148. if(index2 != menuType.size())
  149. return std::bind((void(CMenuScreen::*)(size_t))&CMenuScreen::switchToTab, menu, index2);
  150. break;
  151. }
  152. case 1: //open campaign selection window
  153. {
  154. return std::bind(&CMainMenu::openCampaignScreen, CMM, commands.front());
  155. break;
  156. }
  157. case 2: //start
  158. {
  159. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  160. {
  161. case 0:
  162. return std::bind(CMainMenu::openLobby, ESelectionScreen::newGame, true, nullptr, ELoadMode::NONE);
  163. case 1:
  164. return []() { GH.windows().createAndPushWindow<CMultiMode>(ESelectionScreen::newGame); };
  165. case 2:
  166. return std::bind(CMainMenu::openLobby, ESelectionScreen::campaignList, true, nullptr, ELoadMode::NONE);
  167. case 3:
  168. return std::bind(CMainMenu::startTutorial);
  169. }
  170. break;
  171. }
  172. case 3: //load
  173. {
  174. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  175. {
  176. case 0:
  177. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::SINGLE);
  178. case 1:
  179. return []() { GH.windows().createAndPushWindow<CMultiMode>(ESelectionScreen::loadGame); };
  180. case 2:
  181. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::CAMPAIGN);
  182. case 3:
  183. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::TUTORIAL);
  184. }
  185. }
  186. break;
  187. case 4: //exit
  188. {
  189. return std::bind(CInfoWindow::showYesNoDialog, CGI->generaltexth->allTexts[69], std::vector<std::shared_ptr<CComponent>>(), do_quit, 0, PlayerColor(1));
  190. }
  191. break;
  192. case 5: //highscores
  193. {
  194. return std::bind(CMainMenu::openHighScoreScreen);
  195. }
  196. }
  197. }
  198. }
  199. logGlobal->error("Failed to parse command: %s", string);
  200. return std::function<void()>();
  201. }
  202. std::shared_ptr<CButton> CMenuEntry::createButton(CMenuScreen * parent, const JsonNode & button)
  203. {
  204. std::function<void()> command = genCommand(parent, parent->menuNameToEntry, button["command"].String());
  205. std::pair<std::string, std::string> help;
  206. if(!button["help"].isNull() && button["help"].Float() > 0)
  207. help = CGI->generaltexth->zelp[(size_t)button["help"].Float()];
  208. int posx = static_cast<int>(button["x"].Float());
  209. if(posx < 0)
  210. posx = pos.w + posx;
  211. int posy = static_cast<int>(button["y"].Float());
  212. if(posy < 0)
  213. posy = pos.h + posy;
  214. EShortcut shortcut = GH.shortcuts().findShortcut(button["shortcut"].String());
  215. auto result = std::make_shared<CButton>(Point(posx, posy), AnimationPath::fromJson(button["name"]), help, command, shortcut);
  216. if (button["center"].Bool())
  217. result->moveBy(Point(-result->pos.w/2, -result->pos.h/2));
  218. return result;
  219. }
  220. CMenuEntry::CMenuEntry(CMenuScreen * parent, const JsonNode & config)
  221. {
  222. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  223. setRedrawParent(true);
  224. pos = parent->pos;
  225. for(const JsonNode & node : config["images"].Vector())
  226. images.push_back(CMainMenu::createPicture(node));
  227. for(const JsonNode & node : config["buttons"].Vector())
  228. {
  229. buttons.push_back(createButton(parent, node));
  230. buttons.back()->hoverable = true;
  231. buttons.back()->setRedrawParent(true);
  232. }
  233. }
  234. CMainMenuConfig::CMainMenuConfig()
  235. : campaignSets(JsonPath::builtin("config/campaignSets.json"))
  236. , config(JsonPath::builtin("config/mainmenu.json"))
  237. {
  238. }
  239. CMainMenuConfig & CMainMenuConfig::get()
  240. {
  241. static CMainMenuConfig config;
  242. return config;
  243. }
  244. const JsonNode & CMainMenuConfig::getConfig() const
  245. {
  246. return config;
  247. }
  248. const JsonNode & CMainMenuConfig::getCampaigns() const
  249. {
  250. return campaignSets;
  251. }
  252. CMainMenu::CMainMenu()
  253. {
  254. pos.w = GH.screenDimensions().x;
  255. pos.h = GH.screenDimensions().y;
  256. GH.defActionsDef = 63;
  257. menu = std::make_shared<CMenuScreen>(CMainMenuConfig::get().getConfig()["window"]);
  258. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  259. backgroundAroundMenu = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), pos);
  260. }
  261. CMainMenu::~CMainMenu()
  262. {
  263. if(GH.curInt == this)
  264. GH.curInt = nullptr;
  265. }
  266. void CMainMenu::activate()
  267. {
  268. // check if screen was resized while main menu was inactive - e.g. in gameplay mode
  269. if (pos.dimensions() != GH.screenDimensions())
  270. onScreenResize();
  271. CIntObject::activate();
  272. }
  273. void CMainMenu::onScreenResize()
  274. {
  275. pos.w = GH.screenDimensions().x;
  276. pos.h = GH.screenDimensions().y;
  277. menu = nullptr;
  278. menu = std::make_shared<CMenuScreen>(CMainMenuConfig::get().getConfig()["window"]);
  279. backgroundAroundMenu->pos = pos;
  280. }
  281. void CMainMenu::update()
  282. {
  283. if(CMM != this->shared_from_this()) //don't update if you are not a main interface
  284. return;
  285. if(GH.windows().count() == 0)
  286. {
  287. GH.windows().pushWindow(CMM);
  288. GH.windows().pushWindow(menu);
  289. menu->switchToTab(menu->getActiveTab());
  290. }
  291. static bool warnedAboutModDependencies = false;
  292. if (!warnedAboutModDependencies)
  293. {
  294. warnedAboutModDependencies = true;
  295. auto errorMessages = CGI->modh->getModLoadErrors();
  296. if (!errorMessages.empty())
  297. CInfoWindow::showInfoDialog(errorMessages, std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  298. }
  299. // Handles mouse and key input
  300. GH.handleEvents();
  301. GH.windows().simpleRedraw();
  302. }
  303. void CMainMenu::openLobby(ESelectionScreen screenType, bool host, const std::vector<std::string> * names, ELoadMode loadMode)
  304. {
  305. CSH->resetStateForLobby(screenType == ESelectionScreen::newGame ? StartInfo::NEW_GAME : StartInfo::LOAD_GAME, names);
  306. CSH->screenType = screenType;
  307. CSH->loadMode = loadMode;
  308. GH.windows().createAndPushWindow<CSimpleJoinScreen>(host);
  309. }
  310. void CMainMenu::openCampaignLobby(const std::string & campaignFileName, std::string campaignSet)
  311. {
  312. auto ourCampaign = CampaignHandler::getCampaign(campaignFileName);
  313. ourCampaign->campaignSet = campaignSet;
  314. openCampaignLobby(ourCampaign);
  315. }
  316. void CMainMenu::openCampaignLobby(std::shared_ptr<CampaignState> campaign)
  317. {
  318. CSH->resetStateForLobby(StartInfo::CAMPAIGN);
  319. CSH->screenType = ESelectionScreen::campaignList;
  320. CSH->campaignStateToSend = campaign;
  321. GH.windows().createAndPushWindow<CSimpleJoinScreen>();
  322. }
  323. void CMainMenu::openCampaignScreen(std::string name)
  324. {
  325. auto const & config = CMainMenuConfig::get().getCampaigns();
  326. if(!vstd::contains(config.Struct(), name))
  327. {
  328. logGlobal->error("Unknown campaign set: %s", name);
  329. return;
  330. }
  331. bool campaignsFound = true;
  332. for (auto const & entry : config[name]["items"].Vector())
  333. {
  334. ResourcePath resourceID(entry["file"].String(), EResType::CAMPAIGN);
  335. if (!CResourceHandler::get()->existsResource(resourceID))
  336. campaignsFound = false;
  337. }
  338. if (!campaignsFound)
  339. {
  340. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.client.errors.missingCampaigns"), std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  341. return;
  342. }
  343. GH.windows().createAndPushWindow<CCampaignScreen>(config, name);
  344. }
  345. void CMainMenu::startTutorial()
  346. {
  347. ResourcePath tutorialMap("Maps/Tutorial.tut", EResType::MAP);
  348. if(!CResourceHandler::get()->existsResource(tutorialMap))
  349. {
  350. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("core.genrltxt.742"), std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  351. return;
  352. }
  353. auto mapInfo = std::make_shared<CMapInfo>();
  354. mapInfo->mapInit(tutorialMap.getName());
  355. CMainMenu::openLobby(ESelectionScreen::newGame, true, nullptr, ELoadMode::NONE);
  356. CSH->startMapAfterConnection(mapInfo);
  357. }
  358. void CMainMenu::openHighScoreScreen()
  359. {
  360. GH.windows().createAndPushWindow<CHighScoreScreen>(CHighScoreScreen::HighScorePage::SCENARIO);
  361. return;
  362. }
  363. std::shared_ptr<CMainMenu> CMainMenu::create()
  364. {
  365. if(!CMM)
  366. CMM = std::shared_ptr<CMainMenu>(new CMainMenu());
  367. return CMM;
  368. }
  369. std::shared_ptr<CPicture> CMainMenu::createPicture(const JsonNode & config)
  370. {
  371. return std::make_shared<CPicture>(ImagePath::fromJson(config["name"]), (int)config["x"].Float(), (int)config["y"].Float());
  372. }
  373. CMultiMode::CMultiMode(ESelectionScreen ScreenType)
  374. : screenType(ScreenType)
  375. {
  376. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  377. background = std::make_shared<CPicture>(ImagePath::builtin("MUPOPUP.bmp"));
  378. pos = background->center(); //center, window has size of bg graphic
  379. picture = std::make_shared<CPicture>(ImagePath::builtin("MUMAP.bmp"), 16, 77);
  380. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 465, 440, 18), 7, 465));
  381. playerName = std::make_shared<CTextInput>(Rect(19, 436, 334, 16), background->getSurface());
  382. playerName->setText(getPlayerName());
  383. playerName->cb += std::bind(&CMultiMode::onNameChange, this, _1);
  384. buttonHotseat = std::make_shared<CButton>(Point(373, 78), AnimationPath::builtin("MUBHOT.DEF"), CGI->generaltexth->zelp[266], std::bind(&CMultiMode::hostTCP, this));
  385. buttonHost = std::make_shared<CButton>(Point(373, 78 + 57 * 1), AnimationPath::builtin("MUBHOST.DEF"), CButton::tooltip(CGI->generaltexth->translate("vcmi.mainMenu.hostTCP"), ""), std::bind(&CMultiMode::hostTCP, this));
  386. buttonJoin = std::make_shared<CButton>(Point(373, 78 + 57 * 2), AnimationPath::builtin("MUBJOIN.DEF"), CButton::tooltip(CGI->generaltexth->translate("vcmi.mainMenu.joinTCP"), ""), std::bind(&CMultiMode::joinTCP, this));
  387. buttonLobby = std::make_shared<CButton>(Point(373, 78 + 57 * 4), AnimationPath::builtin("MUBONL.DEF"), CGI->generaltexth->zelp[265], std::bind(&CMultiMode::openLobby, this));
  388. buttonCancel = std::make_shared<CButton>(Point(373, 424), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[288], [=](){ close();}, EShortcut::GLOBAL_CANCEL);
  389. }
  390. void CMultiMode::openLobby()
  391. {
  392. close();
  393. GH.windows().createAndPushWindow<LobbyWindow>();
  394. }
  395. void CMultiMode::hostTCP()
  396. {
  397. auto savedScreenType = screenType;
  398. close();
  399. GH.windows().createAndPushWindow<CMultiPlayers>(getPlayerName(), savedScreenType, true, ELoadMode::MULTI);
  400. }
  401. void CMultiMode::joinTCP()
  402. {
  403. auto savedScreenType = screenType;
  404. close();
  405. GH.windows().createAndPushWindow<CMultiPlayers>(getPlayerName(), savedScreenType, false, ELoadMode::MULTI);
  406. }
  407. std::string CMultiMode::getPlayerName()
  408. {
  409. std::string name = settings["general"]["playerName"].String();
  410. if(name == "Player")
  411. name = CGI->generaltexth->translate("vcmi.mainMenu.playerName");
  412. return name;
  413. }
  414. void CMultiMode::onNameChange(std::string newText)
  415. {
  416. Settings name = settings.write["general"]["playerName"];
  417. name->String() = newText;
  418. }
  419. CMultiPlayers::CMultiPlayers(const std::string & firstPlayer, ESelectionScreen ScreenType, bool Host, ELoadMode LoadMode)
  420. : loadMode(LoadMode), screenType(ScreenType), host(Host)
  421. {
  422. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  423. background = std::make_shared<CPicture>(ImagePath::builtin("MUHOTSEA.bmp"));
  424. pos = background->center(); //center, window has size of bg graphic
  425. std::string text = CGI->generaltexth->allTexts[446];
  426. boost::replace_all(text, "\t", "\n");
  427. textTitle = std::make_shared<CTextBox>(text, Rect(25, 20, 315, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE); //HOTSEAT Please enter names
  428. for(int i = 0; i < inputNames.size(); i++)
  429. {
  430. inputNames[i] = std::make_shared<CTextInput>(Rect(60, 85 + i * 30, 280, 16), background->getSurface());
  431. inputNames[i]->cb += std::bind(&CMultiPlayers::onChange, this, _1);
  432. }
  433. buttonOk = std::make_shared<CButton>(Point(95, 338), AnimationPath::builtin("MUBCHCK.DEF"), CGI->generaltexth->zelp[560], std::bind(&CMultiPlayers::enterSelectionScreen, this), EShortcut::GLOBAL_ACCEPT);
  434. buttonCancel = std::make_shared<CButton>(Point(205, 338), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[561], [=](){ close();}, EShortcut::GLOBAL_CANCEL);
  435. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 381, 348, 18), 7, 381));
  436. inputNames[0]->setText(firstPlayer, true);
  437. #ifndef VCMI_IOS
  438. inputNames[0]->giveFocus();
  439. #endif
  440. }
  441. void CMultiPlayers::onChange(std::string newText)
  442. {
  443. }
  444. void CMultiPlayers::enterSelectionScreen()
  445. {
  446. std::vector<std::string> names;
  447. for(auto name : inputNames)
  448. {
  449. if(name->getText().length())
  450. names.push_back(name->getText());
  451. }
  452. Settings name = settings.write["general"]["playerName"];
  453. name->String() = names[0];
  454. CMainMenu::openLobby(screenType, host, &names, loadMode);
  455. }
  456. CSimpleJoinScreen::CSimpleJoinScreen(bool host)
  457. {
  458. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  459. background = std::make_shared<CPicture>(ImagePath::builtin("MUDIALOG.bmp")); // address background
  460. pos = background->center(); //center, window has size of bg graphic (x,y = 396,278 w=232 h=212)
  461. textTitle = std::make_shared<CTextBox>("", Rect(20, 20, 205, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE);
  462. inputAddress = std::make_shared<CTextInput>(Rect(25, 68, 175, 16), background->getSurface());
  463. inputPort = std::make_shared<CTextInput>(Rect(25, 115, 175, 16), background->getSurface());
  464. buttonOk = std::make_shared<CButton>(Point(26, 142), AnimationPath::builtin("MUBCHCK.DEF"), CGI->generaltexth->zelp[560], std::bind(&CSimpleJoinScreen::connectToServer, this), EShortcut::GLOBAL_ACCEPT);
  465. if(host && !settings["session"]["donotstartserver"].Bool())
  466. {
  467. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverConnecting"));
  468. buttonOk->block(true);
  469. startConnectThread();
  470. }
  471. else
  472. {
  473. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverAddressEnter"));
  474. inputAddress->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  475. inputPort->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  476. inputPort->filters += std::bind(&CTextInput::numberFilter, _1, _2, 0, 65535);
  477. inputAddress->giveFocus();
  478. }
  479. inputAddress->setText(host ? CServerHandler::localhostAddress : CSH->getHostAddress(), true);
  480. inputPort->setText(std::to_string(CSH->getHostPort()), true);
  481. buttonCancel = std::make_shared<CButton>(Point(142, 142), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[561], std::bind(&CSimpleJoinScreen::leaveScreen, this), EShortcut::GLOBAL_CANCEL);
  482. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 186, 218, 18), 7, 186));
  483. }
  484. void CSimpleJoinScreen::connectToServer()
  485. {
  486. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverConnecting"));
  487. buttonOk->block(true);
  488. GH.stopTextInput();
  489. startConnectThread(inputAddress->getText(), boost::lexical_cast<ui16>(inputPort->getText()));
  490. }
  491. void CSimpleJoinScreen::leaveScreen()
  492. {
  493. if(CSH->state == EClientState::CONNECTING)
  494. {
  495. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverClosing"));
  496. CSH->state = EClientState::CONNECTION_CANCELLED;
  497. }
  498. else if(GH.windows().isTopWindow(this))
  499. {
  500. close();
  501. }
  502. }
  503. void CSimpleJoinScreen::onChange(const std::string & newText)
  504. {
  505. buttonOk->block(inputAddress->getText().empty() || inputPort->getText().empty());
  506. }
  507. void CSimpleJoinScreen::startConnectThread(const std::string & addr, ui16 port)
  508. {
  509. #if defined(SINGLE_PROCESS_APP) && defined(VCMI_ANDROID)
  510. // in single process build server must use same JNIEnv as client
  511. // as server runs in a separate thread, it must not attempt to search for Java classes (and they're already cached anyway)
  512. // https://github.com/libsdl-org/SDL/blob/main/docs/README-android.md#threads-and-the-java-vm
  513. CVCMIServer::reuseClientJNIEnv(SDL_AndroidGetJNIEnv());
  514. #endif
  515. boost::thread connector(&CSimpleJoinScreen::connectThread, this, addr, port);
  516. connector.detach();
  517. }
  518. void CSimpleJoinScreen::connectThread(const std::string & addr, ui16 port)
  519. {
  520. setThreadName("connectThread");
  521. if(!addr.length())
  522. CSH->startLocalServerAndConnect();
  523. else
  524. CSH->justConnectToServer(addr, port);
  525. // async call to prevent thread race
  526. GH.dispatchMainThread([this](){
  527. if(CSH->state == EClientState::CONNECTION_FAILED)
  528. {
  529. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  530. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverAddressEnter"));
  531. GH.startTextInput(inputAddress->pos);
  532. buttonOk->block(false);
  533. }
  534. if(GH.windows().isTopWindow(this))
  535. {
  536. close();
  537. }
  538. });
  539. }
  540. CLoadingScreen::CLoadingScreen()
  541. : CWindowObject(BORDERED, getBackground())
  542. {
  543. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  544. addUsedEvents(TIME);
  545. CCS->musich->stopMusic(5000);
  546. const auto & conf = CMainMenuConfig::get().getConfig()["loading"];
  547. if(conf.isStruct())
  548. {
  549. const int posx = conf["x"].Integer();
  550. const int posy = conf["y"].Integer();
  551. const int blockSize = conf["size"].Integer();
  552. const int blocksAmount = conf["amount"].Integer();
  553. for(int i = 0; i < blocksAmount; ++i)
  554. {
  555. progressBlocks.push_back(std::make_shared<CAnimImage>(AnimationPath::fromJson(conf["name"]), i, 0, posx + i * blockSize, posy));
  556. progressBlocks.back()->deactivate();
  557. progressBlocks.back()->visible = false;
  558. }
  559. }
  560. }
  561. CLoadingScreen::~CLoadingScreen()
  562. {
  563. }
  564. void CLoadingScreen::tick(uint32_t msPassed)
  565. {
  566. if(!progressBlocks.empty())
  567. {
  568. int status = float(get()) / 255.f * progressBlocks.size();
  569. for(int i = 0; i < status; ++i)
  570. {
  571. progressBlocks.at(i)->activate();
  572. progressBlocks.at(i)->visible = true;
  573. }
  574. }
  575. }
  576. ImagePath CLoadingScreen::getBackground()
  577. {
  578. ImagePath fname = ImagePath::builtin("loadbar");
  579. const auto & conf = CMainMenuConfig::get().getConfig()["loading"];
  580. if(conf.isStruct())
  581. {
  582. if(conf["background"].isVector())
  583. return ImagePath::fromJson(*RandomGeneratorUtil::nextItem(conf["background"].Vector(), CRandomGenerator::getDefault()));
  584. if(conf["background"].isString())
  585. return ImagePath::fromJson(conf["background"]);
  586. return fname;
  587. }
  588. if(conf.isVector() && !conf.Vector().empty())
  589. return ImagePath::fromJson(*RandomGeneratorUtil::nextItem(conf.Vector(), CRandomGenerator::getDefault()));
  590. return fname;
  591. }