GameTableContextMenu.cs 30 KB

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