ApplicationHelper.cs 18 KB

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