SelectionTab.cpp 34 KB

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