SelectionTab.cpp 26 KB

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