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