SelectionTab.cpp 26 KB

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