SelectionTab.cpp 38 KB

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