GameTableContextMenu.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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.Common.Utilities;
  15. using Ryujinx.HLE.FileSystem;
  16. using Ryujinx.HLE.HOS;
  17. using System;
  18. using System.Buffers;
  19. using System.Collections.Generic;
  20. using System.Diagnostics;
  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
  27. {
  28. public class GameTableContextMenu : Menu
  29. {
  30. private readonly ListStore _gameTableStore;
  31. private readonly TreeIter _rowIter;
  32. private readonly VirtualFileSystem _virtualFileSystem;
  33. private readonly BlitStruct<ApplicationControlProperty> _controlData;
  34. private MessageDialog _dialog;
  35. private bool _cancel;
  36. public GameTableContextMenu(ListStore gameTableStore, BlitStruct<ApplicationControlProperty> controlData, TreeIter rowIter, VirtualFileSystem virtualFileSystem)
  37. {
  38. _gameTableStore = gameTableStore;
  39. _rowIter = rowIter;
  40. _virtualFileSystem = virtualFileSystem;
  41. _controlData = controlData;
  42. MenuItem openSaveUserDir = new MenuItem("Open User Save Directory")
  43. {
  44. Sensitive = !Utilities.IsEmpty(controlData.ByteSpan) && controlData.Value.UserAccountSaveDataSize > 0,
  45. TooltipText = "Open the directory which contains Application's User Saves."
  46. };
  47. MenuItem openSaveDeviceDir = new MenuItem("Open Device Save Directory")
  48. {
  49. Sensitive = !Utilities.IsEmpty(controlData.ByteSpan) && controlData.Value.DeviceSaveDataSize > 0,
  50. TooltipText = "Open the directory which contains Application's Device Saves."
  51. };
  52. MenuItem openSaveBcatDir = new MenuItem("Open BCAT Save Directory")
  53. {
  54. Sensitive = !Utilities.IsEmpty(controlData.ByteSpan) && controlData.Value.BcatDeliveryCacheStorageSize > 0,
  55. TooltipText = "Open the directory which contains Application's BCAT Saves."
  56. };
  57. MenuItem manageTitleUpdates = new MenuItem("Manage Title Updates")
  58. {
  59. TooltipText = "Open the Title Update management window"
  60. };
  61. MenuItem manageDlc = new MenuItem("Manage DLC")
  62. {
  63. TooltipText = "Open the DLC management window"
  64. };
  65. MenuItem openTitleModDir = new MenuItem("Open Mods Directory")
  66. {
  67. TooltipText = "Open the directory which contains Application's Mods."
  68. };
  69. string ext = System.IO.Path.GetExtension(_gameTableStore.GetValue(_rowIter, 9).ToString()).ToLower();
  70. bool hasNca = ext == ".nca" || ext == ".nsp" || ext == ".pfs0" || ext == ".xci";
  71. MenuItem extractMenu = new MenuItem("Extract Data");
  72. MenuItem extractRomFs = new MenuItem("RomFS")
  73. {
  74. Sensitive = hasNca,
  75. TooltipText = "Extract the RomFS section from Application's current config (including updates)."
  76. };
  77. MenuItem extractExeFs = new MenuItem("ExeFS")
  78. {
  79. Sensitive = hasNca,
  80. TooltipText = "Extract the ExeFS section from Application's current config (including updates)."
  81. };
  82. MenuItem extractLogo = new MenuItem("Logo")
  83. {
  84. Sensitive = hasNca,
  85. TooltipText = "Extract the Logo section from Application's current config (including updates)."
  86. };
  87. Menu extractSubMenu = new Menu();
  88. extractSubMenu.Append(extractExeFs);
  89. extractSubMenu.Append(extractRomFs);
  90. extractSubMenu.Append(extractLogo);
  91. extractMenu.Submenu = extractSubMenu;
  92. MenuItem managePtcMenu = new MenuItem("Cache Management");
  93. MenuItem purgePtcCache = new MenuItem("Purge PPTC Cache")
  94. {
  95. TooltipText = "Delete the Application's PPTC cache."
  96. };
  97. MenuItem purgeShaderCache = new MenuItem("Purge Shader Cache")
  98. {
  99. TooltipText = "Delete the Application's shader cache."
  100. };
  101. MenuItem openPtcDir = new MenuItem("Open PPTC Directory")
  102. {
  103. TooltipText = "Open the directory which contains the Application's PPTC cache."
  104. };
  105. MenuItem openShaderCacheDir = new MenuItem("Open Shader Cache Directory")
  106. {
  107. TooltipText = "Open the directory which contains the Application's shader cache."
  108. };
  109. Menu manageSubMenu = new Menu();
  110. manageSubMenu.Append(purgePtcCache);
  111. manageSubMenu.Append(purgeShaderCache);
  112. manageSubMenu.Append(openPtcDir);
  113. manageSubMenu.Append(openShaderCacheDir);
  114. managePtcMenu.Submenu = manageSubMenu;
  115. openSaveUserDir.Activated += OpenSaveUserDir_Clicked;
  116. openSaveDeviceDir.Activated += OpenSaveDeviceDir_Clicked;
  117. openSaveBcatDir.Activated += OpenSaveBcatDir_Clicked;
  118. manageTitleUpdates.Activated += ManageTitleUpdates_Clicked;
  119. manageDlc.Activated += ManageDlc_Clicked;
  120. openTitleModDir.Activated += OpenTitleModDir_Clicked;
  121. extractRomFs.Activated += ExtractRomFs_Clicked;
  122. extractExeFs.Activated += ExtractExeFs_Clicked;
  123. extractLogo.Activated += ExtractLogo_Clicked;
  124. purgePtcCache.Activated += PurgePtcCache_Clicked;
  125. purgeShaderCache.Activated += PurgeShaderCache_Clicked;
  126. openPtcDir.Activated += OpenPtcDir_Clicked;
  127. openShaderCacheDir.Activated += OpenShaderCacheDir_Clicked;
  128. this.Add(openSaveUserDir);
  129. this.Add(openSaveDeviceDir);
  130. this.Add(openSaveBcatDir);
  131. this.Add(new SeparatorMenuItem());
  132. this.Add(manageTitleUpdates);
  133. this.Add(manageDlc);
  134. this.Add(openTitleModDir);
  135. this.Add(new SeparatorMenuItem());
  136. this.Add(managePtcMenu);
  137. this.Add(extractMenu);
  138. }
  139. private bool TryFindSaveData(string titleName, ulong titleId, BlitStruct<ApplicationControlProperty> controlHolder, SaveDataFilter filter, out ulong saveDataId)
  140. {
  141. saveDataId = default;
  142. Result result = _virtualFileSystem.FsClient.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo, SaveDataSpaceId.User, ref filter);
  143. if (ResultFs.TargetNotFound.Includes(result))
  144. {
  145. // Savedata was not found. Ask the user if they want to create it
  146. using MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, null)
  147. {
  148. Title = "Ryujinx",
  149. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  150. Text = $"There is no savedata for {titleName} [{titleId:x16}]",
  151. SecondaryText = "Would you like to create savedata for this game?",
  152. WindowPosition = WindowPosition.Center
  153. };
  154. if (messageDialog.Run() != (int)ResponseType.Yes)
  155. {
  156. return false;
  157. }
  158. ref ApplicationControlProperty control = ref controlHolder.Value;
  159. if (LibHac.Utilities.IsEmpty(controlHolder.ByteSpan))
  160. {
  161. // If the current application doesn't have a loaded control property, create a dummy one
  162. // and set the savedata sizes so a user savedata will be created.
  163. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  164. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  165. control.UserAccountSaveDataSize = 0x4000;
  166. control.UserAccountSaveDataJournalSize = 0x4000;
  167. Logger.Warning?.Print(LogClass.Application,
  168. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  169. }
  170. Uid user = new Uid(1, 0);
  171. result = EnsureApplicationSaveData(_virtualFileSystem.FsClient, out _, new LibHac.Ncm.ApplicationId(titleId), ref control, ref user);
  172. if (result.IsFailure())
  173. {
  174. GtkDialog.CreateErrorDialog($"There was an error creating the specified savedata: {result.ToStringWithName()}");
  175. return false;
  176. }
  177. // Try to find the savedata again after creating it
  178. result = _virtualFileSystem.FsClient.FindSaveDataWithFilter(out saveDataInfo, SaveDataSpaceId.User, ref filter);
  179. }
  180. if (result.IsSuccess())
  181. {
  182. saveDataId = saveDataInfo.SaveDataId;
  183. return true;
  184. }
  185. GtkDialog.CreateErrorDialog($"There was an error finding the specified savedata: {result.ToStringWithName()}");
  186. return false;
  187. }
  188. private string GetSaveDataDirectory(ulong saveDataId)
  189. {
  190. string saveRootPath = System.IO.Path.Combine(_virtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}");
  191. if (!Directory.Exists(saveRootPath))
  192. {
  193. // Inconsistent state. Create the directory
  194. Directory.CreateDirectory(saveRootPath);
  195. }
  196. string committedPath = System.IO.Path.Combine(saveRootPath, "0");
  197. string workingPath = System.IO.Path.Combine(saveRootPath, "1");
  198. // If the committed directory exists, that path will be loaded the next time the savedata is mounted
  199. if (Directory.Exists(committedPath))
  200. {
  201. return committedPath;
  202. }
  203. // If the working directory exists and the committed directory doesn't,
  204. // the working directory will be loaded the next time the savedata is mounted
  205. if (!Directory.Exists(workingPath))
  206. {
  207. Directory.CreateDirectory(workingPath);
  208. }
  209. return workingPath;
  210. }
  211. private void ExtractSection(NcaSectionType ncaSectionType, int programIndex = 0)
  212. {
  213. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to extract into", null, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Extract", ResponseType.Accept);
  214. fileChooser.SetPosition(WindowPosition.Center);
  215. int response = fileChooser.Run();
  216. string destination = fileChooser.Filename;
  217. fileChooser.Dispose();
  218. if (response == (int)ResponseType.Accept)
  219. {
  220. Thread extractorThread = new Thread(() =>
  221. {
  222. string sourceFile = _gameTableStore.GetValue(_rowIter, 9).ToString();
  223. Gtk.Application.Invoke(delegate
  224. {
  225. _dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Cancel, null)
  226. {
  227. Title = "Ryujinx - NCA Section Extractor",
  228. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  229. SecondaryText = $"Extracting {ncaSectionType} section from {System.IO.Path.GetFileName(sourceFile)}...",
  230. WindowPosition = WindowPosition.Center
  231. };
  232. int dialogResponse = _dialog.Run();
  233. if (dialogResponse == (int)ResponseType.Cancel || dialogResponse == (int)ResponseType.DeleteEvent)
  234. {
  235. _cancel = true;
  236. _dialog.Dispose();
  237. }
  238. });
  239. using (FileStream file = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
  240. {
  241. Nca mainNca = null;
  242. Nca patchNca = null;
  243. if ((System.IO.Path.GetExtension(sourceFile).ToLower() == ".nsp") ||
  244. (System.IO.Path.GetExtension(sourceFile).ToLower() == ".pfs0") ||
  245. (System.IO.Path.GetExtension(sourceFile).ToLower() == ".xci"))
  246. {
  247. PartitionFileSystem pfs;
  248. if (System.IO.Path.GetExtension(sourceFile) == ".xci")
  249. {
  250. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  251. pfs = xci.OpenPartition(XciPartitionType.Secure);
  252. }
  253. else
  254. {
  255. pfs = new PartitionFileSystem(file.AsStorage());
  256. }
  257. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  258. {
  259. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  260. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  261. if (nca.Header.ContentType == NcaContentType.Program)
  262. {
  263. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  264. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  265. {
  266. patchNca = nca;
  267. }
  268. else
  269. {
  270. mainNca = nca;
  271. }
  272. }
  273. }
  274. }
  275. else if (System.IO.Path.GetExtension(sourceFile).ToLower() == ".nca")
  276. {
  277. mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  278. }
  279. if (mainNca == null)
  280. {
  281. Logger.Error?.Print(LogClass.Application, "Extraction failed. The main NCA was not present in the selected file.");
  282. Gtk.Application.Invoke(delegate
  283. {
  284. GtkDialog.CreateErrorDialog("Extraction failed. The main NCA was not present in the selected file.");
  285. });
  286. return;
  287. }
  288. (Nca updatePatchNca, _) = ApplicationLoader.GetGameUpdateData(_virtualFileSystem, mainNca.Header.TitleId.ToString("x16"), programIndex, out _);
  289. if (updatePatchNca != null)
  290. {
  291. patchNca = updatePatchNca;
  292. }
  293. int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);
  294. IFileSystem ncaFileSystem = patchNca != null ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
  295. : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  296. FileSystemClient fsClient = _virtualFileSystem.FsClient;
  297. string source = DateTime.Now.ToFileTime().ToString().Substring(10);
  298. string output = DateTime.Now.ToFileTime().ToString().Substring(10);
  299. fsClient.Register(source.ToU8Span(), ncaFileSystem);
  300. fsClient.Register(output.ToU8Span(), new LocalFileSystem(destination));
  301. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/");
  302. if (!canceled)
  303. {
  304. if (resultCode.Value.IsFailure())
  305. {
  306. Logger.Error?.Print(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  307. Gtk.Application.Invoke(delegate
  308. {
  309. _dialog?.Dispose();
  310. GtkDialog.CreateErrorDialog("Extraction failed. Read the log file for further information.");
  311. });
  312. }
  313. else if (resultCode.Value.IsSuccess())
  314. {
  315. Gtk.Application.Invoke(delegate
  316. {
  317. _dialog?.Dispose();
  318. MessageDialog dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null)
  319. {
  320. Title = "Ryujinx - NCA Section Extractor",
  321. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  322. SecondaryText = "Extraction has completed successfully.",
  323. WindowPosition = WindowPosition.Center
  324. };
  325. dialog.Run();
  326. dialog.Dispose();
  327. });
  328. }
  329. }
  330. fsClient.Unmount(source.ToU8Span());
  331. fsClient.Unmount(output.ToU8Span());
  332. }
  333. });
  334. extractorThread.Name = "GUI.NcaSectionExtractorThread";
  335. extractorThread.IsBackground = true;
  336. extractorThread.Start();
  337. }
  338. }
  339. private (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath)
  340. {
  341. Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All);
  342. if (rc.IsFailure()) return (rc, false);
  343. using (sourceHandle)
  344. {
  345. foreach (DirectoryEntryEx entry in fs.EnumerateEntries(sourcePath, "*", SearchOptions.Default))
  346. {
  347. if (_cancel)
  348. {
  349. return (null, true);
  350. }
  351. string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
  352. string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));
  353. if (entry.Type == DirectoryEntryType.Directory)
  354. {
  355. fs.EnsureDirectoryExists(subDstPath);
  356. (Result? result, bool canceled) = CopyDirectory(fs, subSrcPath, subDstPath);
  357. if (canceled || result.Value.IsFailure())
  358. {
  359. return (result, canceled);
  360. }
  361. }
  362. if (entry.Type == DirectoryEntryType.File)
  363. {
  364. fs.CreateOrOverwriteFile(subDstPath, entry.Size);
  365. rc = CopyFile(fs, subSrcPath, subDstPath);
  366. if (rc.IsFailure()) return (rc, false);
  367. }
  368. }
  369. }
  370. return (Result.Success, false);
  371. }
  372. public Result CopyFile(FileSystemClient fs, string sourcePath, string destPath)
  373. {
  374. Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read);
  375. if (rc.IsFailure()) return rc;
  376. using (sourceHandle)
  377. {
  378. rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend);
  379. if (rc.IsFailure()) return rc;
  380. using (destHandle)
  381. {
  382. const int maxBufferSize = 1024 * 1024;
  383. rc = fs.GetFileSize(out long fileSize, sourceHandle);
  384. if (rc.IsFailure()) return rc;
  385. int bufferSize = (int)Math.Min(maxBufferSize, fileSize);
  386. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  387. try
  388. {
  389. for (long offset = 0; offset < fileSize; offset += bufferSize)
  390. {
  391. int toRead = (int)Math.Min(fileSize - offset, bufferSize);
  392. Span<byte> buf = buffer.AsSpan(0, toRead);
  393. rc = fs.ReadFile(out long _, sourceHandle, offset, buf);
  394. if (rc.IsFailure()) return rc;
  395. rc = fs.WriteFile(destHandle, offset, buf);
  396. if (rc.IsFailure()) return rc;
  397. }
  398. }
  399. finally
  400. {
  401. ArrayPool<byte>.Shared.Return(buffer);
  402. }
  403. rc = fs.FlushFile(destHandle);
  404. if (rc.IsFailure()) return rc;
  405. }
  406. }
  407. return Result.Success;
  408. }
  409. // Events
  410. private void OpenSaveUserDir_Clicked(object sender, EventArgs args)
  411. {
  412. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  413. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  414. if (!ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  415. {
  416. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  417. return;
  418. }
  419. SaveDataFilter filter = new SaveDataFilter();
  420. filter.SetUserId(new UserId(1, 0));
  421. OpenSaveDir(titleName, titleIdNumber, filter);
  422. }
  423. private void OpenSaveDir(string titleName, ulong titleId, SaveDataFilter filter)
  424. {
  425. filter.SetProgramId(new ProgramId(titleId));
  426. if (!TryFindSaveData(titleName, titleId, _controlData, filter, out ulong saveDataId))
  427. {
  428. return;
  429. }
  430. string saveDir = GetSaveDataDirectory(saveDataId);
  431. Process.Start(new ProcessStartInfo
  432. {
  433. FileName = saveDir,
  434. UseShellExecute = true,
  435. Verb = "open"
  436. });
  437. }
  438. private void OpenSaveDeviceDir_Clicked(object sender, EventArgs args)
  439. {
  440. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  441. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  442. if (!ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  443. {
  444. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  445. return;
  446. }
  447. SaveDataFilter filter = new SaveDataFilter();
  448. filter.SetSaveDataType(SaveDataType.Device);
  449. OpenSaveDir(titleName, titleIdNumber, filter);
  450. }
  451. private void OpenSaveBcatDir_Clicked(object sender, EventArgs args)
  452. {
  453. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  454. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  455. if (!ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  456. {
  457. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  458. return;
  459. }
  460. SaveDataFilter filter = new SaveDataFilter();
  461. filter.SetSaveDataType(SaveDataType.Bcat);
  462. OpenSaveDir(titleName, titleIdNumber, filter);
  463. }
  464. private void ManageTitleUpdates_Clicked(object sender, EventArgs args)
  465. {
  466. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  467. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  468. TitleUpdateWindow titleUpdateWindow = new TitleUpdateWindow(titleId, titleName, _virtualFileSystem);
  469. titleUpdateWindow.Show();
  470. }
  471. private void ManageDlc_Clicked(object sender, EventArgs args)
  472. {
  473. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  474. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  475. DlcWindow dlcWindow = new DlcWindow(titleId, titleName, _virtualFileSystem);
  476. dlcWindow.Show();
  477. }
  478. private void OpenTitleModDir_Clicked(object sender, EventArgs args)
  479. {
  480. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  481. var modsBasePath = _virtualFileSystem.ModLoader.GetModsBasePath();
  482. var titleModsPath = _virtualFileSystem.ModLoader.GetTitleDir(modsBasePath, titleId);
  483. Process.Start(new ProcessStartInfo
  484. {
  485. FileName = titleModsPath,
  486. UseShellExecute = true,
  487. Verb = "open"
  488. });
  489. }
  490. private void ExtractRomFs_Clicked(object sender, EventArgs args)
  491. {
  492. ExtractSection(NcaSectionType.Data);
  493. }
  494. private void ExtractExeFs_Clicked(object sender, EventArgs args)
  495. {
  496. ExtractSection(NcaSectionType.Code);
  497. }
  498. private void ExtractLogo_Clicked(object sender, EventArgs args)
  499. {
  500. ExtractSection(NcaSectionType.Logo);
  501. }
  502. private void OpenPtcDir_Clicked(object sender, EventArgs args)
  503. {
  504. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  505. string ptcDir = System.IO.Path.Combine(AppDataManager.GamesDirPath, titleId, "cache", "cpu");
  506. string mainPath = System.IO.Path.Combine(ptcDir, "0");
  507. string backupPath = System.IO.Path.Combine(ptcDir, "1");
  508. if (!Directory.Exists(ptcDir))
  509. {
  510. Directory.CreateDirectory(ptcDir);
  511. Directory.CreateDirectory(mainPath);
  512. Directory.CreateDirectory(backupPath);
  513. }
  514. Process.Start(new ProcessStartInfo
  515. {
  516. FileName = ptcDir,
  517. UseShellExecute = true,
  518. Verb = "open"
  519. });
  520. }
  521. private void OpenShaderCacheDir_Clicked(object sender, EventArgs args)
  522. {
  523. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  524. string shaderCacheDir = System.IO.Path.Combine(AppDataManager.GamesDirPath, titleId, "cache", "shader");
  525. if (!Directory.Exists(shaderCacheDir))
  526. {
  527. Directory.CreateDirectory(shaderCacheDir);
  528. }
  529. Process.Start(new ProcessStartInfo
  530. {
  531. FileName = shaderCacheDir,
  532. UseShellExecute = true,
  533. Verb = "open"
  534. });
  535. }
  536. private void PurgePtcCache_Clicked(object sender, EventArgs args)
  537. {
  538. string[] tableEntry = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n");
  539. string titleId = tableEntry[1].ToLower();
  540. DirectoryInfo mainDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, titleId, "cache", "cpu", "0"));
  541. DirectoryInfo backupDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, titleId, "cache", "cpu", "1"));
  542. MessageDialog warningDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  543. {
  544. Title = "Ryujinx - Warning",
  545. Text = $"You are about to delete the PPTC cache for '{tableEntry[0]}'. Are you sure you want to proceed?",
  546. WindowPosition = WindowPosition.Center
  547. };
  548. List<FileInfo> cacheFiles = new List<FileInfo>();
  549. if (mainDir.Exists) { cacheFiles.AddRange(mainDir.EnumerateFiles("*.cache")); }
  550. if (backupDir.Exists) { cacheFiles.AddRange(backupDir.EnumerateFiles("*.cache")); }
  551. if (cacheFiles.Count > 0 && warningDialog.Run() == (int)ResponseType.Yes)
  552. {
  553. foreach (FileInfo file in cacheFiles)
  554. {
  555. try
  556. {
  557. file.Delete();
  558. }
  559. catch(Exception e)
  560. {
  561. Logger.Error?.Print(LogClass.Application, $"Error purging PPTC cache {file.Name}: {e}");
  562. }
  563. }
  564. }
  565. warningDialog.Dispose();
  566. }
  567. private void PurgeShaderCache_Clicked(object sender, EventArgs args)
  568. {
  569. string[] tableEntry = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n");
  570. string titleId = tableEntry[1].ToLower();
  571. DirectoryInfo shaderCacheDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, titleId, "cache", "shader"));
  572. MessageDialog warningDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  573. {
  574. Title = "Ryujinx - Warning",
  575. Text = $"You are about to delete the shader cache for '{tableEntry[0]}'. Are you sure you want to proceed?",
  576. WindowPosition = WindowPosition.Center
  577. };
  578. List<DirectoryInfo> cacheDirectory = new List<DirectoryInfo>();
  579. if (shaderCacheDir.Exists) { cacheDirectory.AddRange(shaderCacheDir.EnumerateDirectories("*")); }
  580. if (cacheDirectory.Count > 0 && warningDialog.Run() == (int)ResponseType.Yes)
  581. {
  582. foreach (DirectoryInfo directory in cacheDirectory)
  583. {
  584. try
  585. {
  586. directory.Delete(true);
  587. }
  588. catch (Exception e)
  589. {
  590. Logger.Error?.Print(LogClass.Application, $"Error purging shader cache {directory.Name}: {e}");
  591. }
  592. }
  593. }
  594. warningDialog.Dispose();
  595. }
  596. }
  597. }