ReplayMainMenu.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. using System.IO.Compression;
  2. using System.Linq;
  3. using Content.Client.Message;
  4. using Content.Client.Replay;
  5. using Content.Client.UserInterface.Systems.EscapeMenu;
  6. using Robust.Client;
  7. using Robust.Client.Replays.Loading;
  8. using Robust.Client.ResourceManagement;
  9. using Robust.Client.Serialization;
  10. using Robust.Client.State;
  11. using Robust.Client.UserInterface;
  12. using Robust.Client.UserInterface.Controls;
  13. using Robust.Shared;
  14. using Robust.Shared.Configuration;
  15. using Robust.Shared.ContentPack;
  16. using Robust.Shared.Serialization.Markdown.Value;
  17. using Robust.Shared.Utility;
  18. using static Robust.Shared.Replays.ReplayConstants;
  19. namespace Content.Replay.Menu;
  20. /// <summary>
  21. /// Main menu screen for selecting and loading replays.
  22. /// </summary>
  23. public sealed class ReplayMainScreen : State
  24. {
  25. [Dependency] private readonly IResourceManager _resMan = default!;
  26. [Dependency] private readonly IComponentFactory _factory = default!;
  27. [Dependency] private readonly IConfigurationManager _cfg = default!;
  28. [Dependency] private readonly IReplayLoadManager _loadMan = default!;
  29. [Dependency] private readonly IResourceCache _resourceCache = default!;
  30. [Dependency] private readonly IGameController _controllerProxy = default!;
  31. [Dependency] private readonly IClientRobustSerializer _serializer = default!;
  32. [Dependency] private readonly IUserInterfaceManager _userInterfaceManager = default!;
  33. [Dependency] private readonly ContentReplayPlaybackManager _replayMan = default!;
  34. private ReplayMainMenuControl _mainMenuControl = default!;
  35. private SelectReplayWindow? _selectWindow;
  36. private ResPath _directory;
  37. private List<(string Name, ResPath Path)> _replays = new();
  38. private ResPath? _selected;
  39. protected override void Startup()
  40. {
  41. _mainMenuControl = new(_resourceCache);
  42. _userInterfaceManager.StateRoot.AddChild(_mainMenuControl);
  43. _mainMenuControl.SelectButton.OnPressed += OnSelectPressed;
  44. _mainMenuControl.QuitButton.OnPressed += QuitButtonPressed;
  45. _mainMenuControl.OptionsButton.OnPressed += OptionsButtonPressed;
  46. _mainMenuControl.FolderButton.OnPressed += OnFolderPressed;
  47. _mainMenuControl.LoadButton.OnPressed += OnLoadPressed;
  48. _directory = new ResPath(_cfg.GetCVar(CVars.ReplayDirectory)).ToRootedPath();
  49. RefreshReplays();
  50. SelectReplay(_replays.FirstOrNull()?.Path);
  51. if (_selected == null) // force initial update
  52. UpdateSelectedInfo();
  53. }
  54. /// <summary>
  55. /// Read replay meta-data and update the replay info box.
  56. /// </summary>
  57. private void UpdateSelectedInfo()
  58. {
  59. var info = _mainMenuControl.Info;
  60. if (_selected is not { } replay)
  61. {
  62. info.SetMarkup(Loc.GetString("replay-info-none-selected"));
  63. info.HorizontalAlignment = Control.HAlignment.Center;
  64. info.VerticalAlignment = Control.VAlignment.Center;
  65. _mainMenuControl.LoadButton.Disabled = true;
  66. return;
  67. }
  68. using var fileReader = new ReplayFileReaderZip(
  69. new ZipArchive(_resMan.UserData.OpenRead(replay)), ReplayZipFolder);
  70. if (!_resMan.UserData.Exists(replay)
  71. || _loadMan.LoadYamlMetadata(fileReader) is not { } data)
  72. {
  73. info.SetMarkup(Loc.GetString("replay-info-invalid"));
  74. info.HorizontalAlignment = Control.HAlignment.Center;
  75. info.VerticalAlignment = Control.VAlignment.Center;
  76. _mainMenuControl.LoadButton.Disabled = true;
  77. return;
  78. }
  79. var file = replay.ToRelativePath().ToString();
  80. data.TryGet<ValueDataNode>(MetaKeyTime, out var timeNode);
  81. data.TryGet<ValueDataNode>(MetaFinalKeyDuration, out var durationNode);
  82. data.TryGet<ValueDataNode>("roundId", out var roundIdNode);
  83. data.TryGet<ValueDataNode>(MetaKeyTypeHash, out var hashNode);
  84. data.TryGet<ValueDataNode>(MetaKeyComponentHash, out var compHashNode);
  85. DateTime.TryParse(timeNode?.Value, out var time);
  86. TimeSpan.TryParse(durationNode?.Value, out var duration);
  87. var forkId = string.Empty;
  88. if (data.TryGet<ValueDataNode>(MetaKeyForkId, out var forkNode))
  89. {
  90. // TODO Replay client build info.
  91. // When distributing the client we need to distribute a build.json or provide these cvars some other way?
  92. var clientFork = _cfg.GetCVar(CVars.BuildForkId);
  93. if (string.IsNullOrWhiteSpace(clientFork))
  94. forkId = forkNode.Value;
  95. else if (forkNode.Value == clientFork)
  96. forkId = $"[color=green]{forkNode.Value}[/color]";
  97. else
  98. forkId = $"[color=yellow]{forkNode.Value}[/color]";
  99. }
  100. var forkVersion = string.Empty;
  101. if (data.TryGet<ValueDataNode>(MetaKeyForkVersion, out var versionNode))
  102. {
  103. forkVersion = versionNode.Value;
  104. // Why does this not have a try-convert function? I just want to check if it looks like a hash code.
  105. try
  106. {
  107. Convert.FromHexString(forkVersion);
  108. // version is a probably some git commit. Crop it to keep the info box small.
  109. forkVersion = forkVersion[..16];
  110. }
  111. catch
  112. {
  113. // ignored
  114. }
  115. // TODO REPLAYS somehow distribute and load from build.json?
  116. var clientVer = _cfg.GetCVar(CVars.BuildVersion);
  117. if (!string.IsNullOrWhiteSpace(clientVer))
  118. {
  119. if (versionNode.Value == clientVer)
  120. forkVersion = $"[color=green]{forkVersion}[/color]";
  121. else
  122. forkVersion = $"[color=yellow]{forkVersion}[/color]";
  123. }
  124. }
  125. if (hashNode == null)
  126. throw new Exception("Invalid metadata file. Missing type hash");
  127. var typeHash = hashNode.Value;
  128. _mainMenuControl.LoadButton.Disabled = false;
  129. if (Convert.FromHexString(typeHash).SequenceEqual(_serializer.GetSerializableTypesHash()))
  130. {
  131. typeHash = $"[color=green]{typeHash[..16]}[/color]";
  132. }
  133. else
  134. {
  135. typeHash = $"[color=red]{typeHash[..16]}[/color]";
  136. _mainMenuControl.LoadButton.Disabled = true;
  137. }
  138. if (compHashNode == null)
  139. throw new Exception("Invalid metadata file. Missing component hash");
  140. var compHash = compHashNode.Value;
  141. if (Convert.FromHexString(compHash).SequenceEqual(_factory.GetHash(true)))
  142. {
  143. compHash = $"[color=green]{compHash[..16]}[/color]";
  144. _mainMenuControl.LoadButton.Disabled = false;
  145. }
  146. else
  147. {
  148. compHash = $"[color=red]{compHash[..16]}[/color]";
  149. _mainMenuControl.LoadButton.Disabled = true;
  150. }
  151. var engineVersion = string.Empty;
  152. if (data.TryGet<ValueDataNode>(MetaKeyEngineVersion, out var engineNode))
  153. {
  154. var clientVer = _cfg.GetCVar(CVars.BuildEngineVersion);
  155. if (string.IsNullOrWhiteSpace(clientVer))
  156. engineVersion = engineNode.Value;
  157. else if (engineNode.Value == clientVer)
  158. engineVersion = $"[color=green]{engineNode.Value}[/color]";
  159. else
  160. engineVersion = $"[color=yellow]{engineNode.Value}[/color]";
  161. }
  162. // Strip milliseconds. Apparently there is no general format string that suppresses milliseconds.
  163. duration = new((int)Math.Floor(duration.TotalDays), duration.Hours, duration.Minutes, duration.Seconds);
  164. data.TryGet<ValueDataNode>(MetaKeyName, out var nameNode);
  165. var name = nameNode?.Value ?? string.Empty;
  166. info.HorizontalAlignment = Control.HAlignment.Left;
  167. info.VerticalAlignment = Control.VAlignment.Top;
  168. info.SetMarkup(Loc.GetString(
  169. "replay-info-info",
  170. ("file", file),
  171. ("name", name),
  172. ("time", time),
  173. ("roundId", roundIdNode?.Value ?? "???"),
  174. ("duration", duration),
  175. ("forkId", forkId),
  176. ("version", forkVersion),
  177. ("engVersion", engineVersion),
  178. ("compHash", compHash),
  179. ("hash", typeHash)));
  180. }
  181. private void OnFolderPressed(BaseButton.ButtonEventArgs obj)
  182. {
  183. _resMan.UserData.CreateDir(_directory);
  184. _resMan.UserData.OpenOsWindow(_directory);
  185. }
  186. private void OnLoadPressed(BaseButton.ButtonEventArgs obj)
  187. {
  188. if (!_selected.HasValue)
  189. return;
  190. _replayMan.LastLoad = (_selected.Value, ReplayZipFolder);
  191. var fileReader = new ReplayFileReaderZip(
  192. new ZipArchive(_resMan.UserData.OpenRead(_selected.Value)), ReplayZipFolder);
  193. _loadMan.LoadAndStartReplay(fileReader);
  194. }
  195. private void RefreshReplays()
  196. {
  197. _replays.Clear();
  198. foreach (var entry in _resMan.UserData.DirectoryEntries(_directory))
  199. {
  200. var file = _directory / entry;
  201. try
  202. {
  203. using var fileReader = new ReplayFileReaderZip(
  204. new ZipArchive(_resMan.UserData.OpenRead(file)), ReplayZipFolder);
  205. var data = _loadMan.LoadYamlMetadata(fileReader);
  206. if (data == null)
  207. continue;
  208. var name = data.Get<ValueDataNode>(MetaKeyName).Value;
  209. _replays.Add((name, file));
  210. }
  211. catch
  212. {
  213. // Ignore file
  214. }
  215. }
  216. _selectWindow?.Repopulate(_replays);
  217. if (_selected.HasValue && _replays.All(x => x.Path != _selected.Value))
  218. SelectReplay(null);
  219. else
  220. _selectWindow?.UpdateSelected(_selected);
  221. }
  222. public void SelectReplay(ResPath? replay)
  223. {
  224. if (_selected == replay)
  225. return;
  226. _selected = replay;
  227. try
  228. {
  229. UpdateSelectedInfo();
  230. }
  231. catch (Exception ex)
  232. {
  233. Logger.Error($"Failed to load replay info. Exception: {ex}");
  234. SelectReplay(null);
  235. return;
  236. }
  237. _selectWindow?.UpdateSelected(replay);
  238. }
  239. protected override void Shutdown()
  240. {
  241. _mainMenuControl.Dispose();
  242. _selectWindow?.Dispose();
  243. }
  244. private void OptionsButtonPressed(BaseButton.ButtonEventArgs args)
  245. {
  246. _userInterfaceManager.GetUIController<OptionsUIController>().ToggleWindow();
  247. }
  248. private void QuitButtonPressed(BaseButton.ButtonEventArgs args)
  249. {
  250. _controllerProxy.Shutdown();
  251. }
  252. private void OnSelectPressed(BaseButton.ButtonEventArgs args)
  253. {
  254. RefreshReplays();
  255. _selectWindow ??= new(this);
  256. _selectWindow.Repopulate(_replays);
  257. _selectWindow.UpdateSelected(_selected);
  258. _selectWindow.OpenCentered();
  259. }
  260. }