SelectionTab.cpp 26 KB

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