SelectionTab.cpp 28 KB

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