SelectionTab.cpp 38 KB

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