ConstructionMenuPresenter.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. using System.Linq;
  2. using System.Numerics;
  3. using Content.Client.Stylesheets;
  4. using Content.Client.UserInterface.Systems.MenuBar.Widgets;
  5. using Content.Shared.Construction.Prototypes;
  6. using Content.Shared.Whitelist;
  7. using Robust.Client.GameObjects;
  8. using Robust.Client.Graphics;
  9. using Robust.Client.Placement;
  10. using Robust.Client.Player;
  11. using Robust.Client.UserInterface;
  12. using Robust.Client.UserInterface.Controls;
  13. using Robust.Client.Utility;
  14. using Robust.Shared.Enums;
  15. using Robust.Shared.Prototypes;
  16. using static Robust.Client.UserInterface.Controls.BaseButton;
  17. namespace Content.Client.Construction.UI
  18. {
  19. /// <summary>
  20. /// This class presents the Construction/Crafting UI to the client, linking the <see cref="ConstructionSystem" /> with the
  21. /// model. This is where the bulk of UI work is done, either calling functions in the model to change state, or collecting
  22. /// data out of the model to *present* to the screen though the UI framework.
  23. /// </summary>
  24. internal sealed class ConstructionMenuPresenter : IDisposable
  25. {
  26. [Dependency] private readonly EntityManager _entManager = default!;
  27. [Dependency] private readonly IEntitySystemManager _systemManager = default!;
  28. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  29. [Dependency] private readonly IPlacementManager _placementManager = default!;
  30. [Dependency] private readonly IUserInterfaceManager _uiManager = default!;
  31. [Dependency] private readonly IPlayerManager _playerManager = default!;
  32. private readonly IConstructionMenuView _constructionView;
  33. private readonly EntityWhitelistSystem _whitelistSystem;
  34. private readonly SpriteSystem _spriteSystem;
  35. private ConstructionSystem? _constructionSystem;
  36. private ConstructionPrototype? _selected;
  37. private List<ConstructionPrototype> _favoritedRecipes = [];
  38. private Dictionary<string, TextureButton> _recipeButtons = new();
  39. private string _selectedCategory = string.Empty;
  40. private string _favoriteCatName = "construction-category-favorites";
  41. private string _forAllCategoryName = "construction-category-all";
  42. private bool CraftingAvailable
  43. {
  44. get => _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.Visible;
  45. set
  46. {
  47. _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.Visible = value;
  48. if (!value)
  49. _constructionView.Close();
  50. }
  51. }
  52. /// <summary>
  53. /// Does the window have focus? If the window is closed, this will always return false.
  54. /// </summary>
  55. private bool IsAtFront => _constructionView.IsOpen && _constructionView.IsAtFront();
  56. private bool WindowOpen
  57. {
  58. get => _constructionView.IsOpen;
  59. set
  60. {
  61. if (value && CraftingAvailable)
  62. {
  63. if (_constructionView.IsOpen)
  64. _constructionView.MoveToFront();
  65. else
  66. _constructionView.OpenCentered();
  67. if (_selected != null)
  68. PopulateInfo(_selected);
  69. }
  70. else
  71. _constructionView.Close();
  72. }
  73. }
  74. /// <summary>
  75. /// Constructs a new instance of <see cref="ConstructionMenuPresenter" />.
  76. /// </summary>
  77. public ConstructionMenuPresenter()
  78. {
  79. // This is a lot easier than a factory
  80. IoCManager.InjectDependencies(this);
  81. _constructionView = new ConstructionMenu();
  82. _whitelistSystem = _entManager.System<EntityWhitelistSystem>();
  83. _spriteSystem = _entManager.System<SpriteSystem>();
  84. // This is required so that if we load after the system is initialized, we can bind to it immediately
  85. if (_systemManager.TryGetEntitySystem<ConstructionSystem>(out var constructionSystem))
  86. SystemBindingChanged(constructionSystem);
  87. _systemManager.SystemLoaded += OnSystemLoaded;
  88. _systemManager.SystemUnloaded += OnSystemUnloaded;
  89. _placementManager.PlacementChanged += OnPlacementChanged;
  90. _constructionView.OnClose += () => _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.Pressed = false;
  91. _constructionView.ClearAllGhosts += (_, _) => _constructionSystem?.ClearAllGhosts();
  92. _constructionView.PopulateRecipes += OnViewPopulateRecipes;
  93. _constructionView.RecipeSelected += OnViewRecipeSelected;
  94. _constructionView.BuildButtonToggled += (_, b) => BuildButtonToggled(b);
  95. _constructionView.EraseButtonToggled += (_, b) =>
  96. {
  97. if (_constructionSystem is null) return;
  98. if (b) _placementManager.Clear();
  99. _placementManager.ToggleEraserHijacked(new ConstructionPlacementHijack(_constructionSystem, null));
  100. _constructionView.EraseButtonPressed = b;
  101. };
  102. _constructionView.RecipeFavorited += (_, _) => OnViewFavoriteRecipe();
  103. PopulateCategories();
  104. OnViewPopulateRecipes(_constructionView, (string.Empty, string.Empty));
  105. }
  106. public void OnHudCraftingButtonToggled(ButtonToggledEventArgs args)
  107. {
  108. WindowOpen = args.Pressed;
  109. }
  110. /// <inheritdoc />
  111. public void Dispose()
  112. {
  113. _constructionView.Dispose();
  114. SystemBindingChanged(null);
  115. _systemManager.SystemLoaded -= OnSystemLoaded;
  116. _systemManager.SystemUnloaded -= OnSystemUnloaded;
  117. _placementManager.PlacementChanged -= OnPlacementChanged;
  118. }
  119. private void OnPlacementChanged(object? sender, EventArgs e)
  120. {
  121. _constructionView.ResetPlacement();
  122. }
  123. private void OnViewRecipeSelected(object? sender, ItemList.Item? item)
  124. {
  125. if (item is null)
  126. {
  127. _selected = null;
  128. _constructionView.ClearRecipeInfo();
  129. return;
  130. }
  131. _selected = (ConstructionPrototype) item.Metadata!;
  132. if (_placementManager.IsActive && !_placementManager.Eraser) UpdateGhostPlacement();
  133. PopulateInfo(_selected);
  134. }
  135. private void OnGridViewRecipeSelected(object? sender, ConstructionPrototype? recipe)
  136. {
  137. if (recipe is null)
  138. {
  139. _selected = null;
  140. _constructionView.ClearRecipeInfo();
  141. return;
  142. }
  143. _selected = recipe;
  144. if (_placementManager.IsActive && !_placementManager.Eraser) UpdateGhostPlacement();
  145. PopulateInfo(_selected);
  146. }
  147. private void OnViewPopulateRecipes(object? sender, (string search, string category) args)
  148. {
  149. var (search, category) = args;
  150. var recipes = new List<ConstructionPrototype>();
  151. var isEmptyCategory = string.IsNullOrEmpty(category) || category == _forAllCategoryName;
  152. if (isEmptyCategory)
  153. _selectedCategory = string.Empty;
  154. else
  155. _selectedCategory = category;
  156. foreach (var recipe in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
  157. {
  158. var CurrentAge = 0; //hardcoded for now
  159. if (recipe.Hide)
  160. continue;
  161. if (CurrentAge < recipe.AgeMin || CurrentAge > recipe.AgeMax)
  162. continue;
  163. if (_playerManager.LocalSession == null
  164. || _playerManager.LocalEntity == null
  165. || _whitelistSystem.IsWhitelistFail(recipe.EntityWhitelist, _playerManager.LocalEntity.Value))
  166. continue;
  167. if (!string.IsNullOrEmpty(search))
  168. {
  169. if (!recipe.Name.ToLowerInvariant().Contains(search.Trim().ToLowerInvariant()))
  170. continue;
  171. }
  172. if (!isEmptyCategory)
  173. {
  174. if (category == _favoriteCatName)
  175. {
  176. if (!_favoritedRecipes.Contains(recipe))
  177. {
  178. continue;
  179. }
  180. }
  181. else if (recipe.Category != category)
  182. {
  183. continue;
  184. }
  185. }
  186. recipes.Add(recipe);
  187. }
  188. recipes.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.InvariantCulture));
  189. var recipesList = _constructionView.Recipes;
  190. recipesList.Clear();
  191. var recipesGrid = _constructionView.RecipesGrid;
  192. recipesGrid.RemoveAllChildren();
  193. _constructionView.RecipesGridScrollContainer.Visible = _constructionView.GridViewButtonPressed;
  194. _constructionView.Recipes.Visible = !_constructionView.GridViewButtonPressed;
  195. if (_constructionView.GridViewButtonPressed)
  196. {
  197. foreach (var recipe in recipes)
  198. {
  199. var itemButton = new TextureButton
  200. {
  201. TextureNormal = _spriteSystem.Frame0(recipe.Icon),
  202. VerticalAlignment = Control.VAlignment.Center,
  203. Name = recipe.Name,
  204. ToolTip = recipe.Name,
  205. Scale = new Vector2(1.35f),
  206. ToggleMode = true,
  207. };
  208. var itemButtonPanelContainer = new PanelContainer
  209. {
  210. PanelOverride = new StyleBoxFlat { BackgroundColor = StyleNano.ButtonColorDefault },
  211. Children = { itemButton },
  212. };
  213. itemButton.OnToggled += buttonToggledEventArgs =>
  214. {
  215. SelectGridButton(itemButton, buttonToggledEventArgs.Pressed);
  216. if (buttonToggledEventArgs.Pressed &&
  217. _selected != null &&
  218. _recipeButtons.TryGetValue(_selected.Name, out var oldButton))
  219. {
  220. oldButton.Pressed = false;
  221. SelectGridButton(oldButton, false);
  222. }
  223. OnGridViewRecipeSelected(this, buttonToggledEventArgs.Pressed ? recipe : null);
  224. };
  225. recipesGrid.AddChild(itemButtonPanelContainer);
  226. _recipeButtons[recipe.Name] = itemButton;
  227. var isCurrentButtonSelected = _selected == recipe;
  228. itemButton.Pressed = isCurrentButtonSelected;
  229. SelectGridButton(itemButton, isCurrentButtonSelected);
  230. }
  231. }
  232. else
  233. {
  234. foreach (var recipe in recipes)
  235. {
  236. recipesList.Add(GetItem(recipe, recipesList));
  237. }
  238. }
  239. }
  240. private void SelectGridButton(TextureButton button, bool select)
  241. {
  242. if (button.Parent is not PanelContainer buttonPanel)
  243. return;
  244. button.Modulate = select ? Color.Green : Color.White;
  245. var buttonColor = select ? StyleNano.ButtonColorDefault : Color.Transparent;
  246. buttonPanel.PanelOverride = new StyleBoxFlat { BackgroundColor = buttonColor };
  247. }
  248. private void PopulateCategories(string? selectCategory = null)
  249. {
  250. var uniqueCategories = new HashSet<string>();
  251. foreach (var prototype in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
  252. {
  253. var category = prototype.Category;
  254. if (!string.IsNullOrEmpty(category))
  255. uniqueCategories.Add(category);
  256. }
  257. var isFavorites = _favoritedRecipes.Count > 0;
  258. var categoriesArray = new string[isFavorites ? uniqueCategories.Count + 2 : uniqueCategories.Count + 1];
  259. // hard-coded to show all recipes
  260. var idx = 0;
  261. categoriesArray[idx++] = _forAllCategoryName;
  262. // hard-coded to show favorites if it need
  263. if (isFavorites)
  264. {
  265. categoriesArray[idx++] = _favoriteCatName;
  266. }
  267. var sortedProtoCategories = uniqueCategories.OrderBy(Loc.GetString);
  268. foreach (var cat in sortedProtoCategories)
  269. {
  270. categoriesArray[idx++] = cat;
  271. }
  272. _constructionView.OptionCategories.Clear();
  273. for (var i = 0; i < categoriesArray.Length; i++)
  274. {
  275. _constructionView.OptionCategories.AddItem(Loc.GetString(categoriesArray[i]), i);
  276. if (!string.IsNullOrEmpty(selectCategory) && selectCategory == categoriesArray[i])
  277. _constructionView.OptionCategories.SelectId(i);
  278. }
  279. _constructionView.Categories = categoriesArray;
  280. }
  281. private void PopulateInfo(ConstructionPrototype prototype)
  282. {
  283. _constructionView.ClearRecipeInfo();
  284. _constructionView.SetRecipeInfo(
  285. prototype.Name, prototype.Description, _spriteSystem.Frame0(prototype.Icon),
  286. prototype.Type != ConstructionType.Item,
  287. !_favoritedRecipes.Contains(prototype));
  288. var stepList = _constructionView.RecipeStepList;
  289. GenerateStepList(prototype, stepList);
  290. }
  291. private void GenerateStepList(ConstructionPrototype prototype, ItemList stepList)
  292. {
  293. if (_constructionSystem?.GetGuide(prototype) is not { } guide)
  294. return;
  295. foreach (var entry in guide.Entries)
  296. {
  297. var text = entry.Arguments != null
  298. ? Loc.GetString(entry.Localization, entry.Arguments) : Loc.GetString(entry.Localization);
  299. if (entry.EntryNumber is { } number)
  300. {
  301. text = Loc.GetString("construction-presenter-step-wrapper",
  302. ("step-number", number), ("text", text));
  303. }
  304. // The padding needs to be applied regardless of text length... (See PadLeft documentation)
  305. text = text.PadLeft(text.Length + entry.Padding);
  306. var icon = entry.Icon != null ? _spriteSystem.Frame0(entry.Icon) : Texture.Transparent;
  307. stepList.AddItem(text, icon, false);
  308. }
  309. }
  310. private ItemList.Item GetItem(ConstructionPrototype recipe, ItemList itemList)
  311. {
  312. return new(itemList)
  313. {
  314. Metadata = recipe,
  315. Text = recipe.Name,
  316. Icon = _spriteSystem.Frame0(recipe.Icon),
  317. TooltipEnabled = true,
  318. TooltipText = recipe.Description,
  319. };
  320. }
  321. private void BuildButtonToggled(bool pressed)
  322. {
  323. if (pressed)
  324. {
  325. if (_selected == null) return;
  326. // not bound to a construction system
  327. if (_constructionSystem is null)
  328. {
  329. _constructionView.BuildButtonPressed = false;
  330. return;
  331. }
  332. if (_selected.Type == ConstructionType.Item)
  333. {
  334. _constructionSystem.TryStartItemConstruction(_selected.ID);
  335. _constructionView.BuildButtonPressed = false;
  336. return;
  337. }
  338. _placementManager.BeginPlacing(new PlacementInformation
  339. {
  340. IsTile = false,
  341. PlacementOption = _selected.PlacementMode
  342. }, new ConstructionPlacementHijack(_constructionSystem, _selected));
  343. UpdateGhostPlacement();
  344. }
  345. else
  346. _placementManager.Clear();
  347. _constructionView.BuildButtonPressed = pressed;
  348. }
  349. private void UpdateGhostPlacement()
  350. {
  351. if (_selected == null)
  352. return;
  353. if (_selected.Type != ConstructionType.Structure)
  354. {
  355. _placementManager.Clear();
  356. return;
  357. }
  358. var constructSystem = _systemManager.GetEntitySystem<ConstructionSystem>();
  359. _placementManager.BeginPlacing(new PlacementInformation()
  360. {
  361. IsTile = false,
  362. PlacementOption = _selected.PlacementMode,
  363. }, new ConstructionPlacementHijack(constructSystem, _selected));
  364. _constructionView.BuildButtonPressed = true;
  365. }
  366. private void OnSystemLoaded(object? sender, SystemChangedArgs args)
  367. {
  368. if (args.System is ConstructionSystem system) SystemBindingChanged(system);
  369. }
  370. private void OnSystemUnloaded(object? sender, SystemChangedArgs args)
  371. {
  372. if (args.System is ConstructionSystem) SystemBindingChanged(null);
  373. }
  374. private void OnViewFavoriteRecipe()
  375. {
  376. if (_selected is not ConstructionPrototype recipe)
  377. return;
  378. if (!_favoritedRecipes.Remove(_selected))
  379. _favoritedRecipes.Add(_selected);
  380. if (_selectedCategory == _favoriteCatName)
  381. {
  382. if (_favoritedRecipes.Count > 0)
  383. OnViewPopulateRecipes(_constructionView, (string.Empty, _favoriteCatName));
  384. else
  385. OnViewPopulateRecipes(_constructionView, (string.Empty, string.Empty));
  386. }
  387. PopulateInfo(_selected);
  388. PopulateCategories(_selectedCategory);
  389. }
  390. private void SystemBindingChanged(ConstructionSystem? newSystem)
  391. {
  392. if (newSystem is null)
  393. {
  394. if (_constructionSystem is null)
  395. return;
  396. UnbindFromSystem();
  397. }
  398. else
  399. {
  400. if (_constructionSystem is null)
  401. {
  402. BindToSystem(newSystem);
  403. return;
  404. }
  405. UnbindFromSystem();
  406. BindToSystem(newSystem);
  407. }
  408. }
  409. private void BindToSystem(ConstructionSystem system)
  410. {
  411. _constructionSystem = system;
  412. system.ToggleCraftingWindow += SystemOnToggleMenu;
  413. system.FlipConstructionPrototype += SystemFlipConstructionPrototype;
  414. system.CraftingAvailabilityChanged += SystemCraftingAvailabilityChanged;
  415. system.ConstructionGuideAvailable += SystemGuideAvailable;
  416. if (_uiManager.GetActiveUIWidgetOrNull<GameTopMenuBar>() != null)
  417. {
  418. CraftingAvailable = system.CraftingEnabled;
  419. }
  420. }
  421. private void UnbindFromSystem()
  422. {
  423. var system = _constructionSystem;
  424. if (system is null)
  425. throw new InvalidOperationException();
  426. system.ToggleCraftingWindow -= SystemOnToggleMenu;
  427. system.FlipConstructionPrototype -= SystemFlipConstructionPrototype;
  428. system.CraftingAvailabilityChanged -= SystemCraftingAvailabilityChanged;
  429. system.ConstructionGuideAvailable -= SystemGuideAvailable;
  430. _constructionSystem = null;
  431. }
  432. private void SystemCraftingAvailabilityChanged(object? sender, CraftingAvailabilityChangedArgs e)
  433. {
  434. if (_uiManager.ActiveScreen == null)
  435. return;
  436. CraftingAvailable = e.Available;
  437. }
  438. private void SystemOnToggleMenu(object? sender, EventArgs eventArgs)
  439. {
  440. if (!CraftingAvailable)
  441. return;
  442. if (WindowOpen)
  443. {
  444. if (IsAtFront)
  445. {
  446. WindowOpen = false;
  447. _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.SetClickPressed(false); // This does not call CraftingButtonToggled
  448. }
  449. else
  450. _constructionView.MoveToFront();
  451. }
  452. else
  453. {
  454. WindowOpen = true;
  455. _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.SetClickPressed(true); // This does not call CraftingButtonToggled
  456. }
  457. }
  458. private void SystemFlipConstructionPrototype(object? sender, EventArgs eventArgs)
  459. {
  460. if (!_placementManager.IsActive || _placementManager.Eraser)
  461. {
  462. return;
  463. }
  464. if (_selected == null || _selected.Mirror == null)
  465. {
  466. return;
  467. }
  468. _selected = _prototypeManager.Index<ConstructionPrototype>(_selected.Mirror);
  469. UpdateGhostPlacement();
  470. }
  471. private void SystemGuideAvailable(object? sender, string e)
  472. {
  473. if (!CraftingAvailable)
  474. return;
  475. if (!WindowOpen)
  476. return;
  477. if (_selected == null)
  478. return;
  479. PopulateInfo(_selected);
  480. }
  481. }
  482. }