GameTableContextMenu.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. using Gtk;
  2. using LibHac;
  3. using LibHac.Account;
  4. using LibHac.Common;
  5. using LibHac.Fs;
  6. using LibHac.Fs.Fsa;
  7. using LibHac.Fs.Shim;
  8. using LibHac.FsSystem;
  9. using LibHac.FsSystem.NcaUtils;
  10. using LibHac.Ncm;
  11. using LibHac.Ns;
  12. using Ryujinx.Common.Configuration;
  13. using Ryujinx.Common.Logging;
  14. using Ryujinx.HLE.FileSystem;
  15. using Ryujinx.HLE.HOS;
  16. using Ryujinx.Ui.Helper;
  17. using Ryujinx.Ui.Windows;
  18. using System;
  19. using System.Buffers;
  20. using System.Collections.Generic;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Reflection;
  24. using System.Threading;
  25. using static LibHac.Fs.ApplicationSaveDataManagement;
  26. namespace Ryujinx.Ui.Widgets
  27. {
  28. public partial class GameTableContextMenu : Menu
  29. {
  30. private readonly MainWindow _parent;
  31. private readonly VirtualFileSystem _virtualFileSystem;
  32. private readonly BlitStruct<ApplicationControlProperty> _controlData;
  33. private readonly string _titleFilePath;
  34. private readonly string _titleName;
  35. private readonly string _titleIdText;
  36. private readonly ulong _titleId;
  37. private MessageDialog _dialog;
  38. private bool _cancel;
  39. public GameTableContextMenu(MainWindow parent, VirtualFileSystem virtualFileSystem, string titleFilePath, string titleName, string titleId, BlitStruct<ApplicationControlProperty> controlData)
  40. {
  41. _parent = parent;
  42. InitializeComponent();
  43. _virtualFileSystem = virtualFileSystem;
  44. _titleFilePath = titleFilePath;
  45. _titleName = titleName;
  46. _titleIdText = titleId;
  47. _controlData = controlData;
  48. if (!ulong.TryParse(_titleIdText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _titleId))
  49. {
  50. GtkDialog.CreateErrorDialog("The selected game did not have a valid Title Id");
  51. return;
  52. }
  53. _openSaveUserDirMenuItem.Sensitive = !Utilities.IsEmpty(controlData.ByteSpan) && controlData.Value.UserAccountSaveDataSize > 0;
  54. _openSaveDeviceDirMenuItem.Sensitive = !Utilities.IsEmpty(controlData.ByteSpan) && controlData.Value.DeviceSaveDataSize > 0;
  55. _openSaveBcatDirMenuItem.Sensitive = !Utilities.IsEmpty(controlData.ByteSpan) && controlData.Value.BcatDeliveryCacheStorageSize > 0;
  56. string fileExt = System.IO.Path.GetExtension(_titleFilePath).ToLower();
  57. bool hasNca = fileExt == ".nca" || fileExt == ".nsp" || fileExt == ".pfs0" || fileExt == ".xci";
  58. _extractRomFsMenuItem.Sensitive = hasNca;
  59. _extractExeFsMenuItem.Sensitive = hasNca;
  60. _extractLogoMenuItem.Sensitive = hasNca;
  61. PopupAtPointer(null);
  62. }
  63. private bool TryFindSaveData(string titleName, ulong titleId, BlitStruct<ApplicationControlProperty> controlHolder, SaveDataFilter filter, out ulong saveDataId)
  64. {
  65. saveDataId = default;
  66. Result result = _virtualFileSystem.FsClient.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo, SaveDataSpaceId.User, ref filter);
  67. if (ResultFs.TargetNotFound.Includes(result))
  68. {
  69. // Savedata was not found. Ask the user if they want to create it
  70. using MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, null)
  71. {
  72. Title = "Ryujinx",
  73. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.Resources.Logo_Ryujinx.png"),
  74. Text = $"There is no savedata for {titleName} [{titleId:x16}]",
  75. SecondaryText = "Would you like to create savedata for this game?",
  76. WindowPosition = WindowPosition.Center
  77. };
  78. if (messageDialog.Run() != (int)ResponseType.Yes)
  79. {
  80. return false;
  81. }
  82. ref ApplicationControlProperty control = ref controlHolder.Value;
  83. if (Utilities.IsEmpty(controlHolder.ByteSpan))
  84. {
  85. // If the current application doesn't have a loaded control property, create a dummy one
  86. // and set the savedata sizes so a user savedata will be created.
  87. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  88. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  89. control.UserAccountSaveDataSize = 0x4000;
  90. control.UserAccountSaveDataJournalSize = 0x4000;
  91. Logger.Warning?.Print(LogClass.Application, "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  92. }
  93. Uid user = new Uid(1, 0); // TODO: Remove Hardcoded value.
  94. result = EnsureApplicationSaveData(_virtualFileSystem.FsClient, out _, new LibHac.Ncm.ApplicationId(titleId), ref control, ref user);
  95. if (result.IsFailure())
  96. {
  97. GtkDialog.CreateErrorDialog($"There was an error creating the specified savedata: {result.ToStringWithName()}");
  98. return false;
  99. }
  100. // Try to find the savedata again after creating it
  101. result = _virtualFileSystem.FsClient.FindSaveDataWithFilter(out saveDataInfo, SaveDataSpaceId.User, ref filter);
  102. }
  103. if (result.IsSuccess())
  104. {
  105. saveDataId = saveDataInfo.SaveDataId;
  106. return true;
  107. }
  108. GtkDialog.CreateErrorDialog($"There was an error finding the specified savedata: {result.ToStringWithName()}");
  109. return false;
  110. }
  111. private void OpenSaveDir(SaveDataFilter saveDataFilter)
  112. {
  113. saveDataFilter.SetProgramId(new ProgramId(_titleId));
  114. if (!TryFindSaveData(_titleName, _titleId, _controlData, saveDataFilter, out ulong saveDataId))
  115. {
  116. return;
  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. OpenHelper.OpenFolder(committedPath);
  130. }
  131. else
  132. {
  133. // If the working directory exists and the committed directory doesn't,
  134. // the working directory will be loaded the next time the savedata is mounted
  135. if (!Directory.Exists(workingPath))
  136. {
  137. Directory.CreateDirectory(workingPath);
  138. }
  139. OpenHelper.OpenFolder(workingPath);
  140. }
  141. }
  142. private void ExtractSection(NcaSectionType ncaSectionType, int programIndex = 0)
  143. {
  144. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to extract into", null, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Extract", ResponseType.Accept);
  145. fileChooser.SetPosition(WindowPosition.Center);
  146. ResponseType response = (ResponseType)fileChooser.Run();
  147. string destination = fileChooser.Filename;
  148. fileChooser.Dispose();
  149. if (response == ResponseType.Accept)
  150. {
  151. Thread extractorThread = new Thread(() =>
  152. {
  153. Gtk.Application.Invoke(delegate
  154. {
  155. _dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Cancel, null)
  156. {
  157. Title = "Ryujinx - NCA Section Extractor",
  158. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.Resources.Logo_Ryujinx.png"),
  159. SecondaryText = $"Extracting {ncaSectionType} section from {System.IO.Path.GetFileName(_titleFilePath)}...",
  160. WindowPosition = WindowPosition.Center
  161. };
  162. int dialogResponse = _dialog.Run();
  163. if (dialogResponse == (int)ResponseType.Cancel || dialogResponse == (int)ResponseType.DeleteEvent)
  164. {
  165. _cancel = true;
  166. _dialog.Dispose();
  167. }
  168. });
  169. using (FileStream file = new FileStream(_titleFilePath, FileMode.Open, FileAccess.Read))
  170. {
  171. Nca mainNca = null;
  172. Nca patchNca = null;
  173. if ((System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".nsp") ||
  174. (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".pfs0") ||
  175. (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".xci"))
  176. {
  177. PartitionFileSystem pfs;
  178. if (System.IO.Path.GetExtension(_titleFilePath) == ".xci")
  179. {
  180. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  181. pfs = xci.OpenPartition(XciPartitionType.Secure);
  182. }
  183. else
  184. {
  185. pfs = new PartitionFileSystem(file.AsStorage());
  186. }
  187. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  188. {
  189. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  190. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  191. if (nca.Header.ContentType == NcaContentType.Program)
  192. {
  193. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  194. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  195. {
  196. patchNca = nca;
  197. }
  198. else
  199. {
  200. mainNca = nca;
  201. }
  202. }
  203. }
  204. }
  205. else if (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".nca")
  206. {
  207. mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  208. }
  209. if (mainNca == null)
  210. {
  211. Logger.Error?.Print(LogClass.Application, "Extraction failed. The main NCA was not present in the selected file.");
  212. Gtk.Application.Invoke(delegate
  213. {
  214. GtkDialog.CreateErrorDialog("Extraction failed. The main NCA was not present in the selected file.");
  215. });
  216. return;
  217. }
  218. (Nca updatePatchNca, _) = ApplicationLoader.GetGameUpdateData(_virtualFileSystem, mainNca.Header.TitleId.ToString("x16"), programIndex, out _);
  219. if (updatePatchNca != null)
  220. {
  221. patchNca = updatePatchNca;
  222. }
  223. int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);
  224. IFileSystem ncaFileSystem = patchNca != null ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
  225. : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  226. FileSystemClient fsClient = _virtualFileSystem.FsClient;
  227. string source = DateTime.Now.ToFileTime().ToString()[10..];
  228. string output = DateTime.Now.ToFileTime().ToString()[10..];
  229. fsClient.Register(source.ToU8Span(), ncaFileSystem);
  230. fsClient.Register(output.ToU8Span(), new LocalFileSystem(destination));
  231. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/");
  232. if (!canceled)
  233. {
  234. if (resultCode.Value.IsFailure())
  235. {
  236. Logger.Error?.Print(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  237. Gtk.Application.Invoke(delegate
  238. {
  239. _dialog?.Dispose();
  240. GtkDialog.CreateErrorDialog("Extraction failed. Read the log file for further information.");
  241. });
  242. }
  243. else if (resultCode.Value.IsSuccess())
  244. {
  245. Gtk.Application.Invoke(delegate
  246. {
  247. _dialog?.Dispose();
  248. MessageDialog dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null)
  249. {
  250. Title = "Ryujinx - NCA Section Extractor",
  251. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.Resources.Logo_Ryujinx.png"),
  252. SecondaryText = "Extraction has completed successfully.",
  253. WindowPosition = WindowPosition.Center
  254. };
  255. dialog.Run();
  256. dialog.Dispose();
  257. });
  258. }
  259. }
  260. fsClient.Unmount(source.ToU8Span());
  261. fsClient.Unmount(output.ToU8Span());
  262. }
  263. });
  264. extractorThread.Name = "GUI.NcaSectionExtractorThread";
  265. extractorThread.IsBackground = true;
  266. extractorThread.Start();
  267. }
  268. }
  269. private (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath)
  270. {
  271. Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All);
  272. if (rc.IsFailure()) return (rc, false);
  273. using (sourceHandle)
  274. {
  275. foreach (DirectoryEntryEx entry in fs.EnumerateEntries(sourcePath, "*", SearchOptions.Default))
  276. {
  277. if (_cancel)
  278. {
  279. return (null, true);
  280. }
  281. string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
  282. string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));
  283. if (entry.Type == DirectoryEntryType.Directory)
  284. {
  285. fs.EnsureDirectoryExists(subDstPath);
  286. (Result? result, bool canceled) = CopyDirectory(fs, subSrcPath, subDstPath);
  287. if (canceled || result.Value.IsFailure())
  288. {
  289. return (result, canceled);
  290. }
  291. }
  292. if (entry.Type == DirectoryEntryType.File)
  293. {
  294. fs.CreateOrOverwriteFile(subDstPath, entry.Size);
  295. rc = CopyFile(fs, subSrcPath, subDstPath);
  296. if (rc.IsFailure()) return (rc, false);
  297. }
  298. }
  299. }
  300. return (Result.Success, false);
  301. }
  302. public Result CopyFile(FileSystemClient fs, string sourcePath, string destPath)
  303. {
  304. Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read);
  305. if (rc.IsFailure()) return rc;
  306. using (sourceHandle)
  307. {
  308. rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend);
  309. if (rc.IsFailure()) return rc;
  310. using (destHandle)
  311. {
  312. const int maxBufferSize = 1024 * 1024;
  313. rc = fs.GetFileSize(out long fileSize, sourceHandle);
  314. if (rc.IsFailure()) return rc;
  315. int bufferSize = (int)Math.Min(maxBufferSize, fileSize);
  316. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  317. try
  318. {
  319. for (long offset = 0; offset < fileSize; offset += bufferSize)
  320. {
  321. int toRead = (int)Math.Min(fileSize - offset, bufferSize);
  322. Span<byte> buf = buffer.AsSpan(0, toRead);
  323. rc = fs.ReadFile(out long _, sourceHandle, offset, buf);
  324. if (rc.IsFailure()) return rc;
  325. rc = fs.WriteFile(destHandle, offset, buf);
  326. if (rc.IsFailure()) return rc;
  327. }
  328. }
  329. finally
  330. {
  331. ArrayPool<byte>.Shared.Return(buffer);
  332. }
  333. rc = fs.FlushFile(destHandle);
  334. if (rc.IsFailure()) return rc;
  335. }
  336. }
  337. return Result.Success;
  338. }
  339. //
  340. // Events
  341. //
  342. private void OpenSaveUserDir_Clicked(object sender, EventArgs args)
  343. {
  344. SaveDataFilter saveDataFilter = new SaveDataFilter();
  345. saveDataFilter.SetUserId(new UserId(1, 0)); // TODO: Remove Hardcoded value.
  346. OpenSaveDir(saveDataFilter);
  347. }
  348. private void OpenSaveDeviceDir_Clicked(object sender, EventArgs args)
  349. {
  350. SaveDataFilter saveDataFilter = new SaveDataFilter();
  351. saveDataFilter.SetSaveDataType(SaveDataType.Device);
  352. OpenSaveDir(saveDataFilter);
  353. }
  354. private void OpenSaveBcatDir_Clicked(object sender, EventArgs args)
  355. {
  356. SaveDataFilter saveDataFilter = new SaveDataFilter();
  357. saveDataFilter.SetSaveDataType(SaveDataType.Bcat);
  358. OpenSaveDir(saveDataFilter);
  359. }
  360. private void ManageTitleUpdates_Clicked(object sender, EventArgs args)
  361. {
  362. new TitleUpdateWindow(_parent, _virtualFileSystem, _titleIdText, _titleName).Show();
  363. }
  364. private void ManageDlc_Clicked(object sender, EventArgs args)
  365. {
  366. new DlcWindow(_virtualFileSystem, _titleIdText, _titleName).Show();
  367. }
  368. private void OpenTitleModDir_Clicked(object sender, EventArgs args)
  369. {
  370. string modsBasePath = _virtualFileSystem.ModLoader.GetModsBasePath();
  371. string titleModsPath = _virtualFileSystem.ModLoader.GetTitleDir(modsBasePath, _titleIdText);
  372. OpenHelper.OpenFolder(titleModsPath);
  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. private void OpenPtcDir_Clicked(object sender, EventArgs args)
  387. {
  388. string ptcDir = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu");
  389. string mainPath = System.IO.Path.Combine(ptcDir, "0");
  390. string backupPath = System.IO.Path.Combine(ptcDir, "1");
  391. if (!Directory.Exists(ptcDir))
  392. {
  393. Directory.CreateDirectory(ptcDir);
  394. Directory.CreateDirectory(mainPath);
  395. Directory.CreateDirectory(backupPath);
  396. }
  397. OpenHelper.OpenFolder(ptcDir);
  398. }
  399. private void OpenShaderCacheDir_Clicked(object sender, EventArgs args)
  400. {
  401. string shaderCacheDir = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "shader");
  402. if (!Directory.Exists(shaderCacheDir))
  403. {
  404. Directory.CreateDirectory(shaderCacheDir);
  405. }
  406. OpenHelper.OpenFolder(shaderCacheDir);
  407. }
  408. private void PurgePtcCache_Clicked(object sender, EventArgs args)
  409. {
  410. DirectoryInfo mainDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu", "0"));
  411. DirectoryInfo backupDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu", "1"));
  412. MessageDialog warningDialog = GtkDialog.CreateConfirmationDialog("Warning", $"You are about to delete the PPTC cache for :\n\n<b>{_titleName}</b>\n\nAre you sure you want to proceed?");
  413. List<FileInfo> cacheFiles = new List<FileInfo>();
  414. if (mainDir.Exists)
  415. {
  416. cacheFiles.AddRange(mainDir.EnumerateFiles("*.cache"));
  417. }
  418. if (backupDir.Exists)
  419. {
  420. cacheFiles.AddRange(backupDir.EnumerateFiles("*.cache"));
  421. }
  422. if (cacheFiles.Count > 0 && warningDialog.Run() == (int)ResponseType.Yes)
  423. {
  424. foreach (FileInfo file in cacheFiles)
  425. {
  426. try
  427. {
  428. file.Delete();
  429. }
  430. catch(Exception e)
  431. {
  432. GtkDialog.CreateErrorDialog($"Error purging PPTC cache {file.Name}: {e}");
  433. }
  434. }
  435. }
  436. warningDialog.Dispose();
  437. }
  438. private void PurgeShaderCache_Clicked(object sender, EventArgs args)
  439. {
  440. DirectoryInfo shaderCacheDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "shader"));
  441. MessageDialog warningDialog = GtkDialog.CreateConfirmationDialog("Warning", $"You are about to delete the shader cache for :\n\n<b>{_titleName}</b>\n\nAre you sure you want to proceed?");
  442. List<DirectoryInfo> cacheDirectory = new List<DirectoryInfo>();
  443. if (shaderCacheDir.Exists)
  444. {
  445. cacheDirectory.AddRange(shaderCacheDir.EnumerateDirectories("*"));
  446. }
  447. if (cacheDirectory.Count > 0 && warningDialog.Run() == (int)ResponseType.Yes)
  448. {
  449. foreach (DirectoryInfo directory in cacheDirectory)
  450. {
  451. try
  452. {
  453. directory.Delete(true);
  454. }
  455. catch (Exception e)
  456. {
  457. GtkDialog.CreateErrorDialog($"Error purging shader cache {directory.Name}: {e}");
  458. }
  459. }
  460. }
  461. warningDialog.Dispose();
  462. }
  463. }
  464. }