SelectionTab.cpp 38 KB

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