SelectionTab.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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::RANDOMMAP : LobbyDelete::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::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]->getNameTranslated(),
  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. std::reverse(std::next(curItems.begin(), boost::starts_with(curItems[0]->folderName, "..") ? 1 : 0), std::next(curItems.begin(), firstMapIndex - 1));
  554. std::reverse(std::next(curItems.begin(), firstMapIndex), curItems.end());
  555. }
  556. updateListItems();
  557. redraw();
  558. }
  559. void SelectionTab::select(int position)
  560. {
  561. if(!curItems.size())
  562. return;
  563. // New selection. py is the index in curItems.
  564. int py = position + slider->getValue();
  565. vstd::amax(py, 0);
  566. vstd::amin(py, curItems.size() - 1);
  567. selectionPos = py;
  568. if(position < 0)
  569. slider->scrollBy(position);
  570. else if(position >= listItems.size())
  571. slider->scrollBy(position - (int)listItems.size() + 1);
  572. if(curItems[py]->isFolder) {
  573. if(boost::starts_with(curItems[py]->folderName, ".."))
  574. {
  575. std::vector<std::string> filetree;
  576. boost::split(filetree, curFolder, boost::is_any_of("/"));
  577. filetree.pop_back();
  578. filetree.pop_back();
  579. curFolder = filetree.size() > 0 ? boost::algorithm::join(filetree, "/") + "/" : "";
  580. }
  581. else
  582. curFolder += curItems[py]->folderName + "/";
  583. filter(-1);
  584. slider->scrollTo(0);
  585. int firstPos = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  586. if(firstPos < curItems.size())
  587. {
  588. selectAbs(firstPos);
  589. }
  590. return;
  591. }
  592. rememberCurrentSelection();
  593. if(inputName && inputName->isActive())
  594. {
  595. auto filename = *CResourceHandler::get()->getResourceName(ResourcePath(curItems[py]->fileURI, EResType::SAVEGAME));
  596. inputName->setText(filename.stem().string());
  597. }
  598. updateListItems();
  599. redraw();
  600. if(callOnSelect)
  601. callOnSelect(curItems[py]);
  602. }
  603. void SelectionTab::selectAbs(int position)
  604. {
  605. if(position == -1)
  606. position = boost::range::find_if(curItems, [](std::shared_ptr<ElementInfo> e) { return !e->isFolder; }) - curItems.begin();
  607. select(position - slider->getValue());
  608. }
  609. void SelectionTab::sliderMove(int slidPos)
  610. {
  611. if(!slider)
  612. return; // ignore spurious call when slider is being created
  613. updateListItems();
  614. redraw();
  615. }
  616. void SelectionTab::updateListItems()
  617. {
  618. // elemIdx is the index of the maps or saved game to display on line 0
  619. // slider->capacity contains the number of available screen lines
  620. // slider->positionsAmnt is the number of elements after filtering
  621. int elemIdx = slider->getValue();
  622. for(auto item : listItems)
  623. {
  624. if(elemIdx < curItems.size())
  625. {
  626. item->updateItem(curItems[elemIdx], elemIdx == selectionPos);
  627. elemIdx++;
  628. }
  629. else
  630. {
  631. item->updateItem();
  632. }
  633. }
  634. }
  635. bool SelectionTab::receiveEvent(const Point & position, int eventType) const
  636. {
  637. // FIXME: widget should instead have well-defined pos so events will be filtered using standard routine
  638. return getLine(position - pos.topLeft()) != -1;
  639. }
  640. int SelectionTab::getLine() const
  641. {
  642. Point clickPos = GH.getCursorPosition() - pos.topLeft();
  643. return getLine(clickPos);
  644. }
  645. int SelectionTab::getLine(const Point & clickPos) const
  646. {
  647. int line = -1;
  648. // Ignore clicks on save name area
  649. int maxPosY;
  650. if(tabType == ESelectionScreen::saveGame)
  651. maxPosY = 516;
  652. else
  653. maxPosY = 564;
  654. if(clickPos.y > 115 && clickPos.y < maxPosY && clickPos.x > 22 && clickPos.x < 371)
  655. {
  656. line = (clickPos.y - 115) / 25; //which line
  657. }
  658. return line;
  659. }
  660. void SelectionTab::selectFileName(std::string fname)
  661. {
  662. boost::to_upper(fname);
  663. for(int i = (int)allItems.size() - 1; i >= 0; i--)
  664. {
  665. if(boost::to_upper_copy(allItems[i]->fileURI) == fname)
  666. {
  667. auto [folderName, baseFolder, parentExists, fileInFolder] = checkSubfolder(allItems[i]->originalFileURI);
  668. curFolder = baseFolder != "" ? baseFolder + "/" : "";
  669. }
  670. }
  671. filter(-1);
  672. for(int i = (int)curItems.size() - 1; i >= 0; i--)
  673. {
  674. if(boost::to_upper_copy(curItems[i]->fileURI) == fname)
  675. {
  676. slider->scrollTo(i);
  677. selectAbs(i);
  678. return;
  679. }
  680. }
  681. selectAbs(-1);
  682. if(tabType == ESelectionScreen::saveGame && inputName->getText().empty())
  683. inputName->setText(CGI->generaltexth->translate("core.genrltxt.11"));
  684. }
  685. void SelectionTab::selectNewestFile()
  686. {
  687. time_t newestTime = 0;
  688. std::string newestFile = "";
  689. for(int i = static_cast<int>(allItems.size()) - 1; i >= 0; i--)
  690. if(allItems[i]->lastWrite > newestTime)
  691. {
  692. newestTime = allItems[i]->lastWrite;
  693. newestFile = allItems[i]->fileURI;
  694. }
  695. selectFileName(newestFile);
  696. }
  697. std::shared_ptr<ElementInfo> SelectionTab::getSelectedMapInfo() const
  698. {
  699. return curItems.empty() || curItems[selectionPos]->isFolder ? nullptr : curItems[selectionPos];
  700. }
  701. void SelectionTab::rememberCurrentSelection()
  702. {
  703. if(getSelectedMapInfo()->isFolder)
  704. return;
  705. // TODO: this can be more elegant
  706. if(tabType == ESelectionScreen::newGame)
  707. {
  708. Settings lastMap = settings.write["general"]["lastMap"];
  709. lastMap->String() = getSelectedMapInfo()->fileURI;
  710. }
  711. else if(tabType == ESelectionScreen::loadGame)
  712. {
  713. Settings lastSave = settings.write["general"]["lastSave"];
  714. lastSave->String() = getSelectedMapInfo()->fileURI;
  715. }
  716. else if(tabType == ESelectionScreen::campaignList)
  717. {
  718. Settings lastCampaign = settings.write["general"]["lastCampaign"];
  719. lastCampaign->String() = getSelectedMapInfo()->fileURI;
  720. }
  721. }
  722. void SelectionTab::restoreLastSelection()
  723. {
  724. switch(tabType)
  725. {
  726. case ESelectionScreen::newGame:
  727. selectFileName(settings["general"]["lastMap"].String());
  728. break;
  729. case ESelectionScreen::campaignList:
  730. selectFileName(settings["general"]["lastCampaign"].String());
  731. break;
  732. case ESelectionScreen::loadGame:
  733. selectNewestFile();
  734. break;
  735. case ESelectionScreen::saveGame:
  736. selectFileName(settings["general"]["lastSave"].String());
  737. }
  738. }
  739. bool SelectionTab::isMapSupported(const CMapInfo & info)
  740. {
  741. switch (info.mapHeader->version)
  742. {
  743. case EMapFormat::ROE:
  744. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_RESTORATION_OF_ERATHIA)["supported"].Bool();
  745. case EMapFormat::AB:
  746. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_ARMAGEDDONS_BLADE)["supported"].Bool();
  747. case EMapFormat::SOD:
  748. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_SHADOW_OF_DEATH)["supported"].Bool();
  749. case EMapFormat::CHR:
  750. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_CHRONICLES)["supported"].Bool();
  751. case EMapFormat::WOG:
  752. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_IN_THE_WAKE_OF_GODS)["supported"].Bool();
  753. case EMapFormat::HOTA:
  754. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_HORN_OF_THE_ABYSS)["supported"].Bool();
  755. case EMapFormat::VCMI:
  756. return CGI->engineSettings()->getValue(EGameSettings::MAP_FORMAT_JSON_VCMI)["supported"].Bool();
  757. }
  758. return false;
  759. }
  760. void SelectionTab::parseMaps(const std::unordered_set<ResourcePath> & files)
  761. {
  762. logGlobal->debug("Parsing %d maps", files.size());
  763. allItems.clear();
  764. for(auto & file : files)
  765. {
  766. try
  767. {
  768. auto mapInfo = std::make_shared<ElementInfo>();
  769. mapInfo->mapInit(file.getOriginalName());
  770. mapInfo->name = mapInfo->getNameForList();
  771. if (isMapSupported(*mapInfo))
  772. allItems.push_back(mapInfo);
  773. }
  774. catch(std::exception & e)
  775. {
  776. logGlobal->error("Map %s is invalid. Message: %s", file.getName(), e.what());
  777. }
  778. }
  779. }
  780. std::vector<ResourcePath> SelectionTab::parseSaves(const std::unordered_set<ResourcePath> & files)
  781. {
  782. std::vector<ResourcePath> unsupported;
  783. for(auto & file : files)
  784. {
  785. try
  786. {
  787. auto mapInfo = std::make_shared<ElementInfo>();
  788. mapInfo->saveInit(file);
  789. mapInfo->name = mapInfo->getNameForList();
  790. // Filter out other game modes
  791. bool isCampaign = mapInfo->scenarioOptionsOfSave->mode == EStartMode::CAMPAIGN;
  792. bool isMultiplayer = mapInfo->amountOfHumanPlayersInSave > 1;
  793. bool isTutorial = boost::to_upper_copy(mapInfo->scenarioOptionsOfSave->mapname) == "MAPS/TUTORIAL";
  794. switch(CSH->getLoadMode())
  795. {
  796. case ELoadMode::SINGLE:
  797. if(isCampaign || isTutorial)
  798. mapInfo->mapHeader.reset();
  799. break;
  800. case ELoadMode::CAMPAIGN:
  801. if(!isCampaign)
  802. mapInfo->mapHeader.reset();
  803. break;
  804. case ELoadMode::TUTORIAL:
  805. if(!isTutorial)
  806. mapInfo->mapHeader.reset();
  807. break;
  808. case ELoadMode::MULTI:
  809. if(!isMultiplayer)
  810. mapInfo->mapHeader.reset();
  811. break;
  812. default:
  813. assert(0);
  814. mapInfo->mapHeader.reset();
  815. break;
  816. }
  817. allItems.push_back(mapInfo);
  818. }
  819. catch(const IdentifierResolutionException & e)
  820. {
  821. logGlobal->error("Error: Failed to process %s: %s", file.getName(), e.what());
  822. }
  823. catch(const std::exception & e)
  824. {
  825. unsupported.push_back(file); // IdentifierResolutionException is not relevant -> not ask to delete, when mods are disabled
  826. logGlobal->error("Error: Failed to process %s: %s", file.getName(), e.what());
  827. }
  828. }
  829. return unsupported;
  830. }
  831. void SelectionTab::handleUnsupportedSavegames(const std::vector<ResourcePath> files)
  832. {
  833. if(CSH->isHost() && files.size())
  834. {
  835. MetaString text = MetaString::createFromTextID("vcmi.lobby.deleteUnsupportedSave");
  836. text.replaceNumber(files.size());
  837. CInfoWindow::showYesNoDialog(text.toString(), std::vector<std::shared_ptr<CComponent>>(), [files](){
  838. for(auto & file : files)
  839. {
  840. LobbyDelete ld;
  841. ld.type = LobbyDelete::SAVEGAME;
  842. ld.name = file.getName();
  843. CSH->sendLobbyPack(ld);
  844. }
  845. }, nullptr);
  846. }
  847. }
  848. void SelectionTab::parseCampaigns(const std::unordered_set<ResourcePath> & files)
  849. {
  850. allItems.reserve(files.size());
  851. for(auto & file : files)
  852. {
  853. auto info = std::make_shared<ElementInfo>();
  854. info->fileURI = file.getOriginalName();
  855. info->campaignInit();
  856. info->name = info->getNameForList();
  857. if(info->campaign)
  858. allItems.push_back(info);
  859. }
  860. }
  861. std::unordered_set<ResourcePath> SelectionTab::getFiles(std::string dirURI, EResType resType)
  862. {
  863. boost::to_upper(dirURI);
  864. CResourceHandler::get()->updateFilteredFiles([&](const std::string & mount)
  865. {
  866. return boost::algorithm::starts_with(mount, dirURI);
  867. });
  868. std::unordered_set<ResourcePath> ret = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  869. {
  870. return ident.getType() == resType && boost::algorithm::starts_with(ident.getName(), dirURI);
  871. });
  872. return ret;
  873. }
  874. SelectionTab::ListItem::ListItem(Point position)
  875. : CIntObject(LCLICK, position)
  876. {
  877. OBJECT_CONSTRUCTION;
  878. pictureEmptyLine = std::make_shared<CPicture>(ImagePath::builtin("camcust"), Rect(25, 121, 349, 26), -8, -14);
  879. labelName = std::make_shared<CLabel>(LABEL_POS_X, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "", 185);
  880. labelName->setAutoRedraw(false);
  881. labelAmountOfPlayers = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  882. labelAmountOfPlayers->setAutoRedraw(false);
  883. labelNumberOfCampaignMaps = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  884. labelNumberOfCampaignMaps->setAutoRedraw(false);
  885. labelMapSizeLetter = std::make_shared<CLabel>(41, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  886. labelMapSizeLetter->setAutoRedraw(false);
  887. // FIXME: This -12 should not be needed, but for some reason CAnimImage displaced otherwise
  888. iconFolder = std::make_shared<CPicture>(ImagePath::builtin("lobby/iconFolder.png"), -8, -12);
  889. iconFormat = std::make_shared<CAnimImage>(AnimationPath::builtin("SCSELC.DEF"), 0, 0, 59, -12);
  890. iconVictoryCondition = std::make_shared<CAnimImage>(AnimationPath::builtin("SCNRVICT.DEF"), 0, 0, 277, -12);
  891. iconLossCondition = std::make_shared<CAnimImage>(AnimationPath::builtin("SCNRLOSS.DEF"), 0, 0, 310, -12);
  892. }
  893. void SelectionTab::ListItem::updateItem(std::shared_ptr<ElementInfo> info, bool selected)
  894. {
  895. if(!info)
  896. {
  897. labelAmountOfPlayers->disable();
  898. labelMapSizeLetter->disable();
  899. iconFolder->disable();
  900. pictureEmptyLine->disable();
  901. iconFormat->disable();
  902. iconVictoryCondition->disable();
  903. iconLossCondition->disable();
  904. labelNumberOfCampaignMaps->disable();
  905. labelName->disable();
  906. return;
  907. }
  908. auto color = selected ? Colors::YELLOW : Colors::WHITE;
  909. if(info->isFolder)
  910. {
  911. labelAmountOfPlayers->disable();
  912. labelMapSizeLetter->disable();
  913. iconFolder->enable();
  914. pictureEmptyLine->enable();
  915. iconFormat->disable();
  916. iconVictoryCondition->disable();
  917. iconLossCondition->disable();
  918. labelNumberOfCampaignMaps->disable();
  919. labelName->enable();
  920. labelName->setMaxWidth(316);
  921. if(info->isAutoSaveFolder) // align autosave folder left (starting timestamps in list should be in one line)
  922. {
  923. labelName->alignment = ETextAlignment::CENTERLEFT;
  924. labelName->moveTo(Point(pos.x + 80, labelName->pos.y));
  925. }
  926. else
  927. {
  928. labelName->alignment = ETextAlignment::CENTER;
  929. labelName->moveTo(Point(pos.x + LABEL_POS_X, labelName->pos.y));
  930. }
  931. labelName->setText(info->folderName);
  932. labelName->setColor(color);
  933. return;
  934. }
  935. labelName->enable();
  936. if(info->campaign)
  937. {
  938. labelAmountOfPlayers->disable();
  939. labelMapSizeLetter->disable();
  940. iconFolder->disable();
  941. pictureEmptyLine->disable();
  942. iconFormat->disable();
  943. iconVictoryCondition->disable();
  944. iconLossCondition->disable();
  945. labelNumberOfCampaignMaps->enable();
  946. std::ostringstream ostr(std::ostringstream::out);
  947. ostr << info->campaign->scenariosCount();
  948. labelNumberOfCampaignMaps->setText(ostr.str());
  949. labelNumberOfCampaignMaps->setColor(color);
  950. labelName->setMaxWidth(316);
  951. labelName->alignment = ETextAlignment::CENTER;
  952. labelName->moveTo(Point(pos.x + LABEL_POS_X, labelName->pos.y));
  953. }
  954. else
  955. {
  956. labelNumberOfCampaignMaps->disable();
  957. std::ostringstream ostr(std::ostringstream::out);
  958. ostr << info->amountOfPlayersOnMap << "/" << info->amountOfHumanControllablePlayers;
  959. labelAmountOfPlayers->enable();
  960. labelAmountOfPlayers->setText(ostr.str());
  961. labelAmountOfPlayers->setColor(color);
  962. labelMapSizeLetter->enable();
  963. labelMapSizeLetter->setText(info->getMapSizeName());
  964. labelMapSizeLetter->setColor(color);
  965. iconFolder->disable();
  966. pictureEmptyLine->disable();
  967. iconFormat->enable();
  968. iconFormat->setFrame(info->getMapSizeFormatIconId());
  969. iconVictoryCondition->enable();
  970. iconVictoryCondition->setFrame(info->mapHeader->victoryIconIndex, 0);
  971. iconLossCondition->enable();
  972. iconLossCondition->setFrame(info->mapHeader->defeatIconIndex, 0);
  973. labelName->setMaxWidth(185);
  974. labelName->alignment = ETextAlignment::CENTER;
  975. labelName->moveTo(Point(pos.x + LABEL_POS_X, labelName->pos.y));
  976. }
  977. labelName->setText(info->name);
  978. labelName->setColor(color);
  979. }