ConstructionMenuPresenter.cs 22 KB

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