ApplicationLibrary.cs 27 KB

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