GameTableContextMenu.cs 24 KB

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