ApplicationHelper.cs 17 KB

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