ApplicationHelper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. using Avalonia.Controls;
  2. using Avalonia.Threading;
  3. using LibHac;
  4. using LibHac.Account;
  5. using LibHac.Common;
  6. using LibHac.Fs;
  7. using LibHac.Fs.Fsa;
  8. using LibHac.Fs.Shim;
  9. using LibHac.FsSystem;
  10. using LibHac.Ns;
  11. using LibHac.Tools.Fs;
  12. using LibHac.Tools.FsSystem;
  13. using LibHac.Tools.FsSystem.NcaUtils;
  14. using Ryujinx.Ava.Common.Locale;
  15. using Ryujinx.Ava.Ui.Controls;
  16. using Ryujinx.Ava.Ui.Windows;
  17. using Ryujinx.Common.Logging;
  18. using Ryujinx.HLE.FileSystem;
  19. using Ryujinx.HLE.HOS;
  20. using Ryujinx.HLE.HOS.Services.Account.Acc;
  21. using Ryujinx.Ui.Common.Helper;
  22. using System;
  23. using System.Buffers;
  24. using System.IO;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. using Path = System.IO.Path;
  28. namespace Ryujinx.Ava.Common
  29. {
  30. internal static class ApplicationHelper
  31. {
  32. private static HorizonClient _horizonClient;
  33. private static AccountManager _accountManager;
  34. private static VirtualFileSystem _virtualFileSystem;
  35. private static StyleableWindow _owner;
  36. public static void Initialize(VirtualFileSystem virtualFileSystem, AccountManager accountManager, HorizonClient horizonClient, StyleableWindow owner)
  37. {
  38. _owner = owner;
  39. _virtualFileSystem = virtualFileSystem;
  40. _horizonClient = horizonClient;
  41. _accountManager = accountManager;
  42. }
  43. private static bool TryFindSaveData(string titleName, ulong titleId,
  44. BlitStruct<ApplicationControlProperty> controlHolder, in SaveDataFilter filter, out ulong saveDataId)
  45. {
  46. saveDataId = default;
  47. Result result = _horizonClient.Fs.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo,
  48. SaveDataSpaceId.User, in filter);
  49. if (ResultFs.TargetNotFound.Includes(result))
  50. {
  51. ref ApplicationControlProperty control = ref controlHolder.Value;
  52. Logger.Info?.Print(LogClass.Application, $"Creating save directory for Title: {titleName} [{titleId:x16}]");
  53. if (Utilities.IsZeros(controlHolder.ByteSpan))
  54. {
  55. // If the current application doesn't have a loaded control property, create a dummy one
  56. // and set the savedata sizes so a user savedata will be created.
  57. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  58. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  59. control.UserAccountSaveDataSize = 0x4000;
  60. control.UserAccountSaveDataJournalSize = 0x4000;
  61. Logger.Warning?.Print(LogClass.Application,
  62. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  63. }
  64. Uid user = new Uid((ulong)_accountManager.LastOpenedUser.UserId.High, (ulong)_accountManager.LastOpenedUser.UserId.Low);
  65. result = _horizonClient.Fs.EnsureApplicationSaveData(out _, new LibHac.Ncm.ApplicationId(titleId), in control, in user);
  66. if (result.IsFailure())
  67. {
  68. Dispatcher.UIThread.Post(async () =>
  69. {
  70. await ContentDialogHelper.CreateErrorDialog(
  71. string.Format(LocaleManager.Instance["DialogMessageCreateSaveErrorMessage"], result.ToStringWithName()));
  72. });
  73. return false;
  74. }
  75. // Try to find the savedata again after creating it
  76. result = _horizonClient.Fs.FindSaveDataWithFilter(out saveDataInfo, SaveDataSpaceId.User, in filter);
  77. }
  78. if (result.IsSuccess())
  79. {
  80. saveDataId = saveDataInfo.SaveDataId;
  81. return true;
  82. }
  83. Dispatcher.UIThread.Post(async () =>
  84. {
  85. await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance["DialogMessageFindSaveErrorMessage"], result.ToStringWithName()));
  86. });
  87. return false;
  88. }
  89. public static void OpenSaveDir(in SaveDataFilter saveDataFilter, ulong titleId,
  90. BlitStruct<ApplicationControlProperty> controlData, string titleName)
  91. {
  92. if (!TryFindSaveData(titleName, titleId, controlData, in saveDataFilter, out ulong saveDataId))
  93. {
  94. return;
  95. }
  96. string saveRootPath = Path.Combine(_virtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}");
  97. if (!Directory.Exists(saveRootPath))
  98. {
  99. // Inconsistent state. Create the directory
  100. Directory.CreateDirectory(saveRootPath);
  101. }
  102. string committedPath = Path.Combine(saveRootPath, "0");
  103. string workingPath = Path.Combine(saveRootPath, "1");
  104. // If the committed directory exists, that path will be loaded the next time the savedata is mounted
  105. if (Directory.Exists(committedPath))
  106. {
  107. OpenHelper.OpenFolder(committedPath);
  108. }
  109. else
  110. {
  111. // If the working directory exists and the committed directory doesn't,
  112. // the working directory will be loaded the next time the savedata is mounted
  113. if (!Directory.Exists(workingPath))
  114. {
  115. Directory.CreateDirectory(workingPath);
  116. }
  117. OpenHelper.OpenFolder(workingPath);
  118. }
  119. }
  120. public static async Task ExtractSection(NcaSectionType ncaSectionType, string titleFilePath,
  121. int programIndex = 0)
  122. {
  123. OpenFolderDialog folderDialog = new() { Title = LocaleManager.Instance["FolderDialogExtractTitle"] };
  124. string destination = await folderDialog.ShowAsync(_owner);
  125. var cancellationToken = new CancellationTokenSource();
  126. if (!string.IsNullOrWhiteSpace(destination))
  127. {
  128. Thread extractorThread = new(() =>
  129. {
  130. Dispatcher.UIThread.Post(async () =>
  131. {
  132. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  133. string.Format(LocaleManager.Instance["DialogNcaExtractionMessage"], ncaSectionType, Path.GetFileName(titleFilePath)),
  134. "",
  135. "",
  136. LocaleManager.Instance["InputDialogCancel"],
  137. LocaleManager.Instance["DialogNcaExtractionTitle"]);
  138. if (result == UserResult.Cancel)
  139. {
  140. cancellationToken.Cancel();
  141. }
  142. });
  143. Thread.Sleep(1000);
  144. using (FileStream file = new(titleFilePath, FileMode.Open, FileAccess.Read))
  145. {
  146. Nca mainNca = null;
  147. Nca patchNca = null;
  148. string extension = Path.GetExtension(titleFilePath).ToLower();
  149. if (extension == ".nsp" || extension == ".pfs0" || extension == ".xci")
  150. {
  151. PartitionFileSystem pfs;
  152. if (extension == ".xci")
  153. {
  154. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  155. pfs = xci.OpenPartition(XciPartitionType.Secure);
  156. }
  157. else
  158. {
  159. pfs = new PartitionFileSystem(file.AsStorage());
  160. }
  161. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  162. {
  163. using var ncaFile = new UniqueRef<IFile>();
  164. pfs.OpenFile(ref ncaFile.Ref(), fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  165. Nca nca = new(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage());
  166. if (nca.Header.ContentType == NcaContentType.Program)
  167. {
  168. int dataIndex =
  169. Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  170. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  171. {
  172. patchNca = nca;
  173. }
  174. else
  175. {
  176. mainNca = nca;
  177. }
  178. }
  179. }
  180. }
  181. else if (extension == ".nca")
  182. {
  183. mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  184. }
  185. if (mainNca == null)
  186. {
  187. Logger.Error?.Print(LogClass.Application,
  188. "Extraction failure. The main NCA was not present in the selected file");
  189. Dispatcher.UIThread.InvokeAsync(async () =>
  190. {
  191. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance["DialogNcaExtractionMainNcaNotFoundErrorMessage"]);
  192. });
  193. return;
  194. }
  195. (Nca updatePatchNca, _) = ApplicationLoader.GetGameUpdateData(_virtualFileSystem,
  196. mainNca.Header.TitleId.ToString("x16"), programIndex, out _);
  197. if (updatePatchNca != null)
  198. {
  199. patchNca = updatePatchNca;
  200. }
  201. int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);
  202. try
  203. {
  204. IFileSystem ncaFileSystem = patchNca != null
  205. ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
  206. : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  207. FileSystemClient fsClient = _horizonClient.Fs;
  208. string source = DateTime.Now.ToFileTime().ToString()[10..];
  209. string output = DateTime.Now.ToFileTime().ToString()[10..];
  210. using var uniqueSourceFs = new UniqueRef<IFileSystem>(ncaFileSystem);
  211. using var uniqueOutputFs = new UniqueRef<IFileSystem>(new LocalFileSystem(destination));
  212. fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref());
  213. fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref());
  214. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/", cancellationToken.Token);
  215. if (!canceled)
  216. {
  217. if (resultCode.Value.IsFailure())
  218. {
  219. Logger.Error?.Print(LogClass.Application,
  220. $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  221. Dispatcher.UIThread.InvokeAsync(async () =>
  222. {
  223. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance["DialogNcaExtractionCheckLogErrorMessage"]);
  224. });
  225. }
  226. else if (resultCode.Value.IsSuccess())
  227. {
  228. Dispatcher.UIThread.InvokeAsync(async () =>
  229. {
  230. await ContentDialogHelper.CreateInfoDialog(
  231. LocaleManager.Instance["DialogNcaExtractionSuccessMessage"],
  232. "",
  233. LocaleManager.Instance["InputDialogOk"],
  234. "",
  235. LocaleManager.Instance["DialogNcaExtractionTitle"]);
  236. });
  237. }
  238. }
  239. fsClient.Unmount(source.ToU8Span());
  240. fsClient.Unmount(output.ToU8Span());
  241. }
  242. catch (ArgumentException ex)
  243. {
  244. Dispatcher.UIThread.InvokeAsync(async () =>
  245. {
  246. await ContentDialogHelper.CreateErrorDialog(ex.Message);
  247. });
  248. }
  249. }
  250. });
  251. extractorThread.Name = "GUI.NcaSectionExtractorThread";
  252. extractorThread.IsBackground = true;
  253. extractorThread.Start();
  254. }
  255. }
  256. public static (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath, CancellationToken token)
  257. {
  258. Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All);
  259. if (rc.IsFailure())
  260. {
  261. return (rc, false);
  262. }
  263. using (sourceHandle)
  264. {
  265. foreach (DirectoryEntryEx entry in fs.EnumerateEntries(sourcePath, "*", SearchOptions.Default))
  266. {
  267. if (token.IsCancellationRequested)
  268. {
  269. return (null, true);
  270. }
  271. string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
  272. string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));
  273. if (entry.Type == DirectoryEntryType.Directory)
  274. {
  275. fs.EnsureDirectoryExists(subDstPath);
  276. (Result? result, bool canceled) = CopyDirectory(fs, subSrcPath, subDstPath, token);
  277. if (canceled || result.Value.IsFailure())
  278. {
  279. return (result, canceled);
  280. }
  281. }
  282. if (entry.Type == DirectoryEntryType.File)
  283. {
  284. fs.CreateOrOverwriteFile(subDstPath, entry.Size);
  285. rc = CopyFile(fs, subSrcPath, subDstPath);
  286. if (rc.IsFailure())
  287. {
  288. return (rc, false);
  289. }
  290. }
  291. }
  292. }
  293. return (Result.Success, false);
  294. }
  295. public static Result CopyFile(FileSystemClient fs, string sourcePath, string destPath)
  296. {
  297. Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read);
  298. if (rc.IsFailure())
  299. {
  300. return rc;
  301. }
  302. using (sourceHandle)
  303. {
  304. rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend);
  305. if (rc.IsFailure())
  306. {
  307. return rc;
  308. }
  309. using (destHandle)
  310. {
  311. const int MaxBufferSize = 1024 * 1024;
  312. rc = fs.GetFileSize(out long fileSize, sourceHandle);
  313. if (rc.IsFailure())
  314. {
  315. return rc;
  316. }
  317. int bufferSize = (int)Math.Min(MaxBufferSize, fileSize);
  318. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  319. try
  320. {
  321. for (long offset = 0; offset < fileSize; offset += bufferSize)
  322. {
  323. int toRead = (int)Math.Min(fileSize - offset, bufferSize);
  324. Span<byte> buf = buffer.AsSpan(0, toRead);
  325. rc = fs.ReadFile(out long _, sourceHandle, offset, buf);
  326. if (rc.IsFailure())
  327. {
  328. return rc;
  329. }
  330. rc = fs.WriteFile(destHandle, offset, buf, WriteOption.None);
  331. if (rc.IsFailure())
  332. {
  333. return rc;
  334. }
  335. }
  336. }
  337. finally
  338. {
  339. ArrayPool<byte>.Shared.Return(buffer);
  340. }
  341. rc = fs.FlushFile(destHandle);
  342. if (rc.IsFailure())
  343. {
  344. return rc;
  345. }
  346. }
  347. }
  348. return Result.Success;
  349. }
  350. }
  351. }