ApplicationLibrary.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Fs;
  4. using LibHac.Fs.Fsa;
  5. using LibHac.FsSystem;
  6. using LibHac.FsSystem.NcaUtils;
  7. using LibHac.Ns;
  8. using Ryujinx.Common.Configuration;
  9. using Ryujinx.Common.Logging;
  10. using Ryujinx.Configuration.System;
  11. using Ryujinx.HLE.FileSystem;
  12. using Ryujinx.HLE.HOS;
  13. using Ryujinx.HLE.Loaders.Npdm;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Reflection;
  18. using System.Text;
  19. using System.Text.Json;
  20. using JsonHelper = Ryujinx.Common.Utilities.JsonHelper;
  21. namespace Ryujinx.Ui.App
  22. {
  23. public class ApplicationLibrary
  24. {
  25. public event EventHandler<ApplicationAddedEventArgs> ApplicationAdded;
  26. public event EventHandler<ApplicationCountUpdatedEventArgs> ApplicationCountUpdated;
  27. private readonly byte[] _nspIcon;
  28. private readonly byte[] _xciIcon;
  29. private readonly byte[] _ncaIcon;
  30. private readonly byte[] _nroIcon;
  31. private readonly byte[] _nsoIcon;
  32. private VirtualFileSystem _virtualFileSystem;
  33. private Language _desiredTitleLanguage;
  34. public ApplicationLibrary(VirtualFileSystem virtualFileSystem)
  35. {
  36. _virtualFileSystem = virtualFileSystem;
  37. _nspIcon = GetResourceBytes("Ryujinx.Ui.Resources.Icon_NSP.png");
  38. _xciIcon = GetResourceBytes("Ryujinx.Ui.Resources.Icon_XCI.png");
  39. _ncaIcon = GetResourceBytes("Ryujinx.Ui.Resources.Icon_NCA.png");
  40. _nroIcon = GetResourceBytes("Ryujinx.Ui.Resources.Icon_NRO.png");
  41. _nsoIcon = GetResourceBytes("Ryujinx.Ui.Resources.Icon_NSO.png");
  42. }
  43. private byte[] GetResourceBytes(string resourceName)
  44. {
  45. Stream resourceStream = Assembly.GetCallingAssembly().GetManifestResourceStream(resourceName);
  46. byte[] resourceByteArray = new byte[resourceStream.Length];
  47. resourceStream.Read(resourceByteArray);
  48. return resourceByteArray;
  49. }
  50. public IEnumerable<string> GetFilesInDirectory(string directory)
  51. {
  52. Stack<string> stack = new Stack<string>();
  53. stack.Push(directory);
  54. while (stack.Count > 0)
  55. {
  56. string dir = stack.Pop();
  57. string[] content = Array.Empty<string>();
  58. try
  59. {
  60. content = Directory.GetFiles(dir, "*");
  61. }
  62. catch (UnauthorizedAccessException)
  63. {
  64. Logger.Warning?.Print(LogClass.Application, $"Failed to get access to directory: \"{dir}\"");
  65. }
  66. if (content.Length > 0)
  67. {
  68. foreach (string file in content)
  69. {
  70. yield return file;
  71. }
  72. }
  73. try
  74. {
  75. content = Directory.GetDirectories(dir);
  76. }
  77. catch (UnauthorizedAccessException)
  78. {
  79. Logger.Warning?.Print(LogClass.Application, $"Failed to get access to directory: \"{dir}\"");
  80. }
  81. if (content.Length > 0)
  82. {
  83. foreach (string subdir in content)
  84. {
  85. stack.Push(subdir);
  86. }
  87. }
  88. }
  89. }
  90. public void ReadControlData(IFileSystem controlFs, Span<byte> outProperty)
  91. {
  92. controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  93. controlFile.Read(out _, 0, outProperty, ReadOption.None).ThrowIfFailure();
  94. }
  95. public void LoadApplications(List<string> appDirs, Language desiredTitleLanguage)
  96. {
  97. int numApplicationsFound = 0;
  98. int numApplicationsLoaded = 0;
  99. _desiredTitleLanguage = desiredTitleLanguage;
  100. // Builds the applications list with paths to found applications
  101. List<string> applications = new List<string>();
  102. foreach (string appDir in appDirs)
  103. {
  104. if (!Directory.Exists(appDir))
  105. {
  106. Logger.Warning?.Print(LogClass.Application, $"The \"game_dirs\" section in \"Config.json\" contains an invalid directory: \"{appDir}\"");
  107. continue;
  108. }
  109. foreach (string app in GetFilesInDirectory(appDir))
  110. {
  111. if ((Path.GetExtension(app).ToLower() == ".nsp") ||
  112. (Path.GetExtension(app).ToLower() == ".pfs0") ||
  113. (Path.GetExtension(app).ToLower() == ".xci") ||
  114. (Path.GetExtension(app).ToLower() == ".nca") ||
  115. (Path.GetExtension(app).ToLower() == ".nro") ||
  116. (Path.GetExtension(app).ToLower() == ".nso"))
  117. {
  118. applications.Add(app);
  119. numApplicationsFound++;
  120. }
  121. }
  122. }
  123. // Loops through applications list, creating a struct and then firing an event containing the struct for each application
  124. foreach (string applicationPath in applications)
  125. {
  126. double fileSize = new FileInfo(applicationPath).Length * 0.000000000931;
  127. string titleName = "Unknown";
  128. string titleId = "0000000000000000";
  129. string developer = "Unknown";
  130. string version = "0";
  131. byte[] applicationIcon = null;
  132. BlitStruct<ApplicationControlProperty> controlHolder = new BlitStruct<ApplicationControlProperty>(1);
  133. try
  134. {
  135. using (FileStream file = new FileStream(applicationPath, FileMode.Open, FileAccess.Read))
  136. {
  137. if ((Path.GetExtension(applicationPath).ToLower() == ".nsp") ||
  138. (Path.GetExtension(applicationPath).ToLower() == ".pfs0") ||
  139. (Path.GetExtension(applicationPath).ToLower() == ".xci"))
  140. {
  141. try
  142. {
  143. PartitionFileSystem pfs;
  144. bool isExeFs = false;
  145. if (Path.GetExtension(applicationPath).ToLower() == ".xci")
  146. {
  147. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  148. pfs = xci.OpenPartition(XciPartitionType.Secure);
  149. }
  150. else
  151. {
  152. pfs = new PartitionFileSystem(file.AsStorage());
  153. // If the NSP doesn't have a main NCA, decrement the number of applications found and then continue to the next application.
  154. bool hasMainNca = false;
  155. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*"))
  156. {
  157. if (Path.GetExtension(fileEntry.FullPath).ToLower() == ".nca")
  158. {
  159. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  160. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  161. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  162. if (nca.Header.ContentType == NcaContentType.Program && !nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  163. {
  164. hasMainNca = true;
  165. break;
  166. }
  167. }
  168. else if (Path.GetFileNameWithoutExtension(fileEntry.FullPath) == "main")
  169. {
  170. isExeFs = true;
  171. }
  172. }
  173. if (!hasMainNca && !isExeFs)
  174. {
  175. numApplicationsFound--;
  176. continue;
  177. }
  178. }
  179. if (isExeFs)
  180. {
  181. applicationIcon = _nspIcon;
  182. Result result = pfs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  183. if (ResultFs.PathNotFound.Includes(result))
  184. {
  185. Npdm npdm = new Npdm(npdmFile.AsStream());
  186. titleName = npdm.TitleName;
  187. titleId = npdm.Aci0.TitleId.ToString("x16");
  188. }
  189. }
  190. else
  191. {
  192. // Store the ControlFS in variable called controlFs
  193. GetControlFsAndTitleId(pfs, out IFileSystem controlFs, out titleId);
  194. ReadControlData(controlFs, controlHolder.ByteSpan);
  195. // Get the title name, title ID, developer name and version number from the NACP
  196. version = IsUpdateApplied(titleId, out string updateVersion) ? updateVersion : controlHolder.Value.DisplayVersion.ToString();
  197. GetNameIdDeveloper(ref controlHolder.Value, out titleName, out _, out developer);
  198. // Read the icon from the ControlFS and store it as a byte array
  199. try
  200. {
  201. controlFs.OpenFile(out IFile icon, $"/icon_{_desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  202. using (MemoryStream stream = new MemoryStream())
  203. {
  204. icon.AsStream().CopyTo(stream);
  205. applicationIcon = stream.ToArray();
  206. }
  207. }
  208. catch (HorizonResultException)
  209. {
  210. foreach (DirectoryEntryEx entry in controlFs.EnumerateEntries("/", "*"))
  211. {
  212. if (entry.Name == "control.nacp")
  213. {
  214. continue;
  215. }
  216. controlFs.OpenFile(out IFile icon, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  217. using (MemoryStream stream = new MemoryStream())
  218. {
  219. icon.AsStream().CopyTo(stream);
  220. applicationIcon = stream.ToArray();
  221. }
  222. if (applicationIcon != null)
  223. {
  224. break;
  225. }
  226. }
  227. if (applicationIcon == null)
  228. {
  229. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  230. }
  231. }
  232. }
  233. }
  234. catch (MissingKeyException exception)
  235. {
  236. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  237. Logger.Warning?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}");
  238. }
  239. catch (InvalidDataException)
  240. {
  241. applicationIcon = Path.GetExtension(applicationPath).ToLower() == ".xci" ? _xciIcon : _nspIcon;
  242. Logger.Warning?.Print(LogClass.Application, $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {applicationPath}");
  243. }
  244. catch (Exception exception)
  245. {
  246. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. File: '{applicationPath}' Error: {exception}");
  247. numApplicationsFound--;
  248. continue;
  249. }
  250. }
  251. else if (Path.GetExtension(applicationPath).ToLower() == ".nro")
  252. {
  253. BinaryReader reader = new BinaryReader(file);
  254. byte[] Read(long position, int size)
  255. {
  256. file.Seek(position, SeekOrigin.Begin);
  257. return reader.ReadBytes(size);
  258. }
  259. try
  260. {
  261. file.Seek(24, SeekOrigin.Begin);
  262. int assetOffset = reader.ReadInt32();
  263. if (Encoding.ASCII.GetString(Read(assetOffset, 4)) == "ASET")
  264. {
  265. byte[] iconSectionInfo = Read(assetOffset + 8, 0x10);
  266. long iconOffset = BitConverter.ToInt64(iconSectionInfo, 0);
  267. long iconSize = BitConverter.ToInt64(iconSectionInfo, 8);
  268. ulong nacpOffset = reader.ReadUInt64();
  269. ulong nacpSize = reader.ReadUInt64();
  270. // Reads and stores game icon as byte array
  271. applicationIcon = Read(assetOffset + iconOffset, (int) iconSize);
  272. // Read the NACP data
  273. Read(assetOffset + (int)nacpOffset, (int)nacpSize).AsSpan().CopyTo(controlHolder.ByteSpan);
  274. // Get the title name, title ID, developer name and version number from the NACP
  275. version = controlHolder.Value.DisplayVersion.ToString();
  276. GetNameIdDeveloper(ref controlHolder.Value, out titleName, out titleId, out developer);
  277. }
  278. else
  279. {
  280. applicationIcon = _nroIcon;
  281. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  282. }
  283. }
  284. catch
  285. {
  286. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  287. numApplicationsFound--;
  288. continue;
  289. }
  290. }
  291. else if (Path.GetExtension(applicationPath).ToLower() == ".nca")
  292. {
  293. try
  294. {
  295. Nca nca = new Nca(_virtualFileSystem.KeySet, new FileStream(applicationPath, FileMode.Open, FileAccess.Read).AsStorage());
  296. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  297. if (nca.Header.ContentType != NcaContentType.Program || nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  298. {
  299. numApplicationsFound--;
  300. continue;
  301. }
  302. }
  303. catch (InvalidDataException)
  304. {
  305. Logger.Warning?.Print(LogClass.Application, $"The NCA header content type check has failed. This is usually because the header key is incorrect or missing. Errored File: {applicationPath}");
  306. }
  307. catch
  308. {
  309. Logger.Warning?.Print(LogClass.Application, $"The file encountered was not of a valid type. Errored File: {applicationPath}");
  310. numApplicationsFound--;
  311. continue;
  312. }
  313. applicationIcon = _ncaIcon;
  314. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  315. }
  316. // If its an NSO we just set defaults
  317. else if (Path.GetExtension(applicationPath).ToLower() == ".nso")
  318. {
  319. applicationIcon = _nsoIcon;
  320. titleName = Path.GetFileNameWithoutExtension(applicationPath);
  321. }
  322. }
  323. }
  324. catch (IOException exception)
  325. {
  326. Logger.Warning?.Print(LogClass.Application, exception.Message);
  327. numApplicationsFound--;
  328. continue;
  329. }
  330. ApplicationMetadata appMetadata = LoadAndSaveMetaData(titleId);
  331. if (appMetadata.LastPlayed != "Never" && !DateTime.TryParse(appMetadata.LastPlayed, out _))
  332. {
  333. Logger.Warning?.Print(LogClass.Application, $"Last played datetime \"{appMetadata.LastPlayed}\" is invalid for current system culture, skipping (did current culture change?)");
  334. appMetadata.LastPlayed = "Never";
  335. }
  336. ApplicationData data = new ApplicationData
  337. {
  338. Favorite = appMetadata.Favorite,
  339. Icon = applicationIcon,
  340. TitleName = titleName,
  341. TitleId = titleId,
  342. Developer = developer,
  343. Version = version,
  344. TimePlayed = ConvertSecondsToReadableString(appMetadata.TimePlayed),
  345. LastPlayed = appMetadata.LastPlayed,
  346. FileExtension = Path.GetExtension(applicationPath).ToUpper().Remove(0, 1),
  347. FileSize = (fileSize < 1) ? (fileSize * 1024).ToString("0.##") + "MB" : fileSize.ToString("0.##") + "GB",
  348. Path = applicationPath,
  349. ControlHolder = controlHolder
  350. };
  351. numApplicationsLoaded++;
  352. OnApplicationAdded(new ApplicationAddedEventArgs()
  353. {
  354. AppData = data
  355. });
  356. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  357. {
  358. NumAppsFound = numApplicationsFound,
  359. NumAppsLoaded = numApplicationsLoaded
  360. });
  361. }
  362. OnApplicationCountUpdated(new ApplicationCountUpdatedEventArgs()
  363. {
  364. NumAppsFound = numApplicationsFound,
  365. NumAppsLoaded = numApplicationsLoaded
  366. });
  367. }
  368. protected void OnApplicationAdded(ApplicationAddedEventArgs e)
  369. {
  370. ApplicationAdded?.Invoke(null, e);
  371. }
  372. protected void OnApplicationCountUpdated(ApplicationCountUpdatedEventArgs e)
  373. {
  374. ApplicationCountUpdated?.Invoke(null, e);
  375. }
  376. private void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
  377. {
  378. (_, _, Nca controlNca) = ApplicationLoader.GetGameData(_virtualFileSystem, pfs, 0);
  379. // Return the ControlFS
  380. controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
  381. titleId = controlNca?.Header.TitleId.ToString("x16");
  382. }
  383. internal ApplicationMetadata LoadAndSaveMetaData(string titleId, Action<ApplicationMetadata> modifyFunction = null)
  384. {
  385. string metadataFolder = Path.Combine(AppDataManager.GamesDirPath, titleId, "gui");
  386. string metadataFile = Path.Combine(metadataFolder, "metadata.json");
  387. ApplicationMetadata appMetadata;
  388. if (!File.Exists(metadataFile))
  389. {
  390. Directory.CreateDirectory(metadataFolder);
  391. appMetadata = new ApplicationMetadata();
  392. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  393. {
  394. JsonHelper.Serialize(stream, appMetadata, true);
  395. }
  396. }
  397. try
  398. {
  399. appMetadata = JsonHelper.DeserializeFromFile<ApplicationMetadata>(metadataFile);
  400. }
  401. catch (JsonException)
  402. {
  403. Logger.Warning?.Print(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults.");
  404. appMetadata = new ApplicationMetadata();
  405. }
  406. if (modifyFunction != null)
  407. {
  408. modifyFunction(appMetadata);
  409. using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough))
  410. {
  411. JsonHelper.Serialize(stream, appMetadata, true);
  412. }
  413. }
  414. return appMetadata;
  415. }
  416. private string ConvertSecondsToReadableString(double seconds)
  417. {
  418. const int secondsPerMinute = 60;
  419. const int secondsPerHour = secondsPerMinute * 60;
  420. const int secondsPerDay = secondsPerHour * 24;
  421. string readableString;
  422. if (seconds < secondsPerMinute)
  423. {
  424. readableString = $"{seconds}s";
  425. }
  426. else if (seconds < secondsPerHour)
  427. {
  428. readableString = $"{Math.Round(seconds / secondsPerMinute, 2, MidpointRounding.AwayFromZero)} mins";
  429. }
  430. else if (seconds < secondsPerDay)
  431. {
  432. readableString = $"{Math.Round(seconds / secondsPerHour, 2, MidpointRounding.AwayFromZero)} hrs";
  433. }
  434. else
  435. {
  436. readableString = $"{Math.Round(seconds / secondsPerDay, 2, MidpointRounding.AwayFromZero)} days";
  437. }
  438. return readableString;
  439. }
  440. private void GetNameIdDeveloper(ref ApplicationControlProperty controlData, out string titleName, out string titleId, out string publisher)
  441. {
  442. _ = Enum.TryParse(_desiredTitleLanguage.ToString(), out TitleLanguage desiredTitleLanguage);
  443. if (controlData.Titles.Length > (int)desiredTitleLanguage)
  444. {
  445. titleName = controlData.Titles[(int)desiredTitleLanguage].Name.ToString();
  446. publisher = controlData.Titles[(int)desiredTitleLanguage].Publisher.ToString();
  447. }
  448. else
  449. {
  450. titleName = null;
  451. publisher = null;
  452. }
  453. if (string.IsNullOrWhiteSpace(titleName))
  454. {
  455. foreach (ApplicationControlTitle controlTitle in controlData.Titles)
  456. {
  457. if (!((U8Span)controlTitle.Name).IsEmpty())
  458. {
  459. titleName = controlTitle.Name.ToString();
  460. break;
  461. }
  462. }
  463. }
  464. if (string.IsNullOrWhiteSpace(publisher))
  465. {
  466. foreach (ApplicationControlTitle controlTitle in controlData.Titles)
  467. {
  468. if (!((U8Span)controlTitle.Publisher).IsEmpty())
  469. {
  470. publisher = controlTitle.Publisher.ToString();
  471. break;
  472. }
  473. }
  474. }
  475. if (controlData.PresenceGroupId != 0)
  476. {
  477. titleId = controlData.PresenceGroupId.ToString("x16");
  478. }
  479. else if (controlData.SaveDataOwnerId.Value != 0)
  480. {
  481. titleId = controlData.SaveDataOwnerId.ToString();
  482. }
  483. else if (controlData.AddOnContentBaseId != 0)
  484. {
  485. titleId = (controlData.AddOnContentBaseId - 0x1000).ToString("x16");
  486. }
  487. else
  488. {
  489. titleId = "0000000000000000";
  490. }
  491. }
  492. private bool IsUpdateApplied(string titleId, out string version)
  493. {
  494. string updatePath = "(unknown)";
  495. try
  496. {
  497. (Nca patchNca, Nca controlNca) = ApplicationLoader.GetGameUpdateData(_virtualFileSystem, titleId, 0, out updatePath);
  498. if (patchNca != null && controlNca != null)
  499. {
  500. ApplicationControlProperty controlData = new ApplicationControlProperty();
  501. controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None).OpenFile(out IFile nacpFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  502. nacpFile.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure();
  503. version = controlData.DisplayVersion.ToString();
  504. return true;
  505. }
  506. }
  507. catch (InvalidDataException)
  508. {
  509. Logger.Warning?.Print(LogClass.Application,
  510. $"The header key is incorrect or missing and therefore the NCA header content type check has failed. Errored File: {updatePath}");
  511. }
  512. catch (MissingKeyException exception)
  513. {
  514. Logger.Warning?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}. Errored File: {updatePath}");
  515. }
  516. version = "";
  517. return false;
  518. }
  519. }
  520. }