SelectionTab.cpp 34 KB

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