SelectionTab.cpp 29 KB

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