SelectionTab.cpp 34 KB

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