GameTableContextMenu.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. using Gtk;
  2. using LibHac;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.Fs.Shim;
  6. using LibHac.FsSystem;
  7. using LibHac.FsSystem.NcaUtils;
  8. using LibHac.Ncm;
  9. using Ryujinx.Common.Logging;
  10. using Ryujinx.HLE.FileSystem;
  11. using System;
  12. using System.Buffers;
  13. using System.Diagnostics;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Reflection;
  17. using System.Threading;
  18. using GUI = Gtk.Builder.ObjectAttribute;
  19. namespace Ryujinx.Ui
  20. {
  21. public class GameTableContextMenu : Menu
  22. {
  23. private ListStore _gameTableStore;
  24. private TreeIter _rowIter;
  25. private VirtualFileSystem _virtualFileSystem;
  26. private MessageDialog _dialog;
  27. private bool _cancel;
  28. #pragma warning disable CS0649
  29. #pragma warning disable IDE0044
  30. [GUI] MenuItem _openSaveDir;
  31. [GUI] MenuItem _extractRomFs;
  32. [GUI] MenuItem _extractExeFs;
  33. [GUI] MenuItem _extractLogo;
  34. #pragma warning restore CS0649
  35. #pragma warning restore IDE0044
  36. public GameTableContextMenu(ListStore gameTableStore, TreeIter rowIter, VirtualFileSystem virtualFileSystem)
  37. : this(new Builder("Ryujinx.Ui.GameTableContextMenu.glade"), gameTableStore, rowIter, virtualFileSystem) { }
  38. private GameTableContextMenu(Builder builder, ListStore gameTableStore, TreeIter rowIter, VirtualFileSystem virtualFileSystem) : base(builder.GetObject("_contextMenu").Handle)
  39. {
  40. builder.Autoconnect(this);
  41. _openSaveDir.Activated += OpenSaveDir_Clicked;
  42. _extractRomFs.Activated += ExtractRomFs_Clicked;
  43. _extractExeFs.Activated += ExtractExeFs_Clicked;
  44. _extractLogo.Activated += ExtractLogo_Clicked;
  45. _gameTableStore = gameTableStore;
  46. _rowIter = rowIter;
  47. _virtualFileSystem = virtualFileSystem;
  48. string ext = System.IO.Path.GetExtension(_gameTableStore.GetValue(_rowIter, 9).ToString()).ToLower();
  49. if (ext != ".nca" && ext != ".nsp" && ext != ".pfs0" && ext != ".xci")
  50. {
  51. _extractRomFs.Sensitive = false;
  52. _extractExeFs.Sensitive = false;
  53. _extractLogo.Sensitive = false;
  54. }
  55. }
  56. private bool TryFindSaveData(string titleName, string titleIdText, out ulong saveDataId)
  57. {
  58. saveDataId = default;
  59. if (!ulong.TryParse(titleIdText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleId))
  60. {
  61. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  62. return false;
  63. }
  64. SaveDataFilter filter = new SaveDataFilter();
  65. filter.SetUserId(new UserId(1, 0));
  66. filter.SetProgramId(new TitleId(titleId));
  67. Result result = _virtualFileSystem.FsClient.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo, SaveDataSpaceId.User, ref filter);
  68. if (ResultFs.TargetNotFound.Includes(result))
  69. {
  70. // Savedata was not found. Ask the user if they want to create it
  71. using MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, null)
  72. {
  73. Title = "Ryujinx",
  74. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  75. Text = $"There is no savedata for {titleName} [{titleId:x16}]",
  76. SecondaryText = "Would you like to create savedata for this game?",
  77. WindowPosition = WindowPosition.Center
  78. };
  79. if (messageDialog.Run() != (int)ResponseType.Yes)
  80. {
  81. return false;
  82. }
  83. result = _virtualFileSystem.FsClient.CreateSaveData(new TitleId(titleId), new UserId(1, 0), new TitleId(titleId), 0, 0, 0);
  84. if (result.IsFailure())
  85. {
  86. GtkDialog.CreateErrorDialog($"There was an error creating the specified savedata: {result.ToStringWithName()}");
  87. return false;
  88. }
  89. // Try to find the savedata again after creating it
  90. result = _virtualFileSystem.FsClient.FindSaveDataWithFilter(out saveDataInfo, SaveDataSpaceId.User, ref filter);
  91. }
  92. if (result.IsSuccess())
  93. {
  94. saveDataId = saveDataInfo.SaveDataId;
  95. return true;
  96. }
  97. GtkDialog.CreateErrorDialog($"There was an error finding the specified savedata: {result.ToStringWithName()}");
  98. return false;
  99. }
  100. private string GetSaveDataDirectory(ulong saveDataId)
  101. {
  102. string saveRootPath = System.IO.Path.Combine(_virtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}");
  103. if (!Directory.Exists(saveRootPath))
  104. {
  105. // Inconsistent state. Create the directory
  106. Directory.CreateDirectory(saveRootPath);
  107. }
  108. string committedPath = System.IO.Path.Combine(saveRootPath, "0");
  109. string workingPath = System.IO.Path.Combine(saveRootPath, "1");
  110. // If the committed directory exists, that path will be loaded the next time the savedata is mounted
  111. if (Directory.Exists(committedPath))
  112. {
  113. return committedPath;
  114. }
  115. // If the working directory exists and the committed directory doesn't,
  116. // the working directory will be loaded the next time the savedata is mounted
  117. if (!Directory.Exists(workingPath))
  118. {
  119. Directory.CreateDirectory(workingPath);
  120. }
  121. return workingPath;
  122. }
  123. private void ExtractSection(NcaSectionType ncaSectionType)
  124. {
  125. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to extract into", null, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Extract", ResponseType.Accept);
  126. fileChooser.SetPosition(WindowPosition.Center);
  127. int response = fileChooser.Run();
  128. string destination = fileChooser.Filename;
  129. fileChooser.Dispose();
  130. if (response == (int)ResponseType.Accept)
  131. {
  132. Thread extractorThread = new Thread(() =>
  133. {
  134. string sourceFile = _gameTableStore.GetValue(_rowIter, 9).ToString();
  135. Gtk.Application.Invoke(delegate
  136. {
  137. _dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Cancel, null)
  138. {
  139. Title = "Ryujinx - NCA Section Extractor",
  140. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  141. SecondaryText = $"Extracting {ncaSectionType} section from {System.IO.Path.GetFileName(sourceFile)}...",
  142. WindowPosition = WindowPosition.Center
  143. };
  144. int dialogResponse = _dialog.Run();
  145. if (dialogResponse == (int)ResponseType.Cancel || dialogResponse == (int)ResponseType.DeleteEvent)
  146. {
  147. _cancel = true;
  148. _dialog.Dispose();
  149. }
  150. });
  151. using (FileStream file = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
  152. {
  153. Nca mainNca = null;
  154. Nca patchNca = null;
  155. if ((System.IO.Path.GetExtension(sourceFile).ToLower() == ".nsp") ||
  156. (System.IO.Path.GetExtension(sourceFile).ToLower() == ".pfs0") ||
  157. (System.IO.Path.GetExtension(sourceFile).ToLower() == ".xci"))
  158. {
  159. PartitionFileSystem pfs;
  160. if (System.IO.Path.GetExtension(sourceFile) == ".xci")
  161. {
  162. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  163. pfs = xci.OpenPartition(XciPartitionType.Secure);
  164. }
  165. else
  166. {
  167. pfs = new PartitionFileSystem(file.AsStorage());
  168. }
  169. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  170. {
  171. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  172. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  173. if (nca.Header.ContentType == NcaContentType.Program)
  174. {
  175. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  176. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  177. {
  178. patchNca = nca;
  179. }
  180. else
  181. {
  182. mainNca = nca;
  183. }
  184. }
  185. }
  186. }
  187. else if (System.IO.Path.GetExtension(sourceFile).ToLower() == ".nca")
  188. {
  189. mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  190. }
  191. if (mainNca == null)
  192. {
  193. Logger.PrintError(LogClass.Application, "Extraction failed. The main NCA was not present in the selected file.");
  194. Gtk.Application.Invoke(delegate
  195. {
  196. GtkDialog.CreateErrorDialog("Extraction failed. The main NCA was not present in the selected file.");
  197. });
  198. return;
  199. }
  200. int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);
  201. IFileSystem ncaFileSystem = patchNca != null ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
  202. : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  203. FileSystemClient fsClient = _virtualFileSystem.FsClient;
  204. string source = DateTime.Now.ToFileTime().ToString().Substring(10);
  205. string output = DateTime.Now.ToFileTime().ToString().Substring(10);
  206. fsClient.Register(source.ToU8Span(), ncaFileSystem);
  207. fsClient.Register(output.ToU8Span(), new LocalFileSystem(destination));
  208. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/");
  209. if (!canceled)
  210. {
  211. if (resultCode.Value.IsFailure())
  212. {
  213. Logger.PrintError(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  214. Gtk.Application.Invoke(delegate
  215. {
  216. _dialog?.Dispose();
  217. GtkDialog.CreateErrorDialog("Extraction failed. Read the log file for further information.");
  218. });
  219. }
  220. else if (resultCode.Value.IsSuccess())
  221. {
  222. Gtk.Application.Invoke(delegate
  223. {
  224. _dialog?.Dispose();
  225. MessageDialog dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null)
  226. {
  227. Title = "Ryujinx - NCA Section Extractor",
  228. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  229. SecondaryText = "Extraction has completed successfully.",
  230. WindowPosition = WindowPosition.Center
  231. };
  232. dialog.Run();
  233. dialog.Dispose();
  234. });
  235. }
  236. }
  237. fsClient.Unmount(source.ToU8Span());
  238. fsClient.Unmount(output.ToU8Span());
  239. }
  240. });
  241. extractorThread.Name = "GUI.NcaSectionExtractorThread";
  242. extractorThread.IsBackground = true;
  243. extractorThread.Start();
  244. }
  245. }
  246. private (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath)
  247. {
  248. Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All);
  249. if (rc.IsFailure()) return (rc, false);
  250. using (sourceHandle)
  251. {
  252. foreach (DirectoryEntryEx entry in fs.EnumerateEntries(sourcePath, "*", SearchOptions.Default))
  253. {
  254. if (_cancel)
  255. {
  256. return (null, true);
  257. }
  258. string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
  259. string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));
  260. if (entry.Type == DirectoryEntryType.Directory)
  261. {
  262. fs.EnsureDirectoryExists(subDstPath);
  263. (Result? result, bool canceled) = CopyDirectory(fs, subSrcPath, subDstPath);
  264. if (canceled || result.Value.IsFailure())
  265. {
  266. return (result, canceled);
  267. }
  268. }
  269. if (entry.Type == DirectoryEntryType.File)
  270. {
  271. fs.CreateOrOverwriteFile(subDstPath, entry.Size);
  272. rc = CopyFile(fs, subSrcPath, subDstPath);
  273. if (rc.IsFailure()) return (rc, false);
  274. }
  275. }
  276. }
  277. return (Result.Success, false);
  278. }
  279. public Result CopyFile(FileSystemClient fs, string sourcePath, string destPath)
  280. {
  281. Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read);
  282. if (rc.IsFailure()) return rc;
  283. using (sourceHandle)
  284. {
  285. rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend);
  286. if (rc.IsFailure()) return rc;
  287. using (destHandle)
  288. {
  289. const int maxBufferSize = 1024 * 1024;
  290. rc = fs.GetFileSize(out long fileSize, sourceHandle);
  291. if (rc.IsFailure()) return rc;
  292. int bufferSize = (int)Math.Min(maxBufferSize, fileSize);
  293. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  294. try
  295. {
  296. for (long offset = 0; offset < fileSize; offset += bufferSize)
  297. {
  298. int toRead = (int)Math.Min(fileSize - offset, bufferSize);
  299. Span<byte> buf = buffer.AsSpan(0, toRead);
  300. rc = fs.ReadFile(out long _, sourceHandle, offset, buf);
  301. if (rc.IsFailure()) return rc;
  302. rc = fs.WriteFile(destHandle, offset, buf);
  303. if (rc.IsFailure()) return rc;
  304. }
  305. }
  306. finally
  307. {
  308. ArrayPool<byte>.Shared.Return(buffer);
  309. }
  310. rc = fs.FlushFile(destHandle);
  311. if (rc.IsFailure()) return rc;
  312. }
  313. }
  314. return Result.Success;
  315. }
  316. // Events
  317. private void OpenSaveDir_Clicked(object sender, EventArgs args)
  318. {
  319. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  320. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  321. if (!TryFindSaveData(titleName, titleId, out ulong saveDataId))
  322. {
  323. return;
  324. }
  325. string saveDir = GetSaveDataDirectory(saveDataId);
  326. Process.Start(new ProcessStartInfo()
  327. {
  328. FileName = saveDir,
  329. UseShellExecute = true,
  330. Verb = "open"
  331. });
  332. }
  333. private void ExtractRomFs_Clicked(object sender, EventArgs args)
  334. {
  335. ExtractSection(NcaSectionType.Data);
  336. }
  337. private void ExtractExeFs_Clicked(object sender, EventArgs args)
  338. {
  339. ExtractSection(NcaSectionType.Code);
  340. }
  341. private void ExtractLogo_Clicked(object sender, EventArgs args)
  342. {
  343. ExtractSection(NcaSectionType.Logo);
  344. }
  345. }
  346. }