SelectionTab.cpp 26 KB

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