GameTableContextMenu.cs 24 KB

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