SelectionTab.cpp 34 KB

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