SelectionTab.cpp 37 KB

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