SelectionTab.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /*
  2. * SelectionTab.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 "SelectionTab.h"
  12. #include "CSelectionBase.h"
  13. #include "CLobbyScreen.h"
  14. #include "../CGameInfo.h"
  15. #include "../CPlayerInterface.h"
  16. #include "../CServerHandler.h"
  17. #include "../gui/CGuiHandler.h"
  18. #include "../gui/Shortcut.h"
  19. #include "../gui/WindowHandler.h"
  20. #include "../widgets/CComponent.h"
  21. #include "../widgets/Buttons.h"
  22. #include "../widgets/MiscWidgets.h"
  23. #include "../widgets/ObjectLists.h"
  24. #include "../widgets/Slider.h"
  25. #include "../widgets/TextControls.h"
  26. #include "../windows/GUIClasses.h"
  27. #include "../windows/InfoWindows.h"
  28. #include "../windows/CMapOverview.h"
  29. #include "../render/CAnimation.h"
  30. #include "../render/IImage.h"
  31. #include "../render/IRenderHandler.h"
  32. #include "../../CCallback.h"
  33. #include "../../lib/NetPacksLobby.h"
  34. #include "../../lib/CGeneralTextHandler.h"
  35. #include "../../lib/CConfigHandler.h"
  36. #include "../../lib/GameSettings.h"
  37. #include "../../lib/filesystem/Filesystem.h"
  38. #include "../../lib/campaign/CampaignState.h"
  39. #include "../../lib/mapping/CMapInfo.h"
  40. #include "../../lib/mapping/CMapHeader.h"
  41. #include "../../lib/mapping/MapFormat.h"
  42. #include "../../lib/TerrainHandler.h"
  43. #include "../../lib/serializer/Connection.h"
  44. bool mapSorter::operator()(const std::shared_ptr<ElementInfo> aaa, const std::shared_ptr<ElementInfo> bbb)
  45. {
  46. if(aaa->isFolder || bbb->isFolder)
  47. {
  48. if(aaa->isFolder != bbb->isFolder)
  49. return (aaa->isFolder > bbb->isFolder);
  50. else
  51. {
  52. if(boost::algorithm::starts_with(aaa->folderName, "..") || boost::algorithm::starts_with(bbb->folderName, ".."))
  53. return boost::algorithm::starts_with(aaa->folderName, "..");
  54. return boost::ilexicographical_compare(aaa->folderName, bbb->folderName);
  55. }
  56. }
  57. auto a = aaa->mapHeader.get();
  58. auto b = bbb->mapHeader.get();
  59. if(a && b) //if we are sorting scenarios
  60. {
  61. switch(sortBy)
  62. {
  63. case _format: //by map format (RoE, WoG, etc)
  64. return (a->version < b->version);
  65. break;
  66. case _loscon: //by loss conditions
  67. return (a->defeatIconIndex < b->defeatIconIndex);
  68. break;
  69. case _playerAm: //by player amount
  70. int playerAmntB, humenPlayersB, playerAmntA, humenPlayersA;
  71. playerAmntB = humenPlayersB = playerAmntA = humenPlayersA = 0;
  72. for(int i = 0; i < 8; i++)
  73. {
  74. if(a->players[i].canHumanPlay)
  75. {
  76. playerAmntA++;
  77. humenPlayersA++;
  78. }
  79. else if(a->players[i].canComputerPlay)
  80. {
  81. playerAmntA++;
  82. }
  83. if(b->players[i].canHumanPlay)
  84. {
  85. playerAmntB++;
  86. humenPlayersB++;
  87. }
  88. else if(b->players[i].canComputerPlay)
  89. {
  90. playerAmntB++;
  91. }
  92. }
  93. if(playerAmntB != playerAmntA)
  94. return (playerAmntA < playerAmntB);
  95. else
  96. return (humenPlayersA < humenPlayersB);
  97. break;
  98. case _size: //by size of map
  99. return (a->width < b->width);
  100. break;
  101. case _viccon: //by victory conditions
  102. return (a->victoryIconIndex < b->victoryIconIndex);
  103. break;
  104. case _name: //by name
  105. return boost::ilexicographical_compare(a->name.toString(), b->name.toString());
  106. case _fileName: //by filename
  107. return boost::ilexicographical_compare(aaa->fileURI, bbb->fileURI);
  108. default:
  109. return boost::ilexicographical_compare(a->name.toString(), b->name.toString());
  110. }
  111. }
  112. else //if we are sorting campaigns
  113. {
  114. switch(sortBy)
  115. {
  116. case _numOfMaps: //by number of maps in campaign
  117. return aaa->campaign->scenariosCount() < bbb->campaign->scenariosCount();
  118. case _name: //by name
  119. return boost::ilexicographical_compare(aaa->campaign->getNameTranslated(), bbb->campaign->getNameTranslated());
  120. default:
  121. return boost::ilexicographical_compare(aaa->campaign->getNameTranslated(), bbb->campaign->getNameTranslated());
  122. }
  123. }
  124. }
  125. // pick sorting order based on selection
  126. static ESortBy getSortBySelectionScreen(ESelectionScreen Type)
  127. {
  128. switch(Type)
  129. {
  130. case ESelectionScreen::newGame:
  131. return ESortBy::_name;
  132. case ESelectionScreen::loadGame:
  133. case ESelectionScreen::saveGame:
  134. return ESortBy::_fileName;
  135. case ESelectionScreen::campaignList:
  136. return ESortBy::_name;
  137. }
  138. // Should not reach here. But let's not crash the game.
  139. return ESortBy::_name;
  140. }
  141. SelectionTab::SelectionTab(ESelectionScreen Type)
  142. : CIntObject(LCLICK | SHOW_POPUP | KEYBOARD | DOUBLECLICK), callOnSelect(nullptr), tabType(Type), selectionPos(0), sortModeAscending(true), inputNameRect{32, 539, 350, 20}, curFolder(""), currentMapSizeFilter(0), showRandom(false)
  143. {
  144. OBJ_CONSTRUCTION;
  145. generalSortingBy = getSortBySelectionScreen(tabType);
  146. if(tabType != ESelectionScreen::campaignList)
  147. {
  148. sortingBy = _format;
  149. background = std::make_shared<CPicture>(ImagePath::builtin("SCSELBCK.bmp"), 0, 6);
  150. pos = background->pos;
  151. inputName = std::make_shared<CTextInput>(inputNameRect, Point(-32, -25), ImagePath::builtin("GSSTRIP.bmp"), 0);
  152. inputName->filters += CTextInput::filenameFilter;
  153. labelMapSizes = std::make_shared<CLabel>(87, 62, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[510]);
  154. int sizes[] = {36, 72, 108, 144, 0};
  155. const char * filterIconNmes[] = {"SCSMBUT.DEF", "SCMDBUT.DEF", "SCLGBUT.DEF", "SCXLBUT.DEF", "SCALBUT.DEF"};
  156. for(int i = 0; i < 5; i++)
  157. buttonsSortBy.push_back(std::make_shared<CButton>(Point(158 + 47 * i, 46), AnimationPath::builtin(filterIconNmes[i]), CGI->generaltexth->zelp[54 + i], std::bind(&SelectionTab::filter, this, sizes[i], true)));
  158. int xpos[] = {23, 55, 88, 121, 306, 339};
  159. const char * sortIconNames[] = {"SCBUTT1.DEF", "SCBUTT2.DEF", "SCBUTCP.DEF", "SCBUTT3.DEF", "SCBUTT4.DEF", "SCBUTT5.DEF"};
  160. for(int i = 0; i < 6; i++)
  161. {
  162. ESortBy criteria = (ESortBy)i;
  163. if(criteria == _name)
  164. criteria = generalSortingBy;
  165. buttonsSortBy.push_back(std::make_shared<CButton>(Point(xpos[i], 86), AnimationPath::builtin(sortIconNames[i]), CGI->generaltexth->zelp[107 + i], std::bind(&SelectionTab::sortBy, this, criteria)));
  166. }
  167. }
  168. int positionsToShow = 18;
  169. std::string tabTitle;
  170. switch(tabType)
  171. {
  172. case ESelectionScreen::newGame:
  173. tabTitle = CGI->generaltexth->arraytxt[229];
  174. break;
  175. case ESelectionScreen::loadGame:
  176. tabTitle = CGI->generaltexth->arraytxt[230];
  177. break;
  178. case ESelectionScreen::saveGame:
  179. positionsToShow = 16;
  180. tabTitle = CGI->generaltexth->arraytxt[231];
  181. break;
  182. case ESelectionScreen::campaignList:
  183. tabTitle = CGI->generaltexth->allTexts[726];
  184. setRedrawParent(true); // we use parent background so we need to make sure it's will be redrawn too
  185. pos.w = parent->pos.w;
  186. pos.h = parent->pos.h;
  187. pos.x += 3;
  188. pos.y += 6;
  189. buttonsSortBy.push_back(std::make_shared<CButton>(Point(23, 86), AnimationPath::builtin("CamCusM.DEF"), CButton::tooltip(), std::bind(&SelectionTab::sortBy, this, _numOfMaps)));
  190. buttonsSortBy.push_back(std::make_shared<CButton>(Point(55, 86), AnimationPath::builtin("CamCusL.DEF"), CButton::tooltip(), std::bind(&SelectionTab::sortBy, this, _name)));
  191. break;
  192. default:
  193. assert(0);
  194. break;
  195. }
  196. iconsMapFormats = GH.renderHandler().loadAnimation(AnimationPath::builtin("SCSELC.DEF"));
  197. iconsVictoryCondition = GH.renderHandler().loadAnimation(AnimationPath::builtin("SCNRVICT.DEF"));
  198. iconsLossCondition = GH.renderHandler().loadAnimation(AnimationPath::builtin("SCNRLOSS.DEF"));
  199. for(int i = 0; i < positionsToShow; i++)
  200. listItems.push_back(std::make_shared<ListItem>(Point(30, 129 + i * 25), iconsMapFormats, iconsVictoryCondition, iconsLossCondition));
  201. labelTabTitle = std::make_shared<CLabel>(205, 28, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, tabTitle);
  202. slider = std::make_shared<CSlider>(Point(372, 86), tabType != ESelectionScreen::saveGame ? 480 : 430, std::bind(&SelectionTab::sliderMove, this, _1), positionsToShow, (int)curItems.size(), 0, Orientation::VERTICAL, CSlider::BLUE);
  203. slider->setPanningStep(24);
  204. // create scroll bounds that encompass all area in this UI element to the left of slider (including area of slider itself)
  205. // entire screen can't be used in here since map description might also have slider
  206. slider->setScrollBounds(Rect(pos.x - slider->pos.x, 0, slider->pos.x + slider->pos.w - pos.x, slider->pos.h ));
  207. filter(0);
  208. }
  209. void SelectionTab::toggleMode()
  210. {
  211. if(CSH->isGuest())
  212. {
  213. allItems.clear();
  214. curItems.clear();
  215. if(slider)
  216. slider->block(true);
  217. }
  218. else
  219. {
  220. switch(tabType)
  221. {
  222. case ESelectionScreen::newGame:
  223. {
  224. inputName->disable();
  225. auto files = getFiles("Maps/", EResType::MAP);
  226. files.erase(ResourcePath("Maps/Tutorial.tut", EResType::MAP));
  227. parseMaps(files);
  228. break;
  229. }
  230. case ESelectionScreen::loadGame:
  231. inputName->disable();
  232. parseSaves(getFiles("Saves/", EResType::SAVEGAME));
  233. break;
  234. case ESelectionScreen::saveGame:
  235. parseSaves(getFiles("Saves/", EResType::SAVEGAME));
  236. inputName->enable();
  237. inputName->activate();
  238. restoreLastSelection();
  239. break;
  240. case ESelectionScreen::campaignList:
  241. parseCampaigns(getFiles("Maps/", EResType::CAMPAIGN));
  242. break;
  243. default:
  244. assert(0);
  245. break;
  246. }
  247. if(slider)
  248. {
  249. slider->block(false);
  250. filter(0);
  251. }
  252. if(CSH->campaignStateToSend)
  253. {
  254. CSH->setCampaignState(CSH->campaignStateToSend);
  255. CSH->campaignStateToSend.reset();
  256. }
  257. else
  258. {
  259. restoreLastSelection();
  260. }
  261. }
  262. slider->setAmount((int)curItems.size());
  263. updateListItems();
  264. redraw();
  265. }
  266. void SelectionTab::clickReleased(const Point & cursorPosition)
  267. {
  268. int line = getLine();
  269. if(line != -1)
  270. {
  271. select(line);
  272. }
  273. #ifdef VCMI_IOS
  274. // focus input field if clicked inside it
  275. else if(inputName && inputName->isActive() && inputNameRect.isInside(cursorPosition))
  276. inputName->giveFocus();
  277. #endif
  278. }
  279. void SelectionTab::keyPressed(EShortcut key)
  280. {
  281. int moveBy = 0;
  282. switch(key)
  283. {
  284. case EShortcut::MOVE_UP:
  285. moveBy = -1;
  286. break;
  287. case EShortcut::MOVE_DOWN:
  288. moveBy = +1;
  289. break;
  290. case EShortcut::MOVE_PAGE_UP:
  291. moveBy = -(int)listItems.size() + 1;
  292. break;
  293. case EShortcut::MOVE_PAGE_DOWN:
  294. moveBy = +(int)listItems.size() - 1;
  295. break;
  296. case EShortcut::MOVE_FIRST:
  297. select(-slider->getValue());
  298. return;
  299. case EShortcut::MOVE_LAST:
  300. select((int)curItems.size() - slider->getValue());
  301. return;
  302. default:
  303. return;
  304. }
  305. select((int)selectionPos - slider->getValue() + moveBy);
  306. }
  307. void SelectionTab::clickDouble(const Point & cursorPosition)
  308. {
  309. int position = getLine();
  310. int itemIndex = position + slider->getValue();
  311. if(itemIndex >= curItems.size())
  312. return;
  313. if(itemIndex >= 0 && curItems[itemIndex]->isFolder)
  314. {
  315. select(position);
  316. return;
  317. }
  318. if(getLine() != -1) //double clicked scenarios list
  319. {
  320. (static_cast<CLobbyScreen *>(parent))->buttonStart->clickPressed(cursorPosition);
  321. (static_cast<CLobbyScreen *>(parent))->buttonStart->clickReleased(cursorPosition);
  322. }
  323. }
  324. void SelectionTab::showPopupWindow(const Point & cursorPosition)
  325. {
  326. int position = getLine();
  327. int py = position + slider->getValue();
  328. if(py >= curItems.size())
  329. return;
  330. if(!curItems[py]->isFolder)
  331. GH.windows().createAndPushWindow<CMapOverview>(curItems[py]->getNameTranslated(), curItems[py]->fullFileURI, curItems[py]->date, ResourcePath(curItems[py]->fileURI), tabType);
  332. else
  333. CRClickPopup::createAndPush(curItems[py]->folderName);
  334. }
  335. auto SelectionTab::checkSubfolder(std::string path)
  336. {
  337. struct Ret
  338. {
  339. std::string folderName;
  340. std::string baseFolder;
  341. bool parentExists;
  342. bool fileInFolder;
  343. } ret;
  344. ret.parentExists = (curFolder != "");
  345. ret.fileInFolder = false;
  346. std::vector<std::string> filetree;
  347. // delete first element (e.g. 'MAPS')
  348. boost::split(filetree, path, boost::is_any_of("/"));
  349. filetree.erase(filetree.begin());
  350. std::string pathWithoutPrefix = boost::algorithm::join(filetree, "/");
  351. if(!filetree.empty())
  352. {
  353. filetree.pop_back();
  354. ret.baseFolder = boost::algorithm::join(filetree, "/");
  355. }
  356. else
  357. ret.baseFolder = "";
  358. if(boost::algorithm::starts_with(ret.baseFolder, curFolder))
  359. {
  360. std::string folder = ret.baseFolder.substr(curFolder.size());
  361. if(folder != "")
  362. {
  363. boost::split(filetree, folder, boost::is_any_of("/"));
  364. ret.folderName = filetree[0];
  365. }
  366. }
  367. if(boost::algorithm::starts_with(pathWithoutPrefix, curFolder))
  368. if(boost::count(pathWithoutPrefix.substr(curFolder.size()), '/') == 0)
  369. ret.fileInFolder = true;
  370. return ret;
  371. }
  372. // A new size filter (Small, Medium, ...) has been selected. Populate
  373. // selMaps with the relevant data.
  374. void SelectionTab::filter(int size, bool selectFirst)
  375. {
  376. if(size == -1)
  377. size = currentMapSizeFilter;
  378. currentMapSizeFilter = size;
  379. curItems.clear();
  380. for(auto elem : allItems)
  381. {
  382. if((elem->mapHeader && (!size || elem->mapHeader->width == size)) || tabType == ESelectionScreen::campaignList)
  383. {
  384. if(showRandom)
  385. curFolder = "RANDOMMAPS/";
  386. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(elem->originalFileURI);
  387. if((showRandom && baseFolder != "RANDOMMAPS") || (!showRandom && baseFolder == "RANDOMMAPS"))
  388. continue;
  389. if(parentExists && !showRandom)
  390. {
  391. auto folder = std::make_shared<ElementInfo>();
  392. folder->isFolder = true;
  393. folder->folderName = ".. (" + curFolder + ")";
  394. auto itemIt = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return boost::starts_with(e->folderName, ".."); });
  395. if (itemIt == curItems.end()) {
  396. curItems.push_back(folder);
  397. }
  398. }
  399. std::shared_ptr<ElementInfo> folder = std::make_shared<ElementInfo>();
  400. folder->isFolder = true;
  401. folder->folderName = folderName;
  402. auto itemIt = boost::range::find_if(curItems, [folder](std::shared_ptr<ElementInfo> e) { return e->folderName == folder->folderName; });
  403. if (itemIt == curItems.end() && folderName != "") {
  404. curItems.push_back(folder);
  405. }
  406. if(fileInFolder)
  407. curItems.push_back(elem);
  408. }
  409. }
  410. if(curItems.size())
  411. {
  412. slider->block(false);
  413. slider->setAmount((int)curItems.size());
  414. sort();
  415. if(selectFirst)
  416. {
  417. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  418. if(firstPos < curItems.size())
  419. {
  420. slider->scrollTo(firstPos);
  421. callOnSelect(curItems[firstPos]);
  422. selectAbs(firstPos);
  423. }
  424. }
  425. }
  426. else
  427. {
  428. updateListItems();
  429. redraw();
  430. slider->block(true);
  431. if(callOnSelect)
  432. callOnSelect(nullptr);
  433. }
  434. }
  435. void SelectionTab::sortBy(int criteria)
  436. {
  437. if(criteria == sortingBy)
  438. {
  439. sortModeAscending = !sortModeAscending;
  440. }
  441. else
  442. {
  443. sortingBy = (ESortBy)criteria;
  444. sortModeAscending = true;
  445. }
  446. sort();
  447. selectAbs(-1);
  448. }
  449. void SelectionTab::sort()
  450. {
  451. if(sortingBy != generalSortingBy)
  452. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(generalSortingBy));
  453. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(sortingBy));
  454. int firstMapIndex = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  455. if(!sortModeAscending)
  456. std::reverse(std::next(curItems.begin(), firstMapIndex), curItems.end());
  457. updateListItems();
  458. redraw();
  459. }
  460. void SelectionTab::select(int position)
  461. {
  462. if(!curItems.size())
  463. return;
  464. // New selection. py is the index in curItems.
  465. int py = position + slider->getValue();
  466. vstd::amax(py, 0);
  467. vstd::amin(py, curItems.size() - 1);
  468. selectionPos = py;
  469. if(position < 0)
  470. slider->scrollBy(position);
  471. else if(position >= listItems.size())
  472. slider->scrollBy(position - (int)listItems.size() + 1);
  473. if(curItems[py]->isFolder) {
  474. if(boost::starts_with(curItems[py]->folderName, ".."))
  475. {
  476. std::vector<std::string> filetree;
  477. boost::split(filetree, curFolder, boost::is_any_of("/"));
  478. filetree.pop_back();
  479. filetree.pop_back();
  480. curFolder = filetree.size() > 0 ? boost::algorithm::join(filetree, "/") + "/" : "";
  481. }
  482. else
  483. curFolder += curItems[py]->folderName + "/";
  484. filter(-1);
  485. slider->scrollTo(0);
  486. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  487. if(firstPos < curItems.size())
  488. {
  489. selectAbs(firstPos);
  490. }
  491. return;
  492. }
  493. rememberCurrentSelection();
  494. if(inputName && inputName->isActive())
  495. {
  496. auto filename = *CResourceHandler::get()->getResourceName(ResourcePath(curItems[py]->fileURI, EResType::SAVEGAME));
  497. inputName->setText(filename.stem().string());
  498. }
  499. updateListItems();
  500. redraw();
  501. if(callOnSelect)
  502. callOnSelect(curItems[py]);
  503. }
  504. void SelectionTab::selectAbs(int position)
  505. {
  506. if(position == -1)
  507. position = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  508. select(position - slider->getValue());
  509. }
  510. void SelectionTab::sliderMove(int slidPos)
  511. {
  512. if(!slider)
  513. return; // ignore spurious call when slider is being created
  514. updateListItems();
  515. redraw();
  516. }
  517. void SelectionTab::updateListItems()
  518. {
  519. // elemIdx is the index of the maps or saved game to display on line 0
  520. // slider->capacity contains the number of available screen lines
  521. // slider->positionsAmnt is the number of elements after filtering
  522. int elemIdx = slider->getValue();
  523. for(auto item : listItems)
  524. {
  525. if(elemIdx < curItems.size())
  526. {
  527. item->updateItem(curItems[elemIdx], elemIdx == selectionPos);
  528. elemIdx++;
  529. }
  530. else
  531. {
  532. item->updateItem();
  533. }
  534. }
  535. }
  536. bool SelectionTab::receiveEvent(const Point & position, int eventType) const
  537. {
  538. // FIXME: widget should instead have well-defined pos so events will be filtered using standard routine
  539. return getLine(position - pos.topLeft()) != -1;
  540. }
  541. int SelectionTab::getLine() const
  542. {
  543. Point clickPos = GH.getCursorPosition() - pos.topLeft();
  544. return getLine(clickPos);
  545. }
  546. int SelectionTab::getLine(const Point & clickPos) const
  547. {
  548. int line = -1;
  549. // Ignore clicks on save name area
  550. int maxPosY;
  551. if(tabType == ESelectionScreen::saveGame)
  552. maxPosY = 516;
  553. else
  554. maxPosY = 564;
  555. if(clickPos.y > 115 && clickPos.y < maxPosY && clickPos.x > 22 && clickPos.x < 371)
  556. {
  557. line = (clickPos.y - 115) / 25; //which line
  558. }
  559. return line;
  560. }
  561. void SelectionTab::selectFileName(std::string fname)
  562. {
  563. boost::to_upper(fname);
  564. for(int i = (int)allItems.size() - 1; i >= 0; i--)
  565. {
  566. if(allItems[i]->fileURI == fname)
  567. {
  568. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(allItems[i]->originalFileURI);
  569. curFolder = baseFolder != "" ? baseFolder + "/" : "";
  570. }
  571. }
  572. for(int i = (int)curItems.size() - 1; i >= 0; i--)
  573. {
  574. if(curItems[i]->fileURI == fname)
  575. {
  576. slider->scrollTo(i);
  577. selectAbs(i);
  578. return;
  579. }
  580. }
  581. filter(-1);
  582. selectAbs(-1);
  583. }
  584. std::shared_ptr<ElementInfo> SelectionTab::getSelectedMapInfo() const
  585. {
  586. return curItems.empty() || curItems[selectionPos]->isFolder ? nullptr : curItems[selectionPos];
  587. }
  588. void SelectionTab::rememberCurrentSelection()
  589. {
  590. if(getSelectedMapInfo()->isFolder)
  591. return;
  592. // TODO: this can be more elegant
  593. if(tabType == ESelectionScreen::newGame)
  594. {
  595. Settings lastMap = settings.write["general"]["lastMap"];
  596. lastMap->String() = getSelectedMapInfo()->fileURI;
  597. }
  598. else if(tabType == ESelectionScreen::loadGame)
  599. {
  600. Settings lastSave = settings.write["general"]["lastSave"];
  601. lastSave->String() = getSelectedMapInfo()->fileURI;
  602. }
  603. else if(tabType == ESelectionScreen::campaignList)
  604. {
  605. Settings lastCampaign = settings.write["general"]["lastCampaign"];
  606. lastCampaign->String() = getSelectedMapInfo()->fileURI;
  607. }
  608. }
  609. void SelectionTab::restoreLastSelection()
  610. {
  611. switch(tabType)
  612. {
  613. case ESelectionScreen::newGame:
  614. selectFileName(settings["general"]["lastMap"].String());
  615. break;
  616. case ESelectionScreen::campaignList:
  617. selectFileName(settings["general"]["lastCampaign"].String());
  618. break;
  619. case ESelectionScreen::loadGame:
  620. case ESelectionScreen::saveGame:
  621. selectFileName(settings["general"]["lastSave"].String());
  622. }
  623. }
  624. bool SelectionTab::isMapSupported(const CMapInfo & info)
  625. {
  626. switch (info.mapHeader->version)
  627. {
  628. case EMapFormat::ROE:
  629. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_RESTORATION_OF_ERATHIA)["supported"].Bool();
  630. case EMapFormat::AB:
  631. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_ARMAGEDDONS_BLADE)["supported"].Bool();
  632. case EMapFormat::SOD:
  633. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_SHADOW_OF_DEATH)["supported"].Bool();
  634. case EMapFormat::WOG:
  635. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_IN_THE_WAKE_OF_GODS)["supported"].Bool();
  636. case EMapFormat::HOTA:
  637. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_HORN_OF_THE_ABYSS)["supported"].Bool();
  638. case EMapFormat::VCMI:
  639. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_JSON_VCMI)["supported"].Bool();
  640. }
  641. return false;
  642. }
  643. void SelectionTab::parseMaps(const std::unordered_set<ResourcePath> & files)
  644. {
  645. logGlobal->debug("Parsing %d maps", files.size());
  646. allItems.clear();
  647. for(auto & file : files)
  648. {
  649. try
  650. {
  651. auto mapInfo = std::make_shared<ElementInfo>();
  652. mapInfo->mapInit(file.getName());
  653. if (isMapSupported(*mapInfo))
  654. allItems.push_back(mapInfo);
  655. }
  656. catch(std::exception & e)
  657. {
  658. logGlobal->error("Map %s is invalid. Message: %s", file.getName(), e.what());
  659. }
  660. }
  661. }
  662. void SelectionTab::parseSaves(const std::unordered_set<ResourcePath> & files)
  663. {
  664. for(auto & file : files)
  665. {
  666. try
  667. {
  668. auto mapInfo = std::make_shared<ElementInfo>();
  669. mapInfo->saveInit(file);
  670. // Filter out other game modes
  671. bool isCampaign = mapInfo->scenarioOptionsOfSave->mode == StartInfo::CAMPAIGN;
  672. bool isMultiplayer = mapInfo->amountOfHumanPlayersInSave > 1;
  673. bool isTutorial = boost::to_upper_copy(mapInfo->scenarioOptionsOfSave->mapname) == "MAPS/TUTORIAL";
  674. switch(CSH->getLoadMode())
  675. {
  676. case ELoadMode::SINGLE:
  677. if(isMultiplayer || isCampaign || isTutorial)
  678. mapInfo->mapHeader.reset();
  679. break;
  680. case ELoadMode::CAMPAIGN:
  681. if(!isCampaign)
  682. mapInfo->mapHeader.reset();
  683. break;
  684. case ELoadMode::TUTORIAL:
  685. if(!isTutorial)
  686. mapInfo->mapHeader.reset();
  687. break;
  688. default:
  689. if(!isMultiplayer)
  690. mapInfo->mapHeader.reset();
  691. break;
  692. }
  693. allItems.push_back(mapInfo);
  694. }
  695. catch(const std::exception & e)
  696. {
  697. logGlobal->error("Error: Failed to process %s: %s", file.getName(), e.what());
  698. }
  699. }
  700. }
  701. void SelectionTab::parseCampaigns(const std::unordered_set<ResourcePath> & files)
  702. {
  703. allItems.reserve(files.size());
  704. for(auto & file : files)
  705. {
  706. auto info = std::make_shared<ElementInfo>();
  707. //allItems[i].date = std::asctime(std::localtime(&files[i].date));
  708. info->fileURI = file.getName();
  709. info->campaignInit();
  710. if(info->campaign)
  711. allItems.push_back(info);
  712. }
  713. }
  714. std::unordered_set<ResourcePath> SelectionTab::getFiles(std::string dirURI, EResType resType)
  715. {
  716. boost::to_upper(dirURI);
  717. CResourceHandler::get()->updateFilteredFiles([&](const std::string & mount)
  718. {
  719. return boost::algorithm::starts_with(mount, dirURI);
  720. });
  721. std::unordered_set<ResourcePath> ret = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  722. {
  723. return ident.getType() == resType && boost::algorithm::starts_with(ident.getName(), dirURI);
  724. });
  725. return ret;
  726. }
  727. SelectionTab::ListItem::ListItem(Point position, std::shared_ptr<CAnimation> iconsFormats, std::shared_ptr<CAnimation> iconsVictory, std::shared_ptr<CAnimation> iconsLoss)
  728. : CIntObject(LCLICK, position)
  729. {
  730. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  731. pictureEmptyLine = std::make_shared<CPicture>(GH.renderHandler().loadImage(ImagePath::builtin("camcust")), Rect(25, 121, 349, 26), -8, -14);
  732. labelName = std::make_shared<CLabel>(184, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  733. labelName->setAutoRedraw(false);
  734. labelAmountOfPlayers = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  735. labelAmountOfPlayers->setAutoRedraw(false);
  736. labelNumberOfCampaignMaps = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  737. labelNumberOfCampaignMaps->setAutoRedraw(false);
  738. labelMapSizeLetter = std::make_shared<CLabel>(41, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  739. labelMapSizeLetter->setAutoRedraw(false);
  740. // FIXME: This -12 should not be needed, but for some reason CAnimImage displaced otherwise
  741. iconFolder = std::make_shared<CPicture>(ImagePath::builtin("lobby/iconFolder.png"), -8, -12);
  742. iconFormat = std::make_shared<CAnimImage>(iconsFormats, 0, 0, 59, -12);
  743. iconVictoryCondition = std::make_shared<CAnimImage>(iconsVictory, 0, 0, 277, -12);
  744. iconLossCondition = std::make_shared<CAnimImage>(iconsLoss, 0, 0, 310, -12);
  745. }
  746. void SelectionTab::ListItem::updateItem(std::shared_ptr<ElementInfo> info, bool selected)
  747. {
  748. if(!info)
  749. {
  750. labelAmountOfPlayers->disable();
  751. labelMapSizeLetter->disable();
  752. iconFolder->disable();
  753. pictureEmptyLine->disable();
  754. iconFormat->disable();
  755. iconVictoryCondition->disable();
  756. iconLossCondition->disable();
  757. labelNumberOfCampaignMaps->disable();
  758. labelName->disable();
  759. return;
  760. }
  761. auto color = selected ? Colors::YELLOW : Colors::WHITE;
  762. if(info->isFolder)
  763. {
  764. labelAmountOfPlayers->disable();
  765. labelMapSizeLetter->disable();
  766. iconFolder->enable();
  767. pictureEmptyLine->enable();
  768. iconFormat->disable();
  769. iconVictoryCondition->disable();
  770. iconLossCondition->disable();
  771. labelNumberOfCampaignMaps->disable();
  772. labelName->enable();
  773. labelName->setText(info->folderName);
  774. labelName->setColor(color);
  775. return;
  776. }
  777. if(info->campaign)
  778. {
  779. labelAmountOfPlayers->disable();
  780. labelMapSizeLetter->disable();
  781. iconFolder->disable();
  782. pictureEmptyLine->disable();
  783. iconFormat->disable();
  784. iconVictoryCondition->disable();
  785. iconLossCondition->disable();
  786. labelNumberOfCampaignMaps->enable();
  787. std::ostringstream ostr(std::ostringstream::out);
  788. ostr << info->campaign->scenariosCount();
  789. labelNumberOfCampaignMaps->setText(ostr.str());
  790. labelNumberOfCampaignMaps->setColor(color);
  791. }
  792. else
  793. {
  794. labelNumberOfCampaignMaps->disable();
  795. std::ostringstream ostr(std::ostringstream::out);
  796. ostr << info->amountOfPlayersOnMap << "/" << info->amountOfHumanControllablePlayers;
  797. labelAmountOfPlayers->enable();
  798. labelAmountOfPlayers->setText(ostr.str());
  799. labelAmountOfPlayers->setColor(color);
  800. labelMapSizeLetter->enable();
  801. labelMapSizeLetter->setText(info->getMapSizeName());
  802. labelMapSizeLetter->setColor(color);
  803. iconFolder->disable();
  804. pictureEmptyLine->disable();
  805. iconFormat->enable();
  806. iconFormat->setFrame(info->getMapSizeFormatIconId());
  807. iconVictoryCondition->enable();
  808. iconVictoryCondition->setFrame(info->mapHeader->victoryIconIndex, 0);
  809. iconLossCondition->enable();
  810. iconLossCondition->setFrame(info->mapHeader->defeatIconIndex, 0);
  811. }
  812. labelName->enable();
  813. labelName->setText(info->getNameForList());
  814. labelName->setColor(color);
  815. }