SelectionTab.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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. {
  356. auto creationDateTime = tabType == ESelectionScreen::newGame && curItems[py]->mapHeader->creationDateTime ? TextOperations::getFormattedDateTimeLocal(curItems[py]->mapHeader->creationDateTime) : curItems[py]->date;
  357. auto author = curItems[py]->mapHeader->author.toString() + (!curItems[py]->mapHeader->authorContact.toString().empty() ? (" <" + curItems[py]->mapHeader->authorContact.toString() + ">") : "");
  358. GH.windows().createAndPushWindow<CMapOverview>(
  359. curItems[py]->getNameTranslated(),
  360. curItems[py]->fullFileURI,
  361. creationDateTime,
  362. author,
  363. curItems[py]->mapHeader->mapVersion.toString(),
  364. ResourcePath(curItems[py]->fileURI),
  365. tabType
  366. );
  367. }
  368. else
  369. CRClickPopup::createAndPush(curItems[py]->folderName);
  370. }
  371. auto SelectionTab::checkSubfolder(std::string path)
  372. {
  373. struct Ret
  374. {
  375. std::string folderName;
  376. std::string baseFolder;
  377. bool parentExists;
  378. bool fileInFolder;
  379. } ret;
  380. ret.parentExists = (curFolder != "");
  381. ret.fileInFolder = false;
  382. std::vector<std::string> filetree;
  383. // delete first element (e.g. 'MAPS')
  384. boost::split(filetree, path, boost::is_any_of("/"));
  385. filetree.erase(filetree.begin());
  386. std::string pathWithoutPrefix = boost::algorithm::join(filetree, "/");
  387. if(!filetree.empty())
  388. {
  389. filetree.pop_back();
  390. ret.baseFolder = boost::algorithm::join(filetree, "/");
  391. }
  392. else
  393. ret.baseFolder = "";
  394. if(boost::algorithm::starts_with(ret.baseFolder, curFolder))
  395. {
  396. std::string folder = ret.baseFolder.substr(curFolder.size());
  397. if(folder != "")
  398. {
  399. boost::split(filetree, folder, boost::is_any_of("/"));
  400. ret.folderName = filetree[0];
  401. }
  402. }
  403. if(boost::algorithm::starts_with(pathWithoutPrefix, curFolder))
  404. if(boost::count(pathWithoutPrefix.substr(curFolder.size()), '/') == 0)
  405. ret.fileInFolder = true;
  406. return ret;
  407. }
  408. // A new size filter (Small, Medium, ...) has been selected. Populate
  409. // selMaps with the relevant data.
  410. void SelectionTab::filter(int size, bool selectFirst)
  411. {
  412. if(size == -1)
  413. size = currentMapSizeFilter;
  414. currentMapSizeFilter = size;
  415. curItems.clear();
  416. for(auto elem : allItems)
  417. {
  418. if((elem->mapHeader && (!size || elem->mapHeader->width == size)) || tabType == ESelectionScreen::campaignList)
  419. {
  420. if(showRandom)
  421. curFolder = "RANDOMMAPS/";
  422. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(elem->originalFileURI);
  423. if((showRandom && baseFolder != "RANDOMMAPS") || (!showRandom && baseFolder == "RANDOMMAPS"))
  424. continue;
  425. if(parentExists && !showRandom)
  426. {
  427. auto folder = std::make_shared<ElementInfo>();
  428. folder->isFolder = true;
  429. folder->folderName = ".. (" + curFolder + ")";
  430. auto itemIt = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return boost::starts_with(e->folderName, ".."); });
  431. if (itemIt == curItems.end()) {
  432. curItems.push_back(folder);
  433. }
  434. }
  435. auto folder = std::make_shared<ElementInfo>();
  436. folder->isFolder = true;
  437. folder->folderName = folderName;
  438. auto itemIt = boost::range::find_if(curItems, [folder](std::shared_ptr<ElementInfo> e) { return e->folderName == folder->folderName; });
  439. if (itemIt == curItems.end() && folderName != "") {
  440. curItems.push_back(folder);
  441. }
  442. if(fileInFolder)
  443. curItems.push_back(elem);
  444. }
  445. }
  446. if(curItems.size())
  447. {
  448. slider->block(false);
  449. slider->setAmount((int)curItems.size());
  450. sort();
  451. if(selectFirst)
  452. {
  453. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  454. if(firstPos < curItems.size())
  455. {
  456. slider->scrollTo(firstPos);
  457. callOnSelect(curItems[firstPos]);
  458. selectAbs(firstPos);
  459. }
  460. }
  461. }
  462. else
  463. {
  464. updateListItems();
  465. redraw();
  466. slider->block(true);
  467. if(callOnSelect)
  468. callOnSelect(nullptr);
  469. }
  470. }
  471. void SelectionTab::sortBy(int criteria)
  472. {
  473. if(criteria == sortingBy)
  474. {
  475. sortModeAscending = !sortModeAscending;
  476. }
  477. else
  478. {
  479. sortingBy = (ESortBy)criteria;
  480. sortModeAscending = true;
  481. }
  482. sort();
  483. selectAbs(-1);
  484. }
  485. void SelectionTab::sort()
  486. {
  487. if(sortingBy != generalSortingBy)
  488. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(generalSortingBy));
  489. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(sortingBy));
  490. int firstMapIndex = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  491. if(!sortModeAscending)
  492. std::reverse(std::next(curItems.begin(), firstMapIndex), curItems.end());
  493. updateListItems();
  494. redraw();
  495. }
  496. void SelectionTab::select(int position)
  497. {
  498. if(!curItems.size())
  499. return;
  500. // New selection. py is the index in curItems.
  501. int py = position + slider->getValue();
  502. vstd::amax(py, 0);
  503. vstd::amin(py, curItems.size() - 1);
  504. selectionPos = py;
  505. if(position < 0)
  506. slider->scrollBy(position);
  507. else if(position >= listItems.size())
  508. slider->scrollBy(position - (int)listItems.size() + 1);
  509. if(curItems[py]->isFolder) {
  510. if(boost::starts_with(curItems[py]->folderName, ".."))
  511. {
  512. std::vector<std::string> filetree;
  513. boost::split(filetree, curFolder, boost::is_any_of("/"));
  514. filetree.pop_back();
  515. filetree.pop_back();
  516. curFolder = filetree.size() > 0 ? boost::algorithm::join(filetree, "/") + "/" : "";
  517. }
  518. else
  519. curFolder += curItems[py]->folderName + "/";
  520. filter(-1);
  521. slider->scrollTo(0);
  522. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  523. if(firstPos < curItems.size())
  524. {
  525. selectAbs(firstPos);
  526. }
  527. return;
  528. }
  529. rememberCurrentSelection();
  530. if(inputName && inputName->isActive())
  531. {
  532. auto filename = *CResourceHandler::get()->getResourceName(ResourcePath(curItems[py]->fileURI, EResType::SAVEGAME));
  533. inputName->setText(filename.stem().string());
  534. }
  535. updateListItems();
  536. redraw();
  537. if(callOnSelect)
  538. callOnSelect(curItems[py]);
  539. }
  540. void SelectionTab::selectAbs(int position)
  541. {
  542. if(position == -1)
  543. position = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  544. select(position - slider->getValue());
  545. }
  546. void SelectionTab::sliderMove(int slidPos)
  547. {
  548. if(!slider)
  549. return; // ignore spurious call when slider is being created
  550. updateListItems();
  551. redraw();
  552. }
  553. void SelectionTab::updateListItems()
  554. {
  555. // elemIdx is the index of the maps or saved game to display on line 0
  556. // slider->capacity contains the number of available screen lines
  557. // slider->positionsAmnt is the number of elements after filtering
  558. int elemIdx = slider->getValue();
  559. for(auto item : listItems)
  560. {
  561. if(elemIdx < curItems.size())
  562. {
  563. item->updateItem(curItems[elemIdx], elemIdx == selectionPos);
  564. elemIdx++;
  565. }
  566. else
  567. {
  568. item->updateItem();
  569. }
  570. }
  571. }
  572. bool SelectionTab::receiveEvent(const Point & position, int eventType) const
  573. {
  574. // FIXME: widget should instead have well-defined pos so events will be filtered using standard routine
  575. return getLine(position - pos.topLeft()) != -1;
  576. }
  577. int SelectionTab::getLine() const
  578. {
  579. Point clickPos = GH.getCursorPosition() - pos.topLeft();
  580. return getLine(clickPos);
  581. }
  582. int SelectionTab::getLine(const Point & clickPos) const
  583. {
  584. int line = -1;
  585. // Ignore clicks on save name area
  586. int maxPosY;
  587. if(tabType == ESelectionScreen::saveGame)
  588. maxPosY = 516;
  589. else
  590. maxPosY = 564;
  591. if(clickPos.y > 115 && clickPos.y < maxPosY && clickPos.x > 22 && clickPos.x < 371)
  592. {
  593. line = (clickPos.y - 115) / 25; //which line
  594. }
  595. return line;
  596. }
  597. void SelectionTab::selectFileName(std::string fname)
  598. {
  599. boost::to_upper(fname);
  600. for(int i = (int)allItems.size() - 1; i >= 0; i--)
  601. {
  602. if(allItems[i]->fileURI == fname)
  603. {
  604. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(allItems[i]->originalFileURI);
  605. curFolder = baseFolder != "" ? baseFolder + "/" : "";
  606. }
  607. }
  608. filter(-1);
  609. for(int i = (int)curItems.size() - 1; i >= 0; i--)
  610. {
  611. if(curItems[i]->fileURI == fname)
  612. {
  613. slider->scrollTo(i);
  614. selectAbs(i);
  615. return;
  616. }
  617. }
  618. selectAbs(-1);
  619. if(tabType == ESelectionScreen::saveGame && inputName->getText().empty())
  620. inputName->setText("NEWGAME");
  621. }
  622. void SelectionTab::selectNewestFile()
  623. {
  624. time_t newestTime = 0;
  625. std::string newestFile = "";
  626. for(int i = static_cast<int>(allItems.size()) - 1; i >= 0; i--)
  627. if(allItems[i]->lastWrite > newestTime)
  628. {
  629. newestTime = allItems[i]->lastWrite;
  630. newestFile = allItems[i]->fileURI;
  631. }
  632. selectFileName(newestFile);
  633. }
  634. std::shared_ptr<ElementInfo> SelectionTab::getSelectedMapInfo() const
  635. {
  636. return curItems.empty() || curItems[selectionPos]->isFolder ? nullptr : curItems[selectionPos];
  637. }
  638. void SelectionTab::rememberCurrentSelection()
  639. {
  640. if(getSelectedMapInfo()->isFolder)
  641. return;
  642. // TODO: this can be more elegant
  643. if(tabType == ESelectionScreen::newGame)
  644. {
  645. Settings lastMap = settings.write["general"]["lastMap"];
  646. lastMap->String() = getSelectedMapInfo()->fileURI;
  647. }
  648. else if(tabType == ESelectionScreen::loadGame)
  649. {
  650. Settings lastSave = settings.write["general"]["lastSave"];
  651. lastSave->String() = getSelectedMapInfo()->fileURI;
  652. }
  653. else if(tabType == ESelectionScreen::campaignList)
  654. {
  655. Settings lastCampaign = settings.write["general"]["lastCampaign"];
  656. lastCampaign->String() = getSelectedMapInfo()->fileURI;
  657. }
  658. }
  659. void SelectionTab::restoreLastSelection()
  660. {
  661. switch(tabType)
  662. {
  663. case ESelectionScreen::newGame:
  664. selectFileName(settings["general"]["lastMap"].String());
  665. break;
  666. case ESelectionScreen::campaignList:
  667. selectFileName(settings["general"]["lastCampaign"].String());
  668. break;
  669. case ESelectionScreen::loadGame:
  670. selectNewestFile();
  671. break;
  672. case ESelectionScreen::saveGame:
  673. selectFileName(settings["general"]["lastSave"].String());
  674. }
  675. }
  676. bool SelectionTab::isMapSupported(const CMapInfo & info)
  677. {
  678. switch (info.mapHeader->version)
  679. {
  680. case EMapFormat::ROE:
  681. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_RESTORATION_OF_ERATHIA)["supported"].Bool();
  682. case EMapFormat::AB:
  683. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_ARMAGEDDONS_BLADE)["supported"].Bool();
  684. case EMapFormat::SOD:
  685. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_SHADOW_OF_DEATH)["supported"].Bool();
  686. case EMapFormat::WOG:
  687. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_IN_THE_WAKE_OF_GODS)["supported"].Bool();
  688. case EMapFormat::HOTA:
  689. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_HORN_OF_THE_ABYSS)["supported"].Bool();
  690. case EMapFormat::VCMI:
  691. return CGI->settings()->getValue(EGameSettings::MAP_FORMAT_JSON_VCMI)["supported"].Bool();
  692. }
  693. return false;
  694. }
  695. void SelectionTab::parseMaps(const std::unordered_set<ResourcePath> & files)
  696. {
  697. logGlobal->debug("Parsing %d maps", files.size());
  698. allItems.clear();
  699. for(auto & file : files)
  700. {
  701. try
  702. {
  703. auto mapInfo = std::make_shared<ElementInfo>();
  704. mapInfo->mapInit(file.getName());
  705. if (isMapSupported(*mapInfo))
  706. allItems.push_back(mapInfo);
  707. }
  708. catch(std::exception & e)
  709. {
  710. logGlobal->error("Map %s is invalid. Message: %s", file.getName(), e.what());
  711. }
  712. }
  713. }
  714. void SelectionTab::parseSaves(const std::unordered_set<ResourcePath> & files)
  715. {
  716. for(auto & file : files)
  717. {
  718. try
  719. {
  720. auto mapInfo = std::make_shared<ElementInfo>();
  721. mapInfo->saveInit(file);
  722. // Filter out other game modes
  723. bool isCampaign = mapInfo->scenarioOptionsOfSave->mode == EStartMode::CAMPAIGN;
  724. bool isMultiplayer = mapInfo->amountOfHumanPlayersInSave > 1;
  725. bool isTutorial = boost::to_upper_copy(mapInfo->scenarioOptionsOfSave->mapname) == "MAPS/TUTORIAL";
  726. switch(CSH->getLoadMode())
  727. {
  728. case ELoadMode::SINGLE:
  729. if(isCampaign || isTutorial)
  730. mapInfo->mapHeader.reset();
  731. break;
  732. case ELoadMode::CAMPAIGN:
  733. if(!isCampaign)
  734. mapInfo->mapHeader.reset();
  735. break;
  736. case ELoadMode::TUTORIAL:
  737. if(!isTutorial)
  738. mapInfo->mapHeader.reset();
  739. break;
  740. case ELoadMode::MULTI:
  741. if(!isMultiplayer)
  742. mapInfo->mapHeader.reset();
  743. break;
  744. default:
  745. assert(0);
  746. mapInfo->mapHeader.reset();
  747. break;
  748. }
  749. allItems.push_back(mapInfo);
  750. }
  751. catch(const std::exception & e)
  752. {
  753. logGlobal->error("Error: Failed to process %s: %s", file.getName(), e.what());
  754. }
  755. }
  756. }
  757. void SelectionTab::parseCampaigns(const std::unordered_set<ResourcePath> & files)
  758. {
  759. allItems.reserve(files.size());
  760. for(auto & file : files)
  761. {
  762. auto info = std::make_shared<ElementInfo>();
  763. //allItems[i].date = std::asctime(std::localtime(&files[i].date));
  764. info->fileURI = file.getName();
  765. info->campaignInit();
  766. if(info->campaign)
  767. allItems.push_back(info);
  768. }
  769. }
  770. std::unordered_set<ResourcePath> SelectionTab::getFiles(std::string dirURI, EResType resType)
  771. {
  772. boost::to_upper(dirURI);
  773. CResourceHandler::get()->updateFilteredFiles([&](const std::string & mount)
  774. {
  775. return boost::algorithm::starts_with(mount, dirURI);
  776. });
  777. std::unordered_set<ResourcePath> ret = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  778. {
  779. return ident.getType() == resType && boost::algorithm::starts_with(ident.getName(), dirURI);
  780. });
  781. return ret;
  782. }
  783. SelectionTab::ListItem::ListItem(Point position, std::shared_ptr<CAnimation> iconsFormats, std::shared_ptr<CAnimation> iconsVictory, std::shared_ptr<CAnimation> iconsLoss)
  784. : CIntObject(LCLICK, position)
  785. {
  786. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  787. pictureEmptyLine = std::make_shared<CPicture>(GH.renderHandler().loadImage(ImagePath::builtin("camcust")), Rect(25, 121, 349, 26), -8, -14);
  788. labelName = std::make_shared<CLabel>(184, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "", 185);
  789. labelName->setAutoRedraw(false);
  790. labelAmountOfPlayers = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  791. labelAmountOfPlayers->setAutoRedraw(false);
  792. labelNumberOfCampaignMaps = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  793. labelNumberOfCampaignMaps->setAutoRedraw(false);
  794. labelMapSizeLetter = std::make_shared<CLabel>(41, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  795. labelMapSizeLetter->setAutoRedraw(false);
  796. // FIXME: This -12 should not be needed, but for some reason CAnimImage displaced otherwise
  797. iconFolder = std::make_shared<CPicture>(ImagePath::builtin("lobby/iconFolder.png"), -8, -12);
  798. iconFormat = std::make_shared<CAnimImage>(iconsFormats, 0, 0, 59, -12);
  799. iconVictoryCondition = std::make_shared<CAnimImage>(iconsVictory, 0, 0, 277, -12);
  800. iconLossCondition = std::make_shared<CAnimImage>(iconsLoss, 0, 0, 310, -12);
  801. }
  802. void SelectionTab::ListItem::updateItem(std::shared_ptr<ElementInfo> info, bool selected)
  803. {
  804. if(!info)
  805. {
  806. labelAmountOfPlayers->disable();
  807. labelMapSizeLetter->disable();
  808. iconFolder->disable();
  809. pictureEmptyLine->disable();
  810. iconFormat->disable();
  811. iconVictoryCondition->disable();
  812. iconLossCondition->disable();
  813. labelNumberOfCampaignMaps->disable();
  814. labelName->disable();
  815. return;
  816. }
  817. auto color = selected ? Colors::YELLOW : Colors::WHITE;
  818. if(info->isFolder)
  819. {
  820. labelAmountOfPlayers->disable();
  821. labelMapSizeLetter->disable();
  822. iconFolder->enable();
  823. pictureEmptyLine->enable();
  824. iconFormat->disable();
  825. iconVictoryCondition->disable();
  826. iconLossCondition->disable();
  827. labelNumberOfCampaignMaps->disable();
  828. labelName->enable();
  829. labelName->setMaxWidth(316);
  830. labelName->setText(info->folderName);
  831. labelName->setColor(color);
  832. return;
  833. }
  834. labelName->enable();
  835. if(info->campaign)
  836. {
  837. labelAmountOfPlayers->disable();
  838. labelMapSizeLetter->disable();
  839. iconFolder->disable();
  840. pictureEmptyLine->disable();
  841. iconFormat->disable();
  842. iconVictoryCondition->disable();
  843. iconLossCondition->disable();
  844. labelNumberOfCampaignMaps->enable();
  845. std::ostringstream ostr(std::ostringstream::out);
  846. ostr << info->campaign->scenariosCount();
  847. labelNumberOfCampaignMaps->setText(ostr.str());
  848. labelNumberOfCampaignMaps->setColor(color);
  849. labelName->setMaxWidth(316);
  850. }
  851. else
  852. {
  853. labelNumberOfCampaignMaps->disable();
  854. std::ostringstream ostr(std::ostringstream::out);
  855. ostr << info->amountOfPlayersOnMap << "/" << info->amountOfHumanControllablePlayers;
  856. labelAmountOfPlayers->enable();
  857. labelAmountOfPlayers->setText(ostr.str());
  858. labelAmountOfPlayers->setColor(color);
  859. labelMapSizeLetter->enable();
  860. labelMapSizeLetter->setText(info->getMapSizeName());
  861. labelMapSizeLetter->setColor(color);
  862. iconFolder->disable();
  863. pictureEmptyLine->disable();
  864. iconFormat->enable();
  865. iconFormat->setFrame(info->getMapSizeFormatIconId());
  866. iconVictoryCondition->enable();
  867. iconVictoryCondition->setFrame(info->mapHeader->victoryIconIndex, 0);
  868. iconLossCondition->enable();
  869. iconLossCondition->setFrame(info->mapHeader->defeatIconIndex, 0);
  870. labelName->setMaxWidth(185);
  871. }
  872. labelName->setText(info->getNameForList());
  873. labelName->setColor(color);
  874. }