[Ryujinx.HLE] Address dotnet-format issues (#5380)

* dotnet format style --severity info

Some changes were manually reverted.

* dotnet format analyzers --serverity info

Some changes have been minimally adapted.

* Restore a few unused methods and variables

* Silence dotnet format IDE0060 warnings

* Silence dotnet format IDE0052 warnings

* Address or silence dotnet format IDE1006 warnings

* Address dotnet format CA1816 warnings

* Address or silence dotnet format CA2208 warnings

* Address or silence dotnet format CA1806 and a few CA1854 warnings

* Address dotnet format CA2211 warnings

* Address dotnet format CA1822 warnings

* Address or silence dotnet format CA1069 warnings

* Make dotnet format succeed in style mode

* Address or silence dotnet format CA2211 warnings

* Address review comments

* Address dotnet format CA2208 warnings properly

* Make ProcessResult readonly

* Address most dotnet format whitespace warnings

* Apply dotnet format whitespace formatting

A few of them have been manually reverted and the corresponding warning was silenced

* Add previously silenced warnings back

I have no clue how these disappeared

* Revert formatting changes for while and for-loops

* Format if-blocks correctly

* Run dotnet format style after rebase

* Run dotnet format whitespace after rebase

* Run dotnet format style after rebase

* Run dotnet format analyzers after rebase

* Run dotnet format after rebase and remove unused usings

- analyzers
- style
- whitespace

* Disable 'prefer switch expression' rule

* Add comments to disabled warnings

* Fix a few disabled warnings

* Fix naming rule violation, Convert shader properties to auto-property and convert values to const

* Simplify properties and array initialization, Use const when possible, Remove trailing commas

* Start working on disabled warnings

* Fix and silence a few dotnet-format warnings again

* Run dotnet format after rebase

* Use using declaration instead of block syntax

* Address IDE0251 warnings

* Address a few disabled IDE0060 warnings

* Silence IDE0060 in .editorconfig

* Revert "Simplify properties and array initialization, Use const when possible, Remove trailing commas"

This reverts commit 9462e4136c0a2100dc28b20cf9542e06790aa67e.

* dotnet format whitespace after rebase

* First dotnet format pass

* Fix naming rule violations

* Fix typo

* Add trailing commas, use targeted new and use array initializer

* Fix build issues

* Fix remaining build issues

* Remove SuppressMessage for CA1069 where possible

* Address dotnet format issues

* Address formatting issues

Co-authored-by: Ac_K <acoustik666@gmail.com>

* Add GetHashCode implementation for RenderingSurfaceInfo

* Explicitly silence CA1822 for every affected method in Syscall

* Address formatting issues in Demangler.cs

* Address review feedback

Co-authored-by: Ac_K <acoustik666@gmail.com>

* Revert marking service methods as static

* Next dotnet format pass

* Address review feedback

---------

Co-authored-by: Ac_K <acoustik666@gmail.com>
This commit is contained in:
TSRBerry 2023-07-16 19:31:14 +02:00 committed by GitHub
parent fec8291c17
commit 326749498b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1015 changed files with 8173 additions and 7615 deletions

View file

@ -114,7 +114,7 @@ namespace Ryujinx.Ava.Common
public static void OpenSaveDir(ulong saveDataId) public static void OpenSaveDir(ulong saveDataId)
{ {
string saveRootPath = Path.Combine(_virtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}"); string saveRootPath = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}");
if (!Directory.Exists(saveRootPath)) if (!Directory.Exists(saveRootPath))
{ {

View file

@ -2,6 +2,7 @@ using LibHac.Fs;
using LibHac.Ncm; using LibHac.Ncm;
using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Ava.UI.ViewModels;
using Ryujinx.Ava.UI.Windows; using Ryujinx.Ava.UI.Windows;
using Ryujinx.HLE.FileSystem;
using Ryujinx.Ui.App.Common; using Ryujinx.Ui.App.Common;
using System; using System;
using System.IO; using System.IO;
@ -81,7 +82,7 @@ namespace Ryujinx.Ava.UI.Models
Task.Run(() => Task.Run(() =>
{ {
var saveRoot = Path.Combine(MainWindow.MainWindowViewModel.VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); var saveRoot = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}");
long totalSize = GetDirectorySize(saveRoot); long totalSize = GetDirectorySize(saveRoot);

View file

@ -105,7 +105,7 @@ namespace Ryujinx.Ava.UI.ViewModels
} }
string contentPath = contentManager.GetInstalledContentPath(0x010000000000080A, StorageId.BuiltInSystem, NcaContentType.Data); string contentPath = contentManager.GetInstalledContentPath(0x010000000000080A, StorageId.BuiltInSystem, NcaContentType.Data);
string avatarPath = virtualFileSystem.SwitchPathToSystemPath(contentPath); string avatarPath = VirtualFileSystem.SwitchPathToSystemPath(contentPath);
if (!string.IsNullOrWhiteSpace(avatarPath)) if (!string.IsNullOrWhiteSpace(avatarPath))
{ {

View file

@ -47,7 +47,7 @@ namespace Ryujinx.HLE.Exceptions
private string BuildMessage() private string BuildMessage()
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
// Print the IPC command details (service name, command ID, and handler) // Print the IPC command details (service name, command ID, and handler)
(Type callingType, MethodBase callingMethod) = WalkStackTrace(new StackTrace(this)); (Type callingType, MethodBase callingMethod) = WalkStackTrace(new StackTrace(this));

View file

@ -30,13 +30,13 @@ namespace Ryujinx.HLE.FileSystem
private Dictionary<StorageId, LinkedList<LocationEntry>> _locationEntries; private Dictionary<StorageId, LinkedList<LocationEntry>> _locationEntries;
private Dictionary<string, ulong> _sharedFontTitleDictionary; private readonly Dictionary<string, ulong> _sharedFontTitleDictionary;
private Dictionary<ulong, string> _systemTitlesNameDictionary; private readonly Dictionary<ulong, string> _systemTitlesNameDictionary;
private Dictionary<string, string> _sharedFontFilenameDictionary; private readonly Dictionary<string, string> _sharedFontFilenameDictionary;
private SortedDictionary<(ulong titleId, NcaContentType type), string> _contentDictionary; private SortedDictionary<(ulong titleId, NcaContentType type), string> _contentDictionary;
private struct AocItem private readonly struct AocItem
{ {
public readonly string ContainerPath; public readonly string ContainerPath;
public readonly string NcaPath; public readonly string NcaPath;
@ -48,9 +48,9 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
private SortedList<ulong, AocItem> _aocData { get; } private SortedList<ulong, AocItem> AocData { get; }
private VirtualFileSystem _virtualFileSystem; private readonly VirtualFileSystem _virtualFileSystem;
private readonly object _lock = new(); private readonly object _lock = new();
@ -66,7 +66,7 @@ namespace Ryujinx.HLE.FileSystem
{ "FontExtendedChineseSimplified", 0x0100000000000814 }, { "FontExtendedChineseSimplified", 0x0100000000000814 },
{ "FontKorean", 0x0100000000000812 }, { "FontKorean", 0x0100000000000812 },
{ "FontChineseTraditional", 0x0100000000000813 }, { "FontChineseTraditional", 0x0100000000000813 },
{ "FontNintendoExtended", 0x0100000000000810 } { "FontNintendoExtended", 0x0100000000000810 },
}; };
_systemTitlesNameDictionary = new Dictionary<ulong, string>() _systemTitlesNameDictionary = new Dictionary<ulong, string>()
@ -86,12 +86,12 @@ namespace Ryujinx.HLE.FileSystem
{ "FontExtendedChineseSimplified", "nintendo_udsg-r_ext_zh-cn_003.bfttf" }, { "FontExtendedChineseSimplified", "nintendo_udsg-r_ext_zh-cn_003.bfttf" },
{ "FontKorean", "nintendo_udsg-r_ko_003.bfttf" }, { "FontKorean", "nintendo_udsg-r_ko_003.bfttf" },
{ "FontChineseTraditional", "nintendo_udjxh-db_zh-tw_003.bfttf" }, { "FontChineseTraditional", "nintendo_udjxh-db_zh-tw_003.bfttf" },
{ "FontNintendoExtended", "nintendo_ext_003.bfttf" } { "FontNintendoExtended", "nintendo_ext_003.bfttf" },
}; };
_virtualFileSystem = virtualFileSystem; _virtualFileSystem = virtualFileSystem;
_aocData = new SortedList<ulong, AocItem>(); AocData = new SortedList<ulong, AocItem>();
} }
public void LoadEntries(Switch device = null) public void LoadEntries(Switch device = null)
@ -110,7 +110,7 @@ namespace Ryujinx.HLE.FileSystem
try try
{ {
contentPathString = ContentPath.GetContentPath(storageId); contentPathString = ContentPath.GetContentPath(storageId);
contentDirectory = ContentPath.GetRealPath(_virtualFileSystem, contentPathString); contentDirectory = ContentPath.GetRealPath(contentPathString);
registeredDirectory = Path.Combine(contentDirectory, "registered"); registeredDirectory = Path.Combine(contentDirectory, "registered");
} }
catch (NotSupportedException) catch (NotSupportedException)
@ -120,7 +120,7 @@ namespace Ryujinx.HLE.FileSystem
Directory.CreateDirectory(registeredDirectory); Directory.CreateDirectory(registeredDirectory);
LinkedList<LocationEntry> locationList = new LinkedList<LocationEntry>(); LinkedList<LocationEntry> locationList = new();
void AddEntry(LocationEntry entry) void AddEntry(LocationEntry entry)
{ {
@ -133,26 +133,21 @@ namespace Ryujinx.HLE.FileSystem
{ {
string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty); string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty);
using (FileStream ncaFile = File.OpenRead(Directory.GetFiles(directoryPath)[0])) using FileStream ncaFile = File.OpenRead(Directory.GetFiles(directoryPath)[0]);
{ Nca nca = new(_virtualFileSystem.KeySet, ncaFile.AsStorage());
Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
string switchPath = contentPathString + ":/" + ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar); string switchPath = contentPathString + ":/" + ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);
// Change path format to switch's // Change path format to switch's
switchPath = switchPath.Replace('\\', '/'); switchPath = switchPath.Replace('\\', '/');
LocationEntry entry = new LocationEntry(switchPath, LocationEntry entry = new(switchPath, 0, nca.Header.TitleId, nca.Header.ContentType);
0,
nca.Header.TitleId,
nca.Header.ContentType);
AddEntry(entry); AddEntry(entry);
_contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName); _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
} }
} }
}
foreach (string filePath in Directory.EnumerateFiles(contentDirectory)) foreach (string filePath in Directory.EnumerateFiles(contentDirectory))
{ {
@ -160,36 +155,28 @@ namespace Ryujinx.HLE.FileSystem
{ {
string ncaName = Path.GetFileNameWithoutExtension(filePath); string ncaName = Path.GetFileNameWithoutExtension(filePath);
using (FileStream ncaFile = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using FileStream ncaFile = new(filePath, FileMode.Open, FileAccess.Read);
{ Nca nca = new(_virtualFileSystem.KeySet, ncaFile.AsStorage());
Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
string switchPath = contentPathString + ":/" + filePath.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar); string switchPath = contentPathString + ":/" + filePath.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);
// Change path format to switch's // Change path format to switch's
switchPath = switchPath.Replace('\\', '/'); switchPath = switchPath.Replace('\\', '/');
LocationEntry entry = new LocationEntry(switchPath, LocationEntry entry = new(switchPath, 0, nca.Header.TitleId, nca.Header.ContentType);
0,
nca.Header.TitleId,
nca.Header.ContentType);
AddEntry(entry); AddEntry(entry);
_contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName); _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
} }
} }
}
if (_locationEntries.TryGetValue(storageId, out var locationEntriesItem) && locationEntriesItem?.Count == 0) if (_locationEntries.TryGetValue(storageId, out var locationEntriesItem) && locationEntriesItem?.Count == 0)
{ {
_locationEntries.Remove(storageId); _locationEntries.Remove(storageId);
} }
if (!_locationEntries.ContainsKey(storageId)) _locationEntries.TryAdd(storageId, locationList);
{
_locationEntries.Add(storageId, locationList);
}
} }
if (device != null) if (device != null)
@ -239,7 +226,7 @@ namespace Ryujinx.HLE.FileSystem
public void AddAocItem(ulong titleId, string containerPath, string ncaPath, bool mergedToContainer = false) public void AddAocItem(ulong titleId, string containerPath, string ncaPath, bool mergedToContainer = false)
{ {
// TODO: Check Aoc version. // TODO: Check Aoc version.
if (!_aocData.TryAdd(titleId, new AocItem(containerPath, ncaPath))) if (!AocData.TryAdd(titleId, new AocItem(containerPath, ncaPath)))
{ {
Logger.Warning?.Print(LogClass.Application, $"Duplicate AddOnContent detected. TitleId {titleId:X16}"); Logger.Warning?.Print(LogClass.Application, $"Duplicate AddOnContent detected. TitleId {titleId:X16}");
} }
@ -257,17 +244,17 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
public void ClearAocData() => _aocData.Clear(); public void ClearAocData() => AocData.Clear();
public int GetAocCount() => _aocData.Count; public int GetAocCount() => AocData.Count;
public IList<ulong> GetAocTitleIds() => _aocData.Select(e => e.Key).ToList(); public IList<ulong> GetAocTitleIds() => AocData.Select(e => e.Key).ToList();
public bool GetAocDataStorage(ulong aocTitleId, out IStorage aocStorage, IntegrityCheckLevel integrityCheckLevel) public bool GetAocDataStorage(ulong aocTitleId, out IStorage aocStorage, IntegrityCheckLevel integrityCheckLevel)
{ {
aocStorage = null; aocStorage = null;
if (_aocData.TryGetValue(aocTitleId, out AocItem aoc)) if (AocData.TryGetValue(aocTitleId, out AocItem aoc))
{ {
var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read); var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read);
using var ncaFile = new UniqueRef<IFile>(); using var ncaFile = new UniqueRef<IFile>();
@ -331,7 +318,7 @@ namespace Ryujinx.HLE.FileSystem
if (_contentDictionary.ContainsValue(ncaId)) if (_contentDictionary.ContainsValue(ncaId))
{ {
var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId);
ulong titleId = content.Key.Item1; ulong titleId = content.Key.titleId;
NcaContentType contentType = content.Key.type; NcaContentType contentType = content.Key.type;
StorageId storage = GetInstalledStorage(titleId, contentType, storageId); StorageId storage = GetInstalledStorage(titleId, contentType, storageId);
@ -403,21 +390,19 @@ namespace Ryujinx.HLE.FileSystem
return false; return false;
} }
string installedPath = _virtualFileSystem.SwitchPathToSystemPath(locationEntry.ContentPath); string installedPath = VirtualFileSystem.SwitchPathToSystemPath(locationEntry.ContentPath);
if (!string.IsNullOrWhiteSpace(installedPath)) if (!string.IsNullOrWhiteSpace(installedPath))
{ {
if (File.Exists(installedPath)) if (File.Exists(installedPath))
{ {
using (FileStream file = new FileStream(installedPath, FileMode.Open, FileAccess.Read)) using FileStream file = new(installedPath, FileMode.Open, FileAccess.Read);
{ Nca nca = new(_virtualFileSystem.KeySet, file.AsStorage());
Nca nca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
bool contentCheck = nca.Header.ContentType == contentType; bool contentCheck = nca.Header.ContentType == contentType;
return contentCheck; return contentCheck;
} }
} }
}
return false; return false;
} }
@ -426,9 +411,9 @@ namespace Ryujinx.HLE.FileSystem
{ {
LinkedList<LocationEntry> locationList = null; LinkedList<LocationEntry> locationList = null;
if (_locationEntries.ContainsKey(storageId)) if (_locationEntries.TryGetValue(storageId, out LinkedList<LocationEntry> locationEntry))
{ {
locationList = _locationEntries[storageId]; locationList = locationEntry;
} }
if (locationList != null) if (locationList != null)
@ -446,9 +431,9 @@ namespace Ryujinx.HLE.FileSystem
{ {
LinkedList<LocationEntry> locationList = null; LinkedList<LocationEntry> locationList = null;
if (_locationEntries.ContainsKey(storageId)) if (_locationEntries.TryGetValue(storageId, out LinkedList<LocationEntry> locationEntry))
{ {
locationList = _locationEntries[storageId]; locationList = locationEntry;
} }
if (locationList != null) if (locationList != null)
@ -488,7 +473,7 @@ namespace Ryujinx.HLE.FileSystem
public void InstallFirmware(string firmwareSource) public void InstallFirmware(string firmwareSource)
{ {
string contentPathString = ContentPath.GetContentPath(StorageId.BuiltInSystem); string contentPathString = ContentPath.GetContentPath(StorageId.BuiltInSystem);
string contentDirectory = ContentPath.GetRealPath(_virtualFileSystem, contentPathString); string contentDirectory = ContentPath.GetRealPath(contentPathString);
string registeredDirectory = Path.Combine(contentDirectory, "registered"); string registeredDirectory = Path.Combine(contentDirectory, "registered");
string temporaryDirectory = Path.Combine(contentDirectory, "temp"); string temporaryDirectory = Path.Combine(contentDirectory, "temp");
@ -510,10 +495,10 @@ namespace Ryujinx.HLE.FileSystem
throw new FileNotFoundException("Firmware file does not exist."); throw new FileNotFoundException("Firmware file does not exist.");
} }
FileInfo info = new FileInfo(firmwareSource); FileInfo info = new(firmwareSource);
using FileStream file = File.OpenRead(firmwareSource);
using (FileStream file = File.OpenRead(firmwareSource))
{
switch (info.Extension) switch (info.Extension)
{ {
case ".zip": case ".zip":
@ -523,7 +508,7 @@ namespace Ryujinx.HLE.FileSystem
} }
break; break;
case ".xci": case ".xci":
Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()); Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
InstallFromCart(xci, temporaryDirectory); InstallFromCart(xci, temporaryDirectory);
break; break;
default: default:
@ -532,7 +517,6 @@ namespace Ryujinx.HLE.FileSystem
FinishInstallation(temporaryDirectory, registeredDirectory); FinishInstallation(temporaryDirectory, registeredDirectory);
} }
}
private void FinishInstallation(string temporaryDirectory, string registeredDirectory) private void FinishInstallation(string temporaryDirectory, string registeredDirectory)
{ {
@ -555,7 +539,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
{ {
Nca nca = new Nca(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage()); Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());
SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory); SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory);
} }
@ -575,9 +559,7 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
private void InstallFromZip(ZipArchive archive, string temporaryDirectory) private static void InstallFromZip(ZipArchive archive, string temporaryDirectory)
{
using (archive)
{ {
foreach (var entry in archive.Entries) foreach (var entry in archive.Entries)
{ {
@ -587,12 +569,12 @@ namespace Ryujinx.HLE.FileSystem
string[] pathComponents = entry.FullName.Replace(".cnmt", "").Split('/'); string[] pathComponents = entry.FullName.Replace(".cnmt", "").Split('/');
string ncaId = pathComponents[pathComponents.Length - 1]; string ncaId = pathComponents[^1];
// If this is a fragmented nca, we need to get the previous element.GetZip // If this is a fragmented nca, we need to get the previous element.GetZip
if (ncaId.Equals("00")) if (ncaId.Equals("00"))
{ {
ncaId = pathComponents[pathComponents.Length - 2]; ncaId = pathComponents[^2];
} }
if (ncaId.Contains(".nca")) if (ncaId.Contains(".nca"))
@ -606,21 +588,18 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
} }
}
public void SaveNca(Nca nca, string ncaId, string temporaryDirectory) public static void SaveNca(Nca nca, string ncaId, string temporaryDirectory)
{ {
string newPath = Path.Combine(temporaryDirectory, ncaId + ".nca"); string newPath = Path.Combine(temporaryDirectory, ncaId + ".nca");
Directory.CreateDirectory(newPath); Directory.CreateDirectory(newPath);
using (FileStream file = File.Create(Path.Combine(newPath, "00"))) using FileStream file = File.Create(Path.Combine(newPath, "00"));
{
nca.BaseStorage.AsStream().CopyTo(file); nca.BaseStorage.AsStream().CopyTo(file);
} }
}
private IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode) private static IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode)
{ {
using var file = new UniqueRef<IFile>(); using var file = new UniqueRef<IFile>();
@ -636,14 +615,12 @@ namespace Ryujinx.HLE.FileSystem
return file.Release(); return file.Release();
} }
private Stream GetZipStream(ZipArchiveEntry entry) private static Stream GetZipStream(ZipArchiveEntry entry)
{ {
MemoryStream dest = MemoryStreamManager.Shared.GetStream(); MemoryStream dest = MemoryStreamManager.Shared.GetStream();
using (Stream src = entry.Open()) using Stream src = entry.Open();
{
src.CopyTo(dest); src.CopyTo(dest);
}
return dest; return dest;
} }
@ -659,7 +636,7 @@ namespace Ryujinx.HLE.FileSystem
throw new MissingKeyException("HeaderKey is empty. Cannot decrypt NCA headers."); throw new MissingKeyException("HeaderKey is empty. Cannot decrypt NCA headers.");
} }
Dictionary<ulong, List<(NcaContentType type, string path)>> updateNcas = new Dictionary<ulong, List<(NcaContentType, string)>>(); Dictionary<ulong, List<(NcaContentType type, string path)>> updateNcas = new();
if (Directory.Exists(firmwarePackage)) if (Directory.Exists(firmwarePackage))
{ {
@ -671,10 +648,10 @@ namespace Ryujinx.HLE.FileSystem
throw new FileNotFoundException("Firmware file does not exist."); throw new FileNotFoundException("Firmware file does not exist.");
} }
FileInfo info = new FileInfo(firmwarePackage); FileInfo info = new(firmwarePackage);
using FileStream file = File.OpenRead(firmwarePackage);
using (FileStream file = File.OpenRead(firmwarePackage))
{
switch (info.Extension) switch (info.Extension)
{ {
case ".zip": case ".zip":
@ -683,7 +660,7 @@ namespace Ryujinx.HLE.FileSystem
return VerifyAndGetVersionZip(archive); return VerifyAndGetVersionZip(archive);
} }
case ".xci": case ".xci":
Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()); Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
if (xci.HasPartition(XciPartitionType.Update)) if (xci.HasPartition(XciPartitionType.Update))
{ {
@ -698,7 +675,6 @@ namespace Ryujinx.HLE.FileSystem
default: default:
break; break;
} }
}
SystemVersion VerifyAndGetVersionDirectory(string firmwareDirectory) SystemVersion VerifyAndGetVersionDirectory(string firmwareDirectory)
{ {
@ -713,11 +689,10 @@ namespace Ryujinx.HLE.FileSystem
{ {
if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
{ {
using (Stream ncaStream = GetZipStream(entry)) using Stream ncaStream = GetZipStream(entry);
{
IStorage storage = ncaStream.AsStorage(); IStorage storage = ncaStream.AsStorage();
Nca nca = new Nca(_virtualFileSystem.KeySet, storage); Nca nca = new(_virtualFileSystem.KeySet, storage);
if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem))
{ {
@ -730,7 +705,6 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
} }
}
if (updateNcas.TryGetValue(SystemUpdateTitleId, out var ncaEntry)) if (updateNcas.TryGetValue(SystemUpdateTitleId, out var ncaEntry))
{ {
@ -742,7 +716,7 @@ namespace Ryujinx.HLE.FileSystem
using (Stream ncaStream = GetZipStream(fileEntry)) using (Stream ncaStream = GetZipStream(fileEntry))
{ {
Nca metaNca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage()); Nca metaNca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage());
IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
@ -772,9 +746,8 @@ namespace Ryujinx.HLE.FileSystem
{ {
string versionEntry = updateNcasItem.Find(x => x.type != NcaContentType.Meta).path; string versionEntry = updateNcasItem.Find(x => x.type != NcaContentType.Meta).path;
using (Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry))) using Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry));
{ Nca nca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage());
Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage());
var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
@ -785,7 +758,6 @@ namespace Ryujinx.HLE.FileSystem
systemVersion = new SystemVersion(systemVersionFile.Get.AsStream()); systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
} }
} }
}
foreach (CnmtContentMetaEntry metaEntry in metaEntries) foreach (CnmtContentMetaEntry metaEntry in metaEntries)
{ {
@ -807,11 +779,9 @@ namespace Ryujinx.HLE.FileSystem
ZipArchiveEntry metaZipEntry = archive.GetEntry(metaPath); ZipArchiveEntry metaZipEntry = archive.GetEntry(metaPath);
ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath); ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath);
using (Stream metaNcaStream = GetZipStream(metaZipEntry)) using Stream metaNcaStream = GetZipStream(metaZipEntry);
{ using Stream contentNcaStream = GetZipStream(contentZipEntry);
using (Stream contentNcaStream = GetZipStream(contentZipEntry)) Nca metaNca = new(_virtualFileSystem.KeySet, metaNcaStream.AsStorage());
{
Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaNcaStream.AsStorage());
IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
@ -828,11 +798,11 @@ namespace Ryujinx.HLE.FileSystem
{ {
byte[] contentData = new byte[size]; byte[] contentData = new byte[size];
Span<byte> content = new Span<byte>(contentData); Span<byte> content = new(contentData);
contentStorage.Read(0, content); contentStorage.Read(0, content);
Span<byte> hash = new Span<byte>(new byte[32]); Span<byte> hash = new(new byte[32]);
LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash); LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
@ -844,8 +814,6 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
} }
}
}
if (updateNcas.Count > 0) if (updateNcas.Count > 0)
{ {
@ -853,9 +821,9 @@ namespace Ryujinx.HLE.FileSystem
foreach (var entry in updateNcas) foreach (var entry in updateNcas)
{ {
foreach (var nca in entry.Value) foreach (var (type, path) in entry.Value)
{ {
extraNcas += nca.path + Environment.NewLine; extraNcas += path + Environment.NewLine;
} }
} }
@ -880,7 +848,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage(); IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();
Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStorage); Nca nca = new(_virtualFileSystem.KeySet, ncaStorage);
if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta) if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta)
{ {
@ -936,7 +904,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry)) if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry))
{ {
var metaNcaEntry = ncaEntry.Find(x => x.type == NcaContentType.Meta); string metaNcaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path; string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
// Nintendo in 9.0.0, removed PPC and only kept the meta nca of it. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
@ -948,10 +916,10 @@ namespace Ryujinx.HLE.FileSystem
continue; continue;
} }
IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaEntry.path, OpenMode.Read).AsStorage(); IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaPath, OpenMode.Read).AsStorage();
IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage(); IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage();
Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaStorage); Nca metaNca = new(_virtualFileSystem.KeySet, metaStorage);
IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
@ -967,11 +935,11 @@ namespace Ryujinx.HLE.FileSystem
{ {
byte[] contentData = new byte[size]; byte[] contentData = new byte[size];
Span<byte> content = new Span<byte>(contentData); Span<byte> content = new(contentData);
contentStorage.Read(0, content); contentStorage.Read(0, content);
Span<byte> hash = new Span<byte>(new byte[32]); Span<byte> hash = new(new byte[32]);
LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash); LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
@ -1017,11 +985,10 @@ namespace Ryujinx.HLE.FileSystem
{ {
if (entry.ContentType == NcaContentType.Data) if (entry.ContentType == NcaContentType.Data)
{ {
var path = _virtualFileSystem.SwitchPathToSystemPath(entry.ContentPath); var path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath);
using (FileStream fileStream = File.OpenRead(path)) using FileStream fileStream = File.OpenRead(path);
{ Nca nca = new(_virtualFileSystem.KeySet, fileStream.AsStorage());
Nca nca = new Nca(_virtualFileSystem.KeySet, fileStream.AsStorage());
if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
{ {
@ -1034,8 +1001,6 @@ namespace Ryujinx.HLE.FileSystem
return new SystemVersion(systemVersionFile.Get.AsStream()); return new SystemVersion(systemVersionFile.Get.AsStream());
} }
} }
}
} }
} }
} }

View file

@ -2,7 +2,6 @@
using LibHac.Ncm; using LibHac.Ncm;
using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration;
using System; using System;
using static Ryujinx.HLE.FileSystem.VirtualFileSystem; using static Ryujinx.HLE.FileSystem.VirtualFileSystem;
using Path = System.IO.Path; using Path = System.IO.Path;
@ -27,16 +26,16 @@ namespace Ryujinx.HLE.FileSystem
public const string Nintendo = "Nintendo"; public const string Nintendo = "Nintendo";
public const string Contents = "Contents"; public const string Contents = "Contents";
public static string GetRealPath(VirtualFileSystem fileSystem, string switchContentPath) public static string GetRealPath(string switchContentPath)
{ {
return switchContentPath switch return switchContentPath switch
{ {
SystemContent => Path.Combine(AppDataManager.BaseDirPath, SystemNandPath, Contents), SystemContent => Path.Combine(AppDataManager.BaseDirPath, SystemNandPath, Contents),
UserContent => Path.Combine(AppDataManager.BaseDirPath, UserNandPath, Contents), UserContent => Path.Combine(AppDataManager.BaseDirPath, UserNandPath, Contents),
SdCardContent => Path.Combine(fileSystem.GetSdCardPath(), Nintendo, Contents), SdCardContent => Path.Combine(GetSdCardPath(), Nintendo, Contents),
System => Path.Combine(AppDataManager.BaseDirPath, SystemNandPath), System => Path.Combine(AppDataManager.BaseDirPath, SystemNandPath),
User => Path.Combine(AppDataManager.BaseDirPath, UserNandPath), User => Path.Combine(AppDataManager.BaseDirPath, UserNandPath),
_ => throw new NotSupportedException($"Content Path \"`{switchContentPath}`\" is not supported.") _ => throw new NotSupportedException($"Content Path \"`{switchContentPath}`\" is not supported."),
}; };
} }
@ -47,7 +46,7 @@ namespace Ryujinx.HLE.FileSystem
ContentStorageId.System => SystemContent, ContentStorageId.System => SystemContent,
ContentStorageId.User => UserContent, ContentStorageId.User => UserContent,
ContentStorageId.SdCard => SdCardContent, ContentStorageId.SdCard => SdCardContent,
_ => throw new NotSupportedException($"Content Storage Id \"`{contentStorageId}`\" is not supported.") _ => throw new NotSupportedException($"Content Storage Id \"`{contentStorageId}`\" is not supported."),
}; };
} }
@ -58,7 +57,7 @@ namespace Ryujinx.HLE.FileSystem
StorageId.BuiltInSystem => SystemContent, StorageId.BuiltInSystem => SystemContent,
StorageId.BuiltInUser => UserContent, StorageId.BuiltInUser => UserContent,
StorageId.SdCard => SdCardContent, StorageId.SdCard => SdCardContent,
_ => throw new NotSupportedException($"Storage Id \"`{storageId}`\" is not supported.") _ => throw new NotSupportedException($"Storage Id \"`{storageId}`\" is not supported."),
}; };
} }
@ -75,7 +74,7 @@ namespace Ryujinx.HLE.FileSystem
GamecardApp or GamecardApp or
GamecardContents or GamecardContents or
GamecardUpdate => StorageId.GameCard, GamecardUpdate => StorageId.GameCard,
_ => StorageId.None _ => StorageId.None,
}; };
} }
} }

View file

@ -17,8 +17,7 @@ namespace Ryujinx.HLE.FileSystem
public SystemVersion(Stream systemVersionFile) public SystemVersion(Stream systemVersionFile)
{ {
using (BinaryReader reader = new BinaryReader(systemVersionFile)) using BinaryReader reader = new(systemVersionFile);
{
Major = reader.ReadByte(); Major = reader.ReadByte();
Minor = reader.ReadByte(); Minor = reader.ReadByte();
Micro = reader.ReadByte(); Micro = reader.ReadByte();
@ -37,4 +36,3 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
} }
}

View file

@ -26,9 +26,9 @@ namespace Ryujinx.HLE.FileSystem
{ {
public class VirtualFileSystem : IDisposable public class VirtualFileSystem : IDisposable
{ {
public static string SafeNandPath = Path.Combine(AppDataManager.DefaultNandDir, "safe"); public static readonly string SafeNandPath = Path.Combine(AppDataManager.DefaultNandDir, "safe");
public static string SystemNandPath = Path.Combine(AppDataManager.DefaultNandDir, "system"); public static readonly string SystemNandPath = Path.Combine(AppDataManager.DefaultNandDir, "system");
public static string UserNandPath = Path.Combine(AppDataManager.DefaultNandDir, "user"); public static readonly string UserNandPath = Path.Combine(AppDataManager.DefaultNandDir, "user");
public KeySet KeySet { get; private set; } public KeySet KeySet { get; private set; }
public EmulatedGameCard GameCard { get; private set; } public EmulatedGameCard GameCard { get; private set; }
@ -85,15 +85,15 @@ namespace Ryujinx.HLE.FileSystem
return _romFsByPid[pid]; return _romFsByPid[pid];
} }
public string GetFullPath(string basePath, string fileName) public static string GetFullPath(string basePath, string fileName)
{ {
if (fileName.StartsWith("//")) if (fileName.StartsWith("//"))
{ {
fileName = fileName.Substring(2); fileName = fileName[2..];
} }
else if (fileName.StartsWith('/')) else if (fileName.StartsWith('/'))
{ {
fileName = fileName.Substring(1); fileName = fileName[1..];
} }
else else
{ {
@ -110,10 +110,10 @@ namespace Ryujinx.HLE.FileSystem
return fullPath; return fullPath;
} }
internal string GetSdCardPath() => MakeFullPath(AppDataManager.DefaultSdcardDir); internal static string GetSdCardPath() => MakeFullPath(AppDataManager.DefaultSdcardDir);
public string GetNandPath() => MakeFullPath(AppDataManager.DefaultNandDir); public static string GetNandPath() => MakeFullPath(AppDataManager.DefaultNandDir);
public string SwitchPathToSystemPath(string switchPath) public static string SwitchPathToSystemPath(string switchPath)
{ {
string[] parts = switchPath.Split(":"); string[] parts = switchPath.Split(":");
@ -125,7 +125,7 @@ namespace Ryujinx.HLE.FileSystem
return GetFullPath(MakeFullPath(parts[0]), parts[1]); return GetFullPath(MakeFullPath(parts[0]), parts[1]);
} }
public string SystemPathToSwitchPath(string systemPath) public static string SystemPathToSwitchPath(string systemPath)
{ {
string baseSystemPath = AppDataManager.BaseDirPath + Path.DirectorySeparatorChar; string baseSystemPath = AppDataManager.BaseDirPath + Path.DirectorySeparatorChar;
@ -148,7 +148,7 @@ namespace Ryujinx.HLE.FileSystem
return null; return null;
} }
private string MakeFullPath(string path, bool isDirectory = true) private static string MakeFullPath(string path, bool isDirectory = true)
{ {
// Handles Common Switch Content Paths // Handles Common Switch Content Paths
switch (path) switch (path)
@ -185,7 +185,7 @@ namespace Ryujinx.HLE.FileSystem
public void InitializeFsServer(LibHac.Horizon horizon, out HorizonClient fsServerClient) public void InitializeFsServer(LibHac.Horizon horizon, out HorizonClient fsServerClient)
{ {
LocalFileSystem serverBaseFs = new LocalFileSystem(AppDataManager.BaseDirPath); LocalFileSystem serverBaseFs = new(AppDataManager.BaseDirPath);
fsServerClient = horizon.CreatePrivilegedHorizonClient(); fsServerClient = horizon.CreatePrivilegedHorizonClient();
var fsServer = new FileSystemServer(fsServerClient); var fsServer = new FileSystemServer(fsServerClient);
@ -207,7 +207,7 @@ namespace Ryujinx.HLE.FileSystem
DeviceOperator = fsServerObjects.DeviceOperator, DeviceOperator = fsServerObjects.DeviceOperator,
ExternalKeySet = KeySet.ExternalKeySet, ExternalKeySet = KeySet.ExternalKeySet,
FsCreators = fsServerObjects.FsCreators, FsCreators = fsServerObjects.FsCreators,
RandomGenerator = randomGenerator RandomGenerator = randomGenerator,
}; };
FileSystemServerInitializer.InitializeWithConfig(fsServerClient, fsServer, fsServerConfig); FileSystemServerInitializer.InitializeWithConfig(fsServerClient, fsServer, fsServerConfig);
@ -282,16 +282,28 @@ namespace Ryujinx.HLE.FileSystem
public static Result FixExtraData(HorizonClient hos) public static Result FixExtraData(HorizonClient hos)
{ {
Result rc = GetSystemSaveList(hos, out List<ulong> systemSaveIds); Result rc = GetSystemSaveList(hos, out List<ulong> systemSaveIds);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
rc = FixUnindexedSystemSaves(hos, systemSaveIds); rc = FixUnindexedSystemSaves(hos, systemSaveIds);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.System); rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.System);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.User); rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.User);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
return Result.Success; return Result.Success;
} }
@ -303,15 +315,23 @@ namespace Ryujinx.HLE.FileSystem
using var iterator = new UniqueRef<SaveDataIterator>(); using var iterator = new UniqueRef<SaveDataIterator>();
Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref, spaceId); Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref, spaceId);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
while (true) while (true)
{ {
rc = iterator.Get.ReadSaveDataInfo(out long count, info); rc = iterator.Get.ReadSaveDataInfo(out long count, info);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
if (count == 0) if (count == 0)
{
return Result.Success; return Result.Success;
}
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
{ {
@ -351,7 +371,9 @@ namespace Ryujinx.HLE.FileSystem
private static Result CreateSaveDataDirectory(HorizonClient hos, in SaveDataInfo info) private static Result CreateSaveDataDirectory(HorizonClient hos, in SaveDataInfo info)
{ {
if (info.SpaceId != SaveDataSpaceId.User && info.SpaceId != SaveDataSpaceId.System) if (info.SpaceId != SaveDataSpaceId.User && info.SpaceId != SaveDataSpaceId.System)
{
return Result.Success; return Result.Success;
}
const string MountName = "SaveDir"; const string MountName = "SaveDir";
var mountNameU8 = MountName.ToU8Span(); var mountNameU8 = MountName.ToU8Span();
@ -360,11 +382,15 @@ namespace Ryujinx.HLE.FileSystem
{ {
SaveDataSpaceId.System => BisPartitionId.System, SaveDataSpaceId.System => BisPartitionId.System,
SaveDataSpaceId.User => BisPartitionId.User, SaveDataSpaceId.User => BisPartitionId.User,
_ => throw new ArgumentOutOfRangeException() _ => throw new ArgumentOutOfRangeException(nameof(info), info.SpaceId, null),
}; };
Result rc = hos.Fs.MountBis(mountNameU8, partitionId); Result rc = hos.Fs.MountBis(mountNameU8, partitionId);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
try try
{ {
var path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span(); var path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span();
@ -391,28 +417,38 @@ namespace Ryujinx.HLE.FileSystem
var mountName = "system".ToU8Span(); var mountName = "system".ToU8Span();
DirectoryHandle handle = default; DirectoryHandle handle = default;
List<ulong> localList = new List<ulong>(); List<ulong> localList = new();
try try
{ {
Result rc = hos.Fs.MountBis(mountName, BisPartitionId.System); Result rc = hos.Fs.MountBis(mountName, BisPartitionId.System);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
rc = hos.Fs.OpenDirectory(out handle, "system:/save".ToU8Span(), OpenDirectoryMode.All); rc = hos.Fs.OpenDirectory(out handle, "system:/save".ToU8Span(), OpenDirectoryMode.All);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
DirectoryEntry entry = new DirectoryEntry(); DirectoryEntry entry = new();
while (true) while (true)
{ {
rc = hos.Fs.ReadDirectory(out long readCount, SpanHelpers.AsSpan(ref entry), handle); rc = hos.Fs.ReadDirectory(out long readCount, SpanHelpers.AsSpan(ref entry), handle);
if (rc.IsFailure()) return rc; if (rc.IsFailure())
{
return rc;
}
if (readCount == 0) if (readCount == 0)
{
break; break;
}
if (Utf8Parser.TryParse(entry.Name, out ulong saveDataId, out int bytesRead, 'x') && if (Utf8Parser.TryParse(entry.Name, out ulong saveDataId, out int bytesRead, 'x') && bytesRead == 16 && (long)saveDataId < 0)
bytesRead == 16 && (long)saveDataId < 0)
{ {
localList.Add(saveDataId); localList.Add(saveDataId);
} }
@ -440,7 +476,7 @@ namespace Ryujinx.HLE.FileSystem
// Only save data IDs added to SystemExtraDataFixInfo will be fixed. // Only save data IDs added to SystemExtraDataFixInfo will be fixed.
private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds) private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds)
{ {
foreach (var fixInfo in SystemExtraDataFixInfo) foreach (var fixInfo in _systemExtraDataFixInfo)
{ {
if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId)) if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId))
{ {
@ -472,7 +508,9 @@ namespace Ryujinx.HLE.FileSystem
if (!rc.IsSuccess()) if (!rc.IsSuccess())
{ {
if (!ResultFs.TargetNotFound.Includes(rc)) if (!ResultFs.TargetNotFound.Includes(rc))
{
return rc; return rc;
}
// We'll reach this point only if the save data directory exists but it's not in the save data indexer. // We'll reach this point only if the save data directory exists but it's not in the save data indexer.
// Creating the save will add it to the indexer while leaving its existing contents intact. // Creating the save will add it to the indexer while leaving its existing contents intact.
@ -492,7 +530,7 @@ namespace Ryujinx.HLE.FileSystem
OwnerId = info.OwnerId, OwnerId = info.OwnerId,
Flags = info.Flags, Flags = info.Flags,
DataSize = info.DataSize, DataSize = info.DataSize,
JournalSize = info.JournalSize JournalSize = info.JournalSize,
}; };
// Make a mask for writing the entire extra data // Make a mask for writing the entire extra data
@ -507,9 +545,11 @@ namespace Ryujinx.HLE.FileSystem
{ {
wasFixNeeded = true; wasFixNeeded = true;
Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.SpaceId, Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.SpaceId, info.SaveDataId);
info.SaveDataId); if (rc.IsFailure())
if (rc.IsFailure()) return rc; {
return rc;
}
// The extra data should have program ID or static save data ID set if it's valid. // The extra data should have program ID or static save data ID set if it's valid.
// We only try to fix the extra data if the info from the save data indexer has a program ID or static save data ID. // We only try to fix the extra data if the info from the save data indexer has a program ID or static save data ID.
@ -543,7 +583,7 @@ namespace Ryujinx.HLE.FileSystem
else else
{ {
// Try to match the system save with one of the known saves // Try to match the system save with one of the known saves
foreach (ExtraDataFixInfo fixInfo in SystemExtraDataFixInfo) foreach (ExtraDataFixInfo fixInfo in _systemExtraDataFixInfo)
{ {
if (extraData.Attribute.StaticSaveDataId == fixInfo.StaticSaveDataId) if (extraData.Attribute.StaticSaveDataId == fixInfo.StaticSaveDataId)
{ {
@ -573,7 +613,7 @@ namespace Ryujinx.HLE.FileSystem
public long JournalSize; public long JournalSize;
} }
private static readonly ExtraDataFixInfo[] SystemExtraDataFixInfo = private static readonly ExtraDataFixInfo[] _systemExtraDataFixInfo =
{ {
new ExtraDataFixInfo() new ExtraDataFixInfo()
{ {
@ -581,7 +621,7 @@ namespace Ryujinx.HLE.FileSystem
OwnerId = 0x010000000000001F, OwnerId = 0x010000000000001F,
Flags = SaveDataFlags.KeepAfterResettingSystemSaveDataWithoutUserSaveData, Flags = SaveDataFlags.KeepAfterResettingSystemSaveDataWithoutUserSaveData,
DataSize = 0x10000, DataSize = 0x10000,
JournalSize = 0x10000 JournalSize = 0x10000,
}, },
new ExtraDataFixInfo() new ExtraDataFixInfo()
{ {
@ -589,12 +629,13 @@ namespace Ryujinx.HLE.FileSystem
OwnerId = 0x0100000000001009, OwnerId = 0x0100000000001009,
Flags = SaveDataFlags.None, Flags = SaveDataFlags.None,
DataSize = 0xC000, DataSize = 0xC000,
JournalSize = 0xC000 JournalSize = 0xC000,
} },
}; };
public void Dispose() public void Dispose()
{ {
GC.SuppressFinalize(this);
Dispose(true); Dispose(true);
} }

View file

@ -8,7 +8,7 @@ namespace Ryujinx.HLE.HOS.Applets
{ {
static class AppletManager static class AppletManager
{ {
private static Dictionary<AppletId, Type> _appletMapping; private static readonly Dictionary<AppletId, Type> _appletMapping;
static AppletManager() static AppletManager()
{ {
@ -20,7 +20,7 @@ namespace Ryujinx.HLE.HOS.Applets
{ AppletId.SoftwareKeyboard, typeof(SoftwareKeyboardApplet) }, { AppletId.SoftwareKeyboard, typeof(SoftwareKeyboardApplet) },
{ AppletId.LibAppletWeb, typeof(BrowserApplet) }, { AppletId.LibAppletWeb, typeof(BrowserApplet) },
{ AppletId.LibAppletShop, typeof(BrowserApplet) }, { AppletId.LibAppletShop, typeof(BrowserApplet) },
{ AppletId.LibAppletOff, typeof(BrowserApplet) } { AppletId.LibAppletOff, typeof(BrowserApplet) },
}; };
} }

View file

@ -6,6 +6,6 @@
Offline, Offline,
Black, Black,
Share, Share,
Lobby Lobby,
} }
} }

View file

@ -13,7 +13,6 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
public event EventHandler AppletStateChanged; public event EventHandler AppletStateChanged;
private AppletSession _normalSession; private AppletSession _normalSession;
private AppletSession _interactiveSession;
private CommonArguments _commonArguments; private CommonArguments _commonArguments;
private List<BrowserArgument> _arguments; private List<BrowserArgument> _arguments;
@ -29,7 +28,6 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
public ResultCode Start(AppletSession normalSession, AppletSession interactiveSession) public ResultCode Start(AppletSession normalSession, AppletSession interactiveSession)
{ {
_normalSession = normalSession; _normalSession = normalSession;
_interactiveSession = interactiveSession;
_commonArguments = IApplet.ReadStruct<CommonArguments>(_normalSession.Pop()); _commonArguments = IApplet.ReadStruct<CommonArguments>(_normalSession.Pop());
@ -48,15 +46,16 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
if ((_commonArguments.AppletVersion >= 0x80000 && _shimKind == ShimKind.Web) || (_commonArguments.AppletVersion >= 0x30000 && _shimKind == ShimKind.Share)) if ((_commonArguments.AppletVersion >= 0x80000 && _shimKind == ShimKind.Web) || (_commonArguments.AppletVersion >= 0x30000 && _shimKind == ShimKind.Share))
{ {
List<BrowserOutput> result = new List<BrowserOutput>(); List<BrowserOutput> result = new()
{
result.Add(new BrowserOutput(BrowserOutputType.ExitReason, (uint)WebExitReason.ExitButton)); new BrowserOutput(BrowserOutputType.ExitReason, (uint)WebExitReason.ExitButton),
};
_normalSession.Push(BuildResponseNew(result)); _normalSession.Push(BuildResponseNew(result));
} }
else else
{ {
WebCommonReturnValue result = new WebCommonReturnValue() WebCommonReturnValue result = new()
{ {
ExitReason = WebExitReason.ExitButton, ExitReason = WebExitReason.ExitButton,
}; };
@ -69,25 +68,22 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
return ResultCode.Success; return ResultCode.Success;
} }
private byte[] BuildResponseOld(WebCommonReturnValue result) private static byte[] BuildResponseOld(WebCommonReturnValue result)
{
using (MemoryStream stream = MemoryStreamManager.Shared.GetStream())
using (BinaryWriter writer = new BinaryWriter(stream))
{ {
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.WriteStruct(result); writer.WriteStruct(result);
return stream.ToArray(); return stream.ToArray();
} }
}
private byte[] BuildResponseNew(List<BrowserOutput> outputArguments) private byte[] BuildResponseNew(List<BrowserOutput> outputArguments)
{ {
using (MemoryStream stream = MemoryStreamManager.Shared.GetStream()) using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
writer.WriteStruct(new WebArgHeader writer.WriteStruct(new WebArgHeader
{ {
Count = (ushort)outputArguments.Count, Count = (ushort)outputArguments.Count,
ShimKind = _shimKind ShimKind = _shimKind,
}); });
foreach (BrowserOutput output in outputArguments) foreach (BrowserOutput output in outputArguments)
@ -101,4 +97,3 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
} }
} }
} }
}

View file

@ -17,7 +17,7 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
Value = value; Value = value;
} }
private static readonly Dictionary<WebArgTLVType, Type> _typeRegistry = new Dictionary<WebArgTLVType, Type> private static readonly Dictionary<WebArgTLVType, Type> _typeRegistry = new()
{ {
{ WebArgTLVType.InitialURL, typeof(string) }, { WebArgTLVType.InitialURL, typeof(string) },
{ WebArgTLVType.CallbackUrl, typeof(string) }, { WebArgTLVType.CallbackUrl, typeof(string) },
@ -64,11 +64,11 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
public static (ShimKind, List<BrowserArgument>) ParseArguments(ReadOnlySpan<byte> data) public static (ShimKind, List<BrowserArgument>) ParseArguments(ReadOnlySpan<byte> data)
{ {
List<BrowserArgument> browserArguments = new List<BrowserArgument>(); List<BrowserArgument> browserArguments = new();
WebArgHeader header = IApplet.ReadStruct<WebArgHeader>(data.Slice(0, 8)); WebArgHeader header = IApplet.ReadStruct<WebArgHeader>(data[..8]);
ReadOnlySpan<byte> rawTLVs = data.Slice(8); ReadOnlySpan<byte> rawTLVs = data[8..];
for (int i = 0; i < header.Count; i++) for (int i = 0; i < header.Count; i++)
{ {
@ -77,7 +77,7 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
browserArguments.Add(new BrowserArgument((WebArgTLVType)tlv.Type, tlvData.ToArray())); browserArguments.Add(new BrowserArgument((WebArgTLVType)tlv.Type, tlvData.ToArray()));
rawTLVs = rawTLVs.Slice(Unsafe.SizeOf<WebArgTLV>() + tlv.Size); rawTLVs = rawTLVs[(Unsafe.SizeOf<WebArgTLV>() + tlv.Size)..];
} }
return (header.ShimKind, browserArguments); return (header.ShimKind, browserArguments);

View file

@ -38,7 +38,7 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
writer.WriteStruct(new WebArgTLV writer.WriteStruct(new WebArgTLV
{ {
Type = (ushort)Type, Type = (ushort)Type,
Size = (ushort)Value.Length Size = (ushort)Value.Length,
}); });
writer.Write(Value); writer.Write(Value);

View file

@ -9,6 +9,6 @@
PostServiceName = 0x5, PostServiceName = 0x5,
PostServiceNameSize = 0x6, PostServiceNameSize = 0x6,
PostId = 0x7, PostId = 0x7,
MediaPlayerAutoClosedByCompletion = 0x8 MediaPlayerAutoClosedByCompletion = 0x8,
} }
} }

View file

@ -4,6 +4,6 @@
{ {
OfflineHtmlPage = 1, OfflineHtmlPage = 1,
ApplicationLegalInformation, ApplicationLegalInformation,
SystemDataPage SystemDataPage,
} }
} }

View file

@ -3,6 +3,6 @@
enum LeftStickMode enum LeftStickMode
{ {
Pointer = 0, Pointer = 0,
Cursor Cursor,
} }
} }

View file

@ -8,6 +8,6 @@
Share, Share,
Web, Web,
Wifi, Wifi,
Lobby Lobby,
} }
} }

View file

@ -57,6 +57,6 @@
OverrideWebAudioVolume = 0x3F, OverrideWebAudioVolume = 0x3F,
OverrideMediaAudioVolume = 0x40, OverrideMediaAudioVolume = 0x40,
BootMode = 0x41, BootMode = 0x41,
MediaPlayerUiEnabled = 0x43 MediaPlayerUiEnabled = 0x43,
} }
} }

View file

@ -6,6 +6,6 @@
BackButton, BackButton,
Requested, Requested,
LastUrl, LastUrl,
ErrorDialog = 7 ErrorDialog = 7,
} }
} }

View file

@ -13,7 +13,7 @@ namespace Ryujinx.HLE.HOS.Applets
{ {
internal class ControllerApplet : IApplet internal class ControllerApplet : IApplet
{ {
private Horizon _system; private readonly Horizon _system;
private AppletSession _normalSession; private AppletSession _normalSession;
@ -65,7 +65,7 @@ namespace Ryujinx.HLE.HOS.Applets
} }
else else
{ {
Logger.Stub?.PrintStub(LogClass.ServiceHid, $"ControllerSupportArg Version Unknown"); Logger.Stub?.PrintStub(LogClass.ServiceHid, "ControllerSupportArg Version Unknown");
argHeader = IApplet.ReadStruct<ControllerSupportArgHeader>(controllerSupportArg); // Read just the header argHeader = IApplet.ReadStruct<ControllerSupportArgHeader>(controllerSupportArg); // Read just the header
} }
@ -82,17 +82,17 @@ namespace Ryujinx.HLE.HOS.Applets
playerMin = playerMax = 1; playerMin = playerMax = 1;
} }
int configuredCount = 0; int configuredCount;
PlayerIndex primaryIndex = PlayerIndex.Unknown; PlayerIndex primaryIndex;
while (!_system.Device.Hid.Npads.Validate(playerMin, playerMax, (ControllerType)privateArg.NpadStyleSet, out configuredCount, out primaryIndex)) while (!_system.Device.Hid.Npads.Validate(playerMin, playerMax, (ControllerType)privateArg.NpadStyleSet, out configuredCount, out primaryIndex))
{ {
ControllerAppletUiArgs uiArgs = new ControllerAppletUiArgs ControllerAppletUiArgs uiArgs = new()
{ {
PlayerCountMin = playerMin, PlayerCountMin = playerMin,
PlayerCountMax = playerMax, PlayerCountMax = playerMax,
SupportedStyles = (ControllerType)privateArg.NpadStyleSet, SupportedStyles = (ControllerType)privateArg.NpadStyleSet,
SupportedPlayers = _system.Device.Hid.Npads.GetSupportedPlayers(), SupportedPlayers = _system.Device.Hid.Npads.GetSupportedPlayers(),
IsDocked = _system.State.DockedMode IsDocked = _system.State.DockedMode,
}; };
if (!_system.Device.UiHandler.DisplayMessageDialog(uiArgs)) if (!_system.Device.UiHandler.DisplayMessageDialog(uiArgs))
@ -101,10 +101,10 @@ namespace Ryujinx.HLE.HOS.Applets
} }
} }
ControllerSupportResultInfo result = new ControllerSupportResultInfo ControllerSupportResultInfo result = new()
{ {
PlayerCount = (sbyte)configuredCount, PlayerCount = (sbyte)configuredCount,
SelectedId = (uint)GetNpadIdTypeFromIndex(primaryIndex) SelectedId = (uint)GetNpadIdTypeFromIndex(primaryIndex),
}; };
Logger.Stub?.PrintStub(LogClass.ServiceHid, $"ControllerApplet ReturnResult {result.PlayerCount} {result.SelectedId}"); Logger.Stub?.PrintStub(LogClass.ServiceHid, $"ControllerApplet ReturnResult {result.PlayerCount} {result.SelectedId}");
@ -122,26 +122,24 @@ namespace Ryujinx.HLE.HOS.Applets
return ResultCode.Success; return ResultCode.Success;
} }
private byte[] BuildResponse(ControllerSupportResultInfo result) private static byte[] BuildResponse(ControllerSupportResultInfo result)
{
using (MemoryStream stream = MemoryStreamManager.Shared.GetStream())
using (BinaryWriter writer = new BinaryWriter(stream))
{ {
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref result, Unsafe.SizeOf<ControllerSupportResultInfo>()))); writer.Write(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref result, Unsafe.SizeOf<ControllerSupportResultInfo>())));
return stream.ToArray(); return stream.ToArray();
} }
}
private byte[] BuildResponse() private static byte[] BuildResponse()
{
using (MemoryStream stream = MemoryStreamManager.Shared.GetStream())
using (BinaryWriter writer = new BinaryWriter(stream))
{ {
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write((ulong)ResultCode.Success); writer.Write((ulong)ResultCode.Success);
return stream.ToArray(); return stream.ToArray();
} }
} }
} }
}

View file

@ -2,7 +2,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Applets namespace Ryujinx.HLE.HOS.Applets
{ {
#pragma warning disable CS0649 #pragma warning disable CS0649 // Field is never assigned to
[StructLayout(LayoutKind.Sequential, Pack = 1)] [StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ControllerSupportArgHeader struct ControllerSupportArgHeader
{ {

View file

@ -1,6 +1,6 @@
namespace Ryujinx.HLE.HOS.Applets namespace Ryujinx.HLE.HOS.Applets
{ {
#pragma warning disable CS0649 #pragma warning disable CS0649 // Field is never assigned to
struct ControllerSupportArgPrivate struct ControllerSupportArgPrivate
{ {
public uint PrivateSize; public uint PrivateSize;

View file

@ -4,7 +4,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Applets namespace Ryujinx.HLE.HOS.Applets
{ {
#pragma warning disable CS0649 #pragma warning disable CS0649 // Field is never assigned to
// (8.0.0+ version) // (8.0.0+ version)
[StructLayout(LayoutKind.Sequential, Pack = 1)] [StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ControllerSupportArgV7 struct ControllerSupportArgV7

View file

@ -4,7 +4,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Applets namespace Ryujinx.HLE.HOS.Applets
{ {
#pragma warning disable CS0649 #pragma warning disable CS0649 // Field is never assigned to
// (1.0.0+ version) // (1.0.0+ version)
[StructLayout(LayoutKind.Sequential, Pack = 1)] [StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ControllerSupportArgVPre7 struct ControllerSupportArgVPre7

View file

@ -4,6 +4,6 @@ namespace Ryujinx.HLE.HOS.Applets
{ {
ShowControllerSupport = 0, ShowControllerSupport = 0,
ShowControllerStrapGuide = 1, ShowControllerStrapGuide = 1,
ShowControllerFirmwareUpdate = 2 ShowControllerFirmwareUpdate = 2,
} }
} }

View file

@ -3,7 +3,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Applets namespace Ryujinx.HLE.HOS.Applets
{ {
#pragma warning disable CS0649 #pragma warning disable CS0649 // Field is never assigned to
[StructLayout(LayoutKind.Sequential, Pack = 1)] [StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ControllerSupportResultInfo struct ControllerSupportResultInfo
{ {

View file

@ -22,7 +22,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error
{ {
private const long ErrorMessageBinaryTitleId = 0x0100000000000801; private const long ErrorMessageBinaryTitleId = 0x0100000000000801;
private Horizon _horizon; private readonly Horizon _horizon;
private AppletSession _normalSession; private AppletSession _normalSession;
private CommonArguments _commonArguments; private CommonArguments _commonArguments;
private ErrorCommonHeader _errorCommonHeader; private ErrorCommonHeader _errorCommonHeader;
@ -63,7 +63,8 @@ namespace Ryujinx.HLE.HOS.Applets.Error
break; break;
} }
default: throw new NotImplementedException($"ErrorApplet type {_errorCommonHeader.Type} is not implemented."); default:
throw new NotImplementedException($"ErrorApplet type {_errorCommonHeader.Type} is not implemented.");
} }
AppletStateChanged?.Invoke(this, null); AppletStateChanged?.Invoke(this, null);
@ -71,15 +72,16 @@ namespace Ryujinx.HLE.HOS.Applets.Error
return ResultCode.Success; return ResultCode.Success;
} }
private (uint module, uint description) HexToResultCode(uint resultCode) private static (uint module, uint description) HexToResultCode(uint resultCode)
{ {
return ((resultCode & 0x1FF) + 2000, (resultCode >> 9) & 0x3FFF); return ((resultCode & 0x1FF) + 2000, (resultCode >> 9) & 0x3FFF);
} }
private string SystemLanguageToLanguageKey(SystemLanguage systemLanguage) private static string SystemLanguageToLanguageKey(SystemLanguage systemLanguage)
{ {
return systemLanguage switch return systemLanguage switch
{ {
#pragma warning disable IDE0055 // Disable formatting
SystemLanguage.Japanese => "ja", SystemLanguage.Japanese => "ja",
SystemLanguage.AmericanEnglish => "en-US", SystemLanguage.AmericanEnglish => "en-US",
SystemLanguage.French => "fr", SystemLanguage.French => "fr",
@ -98,7 +100,8 @@ namespace Ryujinx.HLE.HOS.Applets.Error
SystemLanguage.SimplifiedChinese => "zh-Hans", SystemLanguage.SimplifiedChinese => "zh-Hans",
SystemLanguage.TraditionalChinese => "zh-Hant", SystemLanguage.TraditionalChinese => "zh-Hant",
SystemLanguage.BrazilianPortuguese => "pt-BR", SystemLanguage.BrazilianPortuguese => "pt-BR",
_ => "en-US" _ => "en-US",
#pragma warning restore IDE0055
}; };
} }
@ -111,9 +114,8 @@ namespace Ryujinx.HLE.HOS.Applets.Error
{ {
string binaryTitleContentPath = _horizon.ContentManager.GetInstalledContentPath(ErrorMessageBinaryTitleId, StorageId.BuiltInSystem, NcaContentType.Data); string binaryTitleContentPath = _horizon.ContentManager.GetInstalledContentPath(ErrorMessageBinaryTitleId, StorageId.BuiltInSystem, NcaContentType.Data);
using (LibHac.Fs.IStorage ncaFileStream = new LocalStorage(_horizon.Device.FileSystem.SwitchPathToSystemPath(binaryTitleContentPath), FileAccess.Read, FileMode.Open)) using LibHac.Fs.IStorage ncaFileStream = new LocalStorage(FileSystem.VirtualFileSystem.SwitchPathToSystemPath(binaryTitleContentPath), FileAccess.Read, FileMode.Open);
{ Nca nca = new(_horizon.Device.FileSystem.KeySet, ncaFileStream);
Nca nca = new Nca(_horizon.Device.FileSystem.KeySet, ncaFileStream);
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _horizon.FsIntegrityCheckLevel); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _horizon.FsIntegrityCheckLevel);
string languageCode = SystemLanguageToLanguageKey(_horizon.State.DesiredSystemLanguage); string languageCode = SystemLanguageToLanguageKey(_horizon.State.DesiredSystemLanguage);
string filePath = $"/{module}/{description:0000}/{languageCode}_{key}"; string filePath = $"/{module}/{description:0000}/{languageCode}_{key}";
@ -123,7 +125,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error
using var binaryFile = new UniqueRef<IFile>(); using var binaryFile = new UniqueRef<IFile>();
romfs.OpenFile(ref binaryFile.Ref, filePath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); romfs.OpenFile(ref binaryFile.Ref, filePath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
StreamReader reader = new StreamReader(binaryFile.Get.AsStream(), Encoding.Unicode); StreamReader reader = new(binaryFile.Get.AsStream(), Encoding.Unicode);
return CleanText(reader.ReadToEnd()); return CleanText(reader.ReadToEnd());
} }
@ -132,7 +134,6 @@ namespace Ryujinx.HLE.HOS.Applets.Error
return ""; return "";
} }
} }
}
private string[] GetButtonsText(uint module, uint description, string key) private string[] GetButtonsText(uint module, uint description, string key)
{ {
@ -188,7 +189,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error
string messageText = Encoding.ASCII.GetString(messageTextBuffer.TakeWhile(b => !b.Equals(0)).ToArray()); string messageText = Encoding.ASCII.GetString(messageTextBuffer.TakeWhile(b => !b.Equals(0)).ToArray());
string detailsText = Encoding.ASCII.GetString(detailsTextBuffer.TakeWhile(b => !b.Equals(0)).ToArray()); string detailsText = Encoding.ASCII.GetString(detailsTextBuffer.TakeWhile(b => !b.Equals(0)).ToArray());
List<string> buttons = new List<string>(); List<string> buttons = new();
// TODO: Handle the LanguageCode to return the translated "OK" and "Details". // TODO: Handle the LanguageCode to return the translated "OK" and "Details".

View file

@ -8,6 +8,6 @@
ErrorEulaArg, ErrorEulaArg,
ErrorPctlArg, ErrorPctlArg,
ErrorRecordArg, ErrorRecordArg,
SystemUpdateEulaArg = 8 SystemUpdateEulaArg = 8,
} }
} }

View file

@ -8,10 +8,12 @@ namespace Ryujinx.HLE.HOS.Applets
{ {
internal class PlayerSelectApplet : IApplet internal class PlayerSelectApplet : IApplet
{ {
private Horizon _system; private readonly Horizon _system;
private AppletSession _normalSession; private AppletSession _normalSession;
#pragma warning disable IDE0052 // Remove unread private member
private AppletSession _interactiveSession; private AppletSession _interactiveSession;
#pragma warning restore IDE0052
public event EventHandler AppletStateChanged; public event EventHandler AppletStateChanged;
@ -44,9 +46,9 @@ namespace Ryujinx.HLE.HOS.Applets
{ {
UserProfile currentUser = _system.AccountManager.LastOpenedUser; UserProfile currentUser = _system.AccountManager.LastOpenedUser;
using (MemoryStream stream = MemoryStreamManager.Shared.GetStream()) using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
writer.Write((ulong)PlayerSelectResult.Success); writer.Write((ulong)PlayerSelectResult.Success);
currentUser.UserId.Write(writer); currentUser.UserId.Write(writer);
@ -55,4 +57,3 @@ namespace Ryujinx.HLE.HOS.Applets
} }
} }
} }
}

View file

@ -3,6 +3,6 @@
enum PlayerSelectResult : ulong enum PlayerSelectResult : ulong
{ {
Success = 0, Success = 0,
Failure = 2 Failure = 2,
} }
} }

View file

@ -13,6 +13,6 @@
/// <summary> /// <summary>
/// Position the cursor at the end of the text /// Position the cursor at the end of the text
/// </summary> /// </summary>
End End,
} }
} }

View file

@ -43,6 +43,6 @@
/// <summary> /// <summary>
/// [8.0.0+] Request the keyboard applet to use the MovedCursorV2 response when notifying changes in cursor position. /// [8.0.0+] Request the keyboard applet to use the MovedCursorV2 response when notifying changes in cursor position.
/// </summary> /// </summary>
UseMovedCursorV2 = 0xE UseMovedCursorV2 = 0xE,
} }
} }

View file

@ -88,6 +88,6 @@
/// <summary> /// <summary>
/// Same as MovedCursorUtf8, but with additional fields. /// Same as MovedCursorUtf8, but with additional fields.
/// </summary> /// </summary>
MovedCursorUtf8V2 = 0x10 MovedCursorUtf8V2 = 0x10,
} }
} }

View file

@ -28,6 +28,6 @@
/// <summary> /// <summary>
/// software keyboard is transitioning to a hidden state because the user pressed either OK or Cancel. /// software keyboard is transitioning to a hidden state because the user pressed either OK or Cancel.
/// </summary> /// </summary>
Disappearing = 0x4 Disappearing = 0x4,
} }
} }

View file

@ -60,56 +60,52 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
{ {
uint resSize = 2 * sizeof(uint) + 0x1; uint resSize = 2 * sizeof(uint) + 0x1;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.FinishedInitialize, writer); BeginResponse(state, InlineKeyboardResponse.FinishedInitialize, writer);
writer.Write((byte)1); // Data (ignored by the program) writer.Write((byte)1); // Data (ignored by the program)
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] Default(InlineKeyboardState state) public static byte[] Default(InlineKeyboardState state)
{ {
uint resSize = 2 * sizeof(uint); uint resSize = 2 * sizeof(uint);
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.Default, writer); BeginResponse(state, InlineKeyboardResponse.Default, writer);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] ChangedString(string text, uint cursor, InlineKeyboardState state) public static byte[] ChangedString(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 6 * sizeof(uint) + MaxStrLenUTF16; uint resSize = 6 * sizeof(uint) + MaxStrLenUTF16;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.ChangedString, writer); BeginResponse(state, InlineKeyboardResponse.ChangedString, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, true); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, true);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] MovedCursor(string text, uint cursor, InlineKeyboardState state) public static byte[] MovedCursor(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 4 * sizeof(uint) + MaxStrLenUTF16; uint resSize = 4 * sizeof(uint) + MaxStrLenUTF16;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.MovedCursor, writer); BeginResponse(state, InlineKeyboardResponse.MovedCursor, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, false); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, false);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] MovedTab(string text, uint cursor, InlineKeyboardState state) public static byte[] MovedTab(string text, uint cursor, InlineKeyboardState state)
{ {
@ -117,176 +113,164 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
uint resSize = 4 * sizeof(uint) + MaxStrLenUTF16; uint resSize = 4 * sizeof(uint) + MaxStrLenUTF16;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.MovedTab, writer); BeginResponse(state, InlineKeyboardResponse.MovedTab, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, false); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, false);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] DecidedEnter(string text, InlineKeyboardState state) public static byte[] DecidedEnter(string text, InlineKeyboardState state)
{ {
uint resSize = 3 * sizeof(uint) + MaxStrLenUTF16; uint resSize = 3 * sizeof(uint) + MaxStrLenUTF16;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.DecidedEnter, writer); BeginResponse(state, InlineKeyboardResponse.DecidedEnter, writer);
WriteString(text, writer, MaxStrLenUTF16, Encoding.Unicode); WriteString(text, writer, MaxStrLenUTF16, Encoding.Unicode);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] DecidedCancel(InlineKeyboardState state) public static byte[] DecidedCancel(InlineKeyboardState state)
{ {
uint resSize = 2 * sizeof(uint); uint resSize = 2 * sizeof(uint);
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.DecidedCancel, writer); BeginResponse(state, InlineKeyboardResponse.DecidedCancel, writer);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] ChangedStringUtf8(string text, uint cursor, InlineKeyboardState state) public static byte[] ChangedStringUtf8(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 6 * sizeof(uint) + MaxStrLenUTF8; uint resSize = 6 * sizeof(uint) + MaxStrLenUTF8;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.ChangedStringUtf8, writer); BeginResponse(state, InlineKeyboardResponse.ChangedStringUtf8, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, true); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, true);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] MovedCursorUtf8(string text, uint cursor, InlineKeyboardState state) public static byte[] MovedCursorUtf8(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 4 * sizeof(uint) + MaxStrLenUTF8; uint resSize = 4 * sizeof(uint) + MaxStrLenUTF8;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.MovedCursorUtf8, writer); BeginResponse(state, InlineKeyboardResponse.MovedCursorUtf8, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, false); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, false);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] DecidedEnterUtf8(string text, InlineKeyboardState state) public static byte[] DecidedEnterUtf8(string text, InlineKeyboardState state)
{ {
uint resSize = 3 * sizeof(uint) + MaxStrLenUTF8; uint resSize = 3 * sizeof(uint) + MaxStrLenUTF8;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.DecidedEnterUtf8, writer); BeginResponse(state, InlineKeyboardResponse.DecidedEnterUtf8, writer);
WriteString(text, writer, MaxStrLenUTF8, Encoding.UTF8); WriteString(text, writer, MaxStrLenUTF8, Encoding.UTF8);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] UnsetCustomizeDic(InlineKeyboardState state) public static byte[] UnsetCustomizeDic(InlineKeyboardState state)
{ {
uint resSize = 2 * sizeof(uint); uint resSize = 2 * sizeof(uint);
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.UnsetCustomizeDic, writer); BeginResponse(state, InlineKeyboardResponse.UnsetCustomizeDic, writer);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] ReleasedUserWordInfo(InlineKeyboardState state) public static byte[] ReleasedUserWordInfo(InlineKeyboardState state)
{ {
uint resSize = 2 * sizeof(uint); uint resSize = 2 * sizeof(uint);
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.ReleasedUserWordInfo, writer); BeginResponse(state, InlineKeyboardResponse.ReleasedUserWordInfo, writer);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] UnsetCustomizedDictionaries(InlineKeyboardState state) public static byte[] UnsetCustomizedDictionaries(InlineKeyboardState state)
{ {
uint resSize = 2 * sizeof(uint); uint resSize = 2 * sizeof(uint);
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.UnsetCustomizedDictionaries, writer); BeginResponse(state, InlineKeyboardResponse.UnsetCustomizedDictionaries, writer);
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] ChangedStringV2(string text, uint cursor, InlineKeyboardState state) public static byte[] ChangedStringV2(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 6 * sizeof(uint) + MaxStrLenUTF16 + 0x1; uint resSize = 6 * sizeof(uint) + MaxStrLenUTF16 + 0x1;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.ChangedStringV2, writer); BeginResponse(state, InlineKeyboardResponse.ChangedStringV2, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, true); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, true);
writer.Write((byte)0); // Flag == 0 writer.Write((byte)0); // Flag == 0
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] MovedCursorV2(string text, uint cursor, InlineKeyboardState state) public static byte[] MovedCursorV2(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 4 * sizeof(uint) + MaxStrLenUTF16 + 0x1; uint resSize = 4 * sizeof(uint) + MaxStrLenUTF16 + 0x1;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.MovedCursorV2, writer); BeginResponse(state, InlineKeyboardResponse.MovedCursorV2, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, false); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF16, Encoding.Unicode, false);
writer.Write((byte)0); // Flag == 0 writer.Write((byte)0); // Flag == 0
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] ChangedStringUtf8V2(string text, uint cursor, InlineKeyboardState state) public static byte[] ChangedStringUtf8V2(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 6 * sizeof(uint) + MaxStrLenUTF8 + 0x1; uint resSize = 6 * sizeof(uint) + MaxStrLenUTF8 + 0x1;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.ChangedStringUtf8V2, writer); BeginResponse(state, InlineKeyboardResponse.ChangedStringUtf8V2, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, true); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, true);
writer.Write((byte)0); // Flag == 0 writer.Write((byte)0); // Flag == 0
return stream.ToArray(); return stream.ToArray();
} }
}
public static byte[] MovedCursorUtf8V2(string text, uint cursor, InlineKeyboardState state) public static byte[] MovedCursorUtf8V2(string text, uint cursor, InlineKeyboardState state)
{ {
uint resSize = 4 * sizeof(uint) + MaxStrLenUTF8 + 0x1; uint resSize = 4 * sizeof(uint) + MaxStrLenUTF8 + 0x1;
using (MemoryStream stream = new MemoryStream(new byte[resSize])) using MemoryStream stream = new(new byte[resSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
BeginResponse(state, InlineKeyboardResponse.MovedCursorUtf8V2, writer); BeginResponse(state, InlineKeyboardResponse.MovedCursorUtf8V2, writer);
WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, false); WriteStringWithCursor(text, cursor, writer, MaxStrLenUTF8, Encoding.UTF8, false);
writer.Write((byte)0); // Flag == 0 writer.Write((byte)0); // Flag == 0
@ -295,4 +279,3 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
} }
} }
} }
}

View file

@ -13,6 +13,6 @@
/// <summary> /// <summary>
/// Displays the text entry area as a multi-line field. /// Displays the text entry area as a multi-line field.
/// </summary> /// </summary>
MultiLine MultiLine,
} }
} }

View file

@ -51,6 +51,6 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
/// <summary> /// <summary>
/// Prohibits characters outside of those allowed in Mii Nicknames. /// Prohibits characters outside of those allowed in Mii Nicknames.
/// </summary> /// </summary>
Username = 1 << 8 Username = 1 << 8,
} }
} }

View file

@ -21,6 +21,6 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
DisableSeGroup = 0x4000, DisableSeGroup = 0x4000,
SetBackspaceEnabled = 0x8000, SetBackspaceEnabled = 0x8000,
AppearTrigger = 0x10000, AppearTrigger = 0x10000,
MustShow = Appear | SetInputText | AppearTrigger MustShow = Appear | SetInputText | AppearTrigger,
} }
} }

View file

@ -7,6 +7,6 @@
{ {
None = 0, None = 0,
Auto = 1, Auto = 1,
Forced = 2 Forced = 2,
} }
} }

View file

@ -13,6 +13,6 @@
/// <summary> /// <summary>
/// Hide input characters. /// Hide input characters.
/// </summary> /// </summary>
Enabled Enabled,
} }
} }

View file

@ -85,33 +85,34 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
public SoftwareKeyboardAppearEx ToExtended() public SoftwareKeyboardAppearEx ToExtended()
{ {
SoftwareKeyboardAppearEx appear = new SoftwareKeyboardAppearEx(); SoftwareKeyboardAppearEx appear = new()
{
appear.KeyboardMode = KeyboardMode; KeyboardMode = KeyboardMode,
appear.OkText = OkText; OkText = OkText,
appear.LeftOptionalSymbolKey = LeftOptionalSymbolKey; LeftOptionalSymbolKey = LeftOptionalSymbolKey,
appear.RightOptionalSymbolKey = RightOptionalSymbolKey; RightOptionalSymbolKey = RightOptionalSymbolKey,
appear.PredictionEnabled = PredictionEnabled; PredictionEnabled = PredictionEnabled,
appear.CancelButtonDisabled = CancelButtonDisabled; CancelButtonDisabled = CancelButtonDisabled,
appear.InvalidChars = InvalidChars; InvalidChars = InvalidChars,
appear.TextMaxLength = TextMaxLength; TextMaxLength = TextMaxLength,
appear.TextMinLength = TextMinLength; TextMinLength = TextMinLength,
appear.UseNewLine = UseNewLine; UseNewLine = UseNewLine,
appear.MiniaturizationMode = MiniaturizationMode; MiniaturizationMode = MiniaturizationMode,
appear.Reserved1 = Reserved1; Reserved1 = Reserved1,
appear.Reserved2 = Reserved2; Reserved2 = Reserved2,
appear.InvalidButtons = InvalidButtons; InvalidButtons = InvalidButtons,
appear.UseSaveData = UseSaveData; UseSaveData = UseSaveData,
appear.Reserved3 = Reserved3; Reserved3 = Reserved3,
appear.Reserved4 = Reserved4; Reserved4 = Reserved4,
appear.Reserved5 = Reserved5; Reserved5 = Reserved5,
appear.Uid0 = Reserved6; Uid0 = Reserved6,
appear.Uid1 = Reserved7; Uid1 = Reserved7,
appear.SamplingNumber = 0; SamplingNumber = 0,
appear.Reserved6 = 0; Reserved6 = 0,
appear.Reserved7 = 0; Reserved7 = 0,
appear.Reserved8 = 0; Reserved8 = 0,
appear.Reserved9 = 0; Reserved9 = 0,
};
return appear; return appear;
} }

View file

@ -42,9 +42,11 @@ namespace Ryujinx.HLE.HOS.Applets
private SoftwareKeyboardConfig _keyboardForegroundConfig; private SoftwareKeyboardConfig _keyboardForegroundConfig;
// Configuration for background (inline) mode. // Configuration for background (inline) mode.
#pragma warning disable IDE0052 // Remove unread private member
private SoftwareKeyboardInitialize _keyboardBackgroundInitialize; private SoftwareKeyboardInitialize _keyboardBackgroundInitialize;
private SoftwareKeyboardCustomizeDic _keyboardBackgroundDic; private SoftwareKeyboardCustomizeDic _keyboardBackgroundDic;
private SoftwareKeyboardDictSet _keyboardBackgroundDictSet; private SoftwareKeyboardDictSet _keyboardBackgroundDictSet;
#pragma warning restore IDE0052
private SoftwareKeyboardUserWord[] _keyboardBackgroundUserWords; private SoftwareKeyboardUserWord[] _keyboardBackgroundUserWords;
private byte[] _transferMemory; private byte[] _transferMemory;
@ -217,7 +219,7 @@ namespace Ryujinx.HLE.HOS.Applets
_keyboardForegroundConfig.SubmitText : "OK"), _keyboardForegroundConfig.SubmitText : "OK"),
StringLengthMin = _keyboardForegroundConfig.StringLengthMin, StringLengthMin = _keyboardForegroundConfig.StringLengthMin,
StringLengthMax = _keyboardForegroundConfig.StringLengthMax, StringLengthMax = _keyboardForegroundConfig.StringLengthMax,
InitialText = initialText InitialText = initialText,
}; };
_lastResult = _device.UiHandler.DisplayInputDialog(args, out _textValue) ? KeyboardResult.Accept : KeyboardResult.Cancel; _lastResult = _device.UiHandler.DisplayInputDialog(args, out _textValue) ? KeyboardResult.Accept : KeyboardResult.Cancel;
@ -237,7 +239,7 @@ namespace Ryujinx.HLE.HOS.Applets
// we truncate it. // we truncate it.
if (_textValue.Length > _keyboardForegroundConfig.StringLengthMax) if (_textValue.Length > _keyboardForegroundConfig.StringLengthMax)
{ {
_textValue = _textValue.Substring(0, _keyboardForegroundConfig.StringLengthMax); _textValue = _textValue[.._keyboardForegroundConfig.StringLengthMax];
} }
// Does the application want to validate the text itself? // Does the application want to validate the text itself?
@ -319,9 +321,9 @@ namespace Ryujinx.HLE.HOS.Applets
// request from the game, this is because the inline keyboard is expected to // request from the game, this is because the inline keyboard is expected to
// keep running in the background sending data by itself. // keep running in the background sending data by itself.
using (MemoryStream stream = new MemoryStream(data)) using MemoryStream stream = new(data);
using (BinaryReader reader = new BinaryReader(stream)) using BinaryReader reader = new(stream);
{
var request = (InlineKeyboardRequest)reader.ReadUInt32(); var request = (InlineKeyboardRequest)reader.ReadUInt32();
long remaining; long remaining;
@ -486,11 +488,10 @@ namespace Ryujinx.HLE.HOS.Applets
break; break;
} }
} }
}
private void ActivateFrontend() private void ActivateFrontend()
{ {
Logger.Debug?.Print(LogClass.ServiceAm, $"Activating software keyboard frontend"); Logger.Debug?.Print(LogClass.ServiceAm, "Activating software keyboard frontend");
_inputMode = KeyboardInputMode.ControllerAndKeyboard; _inputMode = KeyboardInputMode.ControllerAndKeyboard;
@ -509,7 +510,7 @@ namespace Ryujinx.HLE.HOS.Applets
private void DeactivateFrontend() private void DeactivateFrontend()
{ {
Logger.Debug?.Print(LogClass.ServiceAm, $"Deactivating software keyboard frontend"); Logger.Debug?.Print(LogClass.ServiceAm, "Deactivating software keyboard frontend");
_inputMode = KeyboardInputMode.ControllerAndKeyboard; _inputMode = KeyboardInputMode.ControllerAndKeyboard;
_canAcceptController = false; _canAcceptController = false;
@ -520,7 +521,7 @@ namespace Ryujinx.HLE.HOS.Applets
private void DestroyFrontend() private void DestroyFrontend()
{ {
Logger.Debug?.Print(LogClass.ServiceAm, $"Destroying software keyboard frontend"); Logger.Debug?.Print(LogClass.ServiceAm, "Destroying software keyboard frontend");
_keyboardRenderer?.Dispose(); _keyboardRenderer?.Dispose();
_keyboardRenderer = null; _keyboardRenderer = null;
@ -575,7 +576,7 @@ namespace Ryujinx.HLE.HOS.Applets
if (text.Length > MaxUiTextSize) if (text.Length > MaxUiTextSize)
{ {
// Limit the text size and change it back. // Limit the text size and change it back.
text = text.Substring(0, MaxUiTextSize); text = text[..MaxUiTextSize];
cursorBegin = Math.Min(cursorBegin, MaxUiTextSize); cursorBegin = Math.Min(cursorBegin, MaxUiTextSize);
cursorEnd = Math.Min(cursorEnd, MaxUiTextSize); cursorEnd = Math.Min(cursorEnd, MaxUiTextSize);
@ -734,9 +735,8 @@ namespace Ryujinx.HLE.HOS.Applets
{ {
int bufferSize = interactive ? InteractiveBufferSize : StandardBufferSize; int bufferSize = interactive ? InteractiveBufferSize : StandardBufferSize;
using (MemoryStream stream = new MemoryStream(new byte[bufferSize])) using MemoryStream stream = new(new byte[bufferSize]);
using (BinaryWriter writer = new BinaryWriter(stream)) using BinaryWriter writer = new(stream);
{
byte[] output = _encoding.GetBytes(_textValue); byte[] output = _encoding.GetBytes(_textValue);
if (!interactive) if (!interactive)
@ -762,7 +762,6 @@ namespace Ryujinx.HLE.HOS.Applets
_interactiveSession.Push(stream.ToArray()); _interactiveSession.Push(stream.ToArray());
} }
} }
}
/// <summary> /// <summary>
/// Removes all Unicode control code characters from the input string. /// Removes all Unicode control code characters from the input string.
@ -787,7 +786,7 @@ namespace Ryujinx.HLE.HOS.Applets
return string.Empty; return string.Empty;
} }
StringBuilder sb = new StringBuilder(capacity: input.Length); StringBuilder sb = new(capacity: input.Length);
foreach (char c in input) foreach (char c in input)
{ {
if (!char.IsControl(c)) if (!char.IsControl(c))

View file

@ -174,45 +174,46 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
public SoftwareKeyboardCalcEx ToExtended() public SoftwareKeyboardCalcEx ToExtended()
{ {
SoftwareKeyboardCalcEx calc = new SoftwareKeyboardCalcEx(); SoftwareKeyboardCalcEx calc = new()
{
calc.Unknown = Unknown; Unknown = Unknown,
calc.Size = Size; Size = Size,
calc.Unknown1 = Unknown1; Unknown1 = Unknown1,
calc.Unknown2 = Unknown2; Unknown2 = Unknown2,
calc.Flags = Flags; Flags = Flags,
calc.Initialize = Initialize; Initialize = Initialize,
calc.Volume = Volume; Volume = Volume,
calc.CursorPos = CursorPos; CursorPos = CursorPos,
calc.Appear = Appear.ToExtended(); Appear = Appear.ToExtended(),
calc.InputText = InputText; InputText = InputText,
calc.UseUtf8 = UseUtf8; UseUtf8 = UseUtf8,
calc.Unknown3 = Unknown3; Unknown3 = Unknown3,
calc.BackspaceEnabled = BackspaceEnabled; BackspaceEnabled = BackspaceEnabled,
calc.Unknown4 = Unknown4; Unknown4 = Unknown4,
calc.Unknown5 = Unknown5; Unknown5 = Unknown5,
calc.KeytopAsFloating = KeytopAsFloating; KeytopAsFloating = KeytopAsFloating,
calc.FooterScalable = FooterScalable; FooterScalable = FooterScalable,
calc.AlphaEnabledInInputMode = AlphaEnabledInInputMode; AlphaEnabledInInputMode = AlphaEnabledInInputMode,
calc.InputModeFadeType = InputModeFadeType; InputModeFadeType = InputModeFadeType,
calc.TouchDisabled = TouchDisabled; TouchDisabled = TouchDisabled,
calc.HardwareKeyboardDisabled = HardwareKeyboardDisabled; HardwareKeyboardDisabled = HardwareKeyboardDisabled,
calc.Unknown6 = Unknown6; Unknown6 = Unknown6,
calc.Unknown7 = Unknown7; Unknown7 = Unknown7,
calc.KeytopScale0 = KeytopScale0; KeytopScale0 = KeytopScale0,
calc.KeytopScale1 = KeytopScale1; KeytopScale1 = KeytopScale1,
calc.KeytopTranslate0 = KeytopTranslate0; KeytopTranslate0 = KeytopTranslate0,
calc.KeytopTranslate1 = KeytopTranslate1; KeytopTranslate1 = KeytopTranslate1,
calc.KeytopBgAlpha = KeytopBgAlpha; KeytopBgAlpha = KeytopBgAlpha,
calc.FooterBgAlpha = FooterBgAlpha; FooterBgAlpha = FooterBgAlpha,
calc.BalloonScale = BalloonScale; BalloonScale = BalloonScale,
calc.Unknown8 = Unknown8; Unknown8 = Unknown8,
calc.Unknown9 = Unknown9; Unknown9 = Unknown9,
calc.Unknown10 = Unknown10; Unknown10 = Unknown10,
calc.Unknown11 = Unknown11; Unknown11 = Unknown11,
calc.SeGroup = SeGroup; SeGroup = SeGroup,
calc.TriggerFlag = TriggerFlag; TriggerFlag = TriggerFlag,
calc.Trigger = Trigger; Trigger = Trigger,
};
return calc; return calc;
} }

View file

@ -15,11 +15,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private readonly object _stateLock = new(); private readonly object _stateLock = new();
private SoftwareKeyboardUiState _state = new SoftwareKeyboardUiState(); private readonly SoftwareKeyboardUiState _state = new();
private SoftwareKeyboardRendererBase _renderer; private readonly SoftwareKeyboardRendererBase _renderer;
private TimedAction _textBoxBlinkTimedAction = new TimedAction(); private readonly TimedAction _textBoxBlinkTimedAction = new();
private TimedAction _renderAction = new TimedAction(); private readonly TimedAction _renderAction = new();
public SoftwareKeyboardRenderer(IHostUiTheme uiTheme) public SoftwareKeyboardRenderer(IHostUiTheme uiTheme)
{ {
@ -47,7 +47,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private static void StartRenderer(TimedAction timedAction, SoftwareKeyboardRendererBase renderer, SoftwareKeyboardUiState state, object stateLock) private static void StartRenderer(TimedAction timedAction, SoftwareKeyboardRendererBase renderer, SoftwareKeyboardUiState state, object stateLock)
{ {
SoftwareKeyboardUiState internalState = new SoftwareKeyboardUiState(); SoftwareKeyboardUiState internalState = new();
bool canCreateSurface = false; bool canCreateSurface = false;
bool needsUpdate = true; bool needsUpdate = true;
@ -61,6 +61,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
return; return;
} }
#pragma warning disable IDE0055 // Disable formatting
needsUpdate = UpdateStateField(ref state.InputText, ref internalState.InputText); needsUpdate = UpdateStateField(ref state.InputText, ref internalState.InputText);
needsUpdate |= UpdateStateField(ref state.CursorBegin, ref internalState.CursorBegin); needsUpdate |= UpdateStateField(ref state.CursorBegin, ref internalState.CursorBegin);
needsUpdate |= UpdateStateField(ref state.CursorEnd, ref internalState.CursorEnd); needsUpdate |= UpdateStateField(ref state.CursorEnd, ref internalState.CursorEnd);
@ -70,6 +71,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
needsUpdate |= UpdateStateField(ref state.TypingEnabled, ref internalState.TypingEnabled); needsUpdate |= UpdateStateField(ref state.TypingEnabled, ref internalState.TypingEnabled);
needsUpdate |= UpdateStateField(ref state.ControllerEnabled, ref internalState.ControllerEnabled); needsUpdate |= UpdateStateField(ref state.ControllerEnabled, ref internalState.ControllerEnabled);
needsUpdate |= UpdateStateField(ref state.TextBoxBlinkCounter, ref internalState.TextBoxBlinkCounter); needsUpdate |= UpdateStateField(ref state.TextBoxBlinkCounter, ref internalState.TextBoxBlinkCounter);
#pragma warning restore IDE0055
canCreateSurface = state.SurfaceInfo != null && internalState.SurfaceInfo == null; canCreateSurface = state.SurfaceInfo != null && internalState.SurfaceInfo == null;
@ -104,14 +106,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
return false; return false;
} }
#pragma warning disable CS8632 public void UpdateTextState(string inputText, int? cursorBegin, int? cursorEnd, bool? overwriteMode, bool? typingEnabled)
public void UpdateTextState(string? inputText, int? cursorBegin, int? cursorEnd, bool? overwriteMode, bool? typingEnabled)
#pragma warning restore CS8632
{ {
lock (_stateLock) lock (_stateLock)
{ {
// Update the parameters that were provided. // Update the parameters that were provided.
_state.InputText = inputText != null ? inputText : _state.InputText; _state.InputText = inputText ?? _state.InputText;
_state.CursorBegin = cursorBegin.GetValueOrDefault(_state.CursorBegin); _state.CursorBegin = cursorBegin.GetValueOrDefault(_state.CursorBegin);
_state.CursorEnd = cursorEnd.GetValueOrDefault(_state.CursorEnd); _state.CursorEnd = cursorEnd.GetValueOrDefault(_state.CursorEnd);
_state.OverwriteMode = overwriteMode.GetValueOrDefault(_state.OverwriteMode); _state.OverwriteMode = overwriteMode.GetValueOrDefault(_state.OverwriteMode);

View file

@ -32,29 +32,29 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private Image<Argb32> _surface = null; private Image<Argb32> _surface = null;
private byte[] _bufferData = null; private byte[] _bufferData = null;
private Image _ryujinxLogo = null; private readonly Image _ryujinxLogo = null;
private Image _padAcceptIcon = null; private readonly Image _padAcceptIcon = null;
private Image _padCancelIcon = null; private readonly Image _padCancelIcon = null;
private Image _keyModeIcon = null; private readonly Image _keyModeIcon = null;
private float _textBoxOutlineWidth; private readonly float _textBoxOutlineWidth;
private float _padPressedPenWidth; private readonly float _padPressedPenWidth;
private Color _textNormalColor; private readonly Color _textNormalColor;
private Color _textSelectedColor; private readonly Color _textSelectedColor;
private Color _textOverCursorColor; private readonly Color _textOverCursorColor;
private IBrush _panelBrush; private readonly IBrush _panelBrush;
private IBrush _disabledBrush; private readonly IBrush _disabledBrush;
private IBrush _cursorBrush; private readonly IBrush _cursorBrush;
private IBrush _selectionBoxBrush; private readonly IBrush _selectionBoxBrush;
private Pen _textBoxOutlinePen; private readonly Pen _textBoxOutlinePen;
private Pen _cursorPen; private readonly Pen _cursorPen;
private Pen _selectionBoxPen; private readonly Pen _selectionBoxPen;
private Pen _padPressedPen; private readonly Pen _padPressedPen;
private int _inputTextFontSize; private readonly int _inputTextFontSize;
private Font _messageFont; private Font _messageFont;
private Font _inputTextFont; private Font _inputTextFont;
private Font _labelsTextFont; private Font _labelsTextFont;
@ -111,13 +111,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
{ {
// Try a list of fonts in case any of them is not available in the system. // Try a list of fonts in case any of them is not available in the system.
string[] availableFonts = new string[] string[] availableFonts = {
{
uiThemeFontFamily, uiThemeFontFamily,
"Liberation Sans", "Liberation Sans",
"FreeSans", "FreeSans",
"DejaVu Sans", "DejaVu Sans",
"Lucida Grande" "Lucida Grande",
}; };
foreach (string fontFamily in availableFonts) foreach (string fontFamily in availableFonts)
@ -138,7 +137,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
throw new Exception($"None of these fonts were found in the system: {String.Join(", ", availableFonts)}!"); throw new Exception($"None of these fonts were found in the system: {String.Join(", ", availableFonts)}!");
} }
private Color ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false) private static Color ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false)
{ {
var a = (byte)(color.A * 255); var a = (byte)(color.A * 255);
var r = (byte)(color.R * 255); var r = (byte)(color.R * 255);
@ -155,14 +154,14 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
return Color.FromRgba(r, g, b, overrideAlpha.GetValueOrDefault(a)); return Color.FromRgba(r, g, b, overrideAlpha.GetValueOrDefault(a));
} }
private Image LoadResource(Assembly assembly, string resourcePath, int newWidth, int newHeight) private static Image LoadResource(Assembly assembly, string resourcePath, int newWidth, int newHeight)
{ {
Stream resourceStream = assembly.GetManifestResourceStream(resourcePath); Stream resourceStream = assembly.GetManifestResourceStream(resourcePath);
return LoadResource(resourceStream, newWidth, newHeight); return LoadResource(resourceStream, newWidth, newHeight);
} }
private Image LoadResource(Stream resourceStream, int newWidth, int newHeight) private static Image LoadResource(Stream resourceStream, int newWidth, int newHeight)
{ {
Debug.Assert(resourceStream != null); Debug.Assert(resourceStream != null);
@ -176,7 +175,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
return image; return image;
} }
private void SetGraphicsOptions(IImageProcessingContext context) private static void SetGraphicsOptions(IImageProcessingContext context)
{ {
context.GetGraphicsOptions().Antialias = true; context.GetGraphicsOptions().Antialias = true;
context.GetShapeGraphicsOptions().GraphicsOptions.Antialias = true; context.GetShapeGraphicsOptions().GraphicsOptions.Antialias = true;
@ -200,7 +199,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
float halfWidth = _panelRectangle.Width / 2; float halfWidth = _panelRectangle.Width / 2;
float buttonsY = _panelRectangle.Y + 185; float buttonsY = _panelRectangle.Y + 185;
PointF disableButtonPosition = new PointF(halfWidth + 180, buttonsY); PointF disableButtonPosition = new(halfWidth + 180, buttonsY);
DrawControllerToggle(context, disableButtonPosition); DrawControllerToggle(context, disableButtonPosition);
}); });
@ -240,9 +239,9 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
float halfWidth = _panelRectangle.Width / 2; float halfWidth = _panelRectangle.Width / 2;
float buttonsY = _panelRectangle.Y + 185; float buttonsY = _panelRectangle.Y + 185;
PointF acceptButtonPosition = new PointF(halfWidth - 180, buttonsY); PointF acceptButtonPosition = new(halfWidth - 180, buttonsY);
PointF cancelButtonPosition = new PointF(halfWidth , buttonsY); PointF cancelButtonPosition = new(halfWidth, buttonsY);
PointF disableButtonPosition = new PointF(halfWidth + 180, buttonsY); PointF disableButtonPosition = new(halfWidth + 180, buttonsY);
DrawPadButton(context, acceptButtonPosition, _padAcceptIcon, AcceptText, state.AcceptPressed, state.ControllerEnabled); DrawPadButton(context, acceptButtonPosition, _padAcceptIcon, AcceptText, state.AcceptPressed, state.ControllerEnabled);
DrawPadButton(context, cancelButtonPosition, _padCancelIcon, CancelText, state.CancelPressed, state.ControllerEnabled); DrawPadButton(context, cancelButtonPosition, _padCancelIcon, CancelText, state.CancelPressed, state.ControllerEnabled);
@ -294,7 +293,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
} }
private static RectangleF MeasureString(string text, Font font) private static RectangleF MeasureString(string text, Font font)
{ {
RendererOptions options = new RendererOptions(font); RendererOptions options = new(font);
if (text == "") if (text == "")
{ {
@ -310,7 +309,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private static RectangleF MeasureString(ReadOnlySpan<char> text, Font font) private static RectangleF MeasureString(ReadOnlySpan<char> text, Font font)
{ {
RendererOptions options = new RendererOptions(font); RendererOptions options = new(font);
if (text == "") if (text == "")
{ {
@ -332,9 +331,9 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
float boxY = _panelRectangle.Y + 110; float boxY = _panelRectangle.Y + 110;
float boxX = (int)((_panelRectangle.Width - boxWidth) / 2); float boxX = (int)((_panelRectangle.Width - boxWidth) / 2);
RectangleF boxRectangle = new RectangleF(boxX, boxY, boxWidth, boxHeight); RectangleF boxRectangle = new(boxX, boxY, boxWidth, boxHeight);
RectangleF boundRectangle = new RectangleF(_panelRectangle.X, boxY - _textBoxOutlineWidth, RectangleF boundRectangle = new(_panelRectangle.X, boxY - _textBoxOutlineWidth,
_panelRectangle.Width, boxHeight + 2 * _textBoxOutlineWidth); _panelRectangle.Width, boxHeight + 2 * _textBoxOutlineWidth);
context.Fill(_panelBrush, boundRectangle); context.Fill(_panelBrush, boundRectangle);
@ -431,8 +430,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
if (cursorWidth == 0) if (cursorWidth == 0)
{ {
PointF[] points = new PointF[] PointF[] points = {
{
new PointF(cursorPositionXLeft, cursorPositionYTop), new PointF(cursorPositionXLeft, cursorPositionYTop),
new PointF(cursorPositionXLeft, cursorPositionYBottom), new PointF(cursorPositionXLeft, cursorPositionYBottom),
}; };
@ -446,7 +444,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
context.Draw(cursorPen, cursorRectangle); context.Draw(cursorPen, cursorRectangle);
context.Fill(cursorBrush, cursorRectangle); context.Fill(cursorBrush, cursorRectangle);
Image<Argb32> textOverCursor = new Image<Argb32>((int)cursorRectangle.Width, (int)cursorRectangle.Height); Image<Argb32> textOverCursor = new((int)cursorRectangle.Width, (int)cursorRectangle.Height);
textOverCursor.Mutate(context => textOverCursor.Mutate(context =>
{ {
var textRelativePosition = new PointF(inputTextPosition.X - cursorRectangle.X, inputTextPosition.Y - cursorRectangle.Y); var textRelativePosition = new PointF(inputTextPosition.X - cursorRectangle.X, inputTextPosition.Y - cursorRectangle.Y);

View file

@ -23,6 +23,6 @@
/// <summary> /// <summary>
/// swkbd has completed. /// swkbd has completed.
/// </summary> /// </summary>
Complete Complete,
} }
} }

View file

@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS
break; break;
default: default:
throw new ArgumentOutOfRangeException(); throw new InvalidOperationException($"{nameof(mode)} contains an invalid value: {mode}");
} }
} }

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ArraySubscriptingExpression : BaseNode public class ArraySubscriptingExpression : BaseNode
{ {
private BaseNode _leftNode; private readonly BaseNode _leftNode;
private BaseNode _subscript; private readonly BaseNode _subscript;
public ArraySubscriptingExpression(BaseNode leftNode, BaseNode subscript) : base(NodeType.ArraySubscriptingExpression) public ArraySubscriptingExpression(BaseNode leftNode, BaseNode subscript) : base(NodeType.ArraySubscriptingExpression)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ArrayType : BaseNode public class ArrayType : BaseNode
{ {
private BaseNode _base; private readonly BaseNode _base;
private BaseNode _dimensionExpression; private readonly BaseNode _dimensionExpression;
private string _dimensionString; private readonly string _dimensionString;
public ArrayType(BaseNode Base, BaseNode dimensionExpression = null) : base(NodeType.ArrayType) public ArrayType(BaseNode Base, BaseNode dimensionExpression = null) : base(NodeType.ArrayType)
{ {
@ -46,9 +46,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
writer.Write(_dimensionString); writer.Write(_dimensionString);
} }
else if (_dimensionExpression != null) else
{ {
_dimensionExpression.Print(writer); _dimensionExpression?.Print(writer);
} }
writer.Write("]"); writer.Write("]");

View file

@ -55,7 +55,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
ConversionOperatorType, ConversionOperatorType,
LocalName, LocalName,
CtorVtableSpecialName, CtorVtableSpecialName,
ArrayType ArrayType,
} }
public abstract class BaseNode public abstract class BaseNode
@ -103,7 +103,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override string ToString() public override string ToString()
{ {
StringWriter writer = new StringWriter(); StringWriter writer = new();
Print(writer); Print(writer);

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class BinaryExpression : BaseNode public class BinaryExpression : BaseNode
{ {
private BaseNode _leftPart; private readonly BaseNode _leftPart;
private string _name; private readonly string _name;
private BaseNode _rightPart; private readonly BaseNode _rightPart;
public BinaryExpression(BaseNode leftPart, string name, BaseNode rightPart) : base(NodeType.BinaryExpression) public BinaryExpression(BaseNode leftPart, string name, BaseNode rightPart) : base(NodeType.BinaryExpression)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class BracedExpression : BaseNode public class BracedExpression : BaseNode
{ {
private BaseNode _element; private readonly BaseNode _element;
private BaseNode _expression; private readonly BaseNode _expression;
private bool _isArrayExpression; private readonly bool _isArrayExpression;
public BracedExpression(BaseNode element, BaseNode expression, bool isArrayExpression) : base(NodeType.BracedExpression) public BracedExpression(BaseNode element, BaseNode expression, bool isArrayExpression) : base(NodeType.BracedExpression)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class BracedRangeExpression : BaseNode public class BracedRangeExpression : BaseNode
{ {
private BaseNode _firstNode; private readonly BaseNode _firstNode;
private BaseNode _lastNode; private readonly BaseNode _lastNode;
private BaseNode _expression; private readonly BaseNode _expression;
public BracedRangeExpression(BaseNode firstNode, BaseNode lastNode, BaseNode expression) : base(NodeType.BracedRangeExpression) public BracedRangeExpression(BaseNode firstNode, BaseNode lastNode, BaseNode expression) : base(NodeType.BracedRangeExpression)
{ {

View file

@ -5,7 +5,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class CallExpression : NodeArray public class CallExpression : NodeArray
{ {
private BaseNode _callee; private readonly BaseNode _callee;
public CallExpression(BaseNode callee, List<BaseNode> nodes) : base(nodes, NodeType.CallExpression) public CallExpression(BaseNode callee, List<BaseNode> nodes) : base(nodes, NodeType.CallExpression)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class CastExpression : BaseNode public class CastExpression : BaseNode
{ {
private string _kind; private readonly string _kind;
private BaseNode _to; private readonly BaseNode _to;
private BaseNode _from; private readonly BaseNode _from;
public CastExpression(string kind, BaseNode to, BaseNode from) : base(NodeType.CastExpression) public CastExpression(string kind, BaseNode to, BaseNode from) : base(NodeType.CastExpression)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ConditionalExpression : BaseNode public class ConditionalExpression : BaseNode
{ {
private BaseNode _thenNode; private readonly BaseNode _thenNode;
private BaseNode _elseNode; private readonly BaseNode _elseNode;
private BaseNode _conditionNode; private readonly BaseNode _conditionNode;
public ConditionalExpression(BaseNode conditionNode, BaseNode thenNode, BaseNode elseNode) : base(NodeType.ConditionalExpression) public ConditionalExpression(BaseNode conditionNode, BaseNode thenNode, BaseNode elseNode) : base(NodeType.ConditionalExpression)
{ {

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ConversionExpression : BaseNode public class ConversionExpression : BaseNode
{ {
private BaseNode _typeNode; private readonly BaseNode _typeNode;
private BaseNode _expressions; private readonly BaseNode _expressions;
public ConversionExpression(BaseNode typeNode, BaseNode expressions) : base(NodeType.ConversionExpression) public ConversionExpression(BaseNode typeNode, BaseNode expressions) : base(NodeType.ConversionExpression)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class CtorDtorNameType : ParentNode public class CtorDtorNameType : ParentNode
{ {
private bool _isDestructor; private readonly bool _isDestructor;
public CtorDtorNameType(BaseNode name, bool isDestructor) : base(NodeType.CtorDtorNameType, name) public CtorDtorNameType(BaseNode name, bool isDestructor) : base(NodeType.CtorDtorNameType, name)
{ {

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class CtorVtableSpecialName : BaseNode public class CtorVtableSpecialName : BaseNode
{ {
private BaseNode _firstType; private readonly BaseNode _firstType;
private BaseNode _secondType; private readonly BaseNode _secondType;
public CtorVtableSpecialName(BaseNode firstType, BaseNode secondType) : base(NodeType.CtorVtableSpecialName) public CtorVtableSpecialName(BaseNode firstType, BaseNode secondType) : base(NodeType.CtorVtableSpecialName)
{ {

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class DeleteExpression : ParentNode public class DeleteExpression : ParentNode
{ {
private bool _isGlobal; private readonly bool _isGlobal;
private bool _isArrayExpression; private readonly bool _isArrayExpression;
public DeleteExpression(BaseNode child, bool isGlobal, bool isArrayExpression) : base(NodeType.DeleteExpression, child) public DeleteExpression(BaseNode child, bool isGlobal, bool isArrayExpression) : base(NodeType.DeleteExpression, child)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ElaboratedType : ParentNode public class ElaboratedType : ParentNode
{ {
private string _elaborated; private readonly string _elaborated;
public ElaboratedType(string elaborated, BaseNode type) : base(NodeType.ElaboratedType, type) public ElaboratedType(string elaborated, BaseNode type) : base(NodeType.ElaboratedType, type)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class EnclosedExpression : BaseNode public class EnclosedExpression : BaseNode
{ {
private string _prefix; private readonly string _prefix;
private BaseNode _expression; private readonly BaseNode _expression;
private string _postfix; private readonly string _postfix;
public EnclosedExpression(string prefix, BaseNode expression, string postfix) : base(NodeType.EnclosedExpression) public EnclosedExpression(string prefix, BaseNode expression, string postfix) : base(NodeType.EnclosedExpression)
{ {

View file

@ -4,12 +4,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class EncodedFunction : BaseNode public class EncodedFunction : BaseNode
{ {
private BaseNode _name; private readonly BaseNode _name;
private BaseNode _params; private readonly BaseNode _params;
private BaseNode _cv; private readonly BaseNode _cv;
private BaseNode _ref; private readonly BaseNode _ref;
private BaseNode _attrs; private readonly BaseNode _attrs;
private BaseNode _ret; private readonly BaseNode _ret;
public EncodedFunction(BaseNode name, BaseNode Params, BaseNode cv, BaseNode Ref, BaseNode attrs, BaseNode ret) : base(NodeType.NameType) public EncodedFunction(BaseNode name, BaseNode Params, BaseNode cv, BaseNode Ref, BaseNode attrs, BaseNode ret) : base(NodeType.NameType)
{ {
@ -45,33 +45,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintRight(TextWriter writer) public override void PrintRight(TextWriter writer)
{ {
writer.Write("("); writer.Write("(");
_params?.Print(writer);
if (_params != null)
{
_params.Print(writer);
}
writer.Write(")"); writer.Write(")");
_ret?.PrintRight(writer);
if (_ret != null) _cv?.Print(writer);
{ _ref?.Print(writer);
_ret.PrintRight(writer); _attrs?.Print(writer);
}
if (_cv != null)
{
_cv.Print(writer);
}
if (_ref != null)
{
_ref.Print(writer);
}
if (_attrs != null)
{
_attrs.Print(writer);
}
} }
} }
} }

View file

@ -4,10 +4,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class FoldExpression : BaseNode public class FoldExpression : BaseNode
{ {
private bool _isLeftFold; private readonly bool _isLeftFold;
private string _operatorName; private readonly string _operatorName;
private BaseNode _expression; private readonly BaseNode _expression;
private BaseNode _initializer; private readonly BaseNode _initializer;
public FoldExpression(bool isLeftFold, string operatorName, BaseNode expression, BaseNode initializer) : base(NodeType.FunctionParameter) public FoldExpression(bool isLeftFold, string operatorName, BaseNode expression, BaseNode initializer) : base(NodeType.FunctionParameter)
{ {

View file

@ -6,7 +6,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
// TODO: Compute inside the Demangler // TODO: Compute inside the Demangler
public BaseNode Reference; public BaseNode Reference;
private int _index; #pragma warning disable IDE0052 // Remove unread private member
private readonly int _index;
#pragma warning restore IDE0052
public ForwardTemplateReference(int index) : base(NodeType.ForwardTemplateReference) public ForwardTemplateReference(int index) : base(NodeType.ForwardTemplateReference)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class FunctionParameter : BaseNode public class FunctionParameter : BaseNode
{ {
private string _number; private readonly string _number;
public FunctionParameter(string number) : base(NodeType.FunctionParameter) public FunctionParameter(string number) : base(NodeType.FunctionParameter)
{ {

View file

@ -4,11 +4,11 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class FunctionType : BaseNode public class FunctionType : BaseNode
{ {
private BaseNode _returnType; private readonly BaseNode _returnType;
private BaseNode _params; private readonly BaseNode _params;
private BaseNode _cvQualifier; private readonly BaseNode _cvQualifier;
private SimpleReferenceType _referenceQualifier; private readonly SimpleReferenceType _referenceQualifier;
private BaseNode _exceptionSpec; private readonly BaseNode _exceptionSpec;
public FunctionType(BaseNode returnType, BaseNode Params, BaseNode cvQualifier, SimpleReferenceType referenceQualifier, BaseNode exceptionSpec) : base(NodeType.FunctionType) public FunctionType(BaseNode returnType, BaseNode Params, BaseNode cvQualifier, SimpleReferenceType referenceQualifier, BaseNode exceptionSpec) : base(NodeType.FunctionType)
{ {

View file

@ -5,8 +5,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class InitListExpression : BaseNode public class InitListExpression : BaseNode
{ {
private BaseNode _typeNode; private readonly BaseNode _typeNode;
private List<BaseNode> _nodes; private readonly List<BaseNode> _nodes;
public InitListExpression(BaseNode typeNode, List<BaseNode> nodes) : base(NodeType.InitListExpression) public InitListExpression(BaseNode typeNode, List<BaseNode> nodes) : base(NodeType.InitListExpression)
{ {
@ -16,10 +16,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintLeft(TextWriter writer) public override void PrintLeft(TextWriter writer)
{ {
if (_typeNode != null) _typeNode?.Print(writer);
{
_typeNode.Print(writer);
}
writer.Write("{"); writer.Write("{");
writer.Write(string.Join<BaseNode>(", ", _nodes.ToArray())); writer.Write(string.Join<BaseNode>(", ", _nodes.ToArray()));

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class IntegerCastExpression : ParentNode public class IntegerCastExpression : ParentNode
{ {
private string _number; private readonly string _number;
public IntegerCastExpression(BaseNode type, string number) : base(NodeType.IntegerCastExpression, type) public IntegerCastExpression(BaseNode type, string number) : base(NodeType.IntegerCastExpression, type)
{ {

View file

@ -5,8 +5,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class IntegerLiteral : BaseNode public class IntegerLiteral : BaseNode
{ {
private string _literalName; private readonly string _literalName;
private string _literalValue; private readonly string _literalValue;
public IntegerLiteral(string literalName, string literalValue) : base(NodeType.IntegerLiteral) public IntegerLiteral(string literalName, string literalValue) : base(NodeType.IntegerLiteral)
{ {

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class LocalName : BaseNode public class LocalName : BaseNode
{ {
private BaseNode _encoding; private readonly BaseNode _encoding;
private BaseNode _entity; private readonly BaseNode _entity;
public LocalName(BaseNode encoding, BaseNode entity) : base(NodeType.LocalName) public LocalName(BaseNode encoding, BaseNode entity) : base(NodeType.LocalName)
{ {

View file

@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class MemberExpression : BaseNode public class MemberExpression : BaseNode
{ {
private BaseNode _leftNode; private readonly BaseNode _leftNode;
private string _kind; private readonly string _kind;
private BaseNode _rightNode; private readonly BaseNode _rightNode;
public MemberExpression(BaseNode leftNode, string kind, BaseNode rightNode) : base(NodeType.MemberExpression) public MemberExpression(BaseNode leftNode, string kind, BaseNode rightNode) : base(NodeType.MemberExpression)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class NameType : BaseNode public class NameType : BaseNode
{ {
private string _nameValue; private readonly string _nameValue;
public NameType(string nameValue, NodeType type) : base(type) public NameType(string nameValue, NodeType type) : base(type)
{ {

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class NameTypeWithTemplateArguments : BaseNode public class NameTypeWithTemplateArguments : BaseNode
{ {
private BaseNode _prev; private readonly BaseNode _prev;
private BaseNode _templateArgument; private readonly BaseNode _templateArgument;
public NameTypeWithTemplateArguments(BaseNode prev, BaseNode templateArgument) : base(NodeType.NameTypeWithTemplateArguments) public NameTypeWithTemplateArguments(BaseNode prev, BaseNode templateArgument) : base(NodeType.NameTypeWithTemplateArguments)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class NestedName : ParentNode public class NestedName : ParentNode
{ {
private BaseNode _name; private readonly BaseNode _name;
public NestedName(BaseNode name, BaseNode type) : base(NodeType.NestedName, type) public NestedName(BaseNode name, BaseNode type) : base(NodeType.NestedName, type)
{ {

View file

@ -4,12 +4,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class NewExpression : BaseNode public class NewExpression : BaseNode
{ {
private NodeArray _expressions; private readonly NodeArray _expressions;
private BaseNode _typeNode; private readonly BaseNode _typeNode;
private NodeArray _initializers; private readonly NodeArray _initializers;
private bool _isGlobal; private readonly bool _isGlobal;
private bool _isArrayExpression; private readonly bool _isArrayExpression;
public NewExpression(NodeArray expressions, BaseNode typeNode, NodeArray initializers, bool isGlobal, bool isArrayExpression) : base(NodeType.NewExpression) public NewExpression(NodeArray expressions, BaseNode typeNode, NodeArray initializers, bool isGlobal, bool isArrayExpression) : base(NodeType.NewExpression)
{ {

View file

@ -8,11 +8,11 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintLeft(TextWriter writer) public override void PrintLeft(TextWriter writer)
{ {
if (Child is PackedTemplateParameter) if (Child is PackedTemplateParameter parameter)
{ {
if (((PackedTemplateParameter)Child).Nodes.Count != 0) if (parameter.Nodes.Count != 0)
{ {
Child.Print(writer); parameter.Print(writer);
} }
} }
else else

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class PointerType : BaseNode public class PointerType : BaseNode
{ {
private BaseNode _child; private readonly BaseNode _child;
public PointerType(BaseNode child) : base(NodeType.PointerType) public PointerType(BaseNode child) : base(NodeType.PointerType)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class PostfixExpression : ParentNode public class PostfixExpression : ParentNode
{ {
private string _operator; private readonly string _operator;
public PostfixExpression(BaseNode type, string Operator) : base(NodeType.PostfixExpression, type) public PostfixExpression(BaseNode type, string Operator) : base(NodeType.PostfixExpression, type)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class PostfixQualifiedType : ParentNode public class PostfixQualifiedType : ParentNode
{ {
private string _postfixQualifier; private readonly string _postfixQualifier;
public PostfixQualifiedType(string postfixQualifier, BaseNode type) : base(NodeType.PostfixQualifiedType, type) public PostfixQualifiedType(string postfixQualifier, BaseNode type) : base(NodeType.PostfixQualifiedType, type)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class PrefixExpression : ParentNode public class PrefixExpression : ParentNode
{ {
private string _prefix; private readonly string _prefix;
public PrefixExpression(string prefix, BaseNode child) : base(NodeType.PrefixExpression, child) public PrefixExpression(string prefix, BaseNode child) : base(NodeType.PrefixExpression, child)
{ {

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class QualifiedName : BaseNode public class QualifiedName : BaseNode
{ {
private BaseNode _qualifier; private readonly BaseNode _qualifier;
private BaseNode _name; private readonly BaseNode _name;
public QualifiedName(BaseNode qualifier, BaseNode name) : base(NodeType.QualifiedName) public QualifiedName(BaseNode qualifier, BaseNode name) : base(NodeType.QualifiedName)
{ {

View file

@ -7,14 +7,14 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
None, None,
Const, Const,
Volatile, Volatile,
Restricted = 4 Restricted = 4,
} }
public enum Reference public enum Reference
{ {
None, None,
RValue, RValue,
LValue LValue,
} }
public class CvType : ParentNode public class CvType : ParentNode
@ -46,10 +46,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintLeft(TextWriter writer) public override void PrintLeft(TextWriter writer)
{ {
if (Child != null) Child?.PrintLeft(writer);
{
Child.PrintLeft(writer);
}
PrintQualifier(writer); PrintQualifier(writer);
} }
@ -61,10 +58,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintRight(TextWriter writer) public override void PrintRight(TextWriter writer)
{ {
if (Child != null) Child?.PrintRight(writer);
{
Child.PrintRight(writer);
}
} }
} }
@ -111,10 +105,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintRight(TextWriter writer) public override void PrintRight(TextWriter writer)
{ {
if (Child != null) Child?.PrintRight(writer);
{
Child.PrintRight(writer);
}
} }
} }
} }

View file

@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ReferenceType : BaseNode public class ReferenceType : BaseNode
{ {
private string _reference; private readonly string _reference;
private BaseNode _child; private readonly BaseNode _child;
public ReferenceType(string reference, BaseNode child) : base(NodeType.ReferenceType) public ReferenceType(string reference, BaseNode child) : base(NodeType.ReferenceType)
{ {

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class SpecialName : ParentNode public class SpecialName : ParentNode
{ {
private string _specialValue; private readonly string _specialValue;
public SpecialName(string specialValue, BaseNode type) : base(NodeType.SpecialName, type) public SpecialName(string specialValue, BaseNode type) : base(NodeType.SpecialName, type)
{ {

View file

@ -14,7 +14,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
IOStream IOStream
} }
private SpecialType _specialSubstitutionKey; private readonly SpecialType _specialSubstitutionKey;
public SpecialSubstitution(SpecialType specialSubstitutionKey) : base(NodeType.SpecialSubstitution) public SpecialSubstitution(SpecialType specialSubstitutionKey) : base(NodeType.SpecialSubstitution)
{ {
@ -54,23 +54,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
private string GetExtendedName() private string GetExtendedName()
{ {
switch (_specialSubstitutionKey) return _specialSubstitutionKey switch
{ {
case SpecialType.Allocator: SpecialType.Allocator => "std::allocator",
return "std::allocator"; SpecialType.BasicString => "std::basic_string",
case SpecialType.BasicString: SpecialType.String => "std::basic_string<char, std::char_traits<char>, std::allocator<char> >",
return "std::basic_string"; SpecialType.IStream => "std::basic_istream<char, std::char_traits<char> >",
case SpecialType.String: SpecialType.OStream => "std::basic_ostream<char, std::char_traits<char> >",
return "std::basic_string<char, std::char_traits<char>, std::allocator<char> >"; SpecialType.IOStream => "std::basic_iostream<char, std::char_traits<char> >",
case SpecialType.IStream: _ => null,
return "std::basic_istream<char, std::char_traits<char> >"; };
case SpecialType.OStream:
return "std::basic_ostream<char, std::char_traits<char> >";
case SpecialType.IOStream:
return "std::basic_iostream<char, std::char_traits<char> >";
}
return null;
} }
public override void PrintLeft(TextWriter writer) public override void PrintLeft(TextWriter writer)

View file

@ -9,13 +9,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
public override void PrintLeft(TextWriter writer) public override void PrintLeft(TextWriter writer)
{ {
string Params = string.Join<BaseNode>(", ", Nodes.ToArray()); string paramsString = string.Join<BaseNode>(", ", Nodes.ToArray());
writer.Write("<"); writer.Write("<");
writer.Write(Params); writer.Write(paramsString);
if (Params.EndsWith('>')) if (paramsString.EndsWith('>'))
{ {
writer.Write(" "); writer.Write(" ");
} }

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ThrowExpression : BaseNode public class ThrowExpression : BaseNode
{ {
private BaseNode _expression; private readonly BaseNode _expression;
public ThrowExpression(BaseNode expression) : base(NodeType.ThrowExpression) public ThrowExpression(BaseNode expression) : base(NodeType.ThrowExpression)
{ {

View file

@ -8,16 +8,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{ {
class Demangler class Demangler
{ {
private static readonly string Base36 = "0123456789abcdefghijklmnopqrstuvwxyz"; private static readonly string _base36 = "0123456789abcdefghijklmnopqrstuvwxyz";
private List<BaseNode> _substitutionList = new List<BaseNode>(); private readonly List<BaseNode> _substitutionList = new();
private List<BaseNode> _templateParamList = new List<BaseNode>(); private List<BaseNode> _templateParamList = new();
private List<ForwardTemplateReference> _forwardTemplateReferenceList = new List<ForwardTemplateReference>(); private readonly List<ForwardTemplateReference> _forwardTemplateReferenceList = new();
public string Mangled { get; private set; } public string Mangled { get; private set; }
private int _position; private int _position;
private int _length; private readonly int _length;
private bool _canForwardTemplateReference; private bool _canForwardTemplateReference;
private bool _canParseTemplateArgs; private bool _canParseTemplateArgs;
@ -87,7 +87,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
for (int i = 0; i < reversedEncoded.Length; i++) for (int i = 0; i < reversedEncoded.Length; i++)
{ {
int value = Base36.IndexOf(reversedEncoded[i]); int value = _base36.IndexOf(reversedEncoded[i]);
if (value == -1) if (value == -1)
{ {
return -1; return -1;
@ -274,7 +274,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
} }
else if (ConsumeIf("Dw")) else if (ConsumeIf("Dw"))
{ {
List<BaseNode> types = new List<BaseNode>(); List<BaseNode> types = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
@ -308,7 +308,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
} }
Reference referenceQualifier = Reference.None; Reference referenceQualifier = Reference.None;
List<BaseNode> Params = new List<BaseNode>(); List<BaseNode> paramsList = new();
while (true) while (true)
{ {
@ -339,10 +339,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
} }
Params.Add(type); paramsList.Add(type);
} }
return new FunctionType(returnType, new NodeArray(Params), new CvType(cvQualifiers, null), new SimpleReferenceType(referenceQualifier, null), exceptionSpec); return new FunctionType(returnType, new NodeArray(paramsList), new CvType(cvQualifiers, null), new SimpleReferenceType(referenceQualifier, null), exceptionSpec);
} }
// <array-type> ::= A <positive dimension number> _ <element type> // <array-type> ::= A <positive dimension number> _ <element type>
@ -416,12 +416,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
private BaseNode ParseType(NameParserContext context = null) private BaseNode ParseType(NameParserContext context = null)
{ {
// Temporary context // Temporary context
if (context == null) context ??= new NameParserContext();
{
context = new NameParserContext();
}
BaseNode result = null; BaseNode result;
switch (Peek()) switch (Peek())
{ {
case 'r': case 'r':
@ -545,8 +542,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
case 'h': case 'h':
_position += 2; _position += 2;
// FIXME: GNU c++flit returns this but that is not what is supposed to be returned. // FIXME: GNU c++flit returns this but that is not what is supposed to be returned.
return new NameType("half"); return new NameType("half"); // return new NameType("decimal16");
// return new NameType("decimal16");
case 'i': case 'i':
_position += 2; _position += 2;
return new NameType("char32_t"); return new NameType("char32_t");
@ -559,8 +555,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
case 'n': case 'n':
_position += 2; _position += 2;
// FIXME: GNU c++flit returns this but that is not what is supposed to be returned. // FIXME: GNU c++flit returns this but that is not what is supposed to be returned.
return new NameType("decltype(nullptr)"); return new NameType("decltype(nullptr)"); // return new NameType("std::nullptr_t");
// return new NameType("std::nullptr_t");
case 't': case 't':
case 'T': case 'T':
_position += 2; _position += 2;
@ -882,7 +877,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new SimpleReferenceType(result, null); return new SimpleReferenceType(result, null);
} }
private BaseNode CreateNameNode(BaseNode prev, BaseNode name, NameParserContext context) private static BaseNode CreateNameNode(BaseNode prev, BaseNode name, NameParserContext context)
{ {
BaseNode result = name; BaseNode result = name;
if (prev != null) if (prev != null)
@ -1327,9 +1322,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// ::= D2 # base object destructor // ::= D2 # base object destructor
private BaseNode ParseCtorDtorName(NameParserContext context, BaseNode prev) private BaseNode ParseCtorDtorName(NameParserContext context, BaseNode prev)
{ {
if (prev.Type == NodeType.SpecialSubstitution && prev is SpecialSubstitution) if (prev.Type == NodeType.SpecialSubstitution && prev is SpecialSubstitution substitution)
{ {
((SpecialSubstitution)prev).SetExtended(); substitution.SetExtended();
} }
if (ConsumeIf("C")) if (ConsumeIf("C"))
@ -1445,7 +1440,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position++; _position++;
string operatorName = null; string operatorName;
switch (PeekString(0, 2)) switch (PeekString(0, 2))
{ {
@ -1567,9 +1562,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
if (isLeftFold && initializer != null) if (isLeftFold && initializer != null)
{ {
BaseNode temp = expression; (initializer, expression) = (expression, initializer);
expression = initializer;
initializer = temp;
} }
return new FoldExpression(isLeftFold, operatorName, new PackedTemplateParameterExpansion(expression), initializer); return new FoldExpression(isLeftFold, operatorName, new PackedTemplateParameterExpansion(expression), initializer);
@ -1595,7 +1588,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
} }
List<BaseNode> expressions = new List<BaseNode>(); List<BaseNode> expressions = new();
if (ConsumeIf("_")) if (ConsumeIf("_"))
{ {
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
@ -1737,8 +1730,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
} }
List<BaseNode> expressions = new List<BaseNode>(); List<BaseNode> expressions = new();
List<BaseNode> initializers = new List<BaseNode>(); List<BaseNode> initializers = new();
while (!ConsumeIf("_")) while (!ConsumeIf("_"))
{ {
@ -1824,7 +1817,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
private BaseNode ParseExpression() private BaseNode ParseExpression()
{ {
bool isGlobal = ConsumeIf("gs"); bool isGlobal = ConsumeIf("gs");
BaseNode expression = null; BaseNode expression;
if (Count() < 2) if (Count() < 2)
{ {
return null; return null;
@ -1906,7 +1899,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
} }
List<BaseNode> names = new List<BaseNode>(); List<BaseNode> names = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
expression = ParseExpression(); expression = ParseExpression();
@ -1929,8 +1922,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
} }
return null; return null;
case 'd': case 'd':
BaseNode leftNode = null; BaseNode leftNode;
BaseNode rightNode = null; BaseNode rightNode;
switch (Peek(1)) switch (Peek(1))
{ {
case 'a': case 'a':
@ -2055,7 +2048,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
case 'l': case 'l':
_position += 2; _position += 2;
List<BaseNode> bracedExpressions = new List<BaseNode>(); List<BaseNode> bracedExpressions = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
expression = ParseBracedExpression(); expression = ParseBracedExpression();
@ -2310,7 +2303,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new EnclosedExpression("sizeof (", expression, ")"); return new EnclosedExpression("sizeof (", expression, ")");
case 'Z': case 'Z':
_position += 2; _position += 2;
BaseNode sizeofParamNode = null; BaseNode sizeofParamNode;
switch (Peek()) switch (Peek())
{ {
case 'T': case 'T':
@ -2334,7 +2327,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
case 'P': case 'P':
_position += 2; _position += 2;
List<BaseNode> arguments = new List<BaseNode>(); List<BaseNode> arguments = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
BaseNode argument = ParseTemplateArgument(); BaseNode argument = ParseTemplateArgument();
@ -2375,7 +2368,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
} }
List<BaseNode> bracedExpressions = new List<BaseNode>(); List<BaseNode> bracedExpressions = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
expression = ParseBracedExpression(); expression = ParseBracedExpression();
@ -2582,7 +2575,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
if (_canForwardTemplateReference) if (_canForwardTemplateReference)
{ {
ForwardTemplateReference forwardTemplateReference = new ForwardTemplateReference(index); ForwardTemplateReference forwardTemplateReference = new(index);
_forwardTemplateReferenceList.Add(forwardTemplateReference); _forwardTemplateReferenceList.Add(forwardTemplateReference);
return forwardTemplateReference; return forwardTemplateReference;
} }
@ -2607,12 +2600,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_templateParamList.Clear(); _templateParamList.Clear();
} }
List<BaseNode> args = new List<BaseNode>(); List<BaseNode> args = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
if (hasContext) if (hasContext)
{ {
List<BaseNode> templateParamListTemp = new List<BaseNode>(_templateParamList); List<BaseNode> templateParamListTemp = new(_templateParamList);
BaseNode templateArgument = ParseTemplateArgument(); BaseNode templateArgument = ParseTemplateArgument();
_templateParamList = templateParamListTemp; _templateParamList = templateParamListTemp;
if (templateArgument == null) if (templateArgument == null)
@ -2666,7 +2659,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// J <template-arg>* E // J <template-arg>* E
case 'J': case 'J':
_position++; _position++;
List<BaseNode> templateArguments = new List<BaseNode>(); List<BaseNode> templateArguments = new();
while (!ConsumeIf("E")) while (!ConsumeIf("E"))
{ {
BaseNode templateArgument = ParseTemplateArgument(); BaseNode templateArgument = ParseTemplateArgument();
@ -2976,7 +2969,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
} }
BaseNode result = null; BaseNode result = null;
CvType cv = new CvType(ParseCvQualifiers(), null); CvType cv = new(ParseCvQualifiers(), null);
if (context != null) if (context != null)
{ {
context.Cv = cv; context.Cv = cv;
@ -3269,7 +3262,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// ::= <special-name> // ::= <special-name>
private BaseNode ParseEncoding() private BaseNode ParseEncoding()
{ {
NameParserContext context = new NameParserContext(); NameParserContext context = new();
if (Peek() == 'T' || (Peek() == 'G' && Peek(1) == 'V')) if (Peek() == 'T' || (Peek() == 'G' && Peek(1) == 'V'))
{ {
return ParseSpecialName(context); return ParseSpecialName(context);
@ -3305,7 +3298,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new EncodedFunction(name, null, context.Cv, context.Ref, null, returnType); return new EncodedFunction(name, null, context.Cv, context.Ref, null, returnType);
} }
List<BaseNode> Params = new List<BaseNode>(); List<BaseNode> paramsList = new();
// backup because that can be destroyed by parseType // backup because that can be destroyed by parseType
CvType cv = context.Cv; CvType cv = context.Cv;
@ -3319,10 +3312,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null; return null;
} }
Params.Add(param); paramsList.Add(param);
} }
return new EncodedFunction(name, new NodeArray(Params), cv, Ref, null, returnType); return new EncodedFunction(name, new NodeArray(paramsList), cv, Ref, null, returnType);
} }
// <mangled-name> ::= _Z <encoding> // <mangled-name> ::= _Z <encoding>
@ -3351,12 +3344,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
public static string Parse(string originalMangled) public static string Parse(string originalMangled)
{ {
Demangler instance = new Demangler(originalMangled); Demangler instance = new(originalMangled);
BaseNode resNode = instance.Parse(); BaseNode resNode = instance.Parse();
if (resNode != null) if (resNode != null)
{ {
StringWriter writer = new StringWriter(); StringWriter writer = new();
resNode.Print(writer); resNode.Print(writer);
return writer.ToString(); return writer.ToString();
} }

View file

@ -5,8 +5,8 @@ namespace Ryujinx.HLE.HOS
{ {
class HomebrewRomFsStream : Stream class HomebrewRomFsStream : Stream
{ {
private Stream _baseStream; private readonly Stream _baseStream;
private long _positionOffset; private readonly long _positionOffset;
public HomebrewRomFsStream(Stream baseStream, long positionOffset) public HomebrewRomFsStream(Stream baseStream, long positionOffset)
{ {

View file

@ -10,7 +10,6 @@ using Ryujinx.Audio.Integration;
using Ryujinx.Audio.Output; using Ryujinx.Audio.Output;
using Ryujinx.Audio.Renderer.Device; using Ryujinx.Audio.Renderer.Device;
using Ryujinx.Audio.Renderer.Server; using Ryujinx.Audio.Renderer.Server;
using Ryujinx.Common.Utilities;
using Ryujinx.Cpu; using Ryujinx.Cpu;
using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.HOS.Kernel; using Ryujinx.HLE.HOS.Kernel;
@ -42,7 +41,6 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using TimeSpanType = Ryujinx.HLE.HOS.Services.Time.Clock.TimeSpanType;
namespace Ryujinx.HLE.HOS namespace Ryujinx.HLE.HOS
{ {
@ -155,11 +153,11 @@ namespace Ryujinx.HLE.HOS
ulong timePa = region.Address + HidSize + FontSize + IirsSize; ulong timePa = region.Address + HidSize + FontSize + IirsSize;
ulong appletCaptureBufferPa = region.Address + HidSize + FontSize + IirsSize + TimeSize; ulong appletCaptureBufferPa = region.Address + HidSize + FontSize + IirsSize + TimeSize;
KPageList hidPageList = new KPageList(); KPageList hidPageList = new();
KPageList fontPageList = new KPageList(); KPageList fontPageList = new();
KPageList iirsPageList = new KPageList(); KPageList iirsPageList = new();
KPageList timePageList = new KPageList(); KPageList timePageList = new();
KPageList appletCaptureBufferPageList = new KPageList(); KPageList appletCaptureBufferPageList = new();
hidPageList.AddRange(hidPa, HidSize / KPageTableBase.PageSize); hidPageList.AddRange(hidPa, HidSize / KPageTableBase.PageSize);
fontPageList.AddRange(fontPa, FontSize / KPageTableBase.PageSize); fontPageList.AddRange(fontPa, FontSize / KPageTableBase.PageSize);
@ -179,7 +177,7 @@ namespace Ryujinx.HLE.HOS
FontSharedMem = new KSharedMemory(KernelContext, fontStorage, 0, 0, KMemoryPermission.Read); FontSharedMem = new KSharedMemory(KernelContext, fontStorage, 0, 0, KMemoryPermission.Read);
IirsSharedMem = new KSharedMemory(KernelContext, iirsStorage, 0, 0, KMemoryPermission.Read); IirsSharedMem = new KSharedMemory(KernelContext, iirsStorage, 0, 0, KMemoryPermission.Read);
KSharedMemory timeSharedMemory = new KSharedMemory(KernelContext, timeStorage, 0, 0, KMemoryPermission.Read); KSharedMemory timeSharedMemory = new(KernelContext, timeStorage, 0, 0, KMemoryPermission.Read);
TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, timeStorage, TimeSize); TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, timeStorage, TimeSize);
@ -203,7 +201,7 @@ namespace Ryujinx.HLE.HOS
// We hardcode a clock source id to avoid it changing between each start. // We hardcode a clock source id to avoid it changing between each start.
// TODO: use set:sys (and get external clock source id from settings) // TODO: use set:sys (and get external clock source id from settings)
// TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate. // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
UInt128 clockSourceId = new UInt128(0x36a0328702ce8bc1, 0x1608eaba02333284); UInt128 clockSourceId = new(0x36a0328702ce8bc1, 0x1608eaba02333284);
IRtcManager.GetExternalRtcValue(out ulong rtcValue); IRtcManager.GetExternalRtcValue(out ulong rtcValue);
// We assume the rtc is system time. // We assume the rtc is system time.
@ -212,7 +210,7 @@ namespace Ryujinx.HLE.HOS
// Configure and setup internal offset // Configure and setup internal offset
TimeSpanType internalOffset = TimeSpanType.FromSeconds(device.Configuration.SystemTimeOffset); TimeSpanType internalOffset = TimeSpanType.FromSeconds(device.Configuration.SystemTimeOffset);
TimeSpanType systemTimeOffset = new TimeSpanType(systemTime.NanoSeconds + internalOffset.NanoSeconds); TimeSpanType systemTimeOffset = new(systemTime.NanoSeconds + internalOffset.NanoSeconds);
if (systemTime.IsDaylightSavingTime() && !systemTimeOffset.IsDaylightSavingTime()) if (systemTime.IsDaylightSavingTime() && !systemTimeOffset.IsDaylightSavingTime())
{ {
@ -232,7 +230,7 @@ namespace Ryujinx.HLE.HOS
if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes)) if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
{ {
TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000); TimeSpanType standardNetworkClockSufficientAccuracy = new((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);
// The network system clock needs a valid system clock, as such we setup this system clock using the local system clock. // The network system clock needs a valid system clock, as such we setup this system clock using the local system clock.
TimeServiceManager.Instance.SetupStandardNetworkSystemClock(localSytemClockContext, standardNetworkClockSufficientAccuracy); TimeServiceManager.Instance.SetupStandardNetworkSystemClock(localSytemClockContext, standardNetworkClockSufficientAccuracy);
@ -267,7 +265,7 @@ namespace Ryujinx.HLE.HOS
for (int i = 0; i < audioOutputRegisterBufferEvents.Length; i++) for (int i = 0; i < audioOutputRegisterBufferEvents.Length; i++)
{ {
KEvent registerBufferEvent = new KEvent(KernelContext); KEvent registerBufferEvent = new(KernelContext);
audioOutputRegisterBufferEvents[i] = new AudioKernelEvent(registerBufferEvent); audioOutputRegisterBufferEvents[i] = new AudioKernelEvent(registerBufferEvent);
} }
@ -279,7 +277,7 @@ namespace Ryujinx.HLE.HOS
for (int i = 0; i < audioInputRegisterBufferEvents.Length; i++) for (int i = 0; i < audioInputRegisterBufferEvents.Length; i++)
{ {
KEvent registerBufferEvent = new KEvent(KernelContext); KEvent registerBufferEvent = new(KernelContext);
audioInputRegisterBufferEvents[i] = new AudioKernelEvent(registerBufferEvent); audioInputRegisterBufferEvents[i] = new AudioKernelEvent(registerBufferEvent);
} }
@ -290,7 +288,7 @@ namespace Ryujinx.HLE.HOS
for (int i = 0; i < systemEvents.Length; i++) for (int i = 0; i < systemEvents.Length; i++)
{ {
KEvent systemEvent = new KEvent(KernelContext); KEvent systemEvent = new(KernelContext);
systemEvents[i] = new AudioKernelEvent(systemEvent); systemEvents[i] = new AudioKernelEvent(systemEvent);
} }
@ -338,16 +336,15 @@ namespace Ryujinx.HLE.HOS
ProcessCreationFlags.Is64Bit | ProcessCreationFlags.Is64Bit |
ProcessCreationFlags.PoolPartitionSystem; ProcessCreationFlags.PoolPartitionSystem;
ProcessCreationInfo creationInfo = new ProcessCreationInfo("Service", 1, 0, 0x8000000, 1, Flags, 0, 0); ProcessCreationInfo creationInfo = new("Service", 1, 0, 0x8000000, 1, Flags, 0, 0);
uint[] defaultCapabilities = new uint[] uint[] defaultCapabilities = {
{
0x030363F7, 0x030363F7,
0x1FFFFFCF, 0x1FFFFFCF,
0x207FFFEF, 0x207FFFEF,
0x47E0060F, 0x47E0060F,
0x0048BFFF, 0x0048BFFF,
0x01007FFF 0x01007FFF,
}; };
// TODO: // TODO:
@ -445,6 +442,7 @@ namespace Ryujinx.HLE.HOS
public void Dispose() public void Dispose()
{ {
GC.SuppressFinalize(this);
Dispose(true); Dispose(true);
} }
@ -464,8 +462,8 @@ namespace Ryujinx.HLE.HOS
AudioRendererManager.StopSendingCommands(); AudioRendererManager.StopSendingCommands();
} }
KProcess terminationProcess = new KProcess(KernelContext); KProcess terminationProcess = new(KernelContext);
KThread terminationThread = new KThread(KernelContext); KThread terminationThread = new(KernelContext);
terminationThread.Initialize(0, 0, 0, 3, 0, terminationProcess, ThreadType.Kernel, () => terminationThread.Initialize(0, 0, 0, 3, 0, terminationProcess, ThreadType.Kernel, () =>
{ {

View file

@ -6,7 +6,7 @@ namespace Ryujinx.HLE.HOS
{ {
class IdDictionary class IdDictionary
{ {
private ConcurrentDictionary<int, object> _objs; private readonly ConcurrentDictionary<int, object> _objs;
public ICollection<object> Values => _objs.Values; public ICollection<object> Values => _objs.Values;
@ -45,12 +45,12 @@ namespace Ryujinx.HLE.HOS
public T GetData<T>(int id) public T GetData<T>(int id)
{ {
if (_objs.TryGetValue(id, out object data) && data is T) if (_objs.TryGetValue(id, out object dataObject) && dataObject is T data)
{ {
return (T)data; return data;
} }
return default(T); return default;
} }
public object Delete(int id) public object Delete(int id)

View file

@ -2,7 +2,6 @@ using Microsoft.IO;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Memory; using Ryujinx.Common.Memory;
using System; using System;
using System.Buffers;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
@ -38,9 +37,9 @@ namespace Ryujinx.HLE.HOS.Ipc
public IpcMessage(ReadOnlySpan<byte> data, long cmdPtr) public IpcMessage(ReadOnlySpan<byte> data, long cmdPtr)
{ {
using (RecyclableMemoryStream ms = MemoryStreamManager.Shared.GetStream(data)) using RecyclableMemoryStream ms = MemoryStreamManager.Shared.GetStream(data);
{
BinaryReader reader = new BinaryReader(ms); BinaryReader reader = new(ms);
int word0 = reader.ReadInt32(); int word0 = reader.ReadInt32();
int word1 = reader.ReadInt32(); int word1 = reader.ReadInt32();
@ -70,7 +69,7 @@ namespace Ryujinx.HLE.HOS.Ipc
static List<IpcBuffDesc> ReadBuff(BinaryReader reader, int count) static List<IpcBuffDesc> ReadBuff(BinaryReader reader, int count)
{ {
List<IpcBuffDesc> buff = new List<IpcBuffDesc>(count); List<IpcBuffDesc> buff = new(count);
for (int index = 0; index < count; index++) for (int index = 0; index < count; index++)
{ {
@ -125,7 +124,6 @@ namespace Ryujinx.HLE.HOS.Ipc
ObjectIds = new List<int>(0); ObjectIds = new List<int>(0);
} }
}
public RecyclableMemoryStream GetStream(long cmdPtr, ulong recvListAddr) public RecyclableMemoryStream GetStream(long cmdPtr, ulong recvListAddr)
{ {
@ -238,7 +236,7 @@ namespace Ryujinx.HLE.HOS.Ipc
return ms; return ms;
} }
private long GetPadSize16(long position) private static long GetPadSize16(long position)
{ {
if ((position & 0xf) != 0) if ((position & 0xf) != 0)
{ {

View file

@ -8,6 +8,6 @@ namespace Ryujinx.HLE.HOS.Ipc
CmifControl = 5, CmifControl = 5,
CmifRequestWithContext = 6, CmifRequestWithContext = 6,
CmifControlWithContext = 7, CmifControlWithContext = 7,
TipcCloseSession = 0xF TipcCloseSession = 0xF,
} }
} }

View file

@ -30,12 +30,12 @@ namespace Ryujinx.HLE.HOS.Ipc
Size = (ushort)(word0 >> 16); Size = (ushort)(word0 >> 16);
} }
public IpcPtrBuffDesc WithSize(ulong size) public readonly IpcPtrBuffDesc WithSize(ulong size)
{ {
return new IpcPtrBuffDesc(Position, Index, size); return new IpcPtrBuffDesc(Position, Index, size);
} }
public uint GetWord0() public readonly uint GetWord0()
{ {
uint word0; uint word0;
@ -50,7 +50,7 @@ namespace Ryujinx.HLE.HOS.Ipc
return word0; return word0;
} }
public uint GetWord1() public readonly uint GetWord1()
{ {
return (uint)Position; return (uint)Position;
} }

View file

@ -1,5 +1,3 @@
using System.IO;
namespace Ryujinx.HLE.HOS.Ipc namespace Ryujinx.HLE.HOS.Ipc
{ {
struct IpcRecvListBuffDesc struct IpcRecvListBuffDesc

View file

@ -30,7 +30,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
MemoryArrange.MemoryArrange4GiBAppletDev => 2048 * MiB, MemoryArrange.MemoryArrange4GiBAppletDev => 2048 * MiB,
MemoryArrange.MemoryArrange6GiB or MemoryArrange.MemoryArrange6GiB or
MemoryArrange.MemoryArrange8GiB => 4916 * MiB, MemoryArrange.MemoryArrange8GiB => 4916 * MiB,
_ => throw new ArgumentException($"Invalid memory arrange \"{arrange}\".") _ => throw new ArgumentException($"Invalid memory arrange \"{arrange}\"."),
}; };
} }
@ -44,7 +44,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
MemoryArrange.MemoryArrange6GiB => 562 * MiB, MemoryArrange.MemoryArrange6GiB => 562 * MiB,
MemoryArrange.MemoryArrange6GiBAppletDev or MemoryArrange.MemoryArrange6GiBAppletDev or
MemoryArrange.MemoryArrange8GiB => 2193 * MiB, MemoryArrange.MemoryArrange8GiB => 2193 * MiB,
_ => throw new ArgumentException($"Invalid memory arrange \"{arrange}\".") _ => throw new ArgumentException($"Invalid memory arrange \"{arrange}\"."),
}; };
} }
@ -71,7 +71,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
MemorySize.MemorySize4GiB => 4 * GiB, MemorySize.MemorySize4GiB => 4 * GiB,
MemorySize.MemorySize6GiB => 6 * GiB, MemorySize.MemorySize6GiB => 6 * GiB,
MemorySize.MemorySize8GiB => 8 * GiB, MemorySize.MemorySize8GiB => 8 * GiB,
_ => throw new ArgumentException($"Invalid memory size \"{size}\".") _ => throw new ArgumentException($"Invalid memory size \"{size}\"."),
}; };
} }
} }

View file

@ -36,9 +36,9 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
_waitingObjects = new List<WaitingObject>(); _waitingObjects = new List<WaitingObject>();
_keepRunning = true; _keepRunning = true;
Thread work = new Thread(WaitAndCheckScheduledObjects) Thread work = new(WaitAndCheckScheduledObjects)
{ {
Name = "HLE.TimeManager" Name = "HLE.TimeManager",
}; };
work.Start(); work.Start();
@ -83,7 +83,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
private void WaitAndCheckScheduledObjects() private void WaitAndCheckScheduledObjects()
{ {
SpinWait spinWait = new SpinWait(); SpinWait spinWait = new();
WaitingObject next; WaitingObject next;
using (_waitEvent = new AutoResetEvent(false)) using (_waitEvent = new AutoResetEvent(false))

View file

@ -22,7 +22,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
public static void InitializeResourceLimit(KResourceLimit resourceLimit, MemorySize size) public static void InitializeResourceLimit(KResourceLimit resourceLimit, MemorySize size)
{ {
void EnsureSuccess(Result result) static void EnsureSuccess(Result result)
{ {
if (result != Result.Success) if (result != Result.Success)
{ {
@ -72,12 +72,12 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
servicePool = new MemoryRegion(DramMemoryMap.SlabHeapEnd, servicePoolSize); servicePool = new MemoryRegion(DramMemoryMap.SlabHeapEnd, servicePoolSize);
return new KMemoryRegionManager[] return new[]
{ {
GetMemoryRegion(applicationPool), GetMemoryRegion(applicationPool),
GetMemoryRegion(appletPool), GetMemoryRegion(appletPool),
GetMemoryRegion(servicePool), GetMemoryRegion(servicePool),
GetMemoryRegion(nvServicesPool) GetMemoryRegion(nvServicesPool),
}; };
} }

View file

@ -8,6 +8,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Common
TransferMemory = 3, TransferMemory = 3,
Session = 4, Session = 4,
Count = 5 Count = 5,
} }
} }

Some files were not shown because too many files have changed in this diff Show more