ApplicationHelper.cs 17 KB

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