SelectionTab.cpp 34 KB

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