GameTableContextMenu.cs 21 KB

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