GameTableContextMenu.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  231. {
  232. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  233. if (result.IsSuccess())
  234. {
  235. Ticket ticket = new Ticket(ticketFile.AsStream());
  236. _virtualFileSystem.KeySet.ExternalKeySet.Add(new LibHac.Fs.RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(_virtualFileSystem.KeySet)));
  237. }
  238. }
  239. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  240. {
  241. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  242. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  243. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
  244. {
  245. break;
  246. }
  247. if (nca.Header.ContentType == NcaContentType.Program)
  248. {
  249. patchNca = nca;
  250. }
  251. }
  252. }
  253. }
  254. int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);
  255. IFileSystem ncaFileSystem = patchNca != null ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
  256. : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  257. FileSystemClient fsClient = _virtualFileSystem.FsClient;
  258. string source = DateTime.Now.ToFileTime().ToString().Substring(10);
  259. string output = DateTime.Now.ToFileTime().ToString().Substring(10);
  260. fsClient.Register(source.ToU8Span(), ncaFileSystem);
  261. fsClient.Register(output.ToU8Span(), new LocalFileSystem(destination));
  262. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/");
  263. if (!canceled)
  264. {
  265. if (resultCode.Value.IsFailure())
  266. {
  267. Logger.PrintError(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  268. Gtk.Application.Invoke(delegate
  269. {
  270. _dialog?.Dispose();
  271. GtkDialog.CreateErrorDialog("Extraction failed. Read the log file for further information.");
  272. });
  273. }
  274. else if (resultCode.Value.IsSuccess())
  275. {
  276. Gtk.Application.Invoke(delegate
  277. {
  278. _dialog?.Dispose();
  279. MessageDialog dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null)
  280. {
  281. Title = "Ryujinx - NCA Section Extractor",
  282. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
  283. SecondaryText = "Extraction has completed successfully.",
  284. WindowPosition = WindowPosition.Center
  285. };
  286. dialog.Run();
  287. dialog.Dispose();
  288. });
  289. }
  290. }
  291. fsClient.Unmount(source.ToU8Span());
  292. fsClient.Unmount(output.ToU8Span());
  293. }
  294. });
  295. extractorThread.Name = "GUI.NcaSectionExtractorThread";
  296. extractorThread.IsBackground = true;
  297. extractorThread.Start();
  298. }
  299. }
  300. private (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath)
  301. {
  302. Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All);
  303. if (rc.IsFailure()) return (rc, false);
  304. using (sourceHandle)
  305. {
  306. foreach (DirectoryEntryEx entry in fs.EnumerateEntries(sourcePath, "*", SearchOptions.Default))
  307. {
  308. if (_cancel)
  309. {
  310. return (null, true);
  311. }
  312. string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
  313. string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));
  314. if (entry.Type == DirectoryEntryType.Directory)
  315. {
  316. fs.EnsureDirectoryExists(subDstPath);
  317. (Result? result, bool canceled) = CopyDirectory(fs, subSrcPath, subDstPath);
  318. if (canceled || result.Value.IsFailure())
  319. {
  320. return (result, canceled);
  321. }
  322. }
  323. if (entry.Type == DirectoryEntryType.File)
  324. {
  325. fs.CreateOrOverwriteFile(subDstPath, entry.Size);
  326. rc = CopyFile(fs, subSrcPath, subDstPath);
  327. if (rc.IsFailure()) return (rc, false);
  328. }
  329. }
  330. }
  331. return (Result.Success, false);
  332. }
  333. public Result CopyFile(FileSystemClient fs, string sourcePath, string destPath)
  334. {
  335. Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read);
  336. if (rc.IsFailure()) return rc;
  337. using (sourceHandle)
  338. {
  339. rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend);
  340. if (rc.IsFailure()) return rc;
  341. using (destHandle)
  342. {
  343. const int maxBufferSize = 1024 * 1024;
  344. rc = fs.GetFileSize(out long fileSize, sourceHandle);
  345. if (rc.IsFailure()) return rc;
  346. int bufferSize = (int)Math.Min(maxBufferSize, fileSize);
  347. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  348. try
  349. {
  350. for (long offset = 0; offset < fileSize; offset += bufferSize)
  351. {
  352. int toRead = (int)Math.Min(fileSize - offset, bufferSize);
  353. Span<byte> buf = buffer.AsSpan(0, toRead);
  354. rc = fs.ReadFile(out long _, sourceHandle, offset, buf);
  355. if (rc.IsFailure()) return rc;
  356. rc = fs.WriteFile(destHandle, offset, buf);
  357. if (rc.IsFailure()) return rc;
  358. }
  359. }
  360. finally
  361. {
  362. ArrayPool<byte>.Shared.Return(buffer);
  363. }
  364. rc = fs.FlushFile(destHandle);
  365. if (rc.IsFailure()) return rc;
  366. }
  367. }
  368. return Result.Success;
  369. }
  370. // Events
  371. private void OpenSaveUserDir_Clicked(object sender, EventArgs args)
  372. {
  373. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  374. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  375. if (!ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  376. {
  377. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  378. return;
  379. }
  380. SaveDataFilter filter = new SaveDataFilter();
  381. filter.SetUserId(new UserId(1, 0));
  382. OpenSaveDir(titleName, titleIdNumber, filter);
  383. }
  384. private void OpenSaveDir(string titleName, ulong titleId, SaveDataFilter filter)
  385. {
  386. filter.SetProgramId(new TitleId(titleId));
  387. if (!TryFindSaveData(titleName, titleId, _controlData, filter, out ulong saveDataId))
  388. {
  389. return;
  390. }
  391. string saveDir = GetSaveDataDirectory(saveDataId);
  392. Process.Start(new ProcessStartInfo()
  393. {
  394. FileName = saveDir,
  395. UseShellExecute = true,
  396. Verb = "open"
  397. });
  398. }
  399. private void OpenSaveDeviceDir_Clicked(object sender, EventArgs args)
  400. {
  401. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  402. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  403. if (!ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  404. {
  405. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  406. return;
  407. }
  408. SaveDataFilter filter = new SaveDataFilter();
  409. filter.SetSaveDataType(SaveDataType.Device);
  410. OpenSaveDir(titleName, titleIdNumber, filter);
  411. }
  412. private void OpenSaveBcatDir_Clicked(object sender, EventArgs args)
  413. {
  414. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  415. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  416. if (!ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  417. {
  418. GtkDialog.CreateErrorDialog("UI error: The selected game did not have a valid title ID");
  419. return;
  420. }
  421. SaveDataFilter filter = new SaveDataFilter();
  422. filter.SetSaveDataType(SaveDataType.Bcat);
  423. OpenSaveDir(titleName, titleIdNumber, filter);
  424. }
  425. private void ManageTitleUpdates_Clicked(object sender, EventArgs args)
  426. {
  427. string titleName = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[0];
  428. string titleId = _gameTableStore.GetValue(_rowIter, 2).ToString().Split("\n")[1].ToLower();
  429. TitleUpdateWindow titleUpdateWindow = new TitleUpdateWindow(titleId, titleName, _virtualFileSystem);
  430. titleUpdateWindow.Show();
  431. }
  432. private void ExtractRomFs_Clicked(object sender, EventArgs args)
  433. {
  434. ExtractSection(NcaSectionType.Data);
  435. }
  436. private void ExtractExeFs_Clicked(object sender, EventArgs args)
  437. {
  438. ExtractSection(NcaSectionType.Code);
  439. }
  440. private void ExtractLogo_Clicked(object sender, EventArgs args)
  441. {
  442. ExtractSection(NcaSectionType.Logo);
  443. }
  444. }
  445. }