GameTableContextMenu.cs 21 KB

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