SelectionTab.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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/CConfigHandler.h"
  35. #include "../../lib/IGameSettings.h"
  36. #include "../../lib/filesystem/Filesystem.h"
  37. #include "../../lib/campaign/CampaignState.h"
  38. #include "../../lib/mapping/CMapInfo.h"
  39. #include "../../lib/mapping/CMapHeader.h"
  40. #include "../../lib/mapping/MapFormat.h"
  41. #include "../../lib/texts/CGeneralTextHandler.h"
  42. #include "../../lib/texts/TextOperations.h"
  43. #include "../../lib/TerrainHandler.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. OBJECT_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. for(int i = 0; i < positionsToShow; i++)
  212. listItems.push_back(std::make_shared<ListItem>(Point(30, 129 + i * 25)));
  213. labelTabTitle = std::make_shared<CLabel>(205, 28, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, tabTitle);
  214. 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);
  215. slider->setPanningStep(24);
  216. // create scroll bounds that encompass all area in this UI element to the left of slider (including area of slider itself)
  217. // entire screen can't be used in here since map description might also have slider
  218. slider->setScrollBounds(Rect(pos.x - slider->pos.x, 0, slider->pos.x + slider->pos.w - pos.x, slider->pos.h ));
  219. filter(0);
  220. }
  221. void SelectionTab::toggleMode()
  222. {
  223. if(CSH->isGuest())
  224. {
  225. allItems.clear();
  226. curItems.clear();
  227. if(slider)
  228. slider->block(true);
  229. }
  230. else
  231. {
  232. switch(tabType)
  233. {
  234. case ESelectionScreen::newGame:
  235. {
  236. inputName->disable();
  237. auto files = getFiles("Maps/", EResType::MAP);
  238. files.erase(ResourcePath("Maps/Tutorial.tut", EResType::MAP));
  239. parseMaps(files);
  240. break;
  241. }
  242. case ESelectionScreen::loadGame:
  243. inputName->disable();
  244. parseSaves(getFiles("Saves/", EResType::SAVEGAME));
  245. break;
  246. case ESelectionScreen::saveGame:
  247. parseSaves(getFiles("Saves/", EResType::SAVEGAME));
  248. inputName->enable();
  249. inputName->activate();
  250. restoreLastSelection();
  251. break;
  252. case ESelectionScreen::campaignList:
  253. parseCampaigns(getFiles("Maps/", EResType::CAMPAIGN));
  254. break;
  255. default:
  256. assert(0);
  257. break;
  258. }
  259. if(slider)
  260. {
  261. slider->block(false);
  262. filter(0);
  263. }
  264. if(CSH->campaignStateToSend)
  265. {
  266. CSH->setCampaignState(CSH->campaignStateToSend);
  267. CSH->campaignStateToSend.reset();
  268. }
  269. else
  270. {
  271. restoreLastSelection();
  272. }
  273. }
  274. slider->setAmount((int)curItems.size());
  275. updateListItems();
  276. redraw();
  277. }
  278. void SelectionTab::clickReleased(const Point & cursorPosition)
  279. {
  280. int line = getLine();
  281. if(line != -1 && curItems.size() > line)
  282. {
  283. select(line);
  284. }
  285. #ifdef VCMI_MOBILE
  286. // focus input field if clicked inside it
  287. else if(inputName && inputName->isActive() && inputNameRect.isInside(cursorPosition))
  288. inputName->giveFocus();
  289. #endif
  290. }
  291. void SelectionTab::keyPressed(EShortcut key)
  292. {
  293. int moveBy = 0;
  294. switch(key)
  295. {
  296. case EShortcut::MOVE_UP:
  297. moveBy = -1;
  298. break;
  299. case EShortcut::MOVE_DOWN:
  300. moveBy = +1;
  301. break;
  302. case EShortcut::MOVE_PAGE_UP:
  303. moveBy = -(int)listItems.size() + 1;
  304. break;
  305. case EShortcut::MOVE_PAGE_DOWN:
  306. moveBy = +(int)listItems.size() - 1;
  307. break;
  308. case EShortcut::MOVE_FIRST:
  309. select(-slider->getValue());
  310. return;
  311. case EShortcut::MOVE_LAST:
  312. select((int)curItems.size() - slider->getValue());
  313. return;
  314. default:
  315. return;
  316. }
  317. select((int)selectionPos - slider->getValue() + moveBy);
  318. }
  319. void SelectionTab::clickDouble(const Point & cursorPosition)
  320. {
  321. int position = getLine();
  322. int itemIndex = position + slider->getValue();
  323. if(itemIndex >= curItems.size())
  324. return;
  325. auto clickedItem = curItems[itemIndex];
  326. auto selectedItem = getSelectedMapInfo();
  327. if (clickedItem != selectedItem)
  328. {
  329. // double-click BUT player hit different item than he had selected
  330. // ignore - clickReleased would still trigger and update selection.
  331. // After which another (3rd) click if it happens would still register as double-click
  332. return;
  333. }
  334. if(itemIndex >= 0 && curItems[itemIndex]->isFolder)
  335. {
  336. select(position);
  337. return;
  338. }
  339. if(getLine() != -1) //double clicked scenarios list
  340. {
  341. (static_cast<CLobbyScreen *>(parent))->buttonStart->clickPressed(cursorPosition);
  342. (static_cast<CLobbyScreen *>(parent))->buttonStart->clickReleased(cursorPosition);
  343. }
  344. }
  345. void SelectionTab::showPopupWindow(const Point & cursorPosition)
  346. {
  347. int position = getLine();
  348. int py = position + slider->getValue();
  349. if(py >= curItems.size())
  350. return;
  351. if(!curItems[py]->isFolder)
  352. {
  353. std::string creationDateTime;
  354. std::string author;
  355. std::string mapVersion;
  356. if(tabType != ESelectionScreen::campaignList)
  357. {
  358. author = curItems[py]->mapHeader->author.toString() + (!curItems[py]->mapHeader->authorContact.toString().empty() ? (" <" + curItems[py]->mapHeader->authorContact.toString() + ">") : "");
  359. mapVersion = curItems[py]->mapHeader->mapVersion.toString();
  360. creationDateTime = tabType == ESelectionScreen::newGame && curItems[py]->mapHeader->creationDateTime ? TextOperations::getFormattedDateTimeLocal(curItems[py]->mapHeader->creationDateTime) : curItems[py]->date;
  361. }
  362. else
  363. {
  364. author = curItems[py]->campaign->getAuthor() + (!curItems[py]->campaign->getAuthorContact().empty() ? (" <" + curItems[py]->campaign->getAuthorContact() + ">") : "");
  365. mapVersion = curItems[py]->campaign->getCampaignVersion();
  366. creationDateTime = curItems[py]->campaign->getCreationDateTime() ? TextOperations::getFormattedDateTimeLocal(curItems[py]->campaign->getCreationDateTime()) : curItems[py]->date;
  367. }
  368. GH.windows().createAndPushWindow<CMapOverview>(
  369. curItems[py]->getNameTranslated(),
  370. curItems[py]->fullFileURI,
  371. creationDateTime,
  372. author,
  373. mapVersion,
  374. ResourcePath(curItems[py]->fileURI),
  375. tabType
  376. );
  377. }
  378. else
  379. CRClickPopup::createAndPush(curItems[py]->folderName);
  380. }
  381. auto SelectionTab::checkSubfolder(std::string path)
  382. {
  383. struct Ret
  384. {
  385. std::string folderName;
  386. std::string baseFolder;
  387. bool parentExists;
  388. bool fileInFolder;
  389. } ret;
  390. ret.parentExists = (curFolder != "");
  391. ret.fileInFolder = false;
  392. std::vector<std::string> filetree;
  393. // delete first element (e.g. 'MAPS')
  394. boost::split(filetree, path, boost::is_any_of("/"));
  395. filetree.erase(filetree.begin());
  396. std::string pathWithoutPrefix = boost::algorithm::join(filetree, "/");
  397. if(!filetree.empty())
  398. {
  399. filetree.pop_back();
  400. ret.baseFolder = boost::algorithm::join(filetree, "/");
  401. }
  402. else
  403. ret.baseFolder = "";
  404. if(boost::algorithm::starts_with(ret.baseFolder, curFolder))
  405. {
  406. std::string folder = ret.baseFolder.substr(curFolder.size());
  407. if(folder != "")
  408. {
  409. boost::split(filetree, folder, boost::is_any_of("/"));
  410. ret.folderName = filetree[0];
  411. }
  412. }
  413. if(boost::algorithm::starts_with(pathWithoutPrefix, curFolder))
  414. if(boost::count(pathWithoutPrefix.substr(curFolder.size()), '/') == 0)
  415. ret.fileInFolder = true;
  416. return ret;
  417. }
  418. // A new size filter (Small, Medium, ...) has been selected. Populate
  419. // selMaps with the relevant data.
  420. void SelectionTab::filter(int size, bool selectFirst)
  421. {
  422. if(size == -1)
  423. size = currentMapSizeFilter;
  424. currentMapSizeFilter = size;
  425. curItems.clear();
  426. for(auto elem : allItems)
  427. {
  428. if((elem->mapHeader && (!size || elem->mapHeader->width == size)) || tabType == ESelectionScreen::campaignList)
  429. {
  430. if(showRandom)
  431. curFolder = "RandomMaps/";
  432. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(elem->originalFileURI);
  433. if((showRandom && baseFolder != "RandomMaps") || (!showRandom && baseFolder == "RandomMaps"))
  434. continue;
  435. if(parentExists && !showRandom)
  436. {
  437. auto folder = std::make_shared<ElementInfo>();
  438. folder->isFolder = true;
  439. folder->folderName = ".. (" + curFolder + ")";
  440. auto itemIt = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return boost::starts_with(e->folderName, ".."); });
  441. if (itemIt == curItems.end()) {
  442. curItems.push_back(folder);
  443. }
  444. }
  445. auto folder = std::make_shared<ElementInfo>();
  446. folder->isFolder = true;
  447. folder->folderName = folderName;
  448. folder->isAutoSaveFolder = boost::starts_with(baseFolder, "Autosave/") && folderName != "Autosave";
  449. auto itemIt = boost::range::find_if(curItems, [folder](std::shared_ptr<ElementInfo> e) { return e->folderName == folder->folderName; });
  450. if (itemIt == curItems.end() && folderName != "") {
  451. curItems.push_back(folder);
  452. }
  453. if(fileInFolder)
  454. curItems.push_back(elem);
  455. }
  456. }
  457. if(curItems.size())
  458. {
  459. slider->block(false);
  460. slider->setAmount((int)curItems.size());
  461. sort();
  462. if(selectFirst)
  463. {
  464. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  465. if(firstPos < curItems.size())
  466. {
  467. slider->scrollTo(firstPos);
  468. callOnSelect(curItems[firstPos]);
  469. selectAbs(firstPos);
  470. }
  471. }
  472. }
  473. else
  474. {
  475. updateListItems();
  476. redraw();
  477. slider->block(true);
  478. if(callOnSelect)
  479. callOnSelect(nullptr);
  480. }
  481. }
  482. void SelectionTab::sortBy(int criteria)
  483. {
  484. if(criteria == sortingBy)
  485. {
  486. sortModeAscending = !sortModeAscending;
  487. }
  488. else
  489. {
  490. sortingBy = (ESortBy)criteria;
  491. sortModeAscending = true;
  492. }
  493. sort();
  494. selectAbs(-1);
  495. }
  496. void SelectionTab::sort()
  497. {
  498. if(sortingBy != generalSortingBy)
  499. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(generalSortingBy));
  500. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(sortingBy));
  501. int firstMapIndex = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  502. if(!sortModeAscending)
  503. {
  504. if(firstMapIndex)
  505. std::reverse(std::next(curItems.begin(), boost::starts_with(curItems[0]->folderName, "..") ? 1 : 0), std::next(curItems.begin(), firstMapIndex - 1));
  506. std::reverse(std::next(curItems.begin(), firstMapIndex), curItems.end());
  507. }
  508. updateListItems();
  509. redraw();
  510. }
  511. void SelectionTab::select(int position)
  512. {
  513. if(!curItems.size())
  514. return;
  515. // New selection. py is the index in curItems.
  516. int py = position + slider->getValue();
  517. vstd::amax(py, 0);
  518. vstd::amin(py, curItems.size() - 1);
  519. selectionPos = py;
  520. if(position < 0)
  521. slider->scrollBy(position);
  522. else if(position >= listItems.size())
  523. slider->scrollBy(position - (int)listItems.size() + 1);
  524. if(curItems[py]->isFolder) {
  525. if(boost::starts_with(curItems[py]->folderName, ".."))
  526. {
  527. std::vector<std::string> filetree;
  528. boost::split(filetree, curFolder, boost::is_any_of("/"));
  529. filetree.pop_back();
  530. filetree.pop_back();
  531. curFolder = filetree.size() > 0 ? boost::algorithm::join(filetree, "/") + "/" : "";
  532. }
  533. else
  534. curFolder += curItems[py]->folderName + "/";
  535. filter(-1);
  536. slider->scrollTo(0);
  537. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  538. if(firstPos < curItems.size())
  539. {
  540. selectAbs(firstPos);
  541. }
  542. return;
  543. }
  544. rememberCurrentSelection();
  545. if(inputName && inputName->isActive())
  546. {
  547. auto filename = *CResourceHandler::get()->getResourceName(ResourcePath(curItems[py]->fileURI, EResType::SAVEGAME));
  548. inputName->setText(filename.stem().string());
  549. }
  550. updateListItems();
  551. redraw();
  552. if(callOnSelect)
  553. callOnSelect(curItems[py]);
  554. }
  555. void SelectionTab::selectAbs(int position)
  556. {
  557. if(position == -1)
  558. position = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  559. select(position - slider->getValue());
  560. }
  561. void SelectionTab::sliderMove(int slidPos)
  562. {
  563. if(!slider)
  564. return; // ignore spurious call when slider is being created
  565. updateListItems();
  566. redraw();
  567. }
  568. void SelectionTab::updateListItems()
  569. {
  570. // elemIdx is the index of the maps or saved game to display on line 0
  571. // slider->capacity contains the number of available screen lines
  572. // slider->positionsAmnt is the number of elements after filtering
  573. int elemIdx = slider->getValue();
  574. for(auto item : listItems)
  575. {
  576. if(elemIdx < curItems.size())
  577. {
  578. item->updateItem(curItems[elemIdx], elemIdx == selectionPos);
  579. elemIdx++;
  580. }
  581. else
  582. {
  583. item->updateItem();
  584. }
  585. }
  586. }
  587. bool SelectionTab::receiveEvent(const Point & position, int eventType) const
  588. {
  589. // FIXME: widget should instead have well-defined pos so events will be filtered using standard routine
  590. return getLine(position - pos.topLeft()) != -1;
  591. }
  592. int SelectionTab::getLine() const
  593. {
  594. Point clickPos = GH.getCursorPosition() - pos.topLeft();
  595. return getLine(clickPos);
  596. }
  597. int SelectionTab::getLine(const Point & clickPos) const
  598. {
  599. int line = -1;
  600. // Ignore clicks on save name area
  601. int maxPosY;
  602. if(tabType == ESelectionScreen::saveGame)
  603. maxPosY = 516;
  604. else
  605. maxPosY = 564;
  606. if(clickPos.y > 115 && clickPos.y < maxPosY && clickPos.x > 22 && clickPos.x < 371)
  607. {
  608. line = (clickPos.y - 115) / 25; //which line
  609. }
  610. return line;
  611. }
  612. void SelectionTab::selectFileName(std::string fname)
  613. {
  614. boost::to_upper(fname);
  615. for(int i = (int)allItems.size() - 1; i >= 0; i--)
  616. {
  617. if(boost::to_upper_copy(allItems[i]->fileURI) == fname)
  618. {
  619. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(allItems[i]->originalFileURI);
  620. curFolder = baseFolder != "" ? baseFolder + "/" : "";
  621. }
  622. }
  623. filter(-1);
  624. for(int i = (int)curItems.size() - 1; i >= 0; i--)
  625. {
  626. if(boost::to_upper_copy(curItems[i]->fileURI) == fname)
  627. {
  628. slider->scrollTo(i);
  629. selectAbs(i);
  630. return;
  631. }
  632. }
  633. selectAbs(-1);
  634. if(tabType == ESelectionScreen::saveGame && inputName->getText().empty())
  635. inputName->setText(CGI->generaltexth->translate("core.genrltxt.11"));
  636. }
  637. void SelectionTab::selectNewestFile()
  638. {
  639. time_t newestTime = 0;
  640. std::string newestFile = "";
  641. for(int i = static_cast<int>(allItems.size()) - 1; i >= 0; i--)
  642. if(allItems[i]->lastWrite > newestTime)
  643. {
  644. newestTime = allItems[i]->lastWrite;
  645. newestFile = allItems[i]->fileURI;
  646. }
  647. selectFileName(newestFile);
  648. }
  649. std::shared_ptr<ElementInfo> SelectionTab::getSelectedMapInfo() const
  650. {
  651. return curItems.empty() || curItems[selectionPos]->isFolder ? nullptr : curItems[selectionPos];
  652. }
  653. void SelectionTab::rememberCurrentSelection()
  654. {
  655. if(getSelectedMapInfo()->isFolder)
  656. return;
  657. // TODO: this can be more elegant
  658. if(tabType == ESelectionScreen::newGame)
  659. {
  660. Settings lastMap = settings.write["general"]["lastMap"];
  661. lastMap->String() = getSelectedMapInfo()->fileURI;
  662. }
  663. else if(tabType == ESelectionScreen::loadGame)
  664. {
  665. Settings lastSave = settings.write["general"]["lastSave"];
  666. lastSave->String() = getSelectedMapInfo()->fileURI;
  667. }
  668. else if(tabType == ESelectionScreen::campaignList)
  669. {
  670. Settings lastCampaign = settings.write["general"]["lastCampaign"];
  671. lastCampaign->String() = getSelectedMapInfo()->fileURI;
  672. }
  673. }
  674. void SelectionTab::restoreLastSelection()
  675. {
  676. switch(tabType)
  677. {
  678. case ESelectionScreen::newGame:
  679. selectFileName(settings["general"]["lastMap"].String());
  680. break;
  681. case ESelectionScreen::campaignList:
  682. selectFileName(settings["general"]["lastCampaign"].String());
  683. break;
  684. case ESelectionScreen::loadGame:
  685. selectNewestFile();
  686. break;
  687. case ESelectionScreen::saveGame:
  688. selectFileName(settings["general"]["lastSave"].String());
  689. }
  690. }
  691. bool SelectionTab::isMapSupported(const CMapInfo & info)
  692. {
  693. switch (info.mapHeader->version)
  694. {
  695. case EMapFormat::ROE:
  696. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_RESTORATION_OF_ERATHIA)["supported"].Bool();
  697. case EMapFormat::AB:
  698. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_ARMAGEDDONS_BLADE)["supported"].Bool();
  699. case EMapFormat::SOD:
  700. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_SHADOW_OF_DEATH)["supported"].Bool();
  701. case EMapFormat::CHR:
  702. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_CHRONICLES)["supported"].Bool();
  703. case EMapFormat::WOG:
  704. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_IN_THE_WAKE_OF_GODS)["supported"].Bool();
  705. case EMapFormat::HOTA:
  706. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_HORN_OF_THE_ABYSS)["supported"].Bool();
  707. case EMapFormat::VCMI:
  708. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_JSON_VCMI)["supported"].Bool();
  709. }
  710. return false;
  711. }
  712. void SelectionTab::parseMaps(const std::unordered_set<ResourcePath> & files)
  713. {
  714. logGlobal->debug("Parsing %d maps", files.size());
  715. allItems.clear();
  716. for(auto & file : files)
  717. {
  718. try
  719. {
  720. auto mapInfo = std::make_shared<ElementInfo>();
  721. mapInfo->mapInit(file.getOriginalName());
  722. mapInfo->name = mapInfo->getNameForList();
  723. if (isMapSupported(*mapInfo))
  724. allItems.push_back(mapInfo);
  725. }
  726. catch(std::exception & e)
  727. {
  728. logGlobal->error("Map %s is invalid. Message: %s", file.getName(), e.what());
  729. }
  730. }
  731. }
  732. void SelectionTab::parseSaves(const std::unordered_set<ResourcePath> & files)
  733. {
  734. for(auto & file : files)
  735. {
  736. try
  737. {
  738. auto mapInfo = std::make_shared<ElementInfo>();
  739. mapInfo->saveInit(file);
  740. mapInfo->name = mapInfo->getNameForList();
  741. // Filter out other game modes
  742. bool isCampaign = mapInfo->scenarioOptionsOfSave->mode == EStartMode::CAMPAIGN;
  743. bool isMultiplayer = mapInfo->amountOfHumanPlayersInSave > 1;
  744. bool isTutorial = boost::to_upper_copy(mapInfo->scenarioOptionsOfSave->mapname) == "MAPS/TUTORIAL";
  745. switch(CSH->getLoadMode())
  746. {
  747. case ELoadMode::SINGLE:
  748. if(isCampaign || isTutorial)
  749. mapInfo->mapHeader.reset();
  750. break;
  751. case ELoadMode::CAMPAIGN:
  752. if(!isCampaign)
  753. mapInfo->mapHeader.reset();
  754. break;
  755. case ELoadMode::TUTORIAL:
  756. if(!isTutorial)
  757. mapInfo->mapHeader.reset();
  758. break;
  759. case ELoadMode::MULTI:
  760. if(!isMultiplayer)
  761. mapInfo->mapHeader.reset();
  762. break;
  763. default:
  764. assert(0);
  765. mapInfo->mapHeader.reset();
  766. break;
  767. }
  768. allItems.push_back(mapInfo);
  769. }
  770. catch(const std::exception & e)
  771. {
  772. logGlobal->error("Error: Failed to process %s: %s", file.getName(), e.what());
  773. }
  774. }
  775. }
  776. void SelectionTab::parseCampaigns(const std::unordered_set<ResourcePath> & files)
  777. {
  778. auto campaignSets = JsonNode(JsonPath::builtin("config/campaignSets.json"));
  779. allItems.reserve(files.size());
  780. for(auto & file : files)
  781. {
  782. auto info = std::make_shared<ElementInfo>();
  783. info->fileURI = file.getOriginalName();
  784. info->campaignInit();
  785. info->name = info->getNameForList();
  786. // skip campaigns organized in sets
  787. bool foundInSet = false;
  788. for (auto const & set : campaignSets.Struct())
  789. for (auto const & item : set.second["items"].Vector())
  790. if(file.getName() == ResourcePath(item["file"].String()).getName())
  791. foundInSet = true;
  792. if(info->campaign && !foundInSet)
  793. allItems.push_back(info);
  794. }
  795. }
  796. std::unordered_set<ResourcePath> SelectionTab::getFiles(std::string dirURI, EResType resType)
  797. {
  798. boost::to_upper(dirURI);
  799. CResourceHandler::get()->updateFilteredFiles([&](const std::string & mount)
  800. {
  801. return boost::algorithm::starts_with(mount, dirURI);
  802. });
  803. std::unordered_set<ResourcePath> ret = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  804. {
  805. return ident.getType() == resType && boost::algorithm::starts_with(ident.getName(), dirURI);
  806. });
  807. return ret;
  808. }
  809. SelectionTab::ListItem::ListItem(Point position)
  810. : CIntObject(LCLICK, position)
  811. {
  812. OBJECT_CONSTRUCTION;
  813. pictureEmptyLine = std::make_shared<CPicture>(ImagePath::builtin("camcust"), Rect(25, 121, 349, 26), -8, -14);
  814. labelName = std::make_shared<CLabel>(LABEL_POS_X, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "", 185);
  815. labelName->setAutoRedraw(false);
  816. labelAmountOfPlayers = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  817. labelAmountOfPlayers->setAutoRedraw(false);
  818. labelNumberOfCampaignMaps = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  819. labelNumberOfCampaignMaps->setAutoRedraw(false);
  820. labelMapSizeLetter = std::make_shared<CLabel>(41, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  821. labelMapSizeLetter->setAutoRedraw(false);
  822. // FIXME: This -12 should not be needed, but for some reason CAnimImage displaced otherwise
  823. iconFolder = std::make_shared<CPicture>(ImagePath::builtin("lobby/iconFolder.png"), -8, -12);
  824. iconFormat = std::make_shared<CAnimImage>(AnimationPath::builtin("SCSELC.DEF"), 0, 0, 59, -12);
  825. iconVictoryCondition = std::make_shared<CAnimImage>(AnimationPath::builtin("SCNRVICT.DEF"), 0, 0, 277, -12);
  826. iconLossCondition = std::make_shared<CAnimImage>(AnimationPath::builtin("SCNRLOSS.DEF"), 0, 0, 310, -12);
  827. }
  828. void SelectionTab::ListItem::updateItem(std::shared_ptr<ElementInfo> info, bool selected)
  829. {
  830. if(!info)
  831. {
  832. labelAmountOfPlayers->disable();
  833. labelMapSizeLetter->disable();
  834. iconFolder->disable();
  835. pictureEmptyLine->disable();
  836. iconFormat->disable();
  837. iconVictoryCondition->disable();
  838. iconLossCondition->disable();
  839. labelNumberOfCampaignMaps->disable();
  840. labelName->disable();
  841. return;
  842. }
  843. auto color = selected ? Colors::YELLOW : Colors::WHITE;
  844. if(info->isFolder)
  845. {
  846. labelAmountOfPlayers->disable();
  847. labelMapSizeLetter->disable();
  848. iconFolder->enable();
  849. pictureEmptyLine->enable();
  850. iconFormat->disable();
  851. iconVictoryCondition->disable();
  852. iconLossCondition->disable();
  853. labelNumberOfCampaignMaps->disable();
  854. labelName->enable();
  855. labelName->setMaxWidth(316);
  856. if(info->isAutoSaveFolder) // align autosave folder left (starting timestamps in list should be in one line)
  857. {
  858. labelName->alignment = ETextAlignment::CENTERLEFT;
  859. labelName->moveTo(Point(pos.x + 80, labelName->pos.y));
  860. }
  861. else
  862. {
  863. labelName->alignment = ETextAlignment::CENTER;
  864. labelName->moveTo(Point(pos.x + LABEL_POS_X, labelName->pos.y));
  865. }
  866. labelName->setText(info->folderName);
  867. labelName->setColor(color);
  868. return;
  869. }
  870. labelName->enable();
  871. if(info->campaign)
  872. {
  873. labelAmountOfPlayers->disable();
  874. labelMapSizeLetter->disable();
  875. iconFolder->disable();
  876. pictureEmptyLine->disable();
  877. iconFormat->disable();
  878. iconVictoryCondition->disable();
  879. iconLossCondition->disable();
  880. labelNumberOfCampaignMaps->enable();
  881. std::ostringstream ostr(std::ostringstream::out);
  882. ostr << info->campaign->scenariosCount();
  883. labelNumberOfCampaignMaps->setText(ostr.str());
  884. labelNumberOfCampaignMaps->setColor(color);
  885. labelName->setMaxWidth(316);
  886. labelName->alignment = ETextAlignment::CENTER;
  887. labelName->moveTo(Point(pos.x + LABEL_POS_X, labelName->pos.y));
  888. }
  889. else
  890. {
  891. labelNumberOfCampaignMaps->disable();
  892. std::ostringstream ostr(std::ostringstream::out);
  893. ostr << info->amountOfPlayersOnMap << "/" << info->amountOfHumanControllablePlayers;
  894. labelAmountOfPlayers->enable();
  895. labelAmountOfPlayers->setText(ostr.str());
  896. labelAmountOfPlayers->setColor(color);
  897. labelMapSizeLetter->enable();
  898. labelMapSizeLetter->setText(info->getMapSizeName());
  899. labelMapSizeLetter->setColor(color);
  900. iconFolder->disable();
  901. pictureEmptyLine->disable();
  902. iconFormat->enable();
  903. iconFormat->setFrame(info->getMapSizeFormatIconId());
  904. iconVictoryCondition->enable();
  905. iconVictoryCondition->setFrame(info->mapHeader->victoryIconIndex, 0);
  906. iconLossCondition->enable();
  907. iconLossCondition->setFrame(info->mapHeader->defeatIconIndex, 0);
  908. labelName->setMaxWidth(185);
  909. labelName->alignment = ETextAlignment::CENTER;
  910. labelName->moveTo(Point(pos.x + LABEL_POS_X, labelName->pos.y));
  911. }
  912. labelName->setText(info->name);
  913. labelName->setColor(color);
  914. }