GameTableContextMenu.cs 30 KB

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