GameTableContextMenu.cs 25 KB

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