From caa2bb28a3c14f71cb531b4bc94971ed00f975bb Mon Sep 17 00:00:00 2001 From: CuteCat233 Date: Wed, 4 Nov 2026 10:42:32 +0800 Subject: [PATCH 01/11] Upgrade to .NET 10 Upgrade to .NET 10, Upgrade packages, Fix Bugs --- .github/workflows/build.yml | 2 +- .github/workflows/package.yml | 12 +- Stardrop/App.axaml | 6 +- Stardrop/App.axaml.cs | 24 +- Stardrop/Converters/EnumConverter.cs | 10 +- Stardrop/Converters/EnumEqualsConverter.cs | 2 +- Stardrop/Models/Config.cs | 6 +- Stardrop/Models/Data/ClientData.cs | 10 +- Stardrop/Models/Data/CollectionInstall.cs | 40 +- Stardrop/Models/Data/CollectionUpdatePlan.cs | 23 +- Stardrop/Models/Data/Enums/ModUpdateState.cs | 9 + Stardrop/Models/Data/ModInstallData.cs | 2 +- Stardrop/Models/Data/ModKeyInfo.cs | 8 +- Stardrop/Models/Data/ModReference.cs | 14 +- Stardrop/Models/Data/ModUpdateInfo.cs | 6 +- Stardrop/Models/Data/PairedKeys.cs | 6 +- Stardrop/Models/Data/RichText.cs | 9 +- Stardrop/Models/Data/UpdateCache.cs | 2 +- Stardrop/Models/Mod.cs | 136 +-- .../Converters/FlexibleNumberConverter.cs | 8 +- Stardrop/Models/Nexus/NexusUser.cs | 4 +- Stardrop/Models/Nexus/Web/ModFiles.cs | 2 +- Stardrop/Models/Nexus/Web/NXM.cs | 7 +- Stardrop/Models/Nexus/Web/Validate.cs | 8 +- Stardrop/Models/Profile.cs | 14 +- Stardrop/Models/ProfileExternal.cs | 2 +- .../SMAPI/Converters/BooleanConverter.cs | 4 +- .../Converters/BooleanConverterAssumeTrue.cs | 4 +- .../SMAPI/Converters/ModKeyConverter.cs | 4 +- Stardrop/Models/SMAPI/GameDetails.cs | 8 +- Stardrop/Models/SMAPI/Manifest.cs | 16 +- .../Models/SMAPI/ManifestContentPackFor.cs | 4 +- Stardrop/Models/SMAPI/ManifestDependency.cs | 17 +- Stardrop/Models/SMAPI/Web/ModEntry.cs | 8 +- Stardrop/Models/SMAPI/Web/ModEntryMetadata.cs | 10 +- Stardrop/Models/SMAPI/Web/ModEntryVersion.cs | 8 +- Stardrop/Models/SMAPI/Web/ModSearchData.cs | 18 +- Stardrop/Models/SMAPI/Web/ModSearchEntry.cs | 12 +- Stardrop/Models/Settings.cs | 20 +- Stardrop/Models/Theme.cs | 2 +- Stardrop/Program.cs | 170 ++-- .../FolderProfile - Linux.pubxml | 2 +- .../FolderProfile - MacOS.pubxml | 2 +- .../FolderProfile - Windows.pubxml | 2 +- Stardrop/Stardrop.csproj | 31 +- .../Utilities/Extension/ColumnExtensions.cs | 4 - .../Utilities/Extension/TranslateExtension.cs | 10 +- Stardrop/Utilities/External/GitHub.cs | 28 +- Stardrop/Utilities/External/NexusClient.cs | 88 +- .../External/NexusClientCollections.cs | 38 +- Stardrop/Utilities/External/SMAPI.cs | 27 +- Stardrop/Utilities/Helper.cs | 18 +- .../Utilities/Internal/CollectionCache.cs | 6 +- .../Internal/CollectionReferenceMatcher.cs | 47 +- .../Utilities/Internal/HyperlinkParser.cs | 47 +- Stardrop/Utilities/Internal/ManifestParser.cs | 14 +- Stardrop/Utilities/Internal/ThemeManager.cs | 4 +- Stardrop/Utilities/JsonTools.cs | 2 +- Stardrop/Utilities/NXMProtocol.cs | 52 +- Stardrop/Utilities/NexusWebsocket.cs | 2 +- Stardrop/Utilities/Pathing.cs | 26 +- Stardrop/Utilities/SimpleObscure.cs | 35 +- Stardrop/Utilities/Toolkit.cs | 14 +- Stardrop/Utilities/Translation.cs | 39 +- Stardrop/ViewLocator.cs | 9 +- .../ViewModels/ChangelogWindowViewModel.cs | 18 +- .../ViewModels/CollectionsWindowViewModel.cs | 46 +- Stardrop/ViewModels/DownloadPanelViewModel.cs | 56 +- .../FlexibleOptionWindowViewModel.cs | 10 +- Stardrop/ViewModels/MainWindowViewModel.cs | 215 +++-- Stardrop/ViewModels/MessageWindowViewModel.cs | 8 +- .../ViewModels/MissingModsWindowViewModel.cs | 10 +- Stardrop/ViewModels/ModDownloadViewModel.cs | 31 +- Stardrop/ViewModels/ProfileEditorViewModel.cs | 18 +- .../ProfileExportWindowViewModel.cs | 4 +- .../ViewModels/SettingsWindowViewModel.cs | 64 +- Stardrop/ViewModels/ViewModelBase.cs | 2 +- Stardrop/ViewModels/WarningWindowViewModel.cs | 8 +- Stardrop/Views/BaseWindow.axaml.cs | 7 +- Stardrop/Views/ChangelogWindow.axaml | 17 +- Stardrop/Views/ChangelogWindow.axaml.cs | 11 +- Stardrop/Views/CollectionsWindow.axaml | 36 +- Stardrop/Views/CollectionsWindow.axaml.cs | 75 +- Stardrop/Views/DownloadPanel.axaml | 28 +- Stardrop/Views/FlexibleOptionWindow.axaml | 7 +- Stardrop/Views/FlexibleOptionWindow.axaml.cs | 30 +- Stardrop/Views/MainWindow.axaml | 170 ++-- Stardrop/Views/MainWindow.axaml.cs | 871 ++++++++++-------- Stardrop/Views/MainWindowCollections.cs | 276 +++--- Stardrop/Views/MessageWindow.axaml | 7 +- Stardrop/Views/MessageWindow.axaml.cs | 18 +- Stardrop/Views/MissingModsWindow.axaml | 14 +- Stardrop/Views/MissingModsWindow.axaml.cs | 30 +- Stardrop/Views/NexusInfo.axaml | 9 +- Stardrop/Views/NexusInfo.axaml.cs | 15 +- Stardrop/Views/NexusLogin.axaml | 10 +- Stardrop/Views/NexusLogin.axaml.cs | 40 +- Stardrop/Views/ProfileEditor.axaml | 12 +- Stardrop/Views/ProfileEditor.axaml.cs | 112 ++- Stardrop/Views/ProfileExportWindow.axaml | 15 +- Stardrop/Views/ProfileExportWindow.axaml.cs | 40 +- Stardrop/Views/ProfileNaming.axaml | 2 +- Stardrop/Views/ProfileNaming.axaml.cs | 30 +- Stardrop/Views/SettingsWindow.axaml | 67 +- Stardrop/Views/SettingsWindow.axaml.cs | 326 +++---- Stardrop/Views/WarningWindow.axaml | 38 +- Stardrop/Views/WarningWindow.axaml.cs | 62 +- Stardrop/i18n/default.json | 2 +- 108 files changed, 2143 insertions(+), 1948 deletions(-) create mode 100644 Stardrop/Models/Data/Enums/ModUpdateState.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 07223e2b..e0962114 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,7 +27,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v4 with: - dotnet-version: 8.0.x + dotnet-version: 10.0.x - name: Restore dependencies run: dotnet restore "${{ env.WORKING_DIRECTORY }}" - name: Build diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 35ab3fe4..15791977 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -45,7 +45,7 @@ jobs: run: | mkdir -p "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/MacOS" mkdir -p "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/Resources" - dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/MacOS" --configuration "${{ env.CONFIGURATION }}" --runtime "osx-arm64" --framework "net8.0" --self-contained + dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/MacOS" --configuration "${{ env.CONFIGURATION }}" --runtime "osx-arm64" --framework "net10.0" --self-contained - name: Publish (MacOS - Packaging) working-directory: "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app" run: | @@ -76,7 +76,7 @@ jobs: run: | mkdir -p "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/MacOS" mkdir -p "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/Resources" - dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/MacOS" --configuration "${{ env.CONFIGURATION }}" --runtime "osx-x64" --framework "net8.0" --self-contained + dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app/Contents/MacOS" --configuration "${{ env.CONFIGURATION }}" --runtime "osx-x64" --framework "net10.0" --self-contained - name: Publish (MacOS - Packaging) working-directory: "${{ env.OUTPUT_PATH_MAC }}/Stardrop.app" run: | @@ -105,7 +105,7 @@ jobs: - run: mkdir -p path/to/release-artifacts - name: Publish (Linux - Creating) run: | - dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_LINUX }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "linux-arm64" --framework "net8.0" --self-contained + dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_LINUX }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "linux-arm64" --framework "net10.0" --self-contained - name: Publish (Linux - Packaging) working-directory: "${{ env.OUTPUT_PATH_LINUX }}/Stardrop" run: | @@ -138,7 +138,7 @@ jobs: - run: mkdir -p path/to/release-artifacts - name: Publish (Linux - Creating) run: | - dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_LINUX }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "linux-x64" --framework "net8.0" --self-contained + dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_LINUX }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "linux-x64" --framework "net10.0" --self-contained - name: Publish (Linux - Packaging) working-directory: "${{ env.OUTPUT_PATH_LINUX }}/Stardrop" run: | @@ -171,7 +171,7 @@ jobs: - run: mkdir -p path/to/release-artifacts - name: Publish (Windows - Creating & Packaging) run: | - dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_WINDOWS }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "win-arm64" --framework "net8.0" --self-contained + dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_WINDOWS }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "win-arm64" --framework "net10.0" --self-contained (cd "${{ env.OUTPUT_PATH_WINDOWS }}" && zip -r ${GITHUB_WORKSPACE}/Stardrop-win-arm64.zip "Stardrop") - name: Upload artifacts uses: actions/upload-artifact@v4 @@ -191,7 +191,7 @@ jobs: - run: mkdir -p path/to/release-artifacts - name: Publish (Windows - Creating & Packaging) run: | - dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_WINDOWS }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "win-x64" --framework "net8.0" --self-contained + dotnet publish "${{ env.WORKING_DIRECTORY }}" --output "${{ env.OUTPUT_PATH_WINDOWS }}/Stardrop" --configuration "${{ env.CONFIGURATION }}" --runtime "win-x64" --framework "net10.0" --self-contained (cd "${{ env.OUTPUT_PATH_WINDOWS }}" && zip -r ${GITHUB_WORKSPACE}/Stardrop-win-x64.zip "Stardrop") - name: Upload artifacts uses: actions/upload-artifact@v4 diff --git a/Stardrop/App.axaml b/Stardrop/App.axaml index 5c386ac8..9350c71c 100644 --- a/Stardrop/App.axaml +++ b/Stardrop/App.axaml @@ -2,13 +2,15 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Stardrop" x:Class="Stardrop.App" - Name="Stardrop"> + Name="Stardrop" + RequestedThemeVariant="Light" + > - + diff --git a/Stardrop/App.axaml.cs b/Stardrop/App.axaml.cs index d9817d26..7de1353d 100644 --- a/Stardrop/App.axaml.cs +++ b/Stardrop/App.axaml.cs @@ -23,13 +23,11 @@ public override void Initialize() if (Program.helper is null) { Program.helper = new Helper(); + Program.translation.LoadTranslations(); } - // Load in translations - Program.translation.LoadTranslations(); - // Handle adding the themes - Dictionary themes = new Dictionary(); + Dictionary themes = []; foreach (string fileFullName in ThemeManager.GetThemeFilePaths()) { try @@ -44,12 +42,15 @@ public override void Initialize() } } - Current.Styles.Insert(ThemeManager.THEME_STYLE_INDEX, !themes.ContainsKey(Program.settings.Theme) ? themes.Values.First() : themes[Program.settings.Theme]); + Styles.Insert(ThemeManager.THEME_STYLE_INDEX, !themes.TryGetValue(Program.settings.Theme, out IStyle? value) ? themes.Values.First() : value); +#if DEBUG + this.AttachDeveloperTools(); +#endif } - private async void OnUrlsOpen(object? sender, UrlOpenedEventArgs e, MainWindow mainWindow) + private static async void OnUrlsOpen(object? sender, UrlOpenedEventArgs e, MainWindow mainWindow) { - foreach (string? url in e.Urls.Where(u => String.IsNullOrEmpty(u) is false)) + foreach (string? url in e.Urls.Where(u => string.IsNullOrEmpty(u) is false)) { await mainWindow.ProcessNXMLink(new NXM() { Link = url, Timestamp = DateTime.Now }); } @@ -63,7 +64,14 @@ public override void OnFrameworkInitializationCompleted() desktop.MainWindow = mainWindow; // Register events - this.UrlsOpened += (sender, e) => OnUrlsOpen(sender, e, mainWindow); + if (Current?.TryGetFeature() is { } activatable) + { + activatable.Activated += (sender, args) => + { + if (args is ProtocolActivatedEventArgs p) + OnUrlsOpen(sender, new UrlOpenedEventArgs([p.Uri.ToString()]), mainWindow); + }; + } } base.OnFrameworkInitializationCompleted(); diff --git a/Stardrop/Converters/EnumConverter.cs b/Stardrop/Converters/EnumConverter.cs index 1550bdaa..dc3c6e93 100644 --- a/Stardrop/Converters/EnumConverter.cs +++ b/Stardrop/Converters/EnumConverter.cs @@ -6,12 +6,16 @@ namespace Stardrop.Converters { public class EnumConverter : IValueConverter { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { - return Enum.GetName((value.GetType()), value); + if (value is null) + { + return null; + } + return Enum.GetName(value.GetType(), value); } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { throw new NotImplementedException(); } diff --git a/Stardrop/Converters/EnumEqualsConverter.cs b/Stardrop/Converters/EnumEqualsConverter.cs index 91c67eeb..7d6b298e 100644 --- a/Stardrop/Converters/EnumEqualsConverter.cs +++ b/Stardrop/Converters/EnumEqualsConverter.cs @@ -17,7 +17,7 @@ public class EnumEqualsConverter : IValueConverter throw new ArgumentOutOfRangeException(nameof(parameter), "Parameter must be a non-null enum."); } - return Enum.Equals(value, parameter); + return Equals(value, parameter); } public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) diff --git a/Stardrop/Models/Config.cs b/Stardrop/Models/Config.cs index aa1022a5..3b4bb623 100644 --- a/Stardrop/Models/Config.cs +++ b/Stardrop/Models/Config.cs @@ -4,9 +4,9 @@ namespace Stardrop.Models { public class Config { - public string UniqueId { get; set; } - public string FilePath { get; set; } + public string UniqueId { get; set; } = null!; + public string FilePath { get; set; } = null!; public DateTime LastWriteTimeUtc { get; set; } - public string Data { get; set; } + public string Data { get; set; } = null!; } } diff --git a/Stardrop/Models/Data/ClientData.cs b/Stardrop/Models/Data/ClientData.cs index 87d6a169..24d23b46 100644 --- a/Stardrop/Models/Data/ClientData.cs +++ b/Stardrop/Models/Data/ClientData.cs @@ -4,12 +4,12 @@ namespace Stardrop.Models.Data { public class ClientData { - public List ModInstallData { get; set; } - public Dictionary ColumnActiveStates { get; set; } = new Dictionary(); - public Dictionary ColumnOrder { get; set; } = new Dictionary(); - public LastSessionData LastSessionData { get; set; } + public List? ModInstallData { get; set; } + public Dictionary ColumnActiveStates { get; set; } = []; + public Dictionary ColumnOrder { get; set; } = []; + public LastSessionData? LastSessionData { get; set; } // Mapping of mod unique id to the ignored suggested version string - public Dictionary IgnoredUpdates { get; set; } = new Dictionary(); + public Dictionary IgnoredUpdates { get; set; } = []; } } diff --git a/Stardrop/Models/Data/CollectionInstall.cs b/Stardrop/Models/Data/CollectionInstall.cs index 424b523c..3221fb6c 100644 --- a/Stardrop/Models/Data/CollectionInstall.cs +++ b/Stardrop/Models/Data/CollectionInstall.cs @@ -25,7 +25,7 @@ public record CollectionFileHash(string Path, string Md5); /// public class CollectionModEntry { - public string Name { get; set; } = String.Empty; + public string Name { get; set; } = string.Empty; public string? Version { get; set; } public string? Author { get; set; } public bool IsOptional { get; set; } @@ -50,9 +50,9 @@ public class CollectionModEntry /// Name of the archive this entry was installed from. The archive itself is removed after installing, so this is a record rather than something to reuse public string? SourceArchivePath { get; set; } /// Everything this entry's archive placed on disk, taken from AddMods rather than matched by name - public List InstalledMods { get; set; } = new List(); + public List InstalledMods { get; set; } = []; /// Names of the mods this entry's files were copied over, when it was applied as an overlay rather than installed - public List OverlayTargets { get; set; } = new List(); + public List OverlayTargets { get; set; } = []; /// /// File name of this entry's configuration archive under . /// Kept so the configuration can be written again once a mod it is ordered after arrives. Null for mods and @@ -63,7 +63,7 @@ public class CollectionModEntry /// The curator's exact file placements, when the entry was replicated rather than installed as is. An entry /// with these and no manifest is placed file by file, which is how one mod's files replace another's /// - public List FileHashes { get; set; } = new List(); + public List FileHashes { get; set; } = []; /// How many of had no matching file in the archive the last time it was placed public int UnmatchedFileCount { get; set; } public CollectionModStatus Status { get; set; } = CollectionModStatus.Pending; @@ -71,7 +71,7 @@ public class CollectionModEntry public bool IsPinnedExactly() { - return String.Equals(UpdatePolicy, "exact", StringComparison.OrdinalIgnoreCase); + return string.Equals(UpdatePolicy, "exact", StringComparison.OrdinalIgnoreCase); } /// @@ -123,11 +123,11 @@ public class CollectionInstall public const int MAX_LISTED_TARGET_NAMES = 3; /// Stable identifier used as both the folder name under the collections root and the SourceId on every mod it installs - public string SourceId { get; set; } = String.Empty; - public string Slug { get; set; } = String.Empty; + public string SourceId { get; set; } = string.Empty; + public string Slug { get; set; } = string.Empty; public string DomainName { get; set; } = "stardewvalley"; public int RevisionNumber { get; set; } - public string Name { get; set; } = String.Empty; + public string Name { get; set; } = string.Empty; public string? Curator { get; set; } public string? Summary { get; set; } /// Free text from the curator that is worth surfacing once the install finishes @@ -146,10 +146,10 @@ public class CollectionInstall /// public int? PendingRevisionNumber { get; set; } /// Name of the profile generated for this collection, so the two can be re-linked after a rename - public string ProfileName { get; set; } = String.Empty; - public List Mods { get; set; } = new List(); + public string ProfileName { get; set; } = string.Empty; + public List Mods { get; set; } = []; /// The curator's modRules, resolved against - public List Rules { get; set; } = new List(); + public List Rules { get; set; } = []; public CollectionInstall() { @@ -174,9 +174,9 @@ public CollectionInstall(string domainName, string slug, int revisionNumber) /// public static string CreateSourceId(string domainName, string slug) { - var invalidCharacters = System.IO.Path.GetInvalidFileNameChars().Concat(new[] { '.', ' ' }).ToArray(); - var safeSlug = String.Join("-", slug.Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries)); - var safeDomain = String.Join("-", domainName.Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries)); + var invalidCharacters = System.IO.Path.GetInvalidFileNameChars().Concat(['.', ' ']).ToArray(); + var safeSlug = string.Join("-", slug.Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries)); + var safeDomain = string.Join("-", domainName.Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries)); return $"{safeDomain}-{safeSlug}"; } @@ -277,7 +277,7 @@ public int GetModCount() /// The collection's own page on Nexus Mods public string GetPageUri() { - var domainName = String.IsNullOrEmpty(DomainName) ? "stardewvalley" : DomainName; + var domainName = string.IsNullOrEmpty(DomainName) ? "stardewvalley" : DomainName; return $"https://next.nexusmods.com/{domainName}/collections/{Slug}"; } @@ -299,7 +299,7 @@ public string GetRevisionPageUri(int revisionNumber) /// Whether a pinned file asks Nexus Mods for the mod manager download public string? GetEntryPageUri(CollectionModEntry entry, bool useModManagerLink = true) { - if (String.IsNullOrEmpty(entry.ExternalUri) is false) + if (string.IsNullOrEmpty(entry.ExternalUri) is false) { return entry.ExternalUri; } @@ -309,7 +309,7 @@ public string GetRevisionPageUri(int revisionNumber) return null; } - var domainName = String.IsNullOrEmpty(DomainName) ? "stardewvalley" : DomainName; + var domainName = string.IsNullOrEmpty(DomainName) ? "stardewvalley" : DomainName; if (entry.NexusFileId is null) { return $"https://www.nexusmods.com/{domainName}/mods/{entry.NexusModId}"; @@ -396,7 +396,7 @@ private List BuildInstallOrder(out bool hasCycle) var dependents = new List[Mods.Count]; for (int index = 0; index < Mods.Count; index++) { - dependents[index] = new List(); + dependents[index] = []; } foreach (var rule in Rules.Where(r => r.IsResolved() && r.Type is CollectionModRuleType.After or CollectionModRuleType.Before)) @@ -500,10 +500,10 @@ public string DescribeBlockingTargets(CollectionModEntry entry, int maxNames, st var names = GetBlockingTargets(entry).Select(t => t.Name).ToList(); if (names.Count <= maxNames) { - return String.Join(", ", names); + return string.Join(", ", names); } - return String.Format(overflowFormat, String.Join(", ", names.Take(maxNames)), names.Count - maxNames); + return string.Format(overflowFormat, string.Join(", ", names.Take(maxNames)), names.Count - maxNames); } /// Configuration entries, including those held back until their targets arrive diff --git a/Stardrop/Models/Data/CollectionUpdatePlan.cs b/Stardrop/Models/Data/CollectionUpdatePlan.cs index f97dbfaf..763f2fb1 100644 --- a/Stardrop/Models/Data/CollectionUpdatePlan.cs +++ b/Stardrop/Models/Data/CollectionUpdatePlan.cs @@ -15,24 +15,19 @@ public record CollectionEntryReplacement(CollectionModEntry Previous, Collection /// so the install pass, the profile amendment and the summary all read the same answer rather than each working /// it out again. /// - public class CollectionUpdatePlan + public class CollectionUpdatePlan(CollectionInstall previous) { /// The record being replaced, kept for the profile amendment and for the summary - public CollectionInstall Previous { get; } + public CollectionInstall Previous { get; } = previous; /// Entries this revision introduces, which install like any other new entry - public List Added { get; } = new List(); + public List Added { get; } = []; /// Entries whose pin has not moved, carried over with their install state intact - public List Unchanged { get; } = new List(); + public List Unchanged { get; } = []; /// Entries the curator has pinned to a different file, which are downloaded again - public List Replaced { get; } = new List(); + public List Replaced { get; } = []; /// Entries this revision no longer lists. Their files stay on disk, though the profile drops them - public List Removed { get; } = new List(); - - public CollectionUpdatePlan(CollectionInstall previous) - { - Previous = previous; - } + public List Removed { get; } = []; /// Whether anything actually differs, so a revision bump with an identical mod list can say so public bool HasChanges() @@ -77,11 +72,11 @@ public List GetStaleFolderNames() continue; } - var writtenFolders = replacement.Updated.InstalledMods.Select(m => m.FolderName).Where(f => String.IsNullOrEmpty(f) is false).ToList(); + var writtenFolders = replacement.Updated.InstalledMods.Select(m => m.FolderName).Where(f => string.IsNullOrEmpty(f) is false).ToList(); foreach (var installedMod in replacement.Previous.InstalledMods) { - if (String.IsNullOrEmpty(installedMod.FolderName)) + if (string.IsNullOrEmpty(installedMod.FolderName)) { continue; } @@ -110,7 +105,7 @@ public List GetReplacedFolderNames() { foreach (var installedMod in replacement.Previous.InstalledMods) { - if (String.IsNullOrEmpty(installedMod.FolderName)) + if (string.IsNullOrEmpty(installedMod.FolderName)) { continue; } diff --git a/Stardrop/Models/Data/Enums/ModUpdateState.cs b/Stardrop/Models/Data/Enums/ModUpdateState.cs new file mode 100644 index 00000000..0ee5a5c4 --- /dev/null +++ b/Stardrop/Models/Data/Enums/ModUpdateState.cs @@ -0,0 +1,9 @@ +namespace Stardrop.Models +{ + public enum ModUpdateState + { + Generic, + Updating, + Failed + } +} \ No newline at end of file diff --git a/Stardrop/Models/Data/ModInstallData.cs b/Stardrop/Models/Data/ModInstallData.cs index 43602325..3747e174 100644 --- a/Stardrop/Models/Data/ModInstallData.cs +++ b/Stardrop/Models/Data/ModInstallData.cs @@ -9,7 +9,7 @@ namespace Stardrop.Models.Data /// public class ModInstallData { - public string UniqueId { get; set; } + public string UniqueId { get; set; } = null!; /// Null for a loose install, which is also how records written before this field existed read public string? SourceId { get; set; } public DateTime InstallTimestamp { get; set; } diff --git a/Stardrop/Models/Data/ModKeyInfo.cs b/Stardrop/Models/Data/ModKeyInfo.cs index d0ac9cd8..8cae6096 100644 --- a/Stardrop/Models/Data/ModKeyInfo.cs +++ b/Stardrop/Models/Data/ModKeyInfo.cs @@ -2,8 +2,8 @@ { public class ModKeyInfo { - public string UniqueId { get; set; } - public string Name { get; set; } - public string PageUrl { get; set; } + public string UniqueId { get; set; } = null!; + public string Name { get; set; } = null!; + public string PageUrl { get; set; } = null!; } -} +} \ No newline at end of file diff --git a/Stardrop/Models/Data/ModReference.cs b/Stardrop/Models/Data/ModReference.cs index 52e975d1..4d0d1690 100644 --- a/Stardrop/Models/Data/ModReference.cs +++ b/Stardrop/Models/Data/ModReference.cs @@ -12,7 +12,7 @@ namespace Stardrop.Models.Data [JsonConverter(typeof(ModReferenceConverter))] public record ModReference(string UniqueId, string? SourceId = null) { - public bool IsFromCollection => String.IsNullOrEmpty(SourceId) is false; + public bool IsFromCollection => string.IsNullOrEmpty(SourceId) is false; public bool Matches(Mod mod) { @@ -31,7 +31,7 @@ public bool Matches(string uniqueId, string? sourceId) return false; } - return String.Equals(SourceId, sourceId, StringComparison.OrdinalIgnoreCase); + return string.Equals(SourceId, sourceId, StringComparison.OrdinalIgnoreCase); } // Manifests are inconsistent about casing, so equality has to ignore it or profiles will silently lose mods @@ -47,7 +47,7 @@ public virtual bool Equals(ModReference? other) public override int GetHashCode() { - return HashCode.Combine(UniqueId.ToLowerInvariant(), SourceId is null ? String.Empty : SourceId.ToLowerInvariant()); + return HashCode.Combine(UniqueId.ToLowerInvariant(), SourceId is null ? string.Empty : SourceId.ToLowerInvariant()); } public override string ToString() @@ -72,7 +72,7 @@ public class ModReferenceConverter : JsonConverter if (reader.TokenType is JsonTokenType.String) { var legacyId = reader.GetString(); - return String.IsNullOrEmpty(legacyId) ? null : new ModReference(legacyId); + return string.IsNullOrEmpty(legacyId) ? null : new ModReference(legacyId); } if (reader.TokenType is not JsonTokenType.StartObject) @@ -97,11 +97,11 @@ public class ModReferenceConverter : JsonConverter var propertyName = reader.GetString(); reader.Read(); - if (String.Equals(propertyName, nameof(ModReference.UniqueId), StringComparison.OrdinalIgnoreCase)) + if (string.Equals(propertyName, nameof(ModReference.UniqueId), StringComparison.OrdinalIgnoreCase)) { uniqueId = reader.GetString(); } - else if (String.Equals(propertyName, nameof(ModReference.SourceId), StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(propertyName, nameof(ModReference.SourceId), StringComparison.OrdinalIgnoreCase)) { sourceId = reader.TokenType is JsonTokenType.Null ? null : reader.GetString(); } @@ -111,7 +111,7 @@ public class ModReferenceConverter : JsonConverter } } - return String.IsNullOrEmpty(uniqueId) ? null : new ModReference(uniqueId, sourceId); + return string.IsNullOrEmpty(uniqueId) ? null : new ModReference(uniqueId, sourceId); } public override void Write(Utf8JsonWriter writer, ModReference value, JsonSerializerOptions options) diff --git a/Stardrop/Models/Data/ModUpdateInfo.cs b/Stardrop/Models/Data/ModUpdateInfo.cs index 2801764b..f0718c34 100644 --- a/Stardrop/Models/Data/ModUpdateInfo.cs +++ b/Stardrop/Models/Data/ModUpdateInfo.cs @@ -4,10 +4,10 @@ namespace Stardrop.Models.Data { public class ModUpdateInfo { - public string UniqueId { get; set; } - public string SuggestedVersion { get; set; } + public string UniqueId { get; set; } = null!; + public string SuggestedVersion { get; set; } = null!; public WikiCompatibilityStatus Status { get; set; } - public string Link { get; set; } + public string Link { get; set; } = null!; public ModUpdateInfo() diff --git a/Stardrop/Models/Data/PairedKeys.cs b/Stardrop/Models/Data/PairedKeys.cs index e1826dea..6376b8da 100644 --- a/Stardrop/Models/Data/PairedKeys.cs +++ b/Stardrop/Models/Data/PairedKeys.cs @@ -2,7 +2,7 @@ { public class PairedKeys { - public byte[] Lock { get; set; } - public byte[] Vector { get; set; } + public byte[] Lock { get; set; } = null!; + public byte[] Vector { get; set; } = null!; } -} +} \ No newline at end of file diff --git a/Stardrop/Models/Data/RichText.cs b/Stardrop/Models/Data/RichText.cs index 9f68e6ad..894f5fce 100644 --- a/Stardrop/Models/Data/RichText.cs +++ b/Stardrop/Models/Data/RichText.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace Stardrop.Models.Data { @@ -9,10 +8,10 @@ namespace Stardrop.Models.Data /// public class RichTextSegment { - public string Text { get; set; } = String.Empty; + public string Text { get; set; } = string.Empty; /// The web address this run opens, or null when the run is plain text public string? Uri { get; set; } - public bool IsLink => String.IsNullOrEmpty(Uri) is false; + public bool IsLink => string.IsNullOrEmpty(Uri) is false; public static RichTextSegment CreateText(string text) { @@ -32,6 +31,6 @@ public static RichTextSegment CreateLink(string text, string uri) public class RichTextLine { public double IndentWidth { get; set; } - public List Segments { get; set; } = new List(); + public List Segments { get; set; } = []; } } diff --git a/Stardrop/Models/Data/UpdateCache.cs b/Stardrop/Models/Data/UpdateCache.cs index 6733477a..d2e5ee10 100644 --- a/Stardrop/Models/Data/UpdateCache.cs +++ b/Stardrop/Models/Data/UpdateCache.cs @@ -11,7 +11,7 @@ public class UpdateCache public UpdateCache(DateTime lastRuntime) { LastRuntime = lastRuntime; - Mods = new List(); + Mods = []; } } } diff --git a/Stardrop/Models/Mod.cs b/Stardrop/Models/Mod.cs index 7d0fbc12..25956197 100644 --- a/Stardrop/Models/Mod.cs +++ b/Stardrop/Models/Mod.cs @@ -16,18 +16,20 @@ namespace Stardrop.Models { public record PortableModData(string UniqueId, string Version, string Name, string Author, string ModPageUri); - public class Mod : INotifyPropertyChanged + public + class Mod : INotifyPropertyChanged { - internal readonly FileInfo ModFileInfo; + internal readonly FileInfo ModFileInfo = null!; internal readonly Manifest Manifest; + public string UniqueId { get; set; } /// /// The collection this copy of the mod belongs to, or null for a loose install. Paired with UniqueId this /// forms the mod's real identity, as a collection can pin a version the user also has installed loosely. /// public string? SourceId { get; set; } - public bool IsFromCollection { get { return String.IsNullOrEmpty(SourceId) is false; } } + public bool IsFromCollection { get { return string.IsNullOrEmpty(SourceId) is false; } } private string? _collectionName; /// /// The display name of the collection this copy belongs to, or null for a loose install. SourceId is a @@ -47,15 +49,15 @@ public class Mod : INotifyPropertyChanged /// Whether the collection's curator pinned this copy, which is true of every collection mod but an add-on public bool IsCuratedByCollection { get { return IsFromCollection && IsCollectionAddOn is false; } } /// What the collection icon says on hover: the collection's name, and for an add-on what being one means - public string? CollectionLabel { get { return IsCollectionAddOn ? String.Format(Program.translation.Get("ui.main_window.tooltips.collection_add_on"), CollectionName) : CollectionName; } } + public string? CollectionLabel { get { return IsCollectionAddOn ? string.Format(Program.translation.Get("ui.main_window.tooltips.collection_add_on"), CollectionName) : CollectionName; } } public SemVersion Version { get; set; } public string ParsedVersion { get { return Version.ToString(); } } - private string _suggestedVersion { get; set; } + private string _suggestedVersion = null!; public string SuggestedVersion { get { return _suggestedVersion; } set { _suggestedVersion = value; NotifyPropertyChanged(nameof(SuggestedVersion)); NotifyPropertyChanged(nameof(ParsedStatus)); NotifyPropertyChanged(nameof(InstallStatus)); NotifyPropertyChanged(nameof(HasNewerVersion)); NotifyPropertyChanged(nameof(IsUpdateIgnored)); NotifyPropertyChanged(nameof(HasAvailableUpdate)); NotifyPropertyChanged(nameof(HasActionableStatus)); NotifyPropertyChanged(nameof(HasChangelog)); NotifyPropertyChanged(nameof(IgnoreUpdateText)); } } public string Name { get; set; } public string Path { get { return _path; } set { _path = value; RootPath = GetRootPath(value); } } // Whole mod path inside installed mods path for grouping mod components in the same mod - private string _path { get; set; } - public string RootPath { get; private set; } // Root mod path inside installed mods path for grouping mod components in the same mod + private string _path = null!; + public string RootPath { get; private set; } = null!; // Root mod path inside installed mods path for grouping mod components in the same mod public string ManifestFilePath { get { return ModFileInfo.FullName; } } public string Description { get; set; } public string Summary { get { return $"Author: {Author}\nVersion: {ParsedVersion}\nHas Config: {HasConfig}\n\n{Description}"; } } @@ -68,37 +70,37 @@ public class Mod : INotifyPropertyChanged /// public DateTime? LastUpdateTimestamp { get; set; } public Config? _config { get; set; } - public Config? Config { get { return _config; } set { _config = value; NotifyPropertyChanged("Config"); NotifyPropertyChanged("HasConfig"); } } + public Config? Config { get { return _config; } set { _config = value; NotifyPropertyChanged(nameof(Config)); NotifyPropertyChanged(nameof(HasConfig)); } } public bool HasConfig { get { return Config is not null; } } public string FrameworkID { get; set; } = string.Empty; - private List _requirements { get; set; } - public List Requirements { get { return _requirements; } set { _requirements = value; NotifyPropertyChanged("Requirements"); NotifyPropertyChanged("MissingRequirements"); NotifyPropertyChanged("HardRequirements"); } } - public List MissingRequirements { get { return _requirements is null ? null : _requirements.Where(r => !String.IsNullOrEmpty(r.Name) && r.IsMissing && r.IsRequired).ToList(); } } - public List HardRequirements { get { return _requirements is null ? null : _requirements.Where(r => !String.IsNullOrEmpty(r.Name) && !r.IsMissing && r.IsRequired).ToList(); } } - private string _updateUri { get; set; } - public string UpdateUri { get { return _updateUri; } set { _updateUri = value; NotifyPropertyChanged("UpdateUri"); } } - private string _modPageUri { get; set; } - public string ModPageUri { get { return _modPageUri; } set { _modPageUri = value; NotifyPropertyChanged("ModPageUri"); } } + private List _requirements = null!; + public List Requirements { get { return _requirements; } set { _requirements = value; NotifyPropertyChanged(nameof(Requirements)); NotifyPropertyChanged(nameof(MissingRequirements)); NotifyPropertyChanged(nameof(HardRequirements)); } } + public List? MissingRequirements { get { return _requirements is null ? null : [.. _requirements.Where(r => !string.IsNullOrEmpty(r.Name) && r.IsMissing && r.IsRequired)]; } } + public List? HardRequirements { get { return _requirements is null ? null : [.. _requirements.Where(r => !string.IsNullOrEmpty(r.Name) && !r.IsMissing && r.IsRequired)]; } } + private string _updateUri = null!; + public string UpdateUri { get { return _updateUri; } set { _updateUri = value; NotifyPropertyChanged(nameof(UpdateUri)); } } + private string _modPageUri = null!; + public string ModPageUri { get { return _modPageUri; } set { _modPageUri = value; NotifyPropertyChanged(nameof(ModPageUri)); } } public int? NexusModId { get { return GetNexusId(); } } private string? _nexusModThumbnailPath { get; set; } - public string? NexusModThumbnailPath { get { return _nexusModThumbnailPath; } set { _nexusModThumbnailPath = value; NexusModThumbnailFile = TryLoadThumbnail(value); NotifyPropertyChanged("NexusModThumbnailFile"); } } + public string? NexusModThumbnailPath { get { return _nexusModThumbnailPath; } set { _nexusModThumbnailPath = value; NexusModThumbnailFile = TryLoadThumbnail(value); NotifyPropertyChanged(nameof(NexusModThumbnailFile)); } } public Bitmap? NexusModThumbnailFile { get; set; } - private bool _isEnabled { get; set; } + private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; - NotifyPropertyChanged("IsEnabled"); - NotifyPropertyChanged("ChangeStateText"); - NotifyPropertyChanged("ChangeWholeModGroupStateText"); + NotifyPropertyChanged(nameof(IsEnabled)); + NotifyPropertyChanged(nameof(ChangeStateText)); + NotifyPropertyChanged(nameof(ChangeWholeModGroupStateText)); } } - private bool _isHidden { get; set; } - public bool IsHidden { get { return _isHidden; } set { _isHidden = value; NotifyPropertyChanged("IsHidden"); } } - private bool _isEndorsement { get; set; } - public bool IsEndorsed { get { return _isEndorsement; } set { _isEndorsement = value; NotifyPropertyChanged("IsEndorsed"); } } + private bool _isHidden; + public bool IsHidden { get { return _isHidden; } set { _isHidden = value; NotifyPropertyChanged(nameof(IsHidden)); } } + private bool _isEndorsement; + public bool IsEndorsed { get { return _isEndorsement; } set { _isEndorsement = value; NotifyPropertyChanged(nameof(IsEndorsed)); } } public string ChangeStateText { get { return IsEnabled ? Program.translation.Get("internal.disable") : Program.translation.Get("internal.enable"); } } public string ChangeWholeModGroupStateText { get { return IsEnabled ? Program.translation.Get("internal.disable_whole_mod") : Program.translation.Get("internal.enable_whole_mod"); } } /// @@ -112,7 +114,7 @@ public bool HasNewerVersion get { // TryParse first, as IsModOutdated parses outright and this getter is reached from a binding - if (String.IsNullOrEmpty(SuggestedVersion) || SemVersion.TryParse(SuggestedVersion, SemVersionStyles.Any, out _) is false) + if (string.IsNullOrEmpty(SuggestedVersion) || SemVersion.TryParse(SuggestedVersion, SemVersionStyles.Any, out _) is false) { return false; } @@ -124,7 +126,7 @@ public bool HasNewerVersion /// Whether the currently suggested version is the one the user chose to ignore. A newer suggestion than the /// ignored one leaves this false, which is what lets an ignore lapse on its own once the mod moves on. /// - public bool IsUpdateIgnored { get { return !String.IsNullOrEmpty(SuggestedVersion) && !String.IsNullOrEmpty(IgnoredVersion) && IgnoredVersion.Equals(SuggestedVersion, StringComparison.OrdinalIgnoreCase); } } + public bool IsUpdateIgnored { get { return !string.IsNullOrEmpty(SuggestedVersion) && !string.IsNullOrEmpty(IgnoredVersion) && IgnoredVersion.Equals(SuggestedVersion, StringComparison.OrdinalIgnoreCase); } } public string IgnoreUpdateText { get { return IsUpdateIgnored ? Program.translation.Get("internal.stop_ignoring_update") : Program.translation.Get("internal.ignore_update"); } } /// /// Whether the mod counts towards the updatable total. This is the single rule that both a fresh smapi.io @@ -150,7 +152,7 @@ public bool HasActionableStatus } } private WikiCompatibilityStatus _status { get; set; } - public WikiCompatibilityStatus Status { get { return _status; } set { _status = value; NotifyPropertyChanged("Status"); NotifyPropertyChanged("ParsedStatus"); NotifyPropertyChanged("InstallStatus"); NotifyPropertyChanged(nameof(HasActionableStatus)); NotifyPropertyChanged(nameof(HasChangelog)); } } + public WikiCompatibilityStatus Status { get { return _status; } set { _status = value; NotifyPropertyChanged(nameof(Status)); NotifyPropertyChanged(nameof(ParsedStatus)); NotifyPropertyChanged(nameof(InstallStatus)); NotifyPropertyChanged(nameof(HasActionableStatus)); NotifyPropertyChanged(nameof(HasChangelog)); } } public string ParsedStatus { get @@ -166,23 +168,23 @@ public string ParsedStatus // one and nothing would hint that the context menu can undo it if (IsUpdateIgnored) { - return String.Format(Program.translation.Get("ui.main_window.hyperlinks.update_ignored"), SuggestedVersion); + return string.Format(Program.translation.Get("ui.main_window.hyperlinks.update_ignored"), SuggestedVersion); } - if (!String.IsNullOrEmpty(SuggestedVersion) && IsModOutdated(SuggestedVersion)) + if (!string.IsNullOrEmpty(SuggestedVersion) && IsModOutdated(SuggestedVersion)) { if (_status == WikiCompatibilityStatus.Unofficial) { - return String.Format(Program.translation.Get("ui.main_window.hyperlinks.unofficial_update_available"), SuggestedVersion); + return string.Format(Program.translation.Get("ui.main_window.hyperlinks.unofficial_update_available"), SuggestedVersion); } - return String.Format(Program.translation.Get("ui.main_window.hyperlinks.update_available"), SuggestedVersion); + return string.Format(Program.translation.Get("ui.main_window.hyperlinks.update_available"), SuggestedVersion); } - return String.Empty; + return string.Empty; } } - private InstallState _installState { get; set; } - public InstallState InstallState { get { return _installState; } set { _installState = value; NotifyPropertyChanged("InstallState"); } } + private InstallState _installState; + public InstallState InstallState { get { return _installState; } set { _installState = value; NotifyPropertyChanged(nameof(InstallState)); } } public string InstallStatus { get @@ -190,15 +192,15 @@ public string InstallStatus // If the suggested version is the same as an ignored version, treat as no update if (IsUpdateIgnored) { - return String.Empty; + return string.Empty; } - if (!String.IsNullOrEmpty(SuggestedVersion) && IsModOutdated(SuggestedVersion)) + if (!string.IsNullOrEmpty(SuggestedVersion) && IsModOutdated(SuggestedVersion)) { var nexusModId = GetNexusId(); if (_status == WikiCompatibilityStatus.Unofficial || nexusModId is null) { - return String.Empty; + return string.Empty; } else if (InstallState == InstallState.Unknown) { @@ -208,24 +210,24 @@ public string InstallStatus return InstallState == InstallState.Downloading ? Program.translation.Get("ui.main_window.hyperlinks.downloading") : Program.translation.Get("ui.main_window.hyperlinks.installing"); } - return String.Empty; + return string.Empty; } } - private ChangelogState _changelogState { get; set; } - public ChangelogState ChangelogState { get { return _changelogState; } set { _changelogState = value; NotifyPropertyChanged("ChangelogState"); } } + private ChangelogState _changelogState; + public ChangelogState ChangelogState { get { return _changelogState; } set { _changelogState = value; NotifyPropertyChanged(nameof(ChangelogState)); } } public bool HasChangelog { get { - return !String.IsNullOrEmpty(SuggestedVersion) && IsModOutdated(SuggestedVersion) && GetNexusId() is not null; + return !string.IsNullOrEmpty(SuggestedVersion) && IsModOutdated(SuggestedVersion) && GetNexusId() is not null; } } - private string _note { get; set; } - public string Note { get { return _note; } set { _note = value; NotifyPropertyChanged("Note"); } } - private string? _ignoredVersion { get; set; } + private string _note = null!; + public string Note { get { return _note; } set { _note = value; NotifyPropertyChanged(nameof(Note)); } } + private string? _ignoredVersion; public string? IgnoredVersion { get { return _ignoredVersion; } set { _ignoredVersion = value; NotifyPropertyChanged(nameof(IgnoredVersion)); NotifyPropertyChanged(nameof(IsUpdateIgnored)); NotifyPropertyChanged(nameof(ParsedStatus)); NotifyPropertyChanged(nameof(InstallStatus)); NotifyPropertyChanged(nameof(HasAvailableUpdate)); NotifyPropertyChanged(nameof(HasActionableStatus)); NotifyPropertyChanged(nameof(IgnoreUpdateText)); } } public event PropertyChangedEventHandler? PropertyChanged; @@ -237,11 +239,11 @@ public Mod(Manifest manifest, FileInfo modFileInfo, string uniqueId, string vers UniqueId = uniqueId; SourceId = Pathing.GetCollectionSourceId(modFileInfo.DirectoryName); Version = SemVersion.TryParse(version, SemVersionStyles.Any, out var parsedVersion) ? parsedVersion : SemVersion.ParsedFrom(0, 0, 0, "bad-version"); - Name = String.IsNullOrEmpty(name) ? uniqueId : name; + Name = string.IsNullOrEmpty(name) ? uniqueId : name; Path = ComputeModPath(modFileInfo); - Description = String.IsNullOrEmpty(description) ? String.Empty : description; - Author = String.IsNullOrEmpty(author) ? Program.translation.Get("internal.unknown") : author; - Requirements = new List(); + Description = string.IsNullOrEmpty(description) ? string.Empty : description; + Author = string.IsNullOrEmpty(author) ? Program.translation.Get("internal.unknown") : author; + Requirements = []; } /// @@ -258,10 +260,10 @@ public Mod(Manifest manifest) Manifest = manifest; UniqueId = manifest.UniqueID; Version = SemVersion.TryParse(manifest.Version, SemVersionStyles.Any, out var parsedVersion) ? parsedVersion : SemVersion.ParsedFrom(0, 0, 0, "bad-version"); - Name = String.IsNullOrEmpty(manifest.Name) ? manifest.UniqueID : manifest.Name; - Description = String.IsNullOrEmpty(manifest.Description) ? String.Empty : manifest.Description; - Author = String.IsNullOrEmpty(manifest.Author) ? Program.translation.Get("internal.unknown") : manifest.Author; - Requirements = new List(); + Name = string.IsNullOrEmpty(manifest.Name) ? manifest.UniqueID : manifest.Name; + Description = string.IsNullOrEmpty(manifest.Description) ? string.Empty : manifest.Description; + Author = string.IsNullOrEmpty(manifest.Author) ? Program.translation.Get("internal.unknown") : manifest.Author; + Requirements = []; } @@ -270,14 +272,14 @@ public Mod(Manifest manifest) /// The mod folder is tested first so that grouping there is unchanged, then the collections folder, which /// sits outside the mod folder and would otherwise match neither. /// - private string ComputeModPath(FileInfo modFileInfo) + private static string ComputeModPath(FileInfo modFileInfo) { // Set whole mod path for grouping with other mods from the same mod. var modNamePath = GetPathUnderRoot(modFileInfo.DirectoryName, Program.settings.ModFolderPath) ?? GetPathUnderRoot(modFileInfo.DirectoryName, Pathing.GetCollectionsFolderPath()); // Grouped as unknown rather than thrown over. This runs from the constructor, so throwing takes down // whatever was building the mod, which for an install is the whole archive - if (String.IsNullOrEmpty(modNamePath)) + if (string.IsNullOrEmpty(modNamePath)) { Program.helper.Log($"The mod at {modFileInfo.DirectoryName} sits under neither the mod folder nor the collections folder, so it has no group", Helper.Status.Warning); return Program.translation.Get("internal.unknown"); @@ -294,8 +296,8 @@ private string ComputeModPath(FileInfo modFileInfo) var foundIndex = modNamePath.LastIndexOf(System.IO.Path.DirectorySeparatorChar); var nameLength = foundIndex == -1 ? modNamePath.Length : foundIndex; - var finalPath = modNamePath.Substring(0, nameLength); - return String.IsNullOrEmpty(finalPath) ? Program.translation.Get("internal.unknown") : finalPath; + var finalPath = modNamePath[..nameLength]; + return string.IsNullOrEmpty(finalPath) ? Program.translation.Get("internal.unknown") : finalPath; } /// @@ -305,7 +307,7 @@ private string ComputeModPath(FileInfo modFileInfo) /// private static string? GetPathUnderRoot(string? modDirectoryName, string? root) { - if (String.IsNullOrEmpty(modDirectoryName) || String.IsNullOrEmpty(root)) + if (string.IsNullOrEmpty(modDirectoryName) || string.IsNullOrEmpty(root)) { return null; } @@ -319,7 +321,7 @@ private string ComputeModPath(FileInfo modFileInfo) return modDirectoryName.Substring(prefix.Length); } - private string GetRootPath(string path) + private static string GetRootPath(string path) { var foundIndex = path.IndexOf(System.IO.Path.DirectorySeparatorChar); if (foundIndex == -1) @@ -327,12 +329,12 @@ private string GetRootPath(string path) return path; } - return path.Substring(0, foundIndex); + return path[..foundIndex]; } public bool IsModOutdated(string version) { - if (String.IsNullOrEmpty(version) || !HasValidVersion()) + if (string.IsNullOrEmpty(version) || !HasValidVersion()) { return false; } @@ -352,7 +354,7 @@ public bool HasValidVersion() public bool HasUpdateKeys() { - if (Manifest is not null && Manifest.UpdateKeys is not null && !Manifest.UpdateKeys.Any(k => String.IsNullOrEmpty(k))) + if (Manifest is not null && Manifest.UpdateKeys is not null && !Manifest.UpdateKeys.Any(k => string.IsNullOrEmpty(k))) { return true; } @@ -433,7 +435,7 @@ private static bool TryParseNexusKey(string key, out int modId, out string? flag var thumbnail = new Bitmap(filePath); return thumbnail; } - catch (Exception ex) + catch (Exception) { Program.helper.Log($"Failed to load thumbnail for mod {UniqueId} using following path {filePath}"); return null; @@ -453,12 +455,10 @@ public ModReference ToReference() return new ModReference(UniqueId, SourceId); } - internal void NotifyPropertyChanged([CallerMemberName] String propertyName = "") + internal void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } + } } diff --git a/Stardrop/Models/Nexus/Converters/FlexibleNumberConverter.cs b/Stardrop/Models/Nexus/Converters/FlexibleNumberConverter.cs index 23909996..c27eaa98 100644 --- a/Stardrop/Models/Nexus/Converters/FlexibleNumberConverter.cs +++ b/Stardrop/Models/Nexus/Converters/FlexibleNumberConverter.cs @@ -49,7 +49,7 @@ public class FlexibleInt32Converter : JsonConverter if (reader.TokenType is JsonTokenType.String) { var parsed = FlexibleNumberReader.ParseInt64(reader.GetString()); - if (parsed is null || parsed.Value > Int32.MaxValue || parsed.Value < Int32.MinValue) + if (parsed is null || parsed.Value > int.MaxValue || parsed.Value < int.MinValue) { return null; } @@ -76,18 +76,18 @@ internal static class FlexibleNumberReader { public static long? ParseInt64(string? raw) { - if (String.IsNullOrWhiteSpace(raw)) + if (string.IsNullOrWhiteSpace(raw)) { return null; } - if (Int64.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) + if (long.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) { return value; } // Byte sizes occasionally arrive with a decimal component - if (Double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var doubleValue)) + if (double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var doubleValue)) { return (long)doubleValue; } diff --git a/Stardrop/Models/Nexus/NexusUser.cs b/Stardrop/Models/Nexus/NexusUser.cs index cf03a1b6..d204159a 100644 --- a/Stardrop/Models/Nexus/NexusUser.cs +++ b/Stardrop/Models/Nexus/NexusUser.cs @@ -2,10 +2,10 @@ { public class NexusUser { - public string Username { get; set; } + public string Username { get; set; } = null!; public bool IsPremium { get; set; } - public byte[] Key { get; set; } + public byte[] Key { get; set; } = null!; public NexusUser() { diff --git a/Stardrop/Models/Nexus/Web/ModFiles.cs b/Stardrop/Models/Nexus/Web/ModFiles.cs index a2a14f4e..f08cb49f 100644 --- a/Stardrop/Models/Nexus/Web/ModFiles.cs +++ b/Stardrop/Models/Nexus/Web/ModFiles.cs @@ -6,6 +6,6 @@ namespace Stardrop.Models.Nexus.Web public class ModFiles { [JsonPropertyName("files")] - public List Files { get; set; } + public List Files { get; set; } = null!; } } diff --git a/Stardrop/Models/Nexus/Web/NXM.cs b/Stardrop/Models/Nexus/Web/NXM.cs index e7b3892f..3a506448 100644 --- a/Stardrop/Models/Nexus/Web/NXM.cs +++ b/Stardrop/Models/Nexus/Web/NXM.cs @@ -22,7 +22,7 @@ public enum NXMPurpose /// public static NXMPurpose CalculatePurpose(NXM nxm) { - if (String.IsNullOrEmpty(nxm.Link)) + if (string.IsNullOrEmpty(nxm.Link)) { return NXMPurpose.Unknown; } @@ -46,10 +46,7 @@ public static NXMPurpose CalculatePurpose(NXM nxm) /// public NXMPurpose ResolvePurpose() { - if (Purpose is null) - { - Purpose = CalculatePurpose(this); - } + Purpose ??= CalculatePurpose(this); return Purpose.Value; } diff --git a/Stardrop/Models/Nexus/Web/Validate.cs b/Stardrop/Models/Nexus/Web/Validate.cs index bec2a50b..d763bd20 100644 --- a/Stardrop/Models/Nexus/Web/Validate.cs +++ b/Stardrop/Models/Nexus/Web/Validate.cs @@ -5,15 +5,15 @@ namespace Stardrop.Models.Nexus.Web public class Validate { [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get; set; } = null!; [JsonPropertyName("is_premium")] public bool IsPremium { get; set; } [JsonPropertyName("profile_url")] - public string ProfileUrl { get; set; } + public string ProfileUrl { get; set; } = null!; [JsonPropertyName("message")] - public string Message { get; set; } + public string Message { get; set; } = null!; } -} +} \ No newline at end of file diff --git a/Stardrop/Models/Profile.cs b/Stardrop/Models/Profile.cs index b4be673b..d7358ef6 100644 --- a/Stardrop/Models/Profile.cs +++ b/Stardrop/Models/Profile.cs @@ -41,19 +41,19 @@ public Profile() { Name = "Unknown"; IsProtected = false; - EnabledModIds = new List(); - PreservedModConfigs = new Dictionary(); - Notes = new List(); + EnabledModIds = []; + PreservedModConfigs = []; + Notes = []; } - public Profile(string name, bool isProtected = false, List? enabledMods = null, Dictionary? preservedModConfigs = null, List notes = null, string? sourceId = null) + public Profile(string name, bool isProtected = false, List? enabledMods = null, Dictionary? preservedModConfigs = null, List? notes = null, string? sourceId = null) { Name = name; IsProtected = isProtected; SourceId = sourceId; - EnabledModIds = enabledMods is null ? new List() : enabledMods; - PreservedModConfigs = preservedModConfigs is null ? new Dictionary() : preservedModConfigs; - Notes = notes is null ? new List() : notes; + EnabledModIds = enabledMods is null ? [] : enabledMods; + PreservedModConfigs = preservedModConfigs is null ? [] : preservedModConfigs; + Notes = notes is null ? [] : notes; } /// diff --git a/Stardrop/Models/ProfileExternal.cs b/Stardrop/Models/ProfileExternal.cs index bf0cd7ed..001b368e 100644 --- a/Stardrop/Models/ProfileExternal.cs +++ b/Stardrop/Models/ProfileExternal.cs @@ -10,7 +10,7 @@ public ProfileExternal() : base() { IsProtected = false; - ModData = new List(); + ModData = []; } public ProfileExternal(List mods) : this() diff --git a/Stardrop/Models/SMAPI/Converters/BooleanConverter.cs b/Stardrop/Models/SMAPI/Converters/BooleanConverter.cs index da88ae9b..c10193a8 100644 --- a/Stardrop/Models/SMAPI/Converters/BooleanConverter.cs +++ b/Stardrop/Models/SMAPI/Converters/BooleanConverter.cs @@ -13,8 +13,8 @@ public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSer return reader.GetBoolean(); } - string value = reader.GetString(); - if (Boolean.TryParse(value, out bool result)) + string? value = reader.GetString(); + if (bool.TryParse(value, out bool result)) { return result; } diff --git a/Stardrop/Models/SMAPI/Converters/BooleanConverterAssumeTrue.cs b/Stardrop/Models/SMAPI/Converters/BooleanConverterAssumeTrue.cs index 0f8efce9..54dc6087 100644 --- a/Stardrop/Models/SMAPI/Converters/BooleanConverterAssumeTrue.cs +++ b/Stardrop/Models/SMAPI/Converters/BooleanConverterAssumeTrue.cs @@ -13,8 +13,8 @@ public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSer return reader.GetBoolean(); } - string value = reader.GetString(); - if (Boolean.TryParse(value, out bool result)) + string? value = reader.GetString(); + if (bool.TryParse(value, out bool result)) { return result; } diff --git a/Stardrop/Models/SMAPI/Converters/ModKeyConverter.cs b/Stardrop/Models/SMAPI/Converters/ModKeyConverter.cs index 3784c51c..110011e6 100644 --- a/Stardrop/Models/SMAPI/Converters/ModKeyConverter.cs +++ b/Stardrop/Models/SMAPI/Converters/ModKeyConverter.cs @@ -19,7 +19,7 @@ public override string[] Read(ref Utf8JsonReader reader, Type typeToConvert, Jso { if (reader.TokenType == JsonTokenType.EndArray) { - return modKeys.ToArray(); + return [.. modKeys]; } if (reader.TokenType == JsonTokenType.Number) @@ -28,7 +28,7 @@ public override string[] Read(ref Utf8JsonReader reader, Type typeToConvert, Jso } else { - modKeys.Add(reader.GetString()); + modKeys.Add(reader.GetString()!); } } diff --git a/Stardrop/Models/SMAPI/GameDetails.cs b/Stardrop/Models/SMAPI/GameDetails.cs index 2b69ef3c..159e624f 100644 --- a/Stardrop/Models/SMAPI/GameDetails.cs +++ b/Stardrop/Models/SMAPI/GameDetails.cs @@ -14,10 +14,10 @@ public enum OS } /// Stardew Valley's game version. - public string GameVersion { get; set; } + public string GameVersion { get; set; } = null!; /// SMAPI's version. - public string SmapiVersion { get; set; } + public string SmapiVersion { get; set; } = null!; /// The operating system. public OS System { get; set; } @@ -52,7 +52,7 @@ public GameDetails(string gameVersion, string smapiVersion, string system) public bool HasSMAPIUpdated(string version) { - if (String.IsNullOrEmpty(version)) + if (string.IsNullOrEmpty(version)) { return false; } @@ -60,7 +60,7 @@ public bool HasSMAPIUpdated(string version) return HasSMAPIUpdated(SemVersion.Parse(version)); } - public bool HasSMAPIUpdated(SemVersion version) + public bool HasSMAPIUpdated(SemVersion? version) { if (version is null) { diff --git a/Stardrop/Models/SMAPI/Manifest.cs b/Stardrop/Models/SMAPI/Manifest.cs index b4be1e48..07c6703d 100644 --- a/Stardrop/Models/SMAPI/Manifest.cs +++ b/Stardrop/Models/SMAPI/Manifest.cs @@ -8,31 +8,31 @@ public class Manifest // Based on SMAPI's Manfiest.cs: https://github.com/Pathoschild/SMAPI/blob/c10685b03574e967c1bf48aafc814f60196812ec/src/SMAPI.Toolkit/Serialization/Models/Manifest.cs /// The mod name. - public string Name { get; set; } + public string Name { get; set; } = null!; /// A brief description of the mod. - public string Description { get; set; } + public string Description { get; set; } = null!; /// The namespaced mod IDs to query for updates (like Nexus:541). [JsonConverter(typeof(ModKeyConverter))] - public string[] UpdateKeys { get; set; } + public string[] UpdateKeys { get; set; } = null!; /// The mod author's name. - public string Author { get; set; } + public string Author { get; set; } = null!; /// The mod version. - public string Version { get; set; } + public string Version { get; set; } = null!; /// The unique mod ID. - public string UniqueID { get; set; } + public string UniqueID { get; set; } = null!; /// The mod which will read this as a content pack. Mutually exclusive with . //[JsonConverter(typeof(ManifestContentPackForConverter))] - public ManifestContentPackFor ContentPackFor { get; set; } + public ManifestContentPackFor ContentPackFor { get; set; } = null!; /// The other mods that must be loaded before this mod. //[JsonConverter(typeof(ManifestDependencyArrayConverter))] - public ManifestDependency[] Dependencies { get; set; } + public ManifestDependency[] Dependencies { get; set; } = null!; /// Custom property for Stardrop. public bool DeleteOldVersion { get; set; } diff --git a/Stardrop/Models/SMAPI/ManifestContentPackFor.cs b/Stardrop/Models/SMAPI/ManifestContentPackFor.cs index a3406f6e..1d87e1a0 100644 --- a/Stardrop/Models/SMAPI/ManifestContentPackFor.cs +++ b/Stardrop/Models/SMAPI/ManifestContentPackFor.cs @@ -5,9 +5,9 @@ public class ManifestContentPackFor // Based on SMAPI's IManifestContentPackFor.cs: https://github.com/Pathoschild/SMAPI/blob/develop/src/SMAPI.Toolkit.CoreInterfaces/IManifestContentPackFor.cs /// The unique ID of the mod which can read this content pack. - public string UniqueID { get; set; } + public string UniqueID { get; set; } = null!; /// The minimum required version (if any). - public string MinimumVersion { get; set; } + public string MinimumVersion { get; set; } = null!; } } diff --git a/Stardrop/Models/SMAPI/ManifestDependency.cs b/Stardrop/Models/SMAPI/ManifestDependency.cs index 6fe6d7ad..6679c572 100644 --- a/Stardrop/Models/SMAPI/ManifestDependency.cs +++ b/Stardrop/Models/SMAPI/ManifestDependency.cs @@ -9,22 +9,26 @@ public class ManifestDependency : INotifyPropertyChanged // Based on SMAPI's IManifestDependency.cs: https://github.com/Pathoschild/SMAPI/blob/develop/src/SMAPI.Toolkit.CoreInterfaces/IManifestDependency.cs /// The unique mod ID to require. - public string UniqueID { get; set; } + public string UniqueID { get; set; } = null!; /// The minimum required version (if any). - public string MinimumVersion { get; set; } + public string MinimumVersion { get; set; } = null!; /// Whether the dependency must be installed to use the mod. [JsonConverter(typeof(BooleanConverterAssumeTrue))] - public bool IsRequired { get; set; } + public bool IsRequired { get; set; } = true; // Custom properties for Stardrop. - private string _name { get; set; } - public string Name { get { return _name; } set { _name = value; NotifyPropertyChanged("Name"); NotifyPropertyChanged("GenericLink"); } } + private string _name = null!; + public string Name { get { return _name; } set { _name = value; NotifyPropertyChanged(nameof(Name)); NotifyPropertyChanged(nameof(GenericLink)); } } public bool IsMissing { get; set; } public string GenericLink { get { return $"https://smapi.io/mods#{Name.Replace(" ", "_")}"; } } public event PropertyChangedEventHandler? PropertyChanged; + /// Construct an empty instance for JSON deserialization. + public ManifestDependency() + { + } public ManifestDependency(string uniqueId, string minimumVersion, bool isRequired = true) { UniqueID = uniqueId; @@ -35,8 +39,7 @@ public ManifestDependency(string uniqueId, string minimumVersion, bool isRequire private void NotifyPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) - handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } diff --git a/Stardrop/Models/SMAPI/Web/ModEntry.cs b/Stardrop/Models/SMAPI/Web/ModEntry.cs index 646446c0..489914b7 100644 --- a/Stardrop/Models/SMAPI/Web/ModEntry.cs +++ b/Stardrop/Models/SMAPI/Web/ModEntry.cs @@ -5,15 +5,15 @@ public class ModEntry // Based on SMAPI's ModEntryModel.cs: https://github.com/Pathoschild/SMAPI/blob/develop/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModEntryModel.cs /// The mod's unique ID. - public string Id { get; set; } + public string Id { get; set; } = null!; /// The update version recommended by the web API based on its version update and mapping rules. - public ModEntryVersion SuggestedUpdate { get; set; } + public ModEntryVersion SuggestedUpdate { get; set; } = null!; /// Optional extended data which isn't needed for update checks. - public ModEntryMetadata Metadata { get; set; } + public ModEntryMetadata Metadata { get; set; } = null!; /// The errors that occurred while fetching update data. - public string[] Errors { get; set; } = new string[0]; + public string[] Errors { get; set; } = []; } } diff --git a/Stardrop/Models/SMAPI/Web/ModEntryMetadata.cs b/Stardrop/Models/SMAPI/Web/ModEntryMetadata.cs index 737f55a8..e87ef601 100644 --- a/Stardrop/Models/SMAPI/Web/ModEntryMetadata.cs +++ b/Stardrop/Models/SMAPI/Web/ModEntryMetadata.cs @@ -35,19 +35,19 @@ public enum WikiCompatibilityStatus // Based on SMAPI's ModExtendedMetadataModel.cs: https://github.com/Pathoschild/SMAPI/blob/develop/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs /// The mod's display name. - public string Name { get; set; } + public string Name { get; set; } = null!; /// The main version. - public ModEntryVersion Main { get; set; } + public ModEntryVersion Main { get; set; } = null!; /// The latest unofficial version, if newer than and . - public ModEntryVersion Unofficial { get; set; } - public string CustomUrl { get; set; } + public ModEntryVersion Unofficial { get; set; } = null!; + public string CustomUrl { get; set; } = null!; [JsonConverter(typeof(JsonStringEnumConverter))] public WikiCompatibilityStatus CompatibilityStatus { get; set; } /// The human-readable summary of the compatibility status or workaround, without HTML formatting. - public string CompatibilitySummary { get; set; } + public string CompatibilitySummary { get; set; } = null!; } } diff --git a/Stardrop/Models/SMAPI/Web/ModEntryVersion.cs b/Stardrop/Models/SMAPI/Web/ModEntryVersion.cs index 82f3294a..14ce4ab6 100644 --- a/Stardrop/Models/SMAPI/Web/ModEntryVersion.cs +++ b/Stardrop/Models/SMAPI/Web/ModEntryVersion.cs @@ -8,10 +8,10 @@ public class ModEntryVersion ** Accessors *********/ /// The version number. - public string Version { get; set; } + public string Version { get; set; } = null!; /// The mod page URL. - public string Url { get; set; } + public string Url { get; set; } = null!; /********* @@ -25,8 +25,8 @@ public ModEntryVersion() { } /// The mod page URL. public ModEntryVersion(string version, string url) { - this.Version = version; - this.Url = url; + Version = version; + Url = url; } } } diff --git a/Stardrop/Models/SMAPI/Web/ModSearchData.cs b/Stardrop/Models/SMAPI/Web/ModSearchData.cs index 944dfb04..faf5034a 100644 --- a/Stardrop/Models/SMAPI/Web/ModSearchData.cs +++ b/Stardrop/Models/SMAPI/Web/ModSearchData.cs @@ -10,19 +10,19 @@ class ModSearchData ** Accessors *********/ /// The mods for which to find data. - public ModSearchEntry[] Mods { get; set; } + public ModSearchEntry[] Mods { get; set; } = null!; /// Whether to include extended metadata for each mod. public bool IncludeExtendedMetadata { get; set; } /// The SMAPI version installed by the player. This is used for version mapping in some cases. - public string ApiVersion { get; set; } + public string ApiVersion { get; set; } = null!; /// The Stardew Valley version installed by the player. - public string GameVersion { get; set; } + public string GameVersion { get; set; } = null!; /// The OS on which the player plays. - public string Platform { get; set; } + public string Platform { get; set; } = null!; /********* @@ -42,11 +42,11 @@ public ModSearchData() /// Whether to include extended metadata for each mod. public ModSearchData(List mods, string apiVersion, string gameVersion, string platform, bool includeExtendedMetadata) { - this.Mods = mods.ToArray(); - this.ApiVersion = apiVersion.ToString(); - this.GameVersion = gameVersion.ToString(); - this.Platform = platform; - this.IncludeExtendedMetadata = includeExtendedMetadata; + Mods = [.. mods]; + ApiVersion = apiVersion.ToString(); + GameVersion = gameVersion.ToString(); + Platform = platform; + IncludeExtendedMetadata = includeExtendedMetadata; } } } diff --git a/Stardrop/Models/SMAPI/Web/ModSearchEntry.cs b/Stardrop/Models/SMAPI/Web/ModSearchEntry.cs index c88b9653..ebf9f2d0 100644 --- a/Stardrop/Models/SMAPI/Web/ModSearchEntry.cs +++ b/Stardrop/Models/SMAPI/Web/ModSearchEntry.cs @@ -10,13 +10,13 @@ public class ModSearchEntry ** Accessors *********/ /// The unique mod ID. - public string Id { get; set; } + public string Id { get; set; } = null!; /// The namespaced mod update keys (if available). - public string[] UpdateKeys { get; set; } + public string[] UpdateKeys { get; set; } = null!; /// The mod version installed by the local player. This is used for version mapping in some cases. - public string InstalledVersion { get; set; } + public string InstalledVersion { get; set; } = null!; /********* @@ -35,9 +35,9 @@ public ModSearchEntry() /// Whether the installed version is broken or could not be loaded. public ModSearchEntry(string id, SemVersion installedVersion, string[] updateKeys, bool isBroken = false) { - this.Id = id; - this.InstalledVersion = installedVersion.ToString(); - this.UpdateKeys = updateKeys ?? new string[0]; + Id = id; + InstalledVersion = installedVersion.ToString(); + UpdateKeys = updateKeys ?? []; } } } diff --git a/Stardrop/Models/Settings.cs b/Stardrop/Models/Settings.cs index 7c16085c..8741e78c 100644 --- a/Stardrop/Models/Settings.cs +++ b/Stardrop/Models/Settings.cs @@ -7,13 +7,13 @@ namespace Stardrop.Models public class Settings { public string Theme { get; set; } = "Stardrop"; - public string Language { get; set; } + public string Language { get; set; } = null!; public ModGrouping ModGroupingMethod { get; set; } = ModGrouping.None; - public string Version { get; set; } - public string LastSelectedProfileName { get; set; } - public string SMAPIFolderPath { get; set; } - public string ModFolderPath { get; set; } - public string ModInstallPath { get; set; } + public string Version { get; set; } = null!; + public string LastSelectedProfileName { get; set; } = null!; + public string SMAPIFolderPath { get; set; } = null!; + public string ModFolderPath { get; set; } = null!; + public string ModInstallPath { get; set; } = null!; /// /// Where a collection installs the mods it pins. Kept outside the mod folder, as a collection installs its /// own copy of every mod and SMAPI skips every copy of a duplicated unique ID rather than picking one. An @@ -21,7 +21,7 @@ public class Settings /// follow this: the collection records stay alongside the profiles under the data folder, as they are small /// and are keyed by source ID rather than by path. /// - public string CollectionInstallPath { get; set; } + public string CollectionInstallPath { get; set; } = null!; public bool IgnoreHiddenFolders { get; set; } = true; public bool EnableProfileSpecificModConfigs { get; set; } public bool ShouldWriteToModConfigs { get; set; } @@ -47,12 +47,12 @@ public class Settings /// updates the user is not meant to act on. /// public bool CollectionsSkipSMAPIUpdateCheck { get; set; } = true; - public GameDetails GameDetails { get; set; } - public NexusUser NexusDetails { get; set; } + public GameDetails GameDetails { get; set; } = null!; + public NexusUser NexusDetails { get; set; } = null!; public Settings ShallowCopy() { - return (Settings)this.MemberwiseClone(); + return (Settings)MemberwiseClone(); } } } diff --git a/Stardrop/Models/Theme.cs b/Stardrop/Models/Theme.cs index 22cc5ee5..185f9bc8 100644 --- a/Stardrop/Models/Theme.cs +++ b/Stardrop/Models/Theme.cs @@ -7,7 +7,7 @@ public class Theme public required string Name { get; set; } public string? Author { get; set; } public bool IsEnabled { get; set; } - + public string FilePath { get; set; } = null!; public IStyle? Style { get; set; } } } diff --git a/Stardrop/Program.cs b/Stardrop/Program.cs index b02fffe9..182f8b0a 100644 --- a/Stardrop/Program.cs +++ b/Stardrop/Program.cs @@ -1,10 +1,9 @@ using Avalonia; using Avalonia.Controls; -using Avalonia.ReactiveUI; -using Avalonia.Shared.PlatformSupport; -using CommandLine; -using Projektanker.Icons.Avalonia; -using Projektanker.Icons.Avalonia.MaterialDesign; +using ReactiveUI.Avalonia.Reactive; +using Optris.Icons.Avalonia; +using Optris.Icons.Avalonia.MaterialDesign; +using System.CommandLine; using Semver; using Stardrop.Models; using Stardrop.Models.Nexus; @@ -24,28 +23,51 @@ namespace Stardrop { - class Program + partial class Program { - internal static Helper helper; - internal static Settings settings = new Settings(); - internal static Translation translation = new Translation(); - internal static AssetLoader assetLoader = new AssetLoader(); + internal static Helper helper = null!; + internal static Settings settings = new(); + internal static Translation translation = new(); + // internal static AssetLoader assetLoader = new AssetLoader(); internal static bool onBootStartSMAPI = false; internal static string? nxmLink = null; internal static readonly string defaultProfileName = "Default"; internal static readonly string executablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Stardrop.exe"); - internal static readonly Regex gameDetailsPattern = new Regex(@"SMAPI (?.+) with Stardew Valley (?.+) on (?.+)"); + [GeneratedRegex(@"SMAPI (?.+) with Stardew Valley (?.+) on (?.+)")] + internal static partial Regex GameDetailsPattern(); + private static readonly JsonSerializerOptions readOptions = new() { AllowTrailingCommas = true }; + private static readonly JsonSerializerOptions writeOptions = new() { WriteIndented = true }; public static string ApplicationVersion { get { return $"{_applicationVersion.WithoutMetadata()}"; } } - private static readonly SemVersion _applicationVersion = SemVersion.Parse(typeof(Program).Assembly.GetCustomAttribute().InformationalVersion, SemVersionStyles.Any); + private static readonly SemVersion _applicationVersion = SemVersion.Parse(typeof(Program).Assembly.GetCustomAttribute()!.InformationalVersion, SemVersionStyles.Any); - public class Options + // public class Options + // { + // [Option("start-smapi", Required = false, HelpText = "Automatically starts SMAPI based on the last selected mod profile.")] + // public bool StartSmapi { get; set; } + // [Option("nxm", Required = false, HelpText = "Downloads the given NXM file from Nexus Mods.")] + // public string? NXMLink { get; set; } + // } + + private static RootCommand BuildRootCommand() { - [Option("start-smapi", Required = false, HelpText = "Automatically starts SMAPI based on the last selected mod profile.")] - public bool StartSmapi { get; set; } - [Option("nxm", Required = false, HelpText = "Downloads the given NXM file from Nexus Mods.")] - public string? NXMLink { get; set; } + // Use Option instead of OptionAttribute to define options + var startSmapiOption = new Option("--start-smapi") + { + Description = "Automatically starts SMAPI based on the last selected mod profile." + }; + + var nxmOption = new Option("--nxm") + { + Description = "Downloads the given NXM file from Nexus Mods." + }; + + var rootCommand = new RootCommand(); + rootCommand.Options.Add(startSmapiOption); + rootCommand.Options.Add(nxmOption); + + return rootCommand; } // Initialization code. Don't use any Avalonia, third-party APIs or any @@ -55,7 +77,7 @@ public class Options public static void Main(string[] args) { // Enforce the directory's path - Directory.SetCurrentDirectory(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); + Directory.SetCurrentDirectory(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule!.FileName)!); // Establish file and folders paths Pathing.SetHomePath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); @@ -78,11 +100,17 @@ public static void Main(string[] args) helper.Log($"{Environment.NewLine}-- Startup Data --{Environment.NewLine}Time: {DateTime.Now}{Environment.NewLine}OS: [{operatingSystem}] {RuntimeInformation.OSDescription}{Environment.NewLine}Settings Directory: {Pathing.defaultHomePath}{Environment.NewLine}Active Directory: {Directory.GetCurrentDirectory()}{Environment.NewLine}Version: v{ApplicationVersion}{Environment.NewLine}----------------------{Environment.NewLine}"); // Set the argument values - Parser.Default.ParseArguments(args).WithParsed(o => - { - onBootStartSMAPI = o.StartSmapi; - nxmLink = o.NXMLink; - }); + // Parser.Default.ParseArguments(args).WithParsed(o => + // { + // onBootStartSMAPI = o.StartSmapi; + // nxmLink = o.NXMLink; + // }); + + var rootCommand = BuildRootCommand(); + var parseResult = rootCommand.Parse(args); + + onBootStartSMAPI = parseResult.GetValue("--start-smapi"); + nxmLink = parseResult.GetValue("--nxm"); // Log which application Windows will hand NXM links to if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) @@ -106,7 +134,7 @@ public static void Main(string[] args) { try { - settings = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetSettingsPath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + settings = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetSettingsPath()), readOptions) ?? new Settings(); } catch (JsonException ex) { @@ -116,7 +144,7 @@ public static void Main(string[] args) } // Set the default paths - if (!String.IsNullOrEmpty(settings.ModFolderPath)) + if (!string.IsNullOrEmpty(settings.ModFolderPath)) { Pathing.SetSmapiPath(settings.SMAPIFolderPath); Pathing.SetModPath(settings.ModFolderPath); @@ -128,7 +156,7 @@ public static void Main(string[] args) } // Set the default mod install path (for mods that are installed by Stardrop) - if (!String.IsNullOrEmpty(Pathing.defaultModPath) && String.IsNullOrEmpty(settings.ModInstallPath)) + if (!string.IsNullOrEmpty(Pathing.defaultModPath) && string.IsNullOrEmpty(settings.ModInstallPath)) { settings.ModInstallPath = Path.Combine(Pathing.defaultModPath, "Stardrop Installed Mods"); } @@ -136,16 +164,13 @@ public static void Main(string[] args) // Set the default collection install path (for mods that are installed by a collection). Unlike the // mod install path this does not depend on where the mod folder points, as collections deliberately // live outside it - if (String.IsNullOrEmpty(settings.CollectionInstallPath)) + if (string.IsNullOrEmpty(settings.CollectionInstallPath)) { settings.CollectionInstallPath = Pathing.GetDefaultCollectionsFolderPath(); } // Set the default Nexus Mods information - if (settings.NexusDetails is null) - { - settings.NexusDetails = new NexusUser(); - } + settings.NexusDetails ??= new NexusUser(); // Delete any files underneath the Nexus folder var nexusDirectory = new DirectoryInfo(Pathing.GetNexusPath()); @@ -160,7 +185,7 @@ public static void Main(string[] args) // Load the translations before selecting one, since the available languages are discovered from i18n. translation.LoadTranslations(); - if (String.IsNullOrEmpty(settings.Language)) + if (string.IsNullOrEmpty(settings.Language)) { settings.Language = translation.GetLanguageFromAbbreviation(CultureInfo.CurrentCulture.TwoLetterISOLanguageName); } @@ -177,63 +202,56 @@ public static void Main(string[] args) private static void HandleSecondaryInstance(string[] args) { - Parser.Default.ParseArguments(args).WithParsed(o => - { - nxmLink = o.NXMLink; - }); + var rootCommand = BuildRootCommand(); + var parseResult = rootCommand.Parse(args); + nxmLink = parseResult.GetValue("--nxm"); // Verify NXM link is valid - if (String.IsNullOrEmpty(nxmLink)) + if (string.IsNullOrEmpty(nxmLink)) { - Program.helper.Log("Given empty NXM link"); + helper.Log("Given empty NXM link"); return; } // Write to bridge file int attempts = 0; - Program.helper.Log("STARTING"); + helper.Log("STARTING"); while (true) { try { - using (FileStream stream = new FileStream(Pathing.GetLinksCachePath(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) + using FileStream stream = new(Pathing.GetLinksCachePath(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + List links; + try + { + links = JsonSerializer.Deserialize>(stream, readOptions) ?? []; + + } + catch (JsonException) + { + links = []; + } + + try + { + links.Add(new NXM() { Link = nxmLink, Timestamp = DateTime.Now }); + helper.Log(links.Count); + + stream.SetLength(0); + + JsonSerializer.SerializeAsync(stream, links, writeOptions); + + break; + } + catch (Exception ex) { - List links; - try - { - links = JsonSerializer.DeserializeAsync>(stream, new JsonSerializerOptions { AllowTrailingCommas = true }).Result; - - if (links is null) - { - links = new List(); - } - } - catch (JsonException ex) - { - links = new List(); - } - - try - { - links.Add(new NXM() { Link = nxmLink, Timestamp = DateTime.Now }); - Program.helper.Log(links.Count()); - - stream.SetLength(0); - - JsonSerializer.SerializeAsync(stream, links, new JsonSerializerOptions() { WriteIndented = true }); - - break; - } - catch (Exception ex) - { - Program.helper.Log(ex); - } + helper.Log(ex); } } catch (Exception ex) { - Program.helper.Log(ex); + helper.Log(ex); } if (attempts >= 3) @@ -247,7 +265,7 @@ private static void HandleSecondaryInstance(string[] args) } } - Program.helper.Log("DONE"); + helper.Log("DONE"); } // Avalonia configuration, don't remove; also used by visual designer. @@ -259,12 +277,12 @@ public static AppBuilder BuildAvaloniaApp() Pathing.SetHomePath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); } + IconProvider.Current.Register(); + return AppBuilder.Configure() - .UseReactiveUI() + .UseReactiveUI(_ => { }) .UsePlatformDetect() - .LogToTrace() - .WithIcons(container => container - .Register()); + .LogToTrace(); } } } diff --git a/Stardrop/Properties/PublishProfiles/FolderProfile - Linux.pubxml b/Stardrop/Properties/PublishProfiles/FolderProfile - Linux.pubxml index 2c9a2882..d8e6af42 100644 --- a/Stardrop/Properties/PublishProfiles/FolderProfile - Linux.pubxml +++ b/Stardrop/Properties/PublishProfiles/FolderProfile - Linux.pubxml @@ -8,7 +8,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Any CPU publish\linux FileSystem - net7.0 + net10.0 linux-x64 true true diff --git a/Stardrop/Properties/PublishProfiles/FolderProfile - MacOS.pubxml b/Stardrop/Properties/PublishProfiles/FolderProfile - MacOS.pubxml index fc07c7a9..f662e9cf 100644 --- a/Stardrop/Properties/PublishProfiles/FolderProfile - MacOS.pubxml +++ b/Stardrop/Properties/PublishProfiles/FolderProfile - MacOS.pubxml @@ -8,7 +8,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Any CPU publish\mac FileSystem - net7.0 + net10.0 osx-x64 true true diff --git a/Stardrop/Properties/PublishProfiles/FolderProfile - Windows.pubxml b/Stardrop/Properties/PublishProfiles/FolderProfile - Windows.pubxml index b5e80546..9f9ec399 100644 --- a/Stardrop/Properties/PublishProfiles/FolderProfile - Windows.pubxml +++ b/Stardrop/Properties/PublishProfiles/FolderProfile - Windows.pubxml @@ -8,7 +8,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Any CPU publish\windows FileSystem - net7.0 + net10.0 win-x64 true true diff --git a/Stardrop/Stardrop.csproj b/Stardrop/Stardrop.csproj index 769aac3f..3ace8a21 100644 --- a/Stardrop/Stardrop.csproj +++ b/Stardrop/Stardrop.csproj @@ -1,7 +1,7 @@  WinExe - net8.0 + net10.0 enable 1.11.0 false @@ -37,20 +37,23 @@ - - - + + + - - - - - - - - - - + + + + + + + + + + + + + diff --git a/Stardrop/Utilities/Extension/ColumnExtensions.cs b/Stardrop/Utilities/Extension/ColumnExtensions.cs index f7c25c92..d6b27f5a 100644 --- a/Stardrop/Utilities/Extension/ColumnExtensions.cs +++ b/Stardrop/Utilities/Extension/ColumnExtensions.cs @@ -1,9 +1,5 @@ using Avalonia; using Avalonia.Controls; -using Avalonia.Data; -using Avalonia.Markup.Xaml; -using Avalonia.Markup.Xaml.MarkupExtensions; -using System; namespace Stardrop.Utilities.Extension diff --git a/Stardrop/Utilities/Extension/TranslateExtension.cs b/Stardrop/Utilities/Extension/TranslateExtension.cs index 39ec3420..54be05f1 100644 --- a/Stardrop/Utilities/Extension/TranslateExtension.cs +++ b/Stardrop/Utilities/Extension/TranslateExtension.cs @@ -6,16 +6,12 @@ namespace Stardrop.Utilities.Extension { - public class TranslateExtension : MarkupExtension + public class TranslateExtension(string key) : MarkupExtension { - public TranslateExtension(string key) - { - this.Key = key; - } - public string Key { get; set; } + public string Key { get; set; } = key; - public string Context { get; set; } + public string? Context { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { diff --git a/Stardrop/Utilities/External/GitHub.cs b/Stardrop/Utilities/External/GitHub.cs index cdff17f2..dfe69fea 100644 --- a/Stardrop/Utilities/External/GitHub.cs +++ b/Stardrop/Utilities/External/GitHub.cs @@ -17,7 +17,7 @@ static class GitHub KeyValuePair? versionToUri = null; // Create a throwaway client - HttpClient client = new HttpClient(); + HttpClient client = new(); client.DefaultRequestHeaders.Add("User-Agent", "Stardrop - SDV Mod Manager"); try @@ -29,7 +29,7 @@ static class GitHub JsonDocument parsedContent = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()); string tagName = parsedContent.RootElement.GetProperty("tag_name").ToString(); string downloadUri = parsedContent.RootElement.GetProperty("html_url").ToString(); - downloadUri = String.Concat(downloadUri, "/", $"SMAPI-{tagName}-installer.zip").Replace("releases/tag/", "releases/download/"); + downloadUri = string.Concat(downloadUri, "/", $"SMAPI-{tagName}-installer.zip").Replace("releases/tag/", "releases/download/"); versionToUri = new KeyValuePair(tagName, downloadUri); } @@ -46,17 +46,17 @@ static class GitHub public async static Task DownloadLatestSMAPIRelease(string uri) { // Create a throwaway client - HttpClient client = new HttpClient(); + HttpClient client = new(); client.DefaultRequestHeaders.Add("User-Agent", "Stardrop - SDV Mod Manager"); - string downloadedArchivePath = String.Empty; + string downloadedArchivePath = string.Empty; try { var response = await client.GetAsync(uri); // TODO refactor this to use async using (var archive = ArchiveFactory.OpenArchive(await response.Content.ReadAsStreamAsync())) { - downloadedArchivePath = Path.Combine(Pathing.GetSmapiUpgradeFolderPath(), Path.GetDirectoryName(archive.Entries.First().Key)); + downloadedArchivePath = Path.Combine(Pathing.GetSmapiUpgradeFolderPath(), Path.GetDirectoryName(archive.Entries.First().Key)!); foreach (var entry in archive.Entries) { await entry.WriteToDirectoryAsync(Pathing.GetSmapiUpgradeFolderPath(), new SharpCompress.Common.ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); @@ -77,7 +77,7 @@ public async static Task DownloadLatestSMAPIRelease(string uri) KeyValuePair? versionToUri = null; // Create a throwaway client - HttpClient client = new HttpClient(); + HttpClient client = new(); client.DefaultRequestHeaders.Add("User-Agent", "Stardrop - SDV Mod Manager"); try @@ -91,26 +91,26 @@ public async static Task DownloadLatestSMAPIRelease(string uri) string downloadUri = parsedContent.RootElement.GetProperty("html_url").ToString(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - downloadUri = String.Concat(downloadUri, "/", "Stardrop-osx-x64.zip"); + downloadUri = string.Concat(downloadUri, "/", "Stardrop-osx-x64.zip"); if (RuntimeInformation.OSArchitecture == Architecture.Arm64) { - downloadUri = String.Concat(downloadUri, "/", "Stardrop-osx-arm64.zip"); + downloadUri = string.Concat(downloadUri, "/", "Stardrop-osx-arm64.zip"); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - downloadUri = String.Concat(downloadUri, "/", "Stardrop-linux-x64.zip"); + downloadUri = string.Concat(downloadUri, "/", "Stardrop-linux-x64.zip"); if (RuntimeInformation.OSArchitecture == Architecture.Arm64) { - downloadUri = String.Concat(downloadUri, "/", "Stardrop-linux-arm64.zip"); + downloadUri = string.Concat(downloadUri, "/", "Stardrop-linux-arm64.zip"); } } else { - downloadUri = String.Concat(downloadUri, "/", "Stardrop-win-x64.zip"); + downloadUri = string.Concat(downloadUri, "/", "Stardrop-win-x64.zip"); if (RuntimeInformation.OSArchitecture == Architecture.Arm64) { - downloadUri = String.Concat(downloadUri, "/", "Stardrop-win-arm64.zip"); + downloadUri = string.Concat(downloadUri, "/", "Stardrop-win-arm64.zip"); } } downloadUri = downloadUri.Replace("releases/tag/", "releases/download/"); @@ -130,10 +130,10 @@ public async static Task DownloadLatestSMAPIRelease(string uri) public async static Task DownloadLatestStardropRelease(string uri) { // Create a throwaway client - HttpClient client = new HttpClient(); + HttpClient client = new(); client.DefaultRequestHeaders.Add("User-Agent", "Stardrop - SDV Mod Manager"); - string downloadedArchivePath = String.Empty; + string downloadedArchivePath = string.Empty; try { var response = await client.GetAsync(uri); diff --git a/Stardrop/Utilities/External/NexusClient.cs b/Stardrop/Utilities/External/NexusClient.cs index beffcd3c..d9c1264a 100644 --- a/Stardrop/Utilities/External/NexusClient.cs +++ b/Stardrop/Utilities/External/NexusClient.cs @@ -21,13 +21,13 @@ namespace Stardrop.Utilities.External { public static class Nexus { - private static readonly Uri _baseUrl = new Uri("https://api.nexusmods.com/v1/"); + private static readonly Uri _baseUrl = new("https://api.nexusmods.com/v1/"); public static NexusClient? Client { get; private set; } public delegate void NexusClientChangedHandler(NexusClient? oldClient, NexusClient? newClient); public static event NexusClientChangedHandler? ClientChanged = null; - + private static readonly JsonSerializerOptions ReadOptions = new() { AllowTrailingCommas = true }; /// /// If the user has entered their Nexus API key in a previous session, this will attempt to retreive /// it. @@ -40,7 +40,7 @@ public static class Nexus return null; } - var pairedKeys = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetNotionCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + var pairedKeys = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetNotionCachePath()), ReadOptions); if (pairedKeys?.Vector is null || pairedKeys?.Lock is null) { return null; @@ -68,8 +68,10 @@ public static class Nexus /// The created client, if successful. Null otherwise. public static async Task CreateClient(string apiKey) { - HttpClient client = new HttpClient(); - client.BaseAddress = _baseUrl; + HttpClient client = new() + { + BaseAddress = _baseUrl + }; client.DefaultRequestHeaders.Add("apiKey", apiKey); client.DefaultRequestHeaders.Add("Application-Name", "Stardrop"); client.DefaultRequestHeaders.Add("Application-Version", Program.ApplicationVersion); @@ -99,17 +101,20 @@ public static void ClearClient() } } - public partial class NexusClient + public partial class NexusClient(HttpClient client) + { - private static readonly Uri _graphQLBaseUrl = new Uri("https://api.nexusmods.com/v2/graphql"); + private static readonly Uri _graphQLBaseUrl = new("https://api.nexusmods.com/v2/graphql"); internal const string NxmModPattern = @"nxm:\/\/(?stardewvalley)\/mods\/(?[0-9]+)\/files\/(?[0-9]+)\?key=(?.*)&expires=(?[0-9]+)&user_id=(?[0-9]+)"; internal const string NxmCollectionPattern = @"nxm:\/\/(?[a-z0-9]+)\/collections\/(?[a-z0-9]+)\/revisions\/(?[0-9]+)"; - private const string _nxmPattern = NxmModPattern; + // private const string _nxmPattern = NxmModPattern; + [GeneratedRegex(NxmModPattern)] + private static partial Regex NxmPattern(); /// Nexus mod ID for SMAPI, which collections list as a mod but which Stardrop must never install into the mod folder internal const int SmapiNexusModId = 2400; - private readonly HttpClient _client; + private readonly HttpClient _client = client; private NexusUser _settings = null!; internal int DailyRequestsLimit { get; private set; } @@ -120,10 +125,6 @@ public partial class NexusClient internal event EventHandler? DownloadCompleted = null; internal event EventHandler? DownloadFailed = null; - public NexusClient(HttpClient client) - { - _client = client; - } /// /// Calls the /validate endpoint on Nexus Mods' API using the API key stored in this client upon creation. @@ -151,9 +152,9 @@ public async Task ValidateKey() string content = await response.Content.ReadAsStringAsync(); - Validate validationModel = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + Validate? validationModel = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); - if (validationModel is null || String.IsNullOrEmpty(validationModel.Message) is false) + if (validationModel is null || string.IsNullOrEmpty(validationModel.Message) is false) { Program.helper.Log($"Unable to validate given API key for Nexus Mods"); @@ -187,8 +188,8 @@ public async Task ValidateKey() return null; } - var match = Regex.Match(Regex.Unescape(nxmData.Link), _nxmPattern); - if (match.Success is false || match.Groups["domain"].ToString().ToLower() != "stardewvalley" || Int32.TryParse(match.Groups["mod"].ToString(), out int modId) is false) + var match = NxmPattern().Match(Regex.Unescape(nxmData.Link)); + if (match.Success is false || match.Groups["domain"].ToString().ToLower() != "stardewvalley" || int.TryParse(match.Groups["mod"].ToString(), out int modId) is false) { return null; } @@ -199,7 +200,7 @@ public async Task ValidateKey() if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content is not null) { string content = await response.Content.ReadAsStringAsync(); - ModDetails modDetails = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + ModDetails? modDetails = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (modDetails is null) { @@ -283,13 +284,13 @@ public async Task ValidateKey() public async Task GetFileByVersion(int modId, string version, string? modFlag = null, bool ignoreCategory = false) { - if (SemVersion.TryParse(version.Replace("v", String.Empty), SemVersionStyles.Any, out var targetVersion) is false) + if (SemVersion.TryParse(version.Replace("v", string.Empty), SemVersionStyles.Any, out var targetVersion) is false) { Program.helper.Log($"Unable to parse given target version {version}"); return null; } - Program.helper.Log($"Requesting version {version} of mod {modId}{(String.IsNullOrEmpty(modFlag) is false ? $" with flag {modFlag}" : String.Empty)}"); + Program.helper.Log($"Requesting version {version} of mod {modId}{(string.IsNullOrEmpty(modFlag) is false ? $" with flag {modFlag}" : string.Empty)}"); try { @@ -297,7 +298,7 @@ public async Task ValidateKey() if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content is not null) { string content = await response.Content.ReadAsStringAsync(); - ModFiles modFiles = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + ModFiles? modFiles = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (modFiles is null || modFiles.Files is null || modFiles.Files.Count == 0) { @@ -307,13 +308,13 @@ public async Task ValidateKey() else { ModFile? selectedFile = null; - foreach (var file in modFiles.Files.Where(x => String.IsNullOrEmpty(x.Version) is false && SemVersion.TryParse(x.Version.Replace("v", String.Empty), SemVersionStyles.Any, out var modVersion) && modVersion == targetVersion)) + foreach (var file in modFiles.Files.Where(x => string.IsNullOrEmpty(x.Version) is false && SemVersion.TryParse(x.Version.Replace("v", string.Empty), SemVersionStyles.Any, out var modVersion) && modVersion == targetVersion)) { - if (String.IsNullOrEmpty(modFlag) is false && ((String.IsNullOrEmpty(file.Name) is false && file.Name.Contains(modFlag, StringComparison.OrdinalIgnoreCase)) || (String.IsNullOrEmpty(file.Description) is false && file.Description.Contains(modFlag, StringComparison.OrdinalIgnoreCase)))) + if (string.IsNullOrEmpty(modFlag) is false && ((string.IsNullOrEmpty(file.Name) is false && file.Name.Contains(modFlag, StringComparison.OrdinalIgnoreCase)) || (string.IsNullOrEmpty(file.Description) is false && file.Description.Contains(modFlag, StringComparison.OrdinalIgnoreCase)))) { selectedFile = file; } - else if (String.IsNullOrEmpty(modFlag) is true && String.IsNullOrEmpty(file.Category) is false && (ignoreCategory || file.Category.Equals("MAIN", StringComparison.OrdinalIgnoreCase))) + else if (string.IsNullOrEmpty(modFlag) is true && string.IsNullOrEmpty(file.Category) is false && (ignoreCategory || file.Category.Equals("MAIN", StringComparison.OrdinalIgnoreCase))) { selectedFile = file; } @@ -321,7 +322,7 @@ public async Task ValidateKey() if (selectedFile is null) { - Program.helper.Log($"Unable to get a matching file for the mod {modId} with version {version}{(String.IsNullOrEmpty(modFlag) is false ? $" and with the flag {modFlag}" : String.Empty)} via Nexus Mods: \n{String.Join("\n", modFiles.Files.Select(m => $"{m.Name} | {m.Version}"))}"); + Program.helper.Log($"Unable to get a matching file for the mod {modId} with version {version}{(string.IsNullOrEmpty(modFlag) is false ? $" and with the flag {modFlag}" : string.Empty)} via Nexus Mods: \n{string.Join("\n", modFiles.Files.Select(m => $"{m.Name} | {m.Version}"))}"); } UpdateRequestCounts(response.Headers); @@ -359,16 +360,16 @@ public async Task ValidateKey() /// public static bool TryParseModNxmLink(string link, out string domainName, out int modId, out int fileId) { - domainName = String.Empty; + domainName = string.Empty; modId = 0; fileId = 0; - if (String.IsNullOrEmpty(link)) + if (string.IsNullOrEmpty(link)) { return false; } - var match = Regex.Match(Regex.Unescape(link), NxmModPattern); + var match = NxmPattern().Match(Regex.Unescape(link)); if (match.Success is false) { return false; @@ -376,7 +377,7 @@ public static bool TryParseModNxmLink(string link, out string domainName, out in domainName = match.Groups["domain"].ToString().ToLower(); - return Int32.TryParse(match.Groups["mod"].ToString(), out modId) && Int32.TryParse(match.Groups["file"].ToString(), out fileId); + return int.TryParse(match.Groups["mod"].ToString(), out modId) && int.TryParse(match.Groups["file"].ToString(), out fileId); } public async Task GetFileDownloadLink(NXM nxmData, string? serverName = null) @@ -386,8 +387,9 @@ public static bool TryParseModNxmLink(string link, out string domainName, out in return null; } - var match = Regex.Match(Regex.Unescape(nxmData.Link), _nxmPattern); - if (match.Success is false || match.Groups["domain"].ToString().ToLower() != "stardewvalley" || Int32.TryParse(match.Groups["mod"].ToString(), out int modId) is false || Int32.TryParse(match.Groups["file"].ToString(), out int fileId) is false) + + var match = NxmPattern().Match(Regex.Unescape(nxmData.Link)); + if (match.Success is false || string.Equals(match.Groups["domain"].Value, "stardewvalley", StringComparison.OrdinalIgnoreCase) is false || int.TryParse(match.Groups["mod"].ToString(), out int modId) is false || int.TryParse(match.Groups["file"].ToString(), out int fileId) is false) { return null; } @@ -397,7 +399,7 @@ public static bool TryParseModNxmLink(string link, out string domainName, out in public async Task GetFileDownloadLink(int modId, int fileId, string? nxmKey = null, string? nxmExpiry = null, string? serverName = null) { - if (String.IsNullOrEmpty(serverName) || _settings.IsPremium is false) + if (string.IsNullOrEmpty(serverName) || _settings.IsPremium is false) { serverName = "Nexus CDN"; } @@ -405,7 +407,7 @@ public static bool TryParseModNxmLink(string link, out string domainName, out in try { string url = $"games/stardewvalley/mods/{modId}/files/{fileId}/download_link.json"; - if (String.IsNullOrEmpty(nxmKey) is false && String.IsNullOrEmpty(nxmExpiry) is false) + if (string.IsNullOrEmpty(nxmKey) is false && string.IsNullOrEmpty(nxmExpiry) is false) { url = $"{url}?key={nxmKey}&expires={nxmExpiry}"; } @@ -414,7 +416,7 @@ public static bool TryParseModNxmLink(string link, out string domainName, out in if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content is not null) { string content = await response.Content.ReadAsStringAsync(); - List downloadLinks = JsonSerializer.Deserialize>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + List? downloadLinks = JsonSerializer.Deserialize>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (downloadLinks is null || downloadLinks.Count == 0) { @@ -534,7 +536,7 @@ public async Task> GetEndorsements() if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content is not null) { string content = await response.Content.ReadAsStringAsync(); - List endorsements = JsonSerializer.Deserialize>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + List? endorsements = JsonSerializer.Deserialize>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (endorsements is null) { @@ -571,7 +573,7 @@ public async Task> GetEndorsements() Program.helper.Log($"Failed to get endorsements for Nexus Mods: {ex}", Helper.Status.Alert); } - return new List(); + return []; } public async Task SetModEndorsement(int modId, bool isEndorsed) @@ -583,7 +585,7 @@ public async Task SetModEndorsement(int modId, bool isEndor if (response.Content is not null) { string content = await response.Content.ReadAsStringAsync(); - EndorsementResult endorsementResult = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + EndorsementResult? endorsementResult = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (endorsementResult is null) { @@ -615,7 +617,7 @@ public async Task SetModEndorsement(int modId, bool isEndor { return EndorsementResponse.NotDownloadedMod; } - Program.helper.Log(parsedMessage); + Program.helper.Log($"Unhandled error message for endorsement: {parsedMessage}"); break; default: Program.helper.Log($"Unhandled status for endorsement: {endorsementResult.Status} | {endorsementResult.Message}"); @@ -693,7 +695,7 @@ public async Task SetModEndorsement(int modId, bool isEndor if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content is not null) { string content = await response.Content.ReadAsStringAsync(); - ModDetails modDetails = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + ModDetails? modDetails = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (modDetails is null) { @@ -748,12 +750,12 @@ public async Task SetModEndorsement(int modId, bool isEndor private void UpdateRequestCounts(HttpResponseHeaders headers) { - if (headers.TryGetValues("x-rl-daily-limit", out var limitValues) && Int32.TryParse(limitValues.First(), out int dailyLimit)) + if (headers.TryGetValues("x-rl-daily-limit", out var limitValues) && int.TryParse(limitValues.First(), out int dailyLimit)) { DailyRequestsLimit = dailyLimit; } - if (headers.TryGetValues("x-rl-daily-remaining", out var remainingValues) && Int32.TryParse(remainingValues.First(), out int dailyRemaining)) + if (headers.TryGetValues("x-rl-daily-remaining", out var remainingValues) && int.TryParse(remainingValues.First(), out int dailyRemaining)) { DailyRequestsRemaining = dailyRemaining; } @@ -773,8 +775,8 @@ private void UpdateRequestCounts(HttpResponseHeaders headers) return null; } - var match = Regex.Match(Regex.Unescape(nxmData.Link), _nxmPattern); - if (match.Success is false || match.Groups["domain"].ToString().ToLower() != "stardewvalley" || Int32.TryParse(match.Groups["mod"].ToString(), out int modId) is false || Int32.TryParse(match.Groups["file"].ToString(), out int fileId) is false) + var match = NxmPattern().Match(Regex.Unescape(nxmData.Link)); + if (match.Success is false || match.Groups["domain"].ToString().ToLower() != "stardewvalley" || int.TryParse(match.Groups["mod"].ToString(), out int modId) is false || int.TryParse(match.Groups["file"].ToString(), out int fileId) is false) { return null; } diff --git a/Stardrop/Utilities/External/NexusClientCollections.cs b/Stardrop/Utilities/External/NexusClientCollections.cs index 53d55a26..e79acfd0 100644 --- a/Stardrop/Utilities/External/NexusClientCollections.cs +++ b/Stardrop/Utilities/External/NexusClientCollections.cs @@ -17,8 +17,12 @@ namespace Stardrop.Utilities.External public partial class NexusClient { // Matches the current collection URL format along with the older next.nexusmods.com one - private static readonly Regex _collectionUrlPattern = new Regex(@"nexusmods\.com\/(?:games\/)?(?[a-z0-9]+)\/collections\/(?[a-z0-9]+)(?:\/revisions\/(?[0-9]+))?", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex _nxmCollectionRegex = new Regex(NxmCollectionPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); + // private static readonly Regex _collectionUrlPattern = new(@"nexusmods\.com\/(?:games\/)?(?[a-z0-9]+)\/collections\/(?[a-z0-9]+)(?:\/revisions\/(?[0-9]+))?", RegexOptions.IgnoreCase | RegexOptions.Compiled); + [GeneratedRegex(@"nexusmods\.com\/(?:games\/)?(?[a-z0-9]+)\/collections\/(?[a-z0-9]+)(?:\/revisions\/(?[0-9]+))?", RegexOptions.IgnoreCase | RegexOptions.Compiled)] + private static partial Regex CollectionUrlPattern(); + // private static readonly Regex _nxmCollectionRegex = new(NxmCollectionPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); + [GeneratedRegex(NxmCollectionPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled)] + private static partial Regex NxmCollectionRegex(); /// /// Pulls a collection revision's metadata from Nexus' v2 GraphQL API. Passing a null revision resolves to the @@ -107,8 +111,8 @@ public partial class NexusClient UpdateRequestCounts(response.Headers); - var preferredLink = downloadLinks.DownloadLinks.FirstOrDefault(l => String.IsNullOrEmpty(serverName) is false && String.IsNullOrEmpty(l.ShortName) is false && l.ShortName.Equals(serverName, StringComparison.OrdinalIgnoreCase)); - if (preferredLink is not null && String.IsNullOrEmpty(preferredLink.Uri) is false) + var preferredLink = downloadLinks.DownloadLinks.FirstOrDefault(l => string.IsNullOrEmpty(serverName) is false && string.IsNullOrEmpty(l.ShortName) is false && l.ShortName.Equals(serverName, StringComparison.OrdinalIgnoreCase)); + if (preferredLink is not null && string.IsNullOrEmpty(preferredLink.Uri) is false) { return preferredLink.Uri; } @@ -132,7 +136,7 @@ public CollectionInstall CreateCollectionInstall(CollectionIndex index, string s var isPremium = Program.settings.NexusDetails is not null && Program.settings.NexusDetails.IsPremium; var install = new CollectionInstall(domainName, slug, revisionNumber) { - Name = index.Info is not null && String.IsNullOrEmpty(index.Info.Name) is false ? index.Info.Name : slug, + Name = index.Info is not null && string.IsNullOrEmpty(index.Info.Name) is false ? index.Info.Name : slug, Curator = index.Info is null ? null : index.Info.Author, Summary = index.Info is null ? null : index.Info.Description, InstallInstructions = index.Info is null ? null : index.Info.InstallInstructions, @@ -162,7 +166,7 @@ public CollectionInstall CreateCollectionInstall(CollectionIndex index, string s var entry = new CollectionModEntry() { - Name = String.IsNullOrEmpty(collectionMod.Name) ? "Unknown mod" : collectionMod.Name, + Name = string.IsNullOrEmpty(collectionMod.Name) ? "Unknown mod" : collectionMod.Name, Version = collectionMod.Version, Author = collectionMod.Author, IsOptional = collectionMod.Optional, @@ -204,7 +208,7 @@ private static List ReadFileHashes(List public static bool TryParseCollectionNxmLink(string link, out string domainName, out string slug, out int? revision) { - domainName = String.Empty; - slug = String.Empty; + domainName = string.Empty; + slug = string.Empty; revision = null; - if (String.IsNullOrEmpty(link)) + if (string.IsNullOrEmpty(link)) { return false; } - var match = _nxmCollectionRegex.Match(Regex.Unescape(link)); + var match = NxmCollectionRegex().Match(Regex.Unescape(link)); if (match.Success is false) { return false; @@ -299,7 +303,7 @@ public static bool TryParseCollectionNxmLink(string link, out string domainName, domainName = match.Groups["domain"].Value; slug = match.Groups["slug"].Value; - if (Int32.TryParse(match.Groups["revision"].Value, out var parsedRevision)) + if (int.TryParse(match.Groups["revision"].Value, out var parsedRevision)) { revision = parsedRevision; } @@ -312,16 +316,16 @@ public static bool TryParseCollectionNxmLink(string link, out string domainName, /// public static bool TryParseCollectionUrl(string url, out string domainName, out string slug, out int? revision) { - domainName = String.Empty; - slug = String.Empty; + domainName = string.Empty; + slug = string.Empty; revision = null; - if (String.IsNullOrEmpty(url)) + if (string.IsNullOrEmpty(url)) { return false; } - var match = _collectionUrlPattern.Match(url); + var match = CollectionUrlPattern().Match(url); if (match.Success is false) { return false; @@ -330,7 +334,7 @@ public static bool TryParseCollectionUrl(string url, out string domainName, out domainName = match.Groups["domain"].Value; slug = match.Groups["slug"].Value; - if (match.Groups["revision"].Success && Int32.TryParse(match.Groups["revision"].Value, out var parsedRevision)) + if (match.Groups["revision"].Success && int.TryParse(match.Groups["revision"].Value, out var parsedRevision)) { revision = parsedRevision; } diff --git a/Stardrop/Utilities/External/SMAPI.cs b/Stardrop/Utilities/External/SMAPI.cs index 371a67b7..6e233e20 100644 --- a/Stardrop/Utilities/External/SMAPI.cs +++ b/Stardrop/Utilities/External/SMAPI.cs @@ -17,11 +17,20 @@ namespace Stardrop.Utilities.External { - static class SMAPI + static partial class SMAPI { internal static bool IsRunning = false; - internal static Process Process; - internal static readonly Regex responseHeadersPattern = new Regex(@"^HEADERS\r?\n=+", RegexOptions.Multiline); + internal static Process Process = null!; + [GeneratedRegex(@"^HEADERS\r?\n=+", RegexOptions.Multiline)] + internal static partial Regex ResponseHeadersPattern(); + + internal static readonly JsonSerializerOptions ResponseOptions = new() { PropertyNameCaseInsensitive = true }; + + + internal static readonly JsonSerializerOptions RequestOptions = new() { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true + }; public static ProcessStartInfo GetPrepareProcess(bool hideConsole) { @@ -29,7 +38,7 @@ public static ProcessStartInfo GetPrepareProcess(bool hideConsole) var fileName = smapiInfo.FullName; var arguments = string.Empty; - var parsedModPath = string.Empty; + string? parsedModPath; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) is true) { fileName = "/usr/bin/env"; @@ -96,7 +105,7 @@ public static string GetProcessName() /// The update data, or null if smapi.io could not provide it (so a failed check is not mistaken for one that found nothing) public async static Task?> GetModUpdateData(GameDetails gameDetails, List mods) { - List searchEntries = new List(); + List searchEntries = []; // Mods installed by a collection are pinned to whatever version their collection asks for, so they are // never sent to smapi.io. Their requirements below are still sent, as those feed the mod key name cache @@ -113,7 +122,7 @@ public static string GetProcessName() } // Create the body to be sent via the POST request - ModSearchData searchData = new ModSearchData(searchEntries, gameDetails.SmapiVersion, gameDetails.GameVersion, gameDetails.System.ToString(), true); + ModSearchData searchData = new(searchEntries, gameDetails.SmapiVersion, gameDetails.GameVersion, gameDetails.System.ToString(), true); // Create a throwaway client using HttpClient client = new HttpClient(); @@ -121,7 +130,7 @@ public static string GetProcessName() client.DefaultRequestHeaders.Add("Application-Version", Program.ApplicationVersion); client.DefaultRequestHeaders.Add("User-Agent", $"Stardrop/{Program.ApplicationVersion} {Environment.OSVersion}"); - var parsedRequest = JsonSerializer.Serialize(searchData, new JsonSerializerOptions() { WriteIndented = true, IgnoreNullValues = true }); + var parsedRequest = JsonSerializer.Serialize(searchData, RequestOptions); var requestPackage = new StringContent(parsedRequest, Encoding.UTF8, "application/json"); // Network failures and timeouts are reported as no data, so the caller treats them the same as an error status from smapi.io @@ -143,7 +152,7 @@ public static string GetProcessName() string content = await response.Content.ReadAsStringAsync(); try { - modUpdateData = JsonSerializer.Deserialize>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + modUpdateData = JsonSerializer.Deserialize>(content, ResponseOptions); } catch (JsonException ex) { @@ -185,7 +194,7 @@ public static string GetProcessName() /// Drops the request headers smapi.io echoes back on its error page private static string GetLoggableResponse(string content) { - var headersMatch = responseHeadersPattern.Match(content); + var headersMatch = ResponseHeadersPattern().Match(content); if (headersMatch.Success is false) { return content; diff --git a/Stardrop/Utilities/Helper.cs b/Stardrop/Utilities/Helper.cs index 42ff8ec3..d232ba3d 100644 --- a/Stardrop/Utilities/Helper.cs +++ b/Stardrop/Utilities/Helper.cs @@ -19,12 +19,12 @@ internal class Helper // Used for identifying different statuses when logging public enum Status { Debug, Alert, Warning, Info }; - public Helper(string fileName = "log", string fileExtension = ".txt", string path = null) + public Helper(string fileName = "log", string fileExtension = ".txt", string? path = null) { // Set the log file name and extension logFileName = fileName; logFileExtension = fileExtension; - basePath = String.IsNullOrEmpty(path) ? basePath : path; + basePath = string.IsNullOrEmpty(path) ? basePath : path; // Delete any previous log file if (File.Exists(GetLogPath())) @@ -51,7 +51,7 @@ public Helper(string fileName = "log", string fileExtension = ".txt", string pat public string GetLogPath() { - return Path.Combine(basePath, String.Concat(logFileName, logFileExtension)); + return Path.Combine(basePath, string.Concat(logFileName, logFileExtension)); } public void DisableTracing() @@ -84,33 +84,33 @@ public void Log(object messageObj, Status status = Status.Debug, [CallerMemberNa { try { - Log(messageObj.ToString(), status, caller, line, path); + Log(messageObj.ToString()!, status, caller, line, path); } catch { - Log(String.Format($"Unable to parse {messageObj} to string!"), Status.Warning); + Log(string.Format($"Unable to parse {messageObj} to string!"), Status.Warning); } } #region Status related tracking public bool HasAlert() { - return totalAlert > 0 ? true : false; + return totalAlert > 0; } public bool HasWarning() { - return totalWarning > 0 ? true : false; + return totalWarning > 0; } public bool HasInfo() { - return totalInfo > 0 ? true : false; + return totalInfo > 0; } public bool HasDebug() { - return totalDebug > 0 ? true : false; + return totalDebug > 0; } #endregion diff --git a/Stardrop/Utilities/Internal/CollectionCache.cs b/Stardrop/Utilities/Internal/CollectionCache.cs index 688a16aa..8b2f5e22 100644 --- a/Stardrop/Utilities/Internal/CollectionCache.cs +++ b/Stardrop/Utilities/Internal/CollectionCache.cs @@ -12,11 +12,11 @@ namespace Stardrop.Utilities.Internal /// internal static class CollectionCache { - private static readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions() { WriteIndented = true, PropertyNameCaseInsensitive = true }; + private static readonly JsonSerializerOptions _serializerOptions = new() { WriteIndented = true, PropertyNameCaseInsensitive = true }; public static List LoadAll() { - List collections = new List(); + List collections = []; var cacheFolder = Pathing.GetCollectionsCacheFolderPath(); if (Directory.Exists(cacheFolder) is false) @@ -29,7 +29,7 @@ public static List LoadAll() try { var collection = JsonSerializer.Deserialize(File.ReadAllText(fileInfo.FullName), _serializerOptions); - if (collection is null || String.IsNullOrEmpty(collection.SourceId)) + if (collection is null || string.IsNullOrEmpty(collection.SourceId)) { Program.helper.Log($"The collection record at {fileInfo.FullName} was empty or not deserializable", Helper.Status.Alert); continue; diff --git a/Stardrop/Utilities/Internal/CollectionReferenceMatcher.cs b/Stardrop/Utilities/Internal/CollectionReferenceMatcher.cs index 8fae150e..a8aa75a4 100644 --- a/Stardrop/Utilities/Internal/CollectionReferenceMatcher.cs +++ b/Stardrop/Utilities/Internal/CollectionReferenceMatcher.cs @@ -13,12 +13,13 @@ namespace Stardrop.Utilities.Internal /// rather than the first one that happens to line up, or a rule written for one mod will attach itself to /// another that shares a single field. /// - internal static class CollectionReferenceMatcher + internal static partial class CollectionReferenceMatcher { // A duplicate download marker is dropped off an archive name before comparing, in either the download // manager's own format or the one browsers use - private static readonly Regex _duplicateSuffixPattern = new Regex(@"(?:\.\d+| \(\d+\))$", RegexOptions.Compiled); - + // private static readonly Regex _duplicateSuffixPattern = new(@"(?:\.\d+| \(\d+\))$", RegexOptions.Compiled); + [GeneratedRegex(@"(?:\.\d+| \(\d+\))$", RegexOptions.Compiled)] + private static partial Regex DuplicateSuffixPattern(); /// /// The entry a rule end points at, or -1 when nothing matches. The first match wins. /// @@ -43,9 +44,9 @@ private static bool Matches(CollectionModEntry entry, CollectionModRuleReference return false; } - if (String.IsNullOrEmpty(reference.Tag) is false) + if (string.IsNullOrEmpty(reference.Tag) is false) { - if (String.Equals(entry.Tag, reference.Tag, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(entry.Tag, reference.Tag, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -57,10 +58,10 @@ private static bool Matches(CollectionModEntry entry, CollectionModRuleReference } } - var hashMatches = String.IsNullOrEmpty(reference.FileMD5) is false && String.Equals(entry.Md5Checksum, reference.FileMD5, StringComparison.OrdinalIgnoreCase); + var hashMatches = string.IsNullOrEmpty(reference.FileMD5) is false && string.Equals(entry.Md5Checksum, reference.FileMD5, StringComparison.OrdinalIgnoreCase); // A hash pins the file outright, so it has to agree unless the reference asks for a range of versions - if (String.IsNullOrEmpty(reference.FileMD5) is false && isFuzzy is false && hashMatches is false) + if (string.IsNullOrEmpty(reference.FileMD5) is false && isFuzzy is false && hashMatches is false) { return false; } @@ -87,43 +88,43 @@ private static bool Matches(CollectionModEntry entry, CollectionModRuleReference private static bool HasIdentifyingMarker(CollectionModEntry entry, CollectionModRuleReference reference, bool isFuzzy, bool allowTag) { - if (isFuzzy is false && String.IsNullOrEmpty(reference.FileMD5) is false && String.IsNullOrEmpty(entry.Md5Checksum) is false) + if (isFuzzy is false && string.IsNullOrEmpty(reference.FileMD5) is false && string.IsNullOrEmpty(entry.Md5Checksum) is false) { return true; } - if (String.IsNullOrEmpty(reference.FileExpression) is false && (String.IsNullOrEmpty(entry.FileExpression) is false || String.IsNullOrEmpty(entry.Name) is false)) + if (string.IsNullOrEmpty(reference.FileExpression) is false && (string.IsNullOrEmpty(entry.FileExpression) is false || string.IsNullOrEmpty(entry.Name) is false)) { return true; } - if (String.IsNullOrEmpty(reference.LogicalFileName) is false && String.IsNullOrEmpty(entry.LogicalFilename) is false) + if (string.IsNullOrEmpty(reference.LogicalFileName) is false && string.IsNullOrEmpty(entry.LogicalFilename) is false) { return true; } - return allowTag && String.IsNullOrEmpty(reference.Tag) is false && String.IsNullOrEmpty(entry.Tag) is false; + return allowTag && string.IsNullOrEmpty(reference.Tag) is false && string.IsNullOrEmpty(entry.Tag) is false; } private static bool MatchesLogicalFileName(CollectionModEntry entry, CollectionModRuleReference reference) { - if (String.IsNullOrEmpty(reference.LogicalFileName)) + if (string.IsNullOrEmpty(reference.LogicalFileName)) { return true; } - if (String.Equals(entry.LogicalFilename, reference.LogicalFileName, StringComparison.OrdinalIgnoreCase) || String.Equals(entry.Name, reference.LogicalFileName, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(entry.LogicalFilename, reference.LogicalFileName, StringComparison.OrdinalIgnoreCase) || string.Equals(entry.Name, reference.LogicalFileName, StringComparison.OrdinalIgnoreCase)) { return true; } // A file expression is allowed to carry the match on its own, so a mismatch here is not the end of it - return String.IsNullOrEmpty(reference.FileExpression) is false; + return string.IsNullOrEmpty(reference.FileExpression) is false; } private static bool MatchesFileExpression(CollectionModEntry entry, CollectionModRuleReference reference) { - if (String.IsNullOrEmpty(reference.FileExpression)) + if (string.IsNullOrEmpty(reference.FileExpression)) { return true; } @@ -141,18 +142,18 @@ private static bool MatchesFileExpression(CollectionModEntry entry, CollectionMo return true; } - return String.Equals(entry.Name, reference.FileExpression, StringComparison.OrdinalIgnoreCase); + return string.Equals(entry.Name, reference.FileExpression, StringComparison.OrdinalIgnoreCase); } private static bool MatchesVersion(CollectionModEntry entry, CollectionModRuleReference reference) { - if (String.IsNullOrEmpty(reference.VersionMatch) || reference.VersionMatch == "*" || String.IsNullOrEmpty(entry.Version)) + if (string.IsNullOrEmpty(reference.VersionMatch) || reference.VersionMatch == "*" || string.IsNullOrEmpty(entry.Version)) { return true; } var versionMatch = reference.VersionMatch.Split('+')[0]; - if (String.Equals(entry.Version, reference.VersionMatch, StringComparison.OrdinalIgnoreCase) || String.Equals(entry.Version, versionMatch, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(entry.Version, reference.VersionMatch, StringComparison.OrdinalIgnoreCase) || string.Equals(entry.Version, versionMatch, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -177,7 +178,7 @@ private static bool MatchesVersion(CollectionModEntry entry, CollectionModRuleRe /// private static bool IsFuzzyVersion(string? versionMatch) { - if (String.IsNullOrEmpty(versionMatch)) + if (string.IsNullOrEmpty(versionMatch)) { return false; } @@ -197,12 +198,12 @@ private static bool IsFuzzyVersion(string? versionMatch) private static bool MatchesExpression(string? value, string expression) { - if (String.IsNullOrEmpty(value)) + if (string.IsNullOrEmpty(value)) { return false; } - if (String.Equals(value, expression, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(value, expression, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -220,12 +221,12 @@ private static bool MatchesExpression(string? value, string expression) private static string? SanitizeExpression(string? filePath) { - if (String.IsNullOrEmpty(filePath)) + if (string.IsNullOrEmpty(filePath)) { return null; } - return _duplicateSuffixPattern.Replace(Path.GetFileNameWithoutExtension(filePath), String.Empty); + return DuplicateSuffixPattern().Replace(Path.GetFileNameWithoutExtension(filePath), string.Empty); } } } diff --git a/Stardrop/Utilities/Internal/HyperlinkParser.cs b/Stardrop/Utilities/Internal/HyperlinkParser.cs index f8704a75..c7cde8c3 100644 --- a/Stardrop/Utilities/Internal/HyperlinkParser.cs +++ b/Stardrop/Utilities/Internal/HyperlinkParser.cs @@ -1,5 +1,4 @@ using Stardrop.Models.Data; -using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -10,14 +9,22 @@ namespace Stardrop.Utilities.Internal /// Curator supplied text arrives as either plain text or light markdown, so bare addresses and [label](url) /// pairs are both handled. /// - internal static class HyperlinkParser + internal static partial class HyperlinkParser { - private static readonly Regex _markdownLinkPattern = new Regex(@"\[((?:\\.|[^\]\\])*)\]\(\s*(\S+?)\s*\)", RegexOptions.Compiled); - private static readonly Regex _bareLinkPattern = new Regex(@"(?:https?://|www\.)\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private static readonly Regex _wordPattern = new Regex(@"\S+", RegexOptions.Compiled); - private static readonly Regex _escapeSequencePattern = new Regex(@"\\(.)", RegexOptions.Compiled); - private static readonly char[] _lineWhitespace = new char[] { ' ', '\t' }; - private static readonly char[] _trailingPunctuation = new char[] { '.', ',', ';', ':', '!', '?', '"', '\'', ')', ']', '}', '>' }; + //private static readonly Regex _markdownLinkPattern = new(@"\[((?:\\.|[^\]\\])*)\]\(\s*(\S+?)\s*\)", RegexOptions.Compiled); + //private static readonly Regex _bareLinkPattern = new(@"(?:https?://|www\.)\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase); + //private static readonly Regex _wordPattern = new(@"\S+", RegexOptions.Compiled); + //private static readonly Regex _escapeSequencePattern = new(@"\\(.)", RegexOptions.Compiled); + [GeneratedRegex(@"\[((?:\\.|[^\]\\])*)\]\(\s*(\S+?)\s*\)", RegexOptions.Compiled)] + private static partial Regex MarkdownLinkPattern(); + [GeneratedRegex(@"(?:https?://|www\.)\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase)] + private static partial Regex BareLinkPattern(); + [GeneratedRegex(@"\S+", RegexOptions.Compiled)] + private static partial Regex WordPattern(); + [GeneratedRegex(@"\\(.)", RegexOptions.Compiled)] + private static partial Regex EscapeSequencePattern(); + private static readonly char[] _lineWhitespace = [' ', '\t']; + private static readonly char[] _trailingPunctuation = ['.', ',', ';', ':', '!', '?', '"', '\'', ')', ']', '}', '>']; /// Width given to each leading space, so indented list entries keep their shape private const double _indentWidthPerSpace = 4; @@ -37,7 +44,7 @@ private sealed record LinkMatch(int Start, int End, string Label, string Uri); public static List Parse(string? text) { var lines = new List(); - if (String.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return lines; } @@ -70,9 +77,9 @@ public static string CreateLink(string? label, string? uri) /// public static string Escape(string? text) { - if (String.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { - return String.Empty; + return string.Empty; } return text.Replace("\\", "\\\\").Replace("[", "\\[").Replace("]", "\\]"); @@ -84,7 +91,7 @@ private static RichTextLine ParseLine(string rawLine) var line = new RichTextLine() { IndentWidth = (rawLine.Length - content.Length) * _indentWidthPerSpace }; // A line with no segments would collapse to no height, taking the blank line separating each list with it - if (String.IsNullOrWhiteSpace(content)) + if (string.IsNullOrWhiteSpace(content)) { line.Segments.Add(RichTextSegment.CreateText(_spacePlaceholder)); return line; @@ -98,7 +105,7 @@ private static RichTextLine ParseLine(string rawLine) // Carried as its own segment rather than as part of the label, to keep the underline off the gap var spacing = GetSpacing(content, link.End); - if (String.IsNullOrEmpty(spacing) is false) + if (string.IsNullOrEmpty(spacing) is false) { line.Segments.Add(RichTextSegment.CreateText(spacing)); } @@ -119,10 +126,10 @@ private static List FindLinks(string content) var links = new List(); int index = 0; - foreach (Match match in _markdownLinkPattern.Matches(content)) + foreach (Match match in MarkdownLinkPattern().Matches(content)) { var label = Unescape(match.Groups[1].Value); - if (String.IsNullOrWhiteSpace(label) || Toolkit.TryGetWebAddress(match.Groups[2].Value, out var webAddress) is false) + if (string.IsNullOrWhiteSpace(label) || Toolkit.TryGetWebAddress(match.Groups[2].Value, out var webAddress) is false) { continue; } @@ -144,7 +151,7 @@ private static List FindBareLinks(string content, int start, int end) return links; } - foreach (Match match in _bareLinkPattern.Matches(content.Substring(start, end - start))) + foreach (Match match in BareLinkPattern().Matches(content.Substring(start, end - start))) { // Sentence punctuation sitting against an address belongs to the sentence rather than to the address var candidate = match.Value.TrimEnd(_trailingPunctuation); @@ -167,7 +174,7 @@ private static void AddWords(RichTextLine line, string content, int start, int e return; } - foreach (Match match in _wordPattern.Matches(content.Substring(start, end - start))) + foreach (Match match in WordPattern().Matches(content.Substring(start, end - start))) { var wordEnd = start + match.Index + match.Length; line.Segments.Add(RichTextSegment.CreateText(Unescape(match.Value) + GetSpacing(content, wordEnd))); @@ -176,17 +183,17 @@ private static void AddWords(RichTextLine line, string content, int start, int e private static string GetSpacing(string content, int index) { - if (index < content.Length && Char.IsWhiteSpace(content[index])) + if (index < content.Length && char.IsWhiteSpace(content[index])) { return _spacePlaceholder; } - return String.Empty; + return string.Empty; } private static string Unescape(string text) { - return _escapeSequencePattern.Replace(text, "$1"); + return EscapeSequencePattern().Replace(text, "$1"); } } } diff --git a/Stardrop/Utilities/Internal/ManifestParser.cs b/Stardrop/Utilities/Internal/ManifestParser.cs index af2f27ac..998130ee 100644 --- a/Stardrop/Utilities/Internal/ManifestParser.cs +++ b/Stardrop/Utilities/Internal/ManifestParser.cs @@ -1,6 +1,5 @@ using SharpCompress.Archives; using Stardrop.Models.SMAPI; -using System; using System.IO; using System.Text.Json; using System.Threading.Tasks; @@ -11,13 +10,10 @@ internal static class ManifestParser { public static async Task GetDataAsync(IArchiveEntry manifestFile) { - using (Stream stream = manifestFile.OpenEntryStream()) - { - using (var reader = new StreamReader(stream)) - { - return GetData(await reader.ReadToEndAsync()); - } - } + using Stream stream = manifestFile.OpenEntryStream(); + using var reader = new StreamReader(stream); + + return GetData(await reader.ReadToEndAsync()); } public static Manifest? GetData(string manifestText) @@ -29,7 +25,7 @@ internal static class ManifestParser catch (JsonException) { // Attempt to parse out illegal JSON characters, as System.Text.Json does not have any native handling (unlike Newtonsoft.Json) - manifestText = manifestText.Replace("\r", String.Empty).Replace("\n", String.Empty); + manifestText = manifestText.Replace("\r", string.Empty).Replace("\n", string.Empty); return JsonSerializer.Deserialize(manifestText, new JsonSerializerOptions() { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, PropertyNameCaseInsensitive = true }); } } diff --git a/Stardrop/Utilities/Internal/ThemeManager.cs b/Stardrop/Utilities/Internal/ThemeManager.cs index 7efdbd70..c7858837 100644 --- a/Stardrop/Utilities/Internal/ThemeManager.cs +++ b/Stardrop/Utilities/Internal/ThemeManager.cs @@ -84,7 +84,7 @@ public static void ApplyDefaults(Styles theme) foreach (var key in defaults.Resources.Keys.ToList()) { // A theme may declare resources at the Styles level or inside a child Style, so ask the theme as a whole - if (((IResourceProvider)theme).TryGetResource(key, out _)) + if (((IResourceProvider)theme).TryGetResource(key, ThemeVariant.Default, out _)) { continue; } @@ -99,7 +99,7 @@ public static void ApplyDefaults(Styles theme) private static Styles? ParseDefaults() { var defaultsFileText = GetDefaultsFileText(); - if (String.IsNullOrEmpty(defaultsFileText)) + if (string.IsNullOrEmpty(defaultsFileText)) { return null; } diff --git a/Stardrop/Utilities/JsonTools.cs b/Stardrop/Utilities/JsonTools.cs index c1dd862f..a57e6509 100644 --- a/Stardrop/Utilities/JsonTools.cs +++ b/Stardrop/Utilities/JsonTools.cs @@ -14,7 +14,7 @@ public static string ParseDocumentToString(JsonDocument jdoc) { using (var stream = new MemoryStream()) { - Utf8JsonWriter writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); + Utf8JsonWriter writer = new(stream, new JsonWriterOptions { Indented = true }); jdoc.WriteTo(writer); writer.Flush(); diff --git a/Stardrop/Utilities/NXMProtocol.cs b/Stardrop/Utilities/NXMProtocol.cs index fe68309e..8ee2c76f 100644 --- a/Stardrop/Utilities/NXMProtocol.cs +++ b/Stardrop/Utilities/NXMProtocol.cs @@ -47,7 +47,7 @@ internal sealed class NXMAssociationState /// /// A display name for whichever application currently owns the protocol (used for warning messages) /// - public string HandlerName { get; init; } = String.Empty; + public string HandlerName { get; init; } = string.Empty; } internal sealed class NXMUnregistrationResult @@ -96,34 +96,34 @@ public static bool Register(string applicationPath) // The dedicated ProgId is what Windows offers under Settings > Default apps using (RegistryKey progIdKey = Registry.CurrentUser.CreateSubKey($@"{ClassesPath}\{ProgId}")) { - progIdKey.SetValue(String.Empty, "URL:Nexus Mods Protocol"); - progIdKey.SetValue("URL Protocol", String.Empty); + progIdKey.SetValue(string.Empty, "URL:Nexus Mods Protocol"); + progIdKey.SetValue("URL Protocol", string.Empty); using (RegistryKey iconKey = progIdKey.CreateSubKey("DefaultIcon")) { - iconKey.SetValue(String.Empty, icon); + iconKey.SetValue(string.Empty, icon); } using (RegistryKey commandKey = progIdKey.CreateSubKey(@"shell\open\command")) { - commandKey.SetValue(String.Empty, command); + commandKey.SetValue(string.Empty, command); } } // The bare protocol key is the fallback Windows uses when no UserChoice has been made using (RegistryKey protocolKey = Registry.CurrentUser.CreateSubKey($@"{ClassesPath}\{ProtocolName}")) { - protocolKey.SetValue(String.Empty, "URL:Nexus Mods Protocol"); - protocolKey.SetValue("URL Protocol", String.Empty); + protocolKey.SetValue(string.Empty, "URL:Nexus Mods Protocol"); + protocolKey.SetValue("URL Protocol", string.Empty); using (RegistryKey iconKey = protocolKey.CreateSubKey("DefaultIcon")) { - iconKey.SetValue(String.Empty, icon); + iconKey.SetValue(string.Empty, icon); } using (RegistryKey commandKey = protocolKey.CreateSubKey(@"shell\open\command")) { - commandKey.SetValue(String.Empty, command); + commandKey.SetValue(string.Empty, command); } } @@ -176,7 +176,7 @@ public static NXMUnregistrationResult Unregister(string applicationPath) // Windows resolves UserChoice ahead of the class keys, so one left pointing at Stardrop would break NXM links outright string? userChoiceProgId = GetUserChoiceProgId(); - if (String.IsNullOrEmpty(userChoiceProgId) is false && IsStardropHandler(userChoiceProgId, expectedCommand)) + if (string.IsNullOrEmpty(userChoiceProgId) is false && IsStardropHandler(userChoiceProgId, expectedCommand)) { if (TryDeleteUserChoice()) { @@ -247,7 +247,7 @@ public static NXMAssociationState GetState(string applicationPath) // Windows checks UserChoice before it looks at the protocol's class key, so anything set there wins string? userChoiceProgId = GetUserChoiceProgId(); - if (String.IsNullOrEmpty(userChoiceProgId) || String.Equals(userChoiceProgId, ProtocolName, StringComparison.OrdinalIgnoreCase)) + if (string.IsNullOrEmpty(userChoiceProgId) || string.Equals(userChoiceProgId, ProtocolName, StringComparison.OrdinalIgnoreCase)) { return new NXMAssociationState() { @@ -259,7 +259,7 @@ public static NXMAssociationState GetState(string applicationPath) } string? userChoiceCommand = GetCommandForProgId(userChoiceProgId); - if (String.Equals(userChoiceProgId, ProgId, StringComparison.OrdinalIgnoreCase) || IsExpectedCommand(userChoiceCommand, expectedCommand)) + if (string.Equals(userChoiceProgId, ProgId, StringComparison.OrdinalIgnoreCase) || IsExpectedCommand(userChoiceCommand, expectedCommand)) { return new NXMAssociationState() { @@ -305,7 +305,7 @@ public static void LogDiagnostics(string applicationPath) { NXMAssociationState state = GetState(applicationPath); - StringBuilder report = new StringBuilder(); + StringBuilder report = new(); report.AppendLine($"{Environment.NewLine}-- NXM Protocol --"); report.AppendLine($"Status: {state.Status}"); report.AppendLine($"Expected Command: {GetExpectedCommand(applicationPath)}"); @@ -333,12 +333,12 @@ private static string GetExpectedCommand(string applicationPath) private static bool IsExpectedCommand(string? command, string expectedCommand) { - return String.Equals(command, expectedCommand, StringComparison.OrdinalIgnoreCase); + return string.Equals(command, expectedCommand, StringComparison.OrdinalIgnoreCase); } private static string GetLoggableValue(string? value) { - return String.IsNullOrEmpty(value) ? "(none)" : value; + return string.IsNullOrEmpty(value) ? "(none)" : value; } [SupportedOSPlatform("windows")] @@ -353,7 +353,7 @@ private static string GetLoggableValue(string? value) private static string? GetCommandForProgId(string progId) { string? command = GetUserCommandForProgId(progId); - if (String.IsNullOrEmpty(command) is false) + if (string.IsNullOrEmpty(command) is false) { return command; } @@ -370,7 +370,7 @@ private static string GetLoggableValue(string? value) { using RegistryKey? userKey = Registry.CurrentUser.OpenSubKey($@"{ClassesPath}\{progId}\shell\open\command"); - return userKey?.GetValue(String.Empty)?.ToString(); + return userKey?.GetValue(string.Empty)?.ToString(); } [SupportedOSPlatform("windows")] @@ -378,21 +378,21 @@ private static string GetLoggableValue(string? value) { using RegistryKey? machineKey = Registry.LocalMachine.OpenSubKey($@"{ClassesPath}\{progId}\shell\open\command"); - return machineKey?.GetValue(String.Empty)?.ToString(); + return machineKey?.GetValue(string.Empty)?.ToString(); } [SupportedOSPlatform("windows")] private static bool HasCapabilities() { using RegistryKey? urlAssociationsKey = Registry.CurrentUser.OpenSubKey($@"{CapabilitiesPath}\UrlAssociations"); - if (String.Equals(urlAssociationsKey?.GetValue(ProtocolName)?.ToString(), ProgId, StringComparison.OrdinalIgnoreCase) is false) + if (string.Equals(urlAssociationsKey?.GetValue(ProtocolName)?.ToString(), ProgId, StringComparison.OrdinalIgnoreCase) is false) { return false; } using RegistryKey? registeredApplicationsKey = Registry.CurrentUser.OpenSubKey(RegisteredApplicationsPath); - return String.Equals(registeredApplicationsKey?.GetValue(RegisteredApplicationName)?.ToString(), CapabilitiesPath, StringComparison.OrdinalIgnoreCase); + return string.Equals(registeredApplicationsKey?.GetValue(RegisteredApplicationName)?.ToString(), CapabilitiesPath, StringComparison.OrdinalIgnoreCase); } /// @@ -413,14 +413,14 @@ private static bool HasStardropRegistryEntries(string expectedCommand) // A UserChoice can outlive the keys it points at, so a dangling one still counts as something to clean up string? userChoiceProgId = GetUserChoiceProgId(); - if (String.IsNullOrEmpty(userChoiceProgId) is false && IsStardropHandler(userChoiceProgId, expectedCommand)) + if (string.IsNullOrEmpty(userChoiceProgId) is false && IsStardropHandler(userChoiceProgId, expectedCommand)) { return true; } using RegistryKey? registeredApplicationsKey = Registry.CurrentUser.OpenSubKey(RegisteredApplicationsPath); - return String.Equals(registeredApplicationsKey?.GetValue(RegisteredApplicationName)?.ToString(), CapabilitiesPath, StringComparison.OrdinalIgnoreCase); + return string.Equals(registeredApplicationsKey?.GetValue(RegisteredApplicationName)?.ToString(), CapabilitiesPath, StringComparison.OrdinalIgnoreCase); } /// @@ -430,7 +430,7 @@ private static bool HasStardropRegistryEntries(string expectedCommand) [SupportedOSPlatform("windows")] private static bool IsStardropHandler(string progId, string expectedCommand) { - if (String.Equals(progId, ProgId, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(progId, ProgId, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -469,7 +469,7 @@ private static bool RemoveCapabilities() using (RegistryKey? registeredApplicationsKey = Registry.CurrentUser.OpenSubKey(RegisteredApplicationsPath, true)) { // Only the entry pointing at Stardrop's own capabilities path is removed - if (registeredApplicationsKey is not null && String.Equals(registeredApplicationsKey.GetValue(RegisteredApplicationName)?.ToString(), CapabilitiesPath, StringComparison.OrdinalIgnoreCase)) + if (registeredApplicationsKey is not null && string.Equals(registeredApplicationsKey.GetValue(RegisteredApplicationName)?.ToString(), CapabilitiesPath, StringComparison.OrdinalIgnoreCase)) { registeredApplicationsKey.DeleteValue(RegisteredApplicationName, false); removedCapabilities = true; @@ -544,7 +544,7 @@ private static bool IsUserSubKeyEmpty(string path) /// private static string GetDisplayName(string progId, string? command) { - if (String.IsNullOrEmpty(command) is false) + if (string.IsNullOrEmpty(command) is false) { string executable = command.Trim(); if (executable.StartsWith('"')) @@ -561,7 +561,7 @@ private static string GetDisplayName(string progId, string? command) try { string name = Path.GetFileNameWithoutExtension(executable); - if (String.IsNullOrEmpty(name) is false) + if (string.IsNullOrEmpty(name) is false) { return name; } diff --git a/Stardrop/Utilities/NexusWebsocket.cs b/Stardrop/Utilities/NexusWebsocket.cs index 7ff464bd..dc86d9db 100644 --- a/Stardrop/Utilities/NexusWebsocket.cs +++ b/Stardrop/Utilities/NexusWebsocket.cs @@ -22,7 +22,7 @@ internal class NexusWebsocket public NexusWebsocket() { - this.ssoUrl = $"https://www.nexusmods.com/sso?id={connectionUUID}&application={connectionSlug}"; + ssoUrl = $"https://www.nexusmods.com/sso?id={connectionUUID}&application={connectionSlug}"; } public async Task ConnectAsync(CancellationToken cancellationToken = default) diff --git a/Stardrop/Utilities/Pathing.cs b/Stardrop/Utilities/Pathing.cs index f42d9573..1e86c146 100644 --- a/Stardrop/Utilities/Pathing.cs +++ b/Stardrop/Utilities/Pathing.cs @@ -11,9 +11,9 @@ public static class Pathing // produced rather than one that collapses into its parent folder private const string _fallbackPathSegment = "unnamed"; - internal static string defaultGamePath; - internal static string defaultModPath; - internal static string defaultHomePath; + internal static string defaultGamePath = null!; + internal static string defaultModPath = null!; + internal static string defaultHomePath = null!; internal static void SetHomePath(string homePath) { @@ -138,7 +138,7 @@ public static string GetCollectionsRootPath() /// public static string GetCollectionsFolderPath() { - return String.IsNullOrWhiteSpace(Program.settings.CollectionInstallPath) ? GetDefaultCollectionsFolderPath() : Program.settings.CollectionInstallPath; + return string.IsNullOrWhiteSpace(Program.settings.CollectionInstallPath) ? GetDefaultCollectionsFolderPath() : Program.settings.CollectionInstallPath; } /// Where collections install to before the setting has been given a value of its own @@ -185,14 +185,14 @@ public static string GetCollectionOverlayPath(string sourceId, string storedName /// public static string GetSafePathSegment(string? name, char replacement = '_') { - if (String.IsNullOrWhiteSpace(name)) + if (string.IsNullOrWhiteSpace(name)) { return _fallbackPathSegment; } var safeName = ReplaceInvalidFileNameCharacters(name, replacement).Trim().TrimEnd('.', ' '); - return String.IsNullOrEmpty(safeName) ? _fallbackPathSegment : safeName; + return string.IsNullOrEmpty(safeName) ? _fallbackPathSegment : safeName; } /// @@ -221,13 +221,13 @@ public static string ReplaceInvalidFileNameCharacters(string name, char replacem /// public static string? GetSafeDestinationPath(string destinationFolder, string? relativePath) { - if (String.IsNullOrWhiteSpace(relativePath)) + if (string.IsNullOrWhiteSpace(relativePath)) { return destinationFolder; } var safePath = destinationFolder; - foreach (var segment in relativePath.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var segment in relativePath.Split(['/', '\\'], StringSplitOptions.RemoveEmptyEntries)) { if (segment == ".") { @@ -251,7 +251,7 @@ public static string ReplaceInvalidFileNameCharacters(string name, char replacem /// public static string? GetCollectionSourceId(string? modDirectoryPath) { - if (String.IsNullOrEmpty(modDirectoryPath) || String.IsNullOrEmpty(defaultHomePath)) + if (string.IsNullOrEmpty(modDirectoryPath) || string.IsNullOrEmpty(defaultHomePath)) { return null; } @@ -275,12 +275,12 @@ public static string ReplaceInvalidFileNameCharacters(string name, char replacem } var relativePath = modPath.Substring(collectionsRoot.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - if (String.IsNullOrEmpty(relativePath)) + if (string.IsNullOrEmpty(relativePath)) { return null; } - var separatorIndex = relativePath.IndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); + var separatorIndex = relativePath.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]); return separatorIndex == -1 ? relativePath : relativePath.Substring(0, separatorIndex); } @@ -297,7 +297,7 @@ public static bool IsSamePath(string? first, string? second) return false; } - return String.Equals(AppendSeparator(fullFirst), AppendSeparator(fullSecond), StringComparison.OrdinalIgnoreCase); + return string.Equals(AppendSeparator(fullFirst), AppendSeparator(fullSecond), StringComparison.OrdinalIgnoreCase); } /// @@ -327,7 +327,7 @@ public static bool IsSameOrUnder(string? path, string? potentialParent) /// private static string? TryGetFullPath(string? path) { - if (String.IsNullOrWhiteSpace(path)) + if (string.IsNullOrWhiteSpace(path)) { return null; } diff --git a/Stardrop/Utilities/SimpleObscure.cs b/Stardrop/Utilities/SimpleObscure.cs index 46587a23..ed5d9a19 100644 --- a/Stardrop/Utilities/SimpleObscure.cs +++ b/Stardrop/Utilities/SimpleObscure.cs @@ -30,11 +30,11 @@ internal static byte[] Encrypt(string plainText, byte[] Key, byte[] IV) ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); // Create the streams used for encryption. - using (MemoryStream msEncrypt = new MemoryStream()) + using (MemoryStream msEncrypt = new()) { - using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write)) { - using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) + using (StreamWriter swEncrypt = new(csEncrypt)) { swEncrypt.Write(plainText); } @@ -48,30 +48,17 @@ internal static byte[] Encrypt(string plainText, byte[] Key, byte[] IV) internal static string Decrypt(byte[] cipherText, byte[] Key, byte[] IV) { - string plaintext = null; + using Aes aes = Aes.Create(); + aes.Key = Key; + aes.IV = IV; - using (Aes aes = Aes.Create()) - { - aes.Key = Key; - aes.IV = IV; - - // Create a decryptor to perform the stream transform. - ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); + ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); - // Create the streams used for decryption. - using (MemoryStream msDecrypt = new MemoryStream(cipherText)) - { - using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) - { - using (StreamReader srDecrypt = new StreamReader(csDecrypt)) - { - plaintext = srDecrypt.ReadToEnd(); - } - } - } - } + using MemoryStream msDecrypt = new(cipherText); + using CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read); + using StreamReader srDecrypt = new(csDecrypt); - return plaintext; + return srDecrypt.ReadToEnd(); } } } \ No newline at end of file diff --git a/Stardrop/Utilities/Toolkit.cs b/Stardrop/Utilities/Toolkit.cs index 523142b6..14e4843c 100644 --- a/Stardrop/Utilities/Toolkit.cs +++ b/Stardrop/Utilities/Toolkit.cs @@ -15,17 +15,17 @@ public static string ToHumanReadableSize(long bytes) { if (bytes >= 1024L * 1024L * 1024L) { - return $"{(bytes / (1024.0 * 1024.0 * 1024.0)):N2} {Program.translation.Get("internal.measurements.gigabytes_size")}"; + return $"{bytes / (1024.0 * 1024.0 * 1024.0):N2} {Program.translation.Get("internal.measurements.gigabytes_size")}"; } if (bytes >= 1024L * 1024L) { - return $"{(bytes / (1024.0 * 1024.0)):N2} {Program.translation.Get("internal.measurements.megabytes_size")}"; + return $"{bytes / (1024.0 * 1024.0):N2} {Program.translation.Get("internal.measurements.megabytes_size")}"; } if (bytes >= 1024L) { - return $"{(bytes / 1024.0):N2} {Program.translation.Get("internal.measurements.kilobytes_size")}"; + return $"{bytes / 1024.0:N2} {Program.translation.Get("internal.measurements.kilobytes_size")}"; } return $"{bytes:N0} {Program.translation.Get("internal.measurements.bytes_size")}"; @@ -54,14 +54,14 @@ public static string ToHumanReadableSize(long bytes) public static void OpenBrowser(string url) { - if (String.IsNullOrEmpty(url)) + if (string.IsNullOrEmpty(url)) { return; } try { - using Process process = Process.Start(new ProcessStartInfo + using Process? process = Process.Start(new ProcessStartInfo { FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? url : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "open" : "xdg-open", @@ -82,8 +82,8 @@ public static void OpenBrowser(string url) /// public static bool TryGetWebAddress(string? url, out string webAddress) { - webAddress = String.Empty; - if (String.IsNullOrWhiteSpace(url)) + webAddress = string.Empty; + if (string.IsNullOrWhiteSpace(url)) { return false; } diff --git a/Stardrop/Utilities/Translation.cs b/Stardrop/Utilities/Translation.cs index e325f333..a1fdd8b9 100644 --- a/Stardrop/Utilities/Translation.cs +++ b/Stardrop/Utilities/Translation.cs @@ -10,16 +10,10 @@ namespace Stardrop.Utilities { internal class Translation : INotifyPropertyChanged { - public sealed class LanguageOption + public sealed class LanguageOption(string code) { - public string Code { get; } - public string DisplayName { get; } - - public LanguageOption(string code) - { - Code = code; - DisplayName = GetDisplayName(code); - } + public string Code { get; } = code; + public string DisplayName { get; } = GetDisplayName(code); public override string ToString() { @@ -28,14 +22,14 @@ public override string ToString() private static string GetDisplayName(string code) { - if (String.Equals(code, "default", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(code, "default", StringComparison.OrdinalIgnoreCase)) { return "English"; } try { - return CultureInfo.GetCultureInfo(code).EnglishName; + return CultureInfo.GetCultureInfo(code).NativeName; } catch (CultureNotFoundException) { @@ -68,6 +62,13 @@ private static string GetDisplayName(string code) private const string IndexerName = "Item"; private const string IndexerArrayName = "Item[]"; + private static readonly JsonSerializerOptions TranslationOptions = new() + { + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip, + PropertyNameCaseInsensitive = true + }; + public string GetLanguageFromAbbreviation(string abbreviation) { if (_languageTranslations.ContainsKey(abbreviation)) @@ -80,7 +81,7 @@ public string GetLanguageFromAbbreviation(string abbreviation) public string NormalizeLanguage(string language) { - if (String.IsNullOrWhiteSpace(language)) + if (string.IsNullOrWhiteSpace(language)) { return "default"; } @@ -110,7 +111,13 @@ public void LoadTranslations() try { var fileName = Path.GetFileNameWithoutExtension(fileFullName); - _languageTranslations[fileName] = JsonSerializer.Deserialize>(File.ReadAllText(fileFullName), new JsonSerializerOptions { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, PropertyNameCaseInsensitive = true }); + Dictionary? translations = JsonSerializer.Deserialize>(File.ReadAllText(fileFullName), TranslationOptions); + if (translations is null) + { + Program.helper.Log($"Translation file {fileName} parsed to nothing", Helper.Status.Warning); + continue; + } + _languageTranslations[fileName] = translations; Program.helper.Log($"Loaded language {fileName}", Helper.Status.Debug); } catch (Exception ex) @@ -123,7 +130,7 @@ public void LoadTranslations() public List GetAvailableTranslations() { return _languageTranslations.Keys - .OrderBy(code => String.Equals(code, "default", StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .OrderBy(code => string.Equals(code, "default", StringComparison.OrdinalIgnoreCase) ? 0 : 1) .ThenBy(code => new LanguageOption(code).DisplayName, StringComparer.CurrentCultureIgnoreCase) .Select(code => new LanguageOption(code)) .ToList(); @@ -151,7 +158,7 @@ public string this[string key] } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; public void Invalidate() { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(IndexerName)); @@ -160,7 +167,7 @@ public void Invalidate() private string GetCanonicalLanguageCode(string code) { - return _languageTranslations.Keys.First(key => String.Equals(key, code, StringComparison.OrdinalIgnoreCase)); + return _languageTranslations.Keys.First(key => string.Equals(key, code, StringComparison.OrdinalIgnoreCase)); } } } diff --git a/Stardrop/ViewLocator.cs b/Stardrop/ViewLocator.cs index 6a7d1322..9776adea 100644 --- a/Stardrop/ViewLocator.cs +++ b/Stardrop/ViewLocator.cs @@ -7,8 +7,13 @@ namespace Stardrop { public class ViewLocator : IDataTemplate { - public IControl Build(object data) + public Control? Build(object? data) { + if (data is null) + { + return null; + } + var name = data.GetType().FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); @@ -22,7 +27,7 @@ public IControl Build(object data) } } - public bool Match(object data) + public bool Match(object? data) { return data is ViewModelBase; } diff --git a/Stardrop/ViewModels/ChangelogWindowViewModel.cs b/Stardrop/ViewModels/ChangelogWindowViewModel.cs index 93326167..04b1b004 100644 --- a/Stardrop/ViewModels/ChangelogWindowViewModel.cs +++ b/Stardrop/ViewModels/ChangelogWindowViewModel.cs @@ -1,4 +1,4 @@ -using ReactiveUI; +using ReactiveUI.Reactive; using Semver; using Stardrop.Models.Nexus.Web; using System; @@ -10,9 +10,15 @@ namespace Stardrop.ViewModels { public class ChangelogWindowViewModel : ViewModelBase { - public ObservableCollection Versions { get; set; } + private ObservableCollection _versions = []; - private string _modName = String.Empty; + public ObservableCollection Versions + { + get => _versions; + set => this.RaiseAndSetIfChanged(ref _versions, value); + } + + private string _modName = string.Empty; public string ModName { get { return _modName; } set { this.RaiseAndSetIfChanged(ref _modName, value); } } private bool _hasChanges; @@ -24,18 +30,18 @@ public class ChangelogWindowViewModel : ViewModelBase private bool _showEmptyMessage; public bool ShowEmptyMessage { get { return _showEmptyMessage; } set { this.RaiseAndSetIfChanged(ref _showEmptyMessage, value); } } - private string _modPageUri = String.Empty; + private string _modPageUri = string.Empty; public string ModPageUri { get { return _modPageUri; } set { this.RaiseAndSetIfChanged(ref _modPageUri, value); } } private bool _hasModPage; public bool HasModPage { get { return _hasModPage; } set { this.RaiseAndSetIfChanged(ref _hasModPage, value); } } - private string _emptyMessage = String.Empty; + private string _emptyMessage = string.Empty; public string EmptyMessage { get { return _emptyMessage; } set { this.RaiseAndSetIfChanged(ref _emptyMessage, value); } } public ChangelogWindowViewModel() { - Versions = new ObservableCollection(); + Versions = []; } /// diff --git a/Stardrop/ViewModels/CollectionsWindowViewModel.cs b/Stardrop/ViewModels/CollectionsWindowViewModel.cs index 9a2a286d..1a3e5dd9 100644 --- a/Stardrop/ViewModels/CollectionsWindowViewModel.cs +++ b/Stardrop/ViewModels/CollectionsWindowViewModel.cs @@ -1,4 +1,4 @@ -using ReactiveUI; +using ReactiveUI.Reactive; using Semver; using Stardrop.Models; using Stardrop.Models.Data; @@ -48,8 +48,8 @@ public CollectionEntryView(CollectionInstall collection, CollectionModEntry entr _collection = collection; _entry = entry; - Name = String.IsNullOrEmpty(entry.Name) ? Program.translation.Get("internal.unknown") : entry.Name; - Version = String.IsNullOrEmpty(entry.Version) ? String.Empty : entry.Version; + Name = string.IsNullOrEmpty(entry.Name) ? Program.translation.Get("internal.unknown") : entry.Name; + Version = string.IsNullOrEmpty(entry.Version) ? string.Empty : entry.Version; Status = DescribeStatus(collection, entry); SortableVersion = SemVersion.TryParse(Version, SemVersionStyles.Any, out var parsedVersion) ? parsedVersion : null; @@ -63,12 +63,12 @@ private static string DescribeStatus(CollectionInstall collection, CollectionMod if (entry.Status is CollectionModStatus.AwaitingTargets) { var blockingNames = collection.DescribeBlockingTargets(entry, CollectionInstall.MAX_LISTED_TARGET_NAMES, Program.translation.Get("ui.message.collection_names_truncated")); - if (String.IsNullOrEmpty(blockingNames)) + if (string.IsNullOrEmpty(blockingNames)) { return Program.translation.Get("ui.collections_window.status.awaiting_targets_unnamed"); } - return String.Format(Program.translation.Get("ui.collections_window.status.awaiting_targets"), blockingNames); + return string.Format(Program.translation.Get("ui.collections_window.status.awaiting_targets"), blockingNames); } // An optional entry Stardrop could not fetch on the user's behalf is theirs to decide on, so it says so @@ -90,7 +90,7 @@ private static string DescribeStatus(CollectionInstall collection, CollectionMod }; // The reason is the useful half of a failure, so it rides along rather than hiding in a tooltip - if (entry.Status is CollectionModStatus.Failed && String.IsNullOrEmpty(entry.FailureReason) is false) + if (entry.Status is CollectionModStatus.Failed && string.IsNullOrEmpty(entry.FailureReason) is false) { return $"{status} ({entry.FailureReason})"; } @@ -98,7 +98,7 @@ private static string DescribeStatus(CollectionInstall collection, CollectionMod // Files the curator listed that were not in the download mean the replacement is only partly in place if (entry.Status is CollectionModStatus.AppliedAsOverlay && entry.UnmatchedFileCount > 0) { - return $"{status} ({String.Format(Program.translation.Get("ui.collections_window.status.files_missing"), entry.UnmatchedFileCount)})"; + return $"{status} ({string.Format(Program.translation.Get("ui.collections_window.status.files_missing"), entry.UnmatchedFileCount)})"; } return status; @@ -145,13 +145,13 @@ public CollectionView(CollectionInstall collection) { SourceId = collection.SourceId; ProfileName = collection.ProfileName; - Name = String.IsNullOrEmpty(collection.Name) ? collection.Slug : collection.Name; - HasCurator = String.IsNullOrEmpty(collection.Curator) is false; - Curator = HasCurator ? String.Format(Program.translation.Get("ui.collections_window.labels.curator"), collection.Curator) : String.Empty; - Revision = String.Format(Program.translation.Get("ui.collections_window.labels.revision"), collection.RevisionNumber, collection.InstallTimestamp.ToShortDateString()); - Profile = String.Format(Program.translation.Get("ui.collections_window.labels.profile"), collection.ProfileName); + Name = string.IsNullOrEmpty(collection.Name) ? collection.Slug : collection.Name; + HasCurator = string.IsNullOrEmpty(collection.Curator) is false; + Curator = HasCurator ? string.Format(Program.translation.Get("ui.collections_window.labels.curator"), collection.Curator) : string.Empty; + Revision = string.Format(Program.translation.Get("ui.collections_window.labels.revision"), collection.RevisionNumber, collection.InstallTimestamp.ToShortDateString()); + Profile = string.Format(Program.translation.Get("ui.collections_window.labels.profile"), collection.ProfileName); InstalledModCount = collection.GetInstalledCount(); - Progress = String.Format(Program.translation.Get("ui.collections_window.labels.installed"), InstalledModCount, collection.GetModCount()); + Progress = string.Format(Program.translation.Get("ui.collections_window.labels.installed"), InstalledModCount, collection.GetModCount()); PageUri = collection.GetPageUri(); DomainName = collection.DomainName; @@ -165,21 +165,21 @@ public CollectionView(CollectionInstall collection) // user has already agreed to it and is looking at what is left of it if (IsUpdateInProgress) { - UpdateStatus = String.Format(Program.translation.Get("ui.collections_window.labels.update_in_progress"), collection.PendingRevisionNumber); + UpdateStatus = string.Format(Program.translation.Get("ui.collections_window.labels.update_in_progress"), collection.PendingRevisionNumber); UpdateMarker = Program.translation.Get("ui.collections_window.labels.update_in_progress_marker"); UpdatePageUri = collection.GetRevisionPageUri(collection.PendingRevisionNumber!.Value); } else if (HasUpdate) { - UpdateStatus = String.Format(Program.translation.Get("ui.collections_window.labels.update_available"), collection.LatestRevisionNumber); + UpdateStatus = string.Format(Program.translation.Get("ui.collections_window.labels.update_available"), collection.LatestRevisionNumber); UpdateMarker = Program.translation.Get("ui.collections_window.labels.update_marker"); UpdatePageUri = collection.GetRevisionPageUri(collection.LatestRevisionNumber!.Value); } else { - UpdateStatus = String.Empty; - UpdateMarker = String.Empty; - UpdatePageUri = String.Empty; + UpdateStatus = string.Empty; + UpdateMarker = string.Empty; + UpdatePageUri = string.Empty; } Entries = collection.Mods.Select(m => new CollectionEntryView(collection, m)).ToList(); @@ -188,8 +188,8 @@ public CollectionView(CollectionInstall collection) public class CollectionsWindowViewModel : ViewModelBase { - public ObservableCollection Collections { get; } = new ObservableCollection(); - public ObservableCollection Entries { get; } = new ObservableCollection(); + public ObservableCollection Collections { get; } = []; + public ObservableCollection Entries { get; } = []; private CollectionView? _selectedCollection; public CollectionView? SelectedCollection @@ -236,7 +236,7 @@ public bool ShowMissingOnly private CollectionSortColumn _sortColumn = CollectionSortColumn.Status; private bool _sortDescending; - private string _statusMessage = String.Empty; + private string _statusMessage = string.Empty; /// /// The result of the last thing that landed while this window was open. Shown in the footer rather than in /// a dialog, since a user fetching a page of missing entries would otherwise have one to dismiss per mod. @@ -259,7 +259,7 @@ public bool IsStatusMessageFailure set { this.RaiseAndSetIfChanged(ref _isStatusMessageFailure, value); } } - public bool HasStatusMessage { get { return String.IsNullOrEmpty(_statusMessage) is false; } } + public bool HasStatusMessage { get { return string.IsNullOrEmpty(_statusMessage) is false; } } public bool HasCollections { get { return Collections.Count > 0; } } /// Whether anything is mid-check, which the refresh button reads so it cannot be pressed twice @@ -329,7 +329,7 @@ public List GetMissingPageUris() foreach (var entry in SortEntries(_selectedCollection.Entries.Where(e => e.IsMissing))) { - if (entry.PageUri is not string pageUri || String.IsNullOrEmpty(pageUri)) + if (entry.PageUri is not string pageUri || string.IsNullOrEmpty(pageUri)) { continue; } diff --git a/Stardrop/ViewModels/DownloadPanelViewModel.cs b/Stardrop/ViewModels/DownloadPanelViewModel.cs index dee06aa5..0f17288d 100644 --- a/Stardrop/ViewModels/DownloadPanelViewModel.cs +++ b/Stardrop/ViewModels/DownloadPanelViewModel.cs @@ -2,7 +2,7 @@ using DynamicData; using DynamicData.Aggregation; using DynamicData.Binding; -using ReactiveUI; +using ReactiveUI.Reactive; using Stardrop.Models.Data; using Stardrop.Utilities.External; using System; @@ -13,11 +13,27 @@ namespace Stardrop.ViewModels { public class DownloadPanelViewModel : ViewModelBase { - private ObservableCollection _downloads = new(); - public ObservableCollection Downloads { get => _downloads; set => this.RaiseAndSetIfChanged(ref _downloads, value); } + private ObservableCollection _downloads = []; + public ObservableCollection Downloads + { + get => _downloads; + set + { + if (ReferenceEquals(_downloads, value)) + { + return; + } - public IObservable InProgressDownloads { get; init; } + _downloads.CollectionChanged -= OnDownloadsCollectionChanged; + this.RaiseAndSetIfChanged(ref _downloads, value); + _downloads.CollectionChanged += OnDownloadsCollectionChanged; + this.RaisePropertyChanged(nameof(HasDownloads)); + } + } + + public IObservable InProgressDownloads { get; } + public bool HasDownloads => Downloads.Count > 0; public DownloadPanelViewModel(NexusClient? nexusClient) { Nexus.ClientChanged += NexusClientChanged; @@ -30,9 +46,15 @@ public DownloadPanelViewModel(NexusClient? nexusClient) // handled in some way by the user InProgressDownloads = Downloads .ToObservableChangeSet(t => t.ModUri) - .AutoRefresh(x => x.DownloadStatus, scheduler: RxApp.MainThreadScheduler) + .AutoRefresh(x => x.DownloadStatus, scheduler: RxSchedulers.MainThreadScheduler) .Filter(x => x.DownloadStatus != ModDownloadStatus.Successful) .Count(); + Downloads.CollectionChanged += OnDownloadsCollectionChanged; + } + + private void OnDownloadsCollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) + { + this.RaisePropertyChanged(nameof(HasDownloads)); } private void NexusClientChanged(NexusClient? oldClient, NexusClient? newClient) @@ -143,13 +165,17 @@ public DownloadPanelViewModel() throw new Exception("This constructor should only be called in design mode."); } + InProgressDownloads = System.Reactive.Linq.Observable.Return(0); + var inProgressDownload = new ModDownloadViewModel( new Uri("https://www.fakeurl.com/testMod"), "Fake Test Mod Download", 1024 * 1024, new() - ); - inProgressDownload.DownloadStatus = ModDownloadStatus.InProgress; + ) + { + DownloadStatus = ModDownloadStatus.InProgress + }; inProgressDownload.DownloadedBytes = inProgressDownload.SizeBytes!.Value / 2; Downloads.Add(inProgressDownload); @@ -158,9 +184,11 @@ public DownloadPanelViewModel() "Fake Succeeded Download", 1234, new() - ); - succeededDownload.DownloadStatus = ModDownloadStatus.Successful; - succeededDownload.DownloadedBytes = 1234; + ) + { + DownloadStatus = ModDownloadStatus.Successful, + DownloadedBytes = 1234 + }; Downloads.Add(succeededDownload); var failedDownload = new ModDownloadViewModel( @@ -188,9 +216,11 @@ public DownloadPanelViewModel() "In Progress Download of Unknown Size", null, new() - ); - indeterminateInProgressDownload.DownloadedBytes = 1024 * 1024 * 2; - indeterminateInProgressDownload.DownloadStatus = ModDownloadStatus.InProgress; + ) + { + DownloadedBytes = 1024 * 1024 * 2, + DownloadStatus = ModDownloadStatus.InProgress + }; Downloads.Add(indeterminateInProgressDownload); } } diff --git a/Stardrop/ViewModels/FlexibleOptionWindowViewModel.cs b/Stardrop/ViewModels/FlexibleOptionWindowViewModel.cs index 895123f3..e955928f 100644 --- a/Stardrop/ViewModels/FlexibleOptionWindowViewModel.cs +++ b/Stardrop/ViewModels/FlexibleOptionWindowViewModel.cs @@ -1,17 +1,17 @@ using Avalonia.Controls; -using ReactiveUI; +using ReactiveUI.Reactive; namespace Stardrop.ViewModels { public class FlexibleOptionWindowViewModel : ViewModelBase { - private string _messageText; + private string _messageText = null!; public string MessageText { get { return _messageText; } set { this.RaiseAndSetIfChanged(ref _messageText, value); } } - private string _firstButtonText; + private string _firstButtonText = null!; public string FirstButtonText { get { return _firstButtonText; } set { this.RaiseAndSetIfChanged(ref _firstButtonText, value); } } - private string _secondButtonText; + private string _secondButtonText = null!; public string SecondButtonText { get { return _secondButtonText; } set { this.RaiseAndSetIfChanged(ref _secondButtonText, value); } } - private string _thirdButtonText; + private string _thirdButtonText = null!; public string ThirdButtonText { get { return _thirdButtonText; } set { this.RaiseAndSetIfChanged(ref _thirdButtonText, value); } } private bool _isFirstButtonVisible; diff --git a/Stardrop/ViewModels/MainWindowViewModel.cs b/Stardrop/ViewModels/MainWindowViewModel.cs index e66a7c74..90fbc18b 100644 --- a/Stardrop/ViewModels/MainWindowViewModel.cs +++ b/Stardrop/ViewModels/MainWindowViewModel.cs @@ -1,7 +1,7 @@ using Avalonia.Collections; using Avalonia.Controls; using Json.More; -using ReactiveUI; +using ReactiveUI.Reactive; using SharpCompress.Archives; using SharpCompress.Common; using Stardrop.Models; @@ -27,15 +27,15 @@ namespace Stardrop.ViewModels { public class MainWindowViewModel : ViewModelBase { - private string ChromeHint { get; set; } = "NoChrome"; - private bool HasSystemDecorations { get; set; } = true; - private bool ShowTitle { get; set; } = true; - private bool ShowMainMenu { get; set; } = true; - private bool ShowWindowMenu { get; set; } = true; + // public string ChromeHint { get; set; } = "NoChrome"; + // private bool HasSystemDecorations { get; set; } = true; + public bool ShowTitle { get; set; } = true; + public bool ShowMainMenu { get; set; } = true; + public bool ShowWindowMenu { get; set; } = true; - private DataGridPathGroupDescription _modPathGrouping = new DataGridPathGroupDescription(nameof(Mod.Path)); - private DataGridPathGroupDescription _rootPathGrouping = new DataGridPathGroupDescription(nameof(Mod.RootPath)); - private DataGridPathGroupDescription _frameworkGrouping = new DataGridPathGroupDescription(nameof(Mod.FrameworkID)); + private DataGridPathGroupDescription _modPathGrouping = new(nameof(Mod.Path)); + private DataGridPathGroupDescription _rootPathGrouping = new(nameof(Mod.RootPath)); + private DataGridPathGroupDescription _frameworkGrouping = new(nameof(Mod.FrameworkID)); private string _dragOverColor = "#ff9f2a"; public string DragOverColor { get { return _dragOverColor; } set { this.RaiseAndSetIfChanged(ref _dragOverColor, value); } } @@ -43,7 +43,7 @@ public class MainWindowViewModel : ViewModelBase public bool IsLocked { get { return _isLocked; } set { this.RaiseAndSetIfChanged(ref _isLocked, value); } } private bool _isCheckingForUpdates; public bool IsCheckingForUpdates { get { return _isCheckingForUpdates; } set { this.RaiseAndSetIfChanged(ref _isCheckingForUpdates, value); } } - public ObservableCollection Mods { get; set; } + public ObservableCollection Mods { get; set; } = null!; private int _enabledModCount; public int EnabledModCount { get { return _enabledModCount; } set { this.RaiseAndSetIfChanged(ref _enabledModCount, value); } } private int _actualModCount; @@ -62,25 +62,36 @@ public class MainWindowViewModel : ViewModelBase /// Whether any installed mod belongs to a collection. Drives the visibility of the source filter, which is noise for users with no collections public bool HasCollectionMods { get { return _hasCollectionMods; } set { this.RaiseAndSetIfChanged(ref _hasCollectionMods, value); } } private Profile? _activeProfile; - private HashSet _activeProfileReferences = new HashSet(); + private HashSet _activeProfileReferences = []; private bool _showEndorsements; public bool ShowEndorsements { get { return _showEndorsements; } set { this.RaiseAndSetIfChanged(ref _showEndorsements, value); } } private bool _showInstalls; public bool ShowInstalls { get { return _showInstalls; } set { this.RaiseAndSetIfChanged(ref _showInstalls, value); } } private bool _isNexusConnected; + public bool IsNexusConnected + { + get => _isNexusConnected; + set => this.RaiseAndSetIfChanged(ref _isNexusConnected, value); + } /// Visibility preferences from the column context menu, keyed by ext:ColumnExtensions.Key - private Dictionary _columnPreferences = new Dictionary(); - private string _filterText; + private Dictionary _columnPreferences = []; + private string _filterText = null!; public string FilterText { get { return _filterText; } set { _filterText = value; UpdateFilter(); } } - private List _columnFilter; + private List _columnFilter = null!; public List ColumnFilter { get { return _columnFilter; } set { _columnFilter = value; UpdateFilter(); } } private string _updateStatusText = Program.translation.Get("ui.main_window.button.update_status.generic"); public string UpdateStatusText { get { return _updateStatusText; } set { this.RaiseAndSetIfChanged(ref _updateStatusText, value); } } - private string _downloadsButtonText; + private string _downloadsButtonText = null!; public string DownloadsButtonText { get => _downloadsButtonText; set => this.RaiseAndSetIfChanged(ref _downloadsButtonText, value); } private int _modsWithCachedUpdates; public int ModsWithCachedUpdates { get { return _modsWithCachedUpdates; } set { this.RaiseAndSetIfChanged(ref _modsWithCachedUpdates, value); } } private int _collectionsWithUpdates; + + private ModUpdateState _updateState = ModUpdateState.Generic; + public ModUpdateState UpdateState { + get => _updateState; + set => this.RaiseAndSetIfChanged(ref _updateState, value); + } /// /// Collections sitting behind a newer revision. Shown beside the mod update count as a pointer towards the /// collections window, which is where the update itself is described and acted on. @@ -98,28 +109,31 @@ public int CollectionsWithUpdates public bool HasCollectionUpdates { get { return _collectionsWithUpdates > 0; } } public string Version { get; set; } - private string _nexusStatus = String.Concat("Nexus Mods: ", Program.translation.Get("internal.disconnected")); - public string NexusStatus { get { return _nexusStatus; } set { this.RaiseAndSetIfChanged(ref _nexusStatus, String.Concat("Nexus Mods: ", value)); } } - - private string _nexusLimits; + private string _nexusLimits = null!; public string NexusLimits { get { return _nexusLimits; } set { this.RaiseAndSetIfChanged(ref _nexusLimits, value); } } - private string _smapiVersion; - public string SmapiVersion { get { return String.IsNullOrEmpty(_smapiVersion) ? Program.translation.Get("ui.main_window.labels.unknown_SMAPI") : $"v{_smapiVersion}"; } set { this.RaiseAndSetIfChanged(ref _smapiVersion, value); } } + private string _smapiVersion = null!; + public string SmapiVersion { get { return string.IsNullOrEmpty(_smapiVersion) ? Program.translation.Get("ui.main_window.labels.unknown_SMAPI") : $"v{_smapiVersion}"; } set { this.RaiseAndSetIfChanged(ref _smapiVersion, value); } } public bool ShowSaveProfileChanges { get { return _showSaveProfileChanges; } set { this.RaiseAndSetIfChanged(ref _showSaveProfileChanges, value); } } private bool _showSaveProfileChanges; public bool AreModGroupsEnabled { get { return _areModGroupsEnabled; } set { this.RaiseAndSetIfChanged(ref _areModGroupsEnabled, value); } } private bool _areModGroupsEnabled = Program.settings.ModGroupingMethod != ModGrouping.None; + private bool _areModGroupsExpanded = true; + public bool AreModGroupsExpanded + { + get => _areModGroupsExpanded; + set => this.RaiseAndSetIfChanged(ref _areModGroupsExpanded, value); + } public bool ShowModThumbnails { get { return _showModThumbnails; } set { this.RaiseAndSetIfChanged(ref _showModThumbnails, value); } } private bool _showModThumbnails = Program.settings.ShowModThumbnails; - public string ModGroupsStateButtonText { get { return _modGroupsStateButtonText; } set { this.RaiseAndSetIfChanged(ref _modGroupsStateButtonText, value); } } - private string _modGroupsStateButtonText = Program.settings.ModGroupingMethod != ModGrouping.None ? Program.translation.Get("ui.main_window.buttons.mod_groups_state.collapse") : Program.translation.Get("ui.main_window.buttons.mod_groups_state.expand"); + private static readonly JsonSerializerOptions ReadOptions = new() { AllowTrailingCommas = true }; + private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true }; public MainWindowViewModel(string modsFilePath, string version) { DiscoverMods(modsFilePath); Version = $"v{version}"; - SmapiVersion = Program.settings.GameDetails?.SmapiVersion; + SmapiVersion = Program.settings.GameDetails?.SmapiVersion ?? string.Empty; // Create data view DataView = new DataGridCollectionView(Mods, isDataSorted: false, isDataInGroupOrder: false); @@ -132,13 +146,11 @@ public MainWindowViewModel(string modsFilePath, string version) // Do OS specific setup if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - ChromeHint = "Default"; ShowMainMenu = false; ShowWindowMenu = false; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - ChromeHint = "Default"; ShowWindowMenu = false; ShowTitle = false; } @@ -186,10 +198,10 @@ public void SetColumnVisibility(MenuItem column, DataGrid modGrid, bool isActive } // Get the local data - ClientData localDataCache = new ClientData(); + ClientData localDataCache = new(); if (File.Exists(Pathing.GetDataCachePath())) { - localDataCache = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + localDataCache = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), ReadOptions) ?? new ClientData(); } if (isActive) @@ -207,7 +219,7 @@ public void SetColumnVisibility(MenuItem column, DataGrid modGrid, bool isActive localDataCache.ColumnActiveStates[header] = isActive; // Cache the local data - File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(localDataCache, new JsonSerializerOptions() { WriteIndented = true })); + File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(localDataCache, WriteOptions)); } /// @@ -217,7 +229,7 @@ public void SetColumnVisibility(MenuItem column, DataGrid modGrid, bool isActive private void ApplyColumnVisibility(DataGridColumn targetColumn, bool isActive) { var columnKey = ColumnExtensions.GetKey(targetColumn); - if (String.IsNullOrEmpty(columnKey) is false) + if (string.IsNullOrEmpty(columnKey) is false) { _columnPreferences[columnKey] = isActive; } @@ -252,13 +264,13 @@ public void RefreshGatedColumns(DataGrid modGrid, bool isNexusConnected) } var columnKey = ColumnExtensions.GetKey(targetColumn); - if (String.IsNullOrEmpty(columnKey)) + if (string.IsNullOrEmpty(columnKey)) { Program.helper.Log($"Failed to gate column {targetColumn.Header}: it lacks an ext:ColumnExtensions.Key value in the XAML."); continue; } - bool isEnabled = _columnPreferences.TryGetValue(columnKey, out bool preference) ? preference : true; + bool isEnabled = !_columnPreferences.TryGetValue(columnKey, out bool preference) || preference; targetColumn.IsVisible = isEnabled && isNexusConnected; } } @@ -266,10 +278,10 @@ public void RefreshGatedColumns(DataGrid modGrid, bool isNexusConnected) public void SetColumnOrder(DataGrid modGrid) { // Get the local data - ClientData localDataCache = new ClientData(); + ClientData localDataCache = new(); if (File.Exists(Pathing.GetDataCachePath())) { - localDataCache = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + localDataCache = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), ReadOptions) ?? new ClientData(); } if (localDataCache is not null && modGrid is not null && modGrid.Columns is not null) @@ -287,7 +299,7 @@ public void SetColumnOrder(DataGrid modGrid) } // Cache the local data - File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(localDataCache, new JsonSerializerOptions() { WriteIndented = true })); + File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(localDataCache, WriteOptions)); } } @@ -342,7 +354,7 @@ private static Dictionary GetCollectionsBySourceId() /// private static void ApplyCollectionDetails(Mod mod, Dictionary collectionsBySourceId) { - if (String.IsNullOrEmpty(mod.SourceId)) + if (string.IsNullOrEmpty(mod.SourceId)) { return; } @@ -354,7 +366,7 @@ private static void ApplyCollectionDetails(Mod mod, Dictionary GetScanRoots(string modsFilePath) { var roots = new List(); - if (String.IsNullOrEmpty(modsFilePath) is false && Directory.Exists(modsFilePath)) + if (string.IsNullOrEmpty(modsFilePath) is false && Directory.Exists(modsFilePath)) { roots.Add(modsFilePath); } @@ -438,7 +450,7 @@ private static List GetScanRoots(string modsFilePath) /// public List<(FileInfo Manifest, FileInfo? Config)> GetModFolders(DirectoryInfo modDirectory) { - List<(FileInfo Manifest, FileInfo? Config)> modFolders = new List<(FileInfo Manifest, FileInfo? Config)>(); + List<(FileInfo Manifest, FileInfo? Config)> modFolders = []; foreach (var directory in modDirectory.EnumerateDirectories()) { try @@ -468,7 +480,7 @@ private static List GetScanRoots(string modsFilePath) } catch (Exception ex) { - Program.helper.Log($"There was an error when attempting to get the manifest.json within the directory ({(directory is null ? String.Empty : directory.FullName)}): {ex}", Helper.Status.Alert); + Program.helper.Log($"There was an error when attempting to get the manifest.json within the directory ({(directory is null ? string.Empty : directory.FullName)}): {ex}", Helper.Status.Alert); } } @@ -487,7 +499,7 @@ public bool HasModInstalled(string uniqueID) /// public async Task> DirectModInstallAsync(string? fileFullName) { - List addedMods = new List(); + List addedMods = []; if (string.IsNullOrEmpty(fileFullName)) { return addedMods; @@ -498,7 +510,7 @@ public async Task> DirectModInstallAsync(string? fileFullName) // Extract the archive data using (var archive = ArchiveFactory.OpenArchive(fileFullName)) { - Dictionary pathToManifests = new Dictionary(); + Dictionary pathToManifests = []; foreach (var manifest in archive.Entries.Where(e => Path.GetFileName(e.Key)!.Equals("manifest.json", StringComparison.OrdinalIgnoreCase))) { if (manifest.Key is not null) @@ -518,7 +530,7 @@ public async Task> DirectModInstallAsync(string? fileFullName) // Warn and skip the install logic if the given archive has no manifest.json if (pathToManifests.Count == 0) { - Program.helper.Log(String.Format(Program.translation.Get("ui.warning.no_manifest"), fileFullName)); + Program.helper.Log(string.Format(Program.translation.Get("ui.warning.no_manifest"), fileFullName)); return addedMods; } @@ -532,7 +544,7 @@ public async Task> DirectModInstallAsync(string? fileFullName) if (manifest is not null) { var installPath = Program.settings.ModInstallPath; - if (String.IsNullOrEmpty(manifestPath.Replace("manifest.json", String.Empty, StringComparison.OrdinalIgnoreCase))) + if (string.IsNullOrEmpty(manifestPath.Replace("manifest.json", string.Empty, StringComparison.OrdinalIgnoreCase))) { installPath = Path.Combine(installPath, manifest.UniqueID); } @@ -544,22 +556,22 @@ public async Task> DirectModInstallAsync(string? fileFullName) } Program.helper.Log($"Install path for mod {manifest.UniqueID}:{installPath}"); - var manifestFolderPath = manifestPath.Replace("manifest.json", String.Empty, StringComparison.OrdinalIgnoreCase); - foreach (var entry in archive.Entries.Where(e => e.Key.StartsWith(manifestFolderPath))) + var manifestFolderPath = manifestPath.Replace("manifest.json", string.Empty, StringComparison.OrdinalIgnoreCase); + foreach (var entry in archive.Entries.Where(e => e.Key!.StartsWith(manifestFolderPath))) { - if (entry.Key.Contains("__MACOSX", StringComparison.OrdinalIgnoreCase) || entry.Key.Contains(".DS_Store", StringComparison.OrdinalIgnoreCase)) + if (entry.Key!.Contains("__MACOSX", StringComparison.OrdinalIgnoreCase) || entry.Key.Contains(".DS_Store", StringComparison.OrdinalIgnoreCase)) { continue; } - var outputPath = Path.Combine(installPath, manifestFolderPath, String.IsNullOrEmpty(manifestFolderPath) ? entry.Key : Path.GetRelativePath(manifestFolderPath, entry.Key)); + var outputPath = Path.Combine(installPath, manifestFolderPath, string.IsNullOrEmpty(manifestFolderPath) ? entry.Key : Path.GetRelativePath(manifestFolderPath, entry.Key)); - if (String.IsNullOrEmpty(manifestFolderPath) is false) + if (string.IsNullOrEmpty(manifestFolderPath) is false) { var installDirectory = new DirectoryInfo(installPath); var manifestDirectory = new DirectoryInfo(manifestFolderPath); if (installDirectory.Exists && (installDirectory.Name.Equals(manifestDirectory.Name, StringComparison.OrdinalIgnoreCase) || installDirectory.Name.Equals(manifest.UniqueID))) { - outputPath = Path.Combine(installPath, String.IsNullOrEmpty(manifestFolderPath) ? entry.Key : Path.GetRelativePath(manifestFolderPath, entry.Key)); + outputPath = Path.Combine(installPath, string.IsNullOrEmpty(manifestFolderPath) ? entry.Key : Path.GetRelativePath(manifestFolderPath, entry.Key)); Program.helper.Log(outputPath); } @@ -570,16 +582,16 @@ public async Task> DirectModInstallAsync(string? fileFullName) // system rejects or a segment aiming above the install path. Rebuilding the path // below installPath keeps both out, at the cost of a folder named slightly differently var safeOutputPath = Pathing.GetSafeDestinationPath(installPath, Path.GetRelativePath(installPath, outputPath)); - if (String.IsNullOrEmpty(safeOutputPath)) + if (string.IsNullOrEmpty(safeOutputPath)) { - Program.helper.Log($"Skipping {entry.Key}, as it does not resolve to a path inside {installPath}", Utilities.Helper.Status.Warning); + Program.helper.Log($"Skipping {entry.Key}, as it does not resolve to a path inside {installPath}", Helper.Status.Warning); continue; } outputPath = safeOutputPath; // Create the default location if it doesn't existe var outputFolder = Path.GetDirectoryName(outputPath); - if (String.IsNullOrEmpty(outputFolder)) + if (string.IsNullOrEmpty(outputFolder)) { continue; } @@ -601,7 +613,7 @@ public async Task> DirectModInstallAsync(string? fileFullName) } else { - Program.helper.Log(String.Format(Program.translation.Get("ui.warning.no_manifest"), fileFullName)); + Program.helper.Log(string.Format(Program.translation.Get("ui.warning.no_manifest"), fileFullName)); } currentManifestIndex += 1; @@ -610,7 +622,7 @@ public async Task> DirectModInstallAsync(string? fileFullName) } catch (Exception ex) { - Program.helper.Log($"Failed to unzip the file {fileFullName} due to the following error: {ex}", Utilities.Helper.Status.Warning); + Program.helper.Log($"Failed to unzip the file {fileFullName} due to the following error: {ex}", Helper.Status.Warning); } return addedMods; @@ -618,10 +630,7 @@ public async Task> DirectModInstallAsync(string? fileFullName) public void DiscoverMods(string modsFilePath) { - if (Mods is null) - { - Mods = new ObservableCollection(); - } + Mods ??= []; Mods.Clear(); var scanRoots = GetScanRoots(modsFilePath); @@ -631,12 +640,12 @@ public void DiscoverMods(string modsFilePath) } // Get cached key data - List modKeysCache = new List(); + List modKeysCache = []; if (File.Exists(Pathing.GetKeyCachePath())) { try { - modKeysCache = JsonSerializer.Deserialize>(File.ReadAllText(Pathing.GetKeyCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + modKeysCache = JsonSerializer.Deserialize>(File.ReadAllText(Pathing.GetKeyCachePath()), ReadOptions) ?? []; } catch (Exception ex) { @@ -645,12 +654,12 @@ public void DiscoverMods(string modsFilePath) } // Get the local data - ClientData localDataCache = new ClientData(); + ClientData localDataCache = new(); if (File.Exists(Pathing.GetDataCachePath())) { try { - localDataCache = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + localDataCache = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), ReadOptions) ?? new ClientData(); } catch (Exception ex) { @@ -669,7 +678,7 @@ public void DiscoverMods(string modsFilePath) { foreach (var modKey in modKeysCache) { - if (modKey is null || String.IsNullOrEmpty(modKey.UniqueId)) + if (modKey is null || string.IsNullOrEmpty(modKey.UniqueId)) { continue; } @@ -685,7 +694,7 @@ public void DiscoverMods(string modsFilePath) { foreach (var installData in localDataCache.ModInstallData) { - if (installData is null || String.IsNullOrEmpty(installData.UniqueId)) + if (installData is null || string.IsNullOrEmpty(installData.UniqueId)) { continue; } @@ -700,7 +709,7 @@ public void DiscoverMods(string modsFilePath) ModKeyInfo? GetModKey(string? uniqueId) { - if (String.IsNullOrEmpty(uniqueId)) + if (string.IsNullOrEmpty(uniqueId)) { return null; } @@ -718,7 +727,7 @@ public void DiscoverMods(string modsFilePath) try { var manifest = ManifestParser.GetData(File.ReadAllText(manifestInfo.FullName)); - if (manifest is null || String.IsNullOrEmpty(manifest.UniqueID)) + if (manifest is null || string.IsNullOrEmpty(manifest.UniqueID)) { Program.helper.Log($"The manifest.json was empty or not deserializable from {manifestInfo.DirectoryName}", Helper.Status.Alert); continue; @@ -802,17 +811,14 @@ public void DiscoverMods(string modsFilePath) var modInstallData = new List(); foreach (var mod in Mods.Where(m => m is not null)) { - if (mod.InstallTimestamp is null) - { - mod.InstallTimestamp = DateTime.Now; - } + mod.InstallTimestamp ??= DateTime.Now; modInstallData.Add(new ModInstallData() { UniqueId = mod.UniqueId, SourceId = mod.SourceId, InstallTimestamp = mod.InstallTimestamp.Value, LastUpdateTimestamp = mod.LastUpdateTimestamp }); } - localDataCache.ModInstallData = modInstallData; + localDataCache!.ModInstallData = modInstallData; // Cache the local data - File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(localDataCache, new JsonSerializerOptions() { WriteIndented = true })); + File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(localDataCache, WriteOptions)); EvaluateRequirements(); @@ -850,11 +856,8 @@ public void HideRequiredMods() // An enabled copy wins over everything else, the dependent's own source first. Each enabled mod is // handed to SMAPI as a junction of its own, so resolving past one that is already on and enabling a // second copy puts two folders claiming the same unique ID in the mods folder - var enabledMatch = candidates.FirstOrDefault(m => m.IsEnabled && String.Equals(m.SourceId, dependent.SourceId, StringComparison.OrdinalIgnoreCase)); - if (enabledMatch is null) - { - enabledMatch = candidates.FirstOrDefault(m => m.IsEnabled); - } + var enabledMatch = candidates.FirstOrDefault(m => m.IsEnabled && string.Equals(m.SourceId, dependent.SourceId, StringComparison.OrdinalIgnoreCase)); + enabledMatch ??= candidates.FirstOrDefault(m => m.IsEnabled); if (enabledMatch is not null) { @@ -862,7 +865,7 @@ public void HideRequiredMods() } // Nothing is on yet, so the copy that belongs alongside the dependent is the one to reach for - var sameSourceMatch = candidates.FirstOrDefault(m => String.Equals(m.SourceId, dependent.SourceId, StringComparison.OrdinalIgnoreCase)); + var sameSourceMatch = candidates.FirstOrDefault(m => string.Equals(m.SourceId, dependent.SourceId, StringComparison.OrdinalIgnoreCase)); if (sameSourceMatch is not null) { return sameSourceMatch; @@ -902,10 +905,10 @@ internal List GetDependents(Mod mod) public void EvaluateRequirements() { // Get cached key data - List modKeysCache = new List(); + List modKeysCache = []; if (File.Exists(Pathing.GetKeyCachePath())) { - modKeysCache = JsonSerializer.Deserialize>(File.ReadAllText(Pathing.GetKeyCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }); + modKeysCache = JsonSerializer.Deserialize>(File.ReadAllText(Pathing.GetKeyCachePath()), ReadOptions) ?? []; } // Flag any missing requirements @@ -936,6 +939,7 @@ public void EvaluateRequirements() mod.NotifyPropertyChanged("Requirements"); mod.NotifyPropertyChanged("MissingRequirements"); + mod.NotifyPropertyChanged("HardRequirements"); } catch (Exception ex) { @@ -946,7 +950,7 @@ public void EvaluateRequirements() public List GetConfigFiles(DirectoryInfo modDirectory) { - List configs = new List(); + List configs = []; foreach (var directory in modDirectory.EnumerateDirectories()) { var localConfigs = directory.EnumerateFiles("config.json"); @@ -1010,7 +1014,7 @@ public void DiscoverConfigs(string modsFilePath, bool useArchive = false) internal List GetPendingConfigUpdates(Profile profile, bool excludeMissingConfigs = false, bool useArchiveAsBase = false) { // Merge any existing preserved configs - List pendingConfigUpdates = new List(); + List pendingConfigUpdates = []; foreach (var reference in profile.EnabledModIds) { var modId = reference.UniqueId.ToLower(); @@ -1036,7 +1040,7 @@ internal List GetPendingConfigUpdates(Profile profile, bool excludeMissi // Write the archived config, if the current one doesn't exist if (mod.Config is null) { - if (excludeMissingConfigs || String.IsNullOrEmpty(mod.ModFileInfo.DirectoryName)) + if (excludeMissingConfigs || string.IsNullOrEmpty(mod.ModFileInfo.DirectoryName)) { continue; } @@ -1052,7 +1056,7 @@ internal List GetPendingConfigUpdates(Profile profile, bool excludeMissi if (JsonDocumentEqualityComparer.Instance.Equals(JsonDocument.Parse(mod.Config.Data), profile.PreservedModConfigs[modId]) is false) { // JsonTools.Merge will preserve the originalJson values, but will add new properties from archivedJson - string mergedJson = String.Empty; + string mergedJson = string.Empty; if (useArchiveAsBase is false) { mergedJson = JsonTools.Merge(archivedJson, currentJson, false); ; @@ -1116,7 +1120,7 @@ internal async void UpdateThumbnails() } else if (Nexus.Client is not null && mod.NexusModThumbnailPath is null) { - mod.NexusModThumbnailPath = await Nexus.Client.DownloadThumbnail((int)mod.NexusModId); + mod.NexusModThumbnailPath = await Nexus.Client.DownloadThumbnail(mod.NexusModId!.Value); } } } @@ -1256,7 +1260,7 @@ private bool PassesSourceFilter(Mod mod) // collection is what defines the profile's contents. Answered from SourceId, which comes off the // folder path and so outlives the profile being saved without the mod in it. Reading membership from // the references alone made disabling a mod remove it from the view at the next profile pass - if (String.Equals(mod.SourceId, _activeProfile.SourceId, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(mod.SourceId, _activeProfile.SourceId, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -1341,16 +1345,10 @@ internal void ResolveEnabledDuplicates() continue; } - var keptCopy = copies.FirstOrDefault(m => String.Equals(m.SourceId, preferredSourceId, StringComparison.OrdinalIgnoreCase)); - if (keptCopy is null) - { - keptCopy = copies.FirstOrDefault(m => m.IsFromCollection is false); - } + var keptCopy = copies.FirstOrDefault(m => string.Equals(m.SourceId, preferredSourceId, StringComparison.OrdinalIgnoreCase)); + keptCopy ??= copies.FirstOrDefault(m => m.IsFromCollection is false); - if (keptCopy is null) - { - keptCopy = copies.First(); - } + keptCopy ??= copies.First(); DisableDuplicatesOf(new List { keptCopy }); } @@ -1440,8 +1438,7 @@ private void TrackEnabledModsForSourceFilter() private bool ModFilter(object item) { - var mod = item as Mod; - if (mod is null) + if (item is not Mod mod) { return false; } @@ -1474,15 +1471,15 @@ private bool ModFilter(object item) return false; } - if (String.IsNullOrEmpty(_filterText) || _columnFilter is null || !_columnFilter.Any()) + if (string.IsNullOrEmpty(_filterText) || _columnFilter is null || !_columnFilter.Any()) { return true; } - if (!String.IsNullOrEmpty(_filterText) && _columnFilter.Any()) + if (!string.IsNullOrEmpty(_filterText) && _columnFilter.Any()) { - var filterTextNoWhitespace = _filterText.Replace(" ", String.Empty); - if (_columnFilter.Contains(Program.translation.Get("ui.main_window.combobox.mod_name")) && mod.Name.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase)) + var filterTextNoWhitespace = _filterText.Replace(" ", string.Empty); + if (_columnFilter.Contains(Program.translation.Get("ui.main_window.combobox.mod_name")) && mod.Name.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -1492,19 +1489,19 @@ private bool ModFilter(object item) switch (Program.settings.ModGroupingMethod) { case ModGrouping.Folder: - if (mod.Path.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) + if (mod.Path.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) { return true; } break; case ModGrouping.FolderCondensed: - if (mod.RootPath.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) + if (mod.RootPath.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) { return true; } break; case ModGrouping.ContentPack: - if (mod.FrameworkID is not null && mod.FrameworkID.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) + if (mod.FrameworkID is not null && mod.FrameworkID.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) { return true; } @@ -1518,24 +1515,24 @@ private bool ModFilter(object item) { case ModGrouping.Folder: case ModGrouping.FolderCondensed: - if (mod.RootPath is not null && mod.RootPath.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) + if (mod.RootPath is not null && mod.RootPath.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) { return true; } break; case ModGrouping.ContentPack: - if (mod.FrameworkID is not null && mod.FrameworkID.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) + if (mod.FrameworkID is not null && mod.FrameworkID.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase) is true) { return true; } break; } } - if (_columnFilter.Contains(Program.translation.Get("ui.main_window.combobox.author")) && mod.Author.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase)) + if (_columnFilter.Contains(Program.translation.Get("ui.main_window.combobox.author")) && mod.Author.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase)) { return true; } - if (_columnFilter.Contains(Program.translation.Get("ui.main_window.combobox.requirements")) && ((mod.HardRequirements is not null && mod.HardRequirements.Any(r => r.Name is null || r.Name.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase))) || (mod.MissingRequirements is not null && mod.MissingRequirements.Any(r => r.Name is null || r.Name.Replace(" ", String.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase))))) + if (_columnFilter.Contains(Program.translation.Get("ui.main_window.combobox.requirements")) && ((mod.HardRequirements is not null && mod.HardRequirements.Any(r => r.Name is null || r.Name.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase))) || (mod.MissingRequirements is not null && mod.MissingRequirements.Any(r => r.Name is null || r.Name.Replace(" ", string.Empty).Contains(filterTextNoWhitespace, StringComparison.OrdinalIgnoreCase))))) { return true; } diff --git a/Stardrop/ViewModels/MessageWindowViewModel.cs b/Stardrop/ViewModels/MessageWindowViewModel.cs index 0914e50f..46fe1205 100644 --- a/Stardrop/ViewModels/MessageWindowViewModel.cs +++ b/Stardrop/ViewModels/MessageWindowViewModel.cs @@ -1,14 +1,14 @@ -using ReactiveUI; +using ReactiveUI.Reactive; namespace Stardrop.ViewModels { public class MessageWindowViewModel : ViewModelBase { - private string _messageText; + private string _messageText = null!; public string MessageText { get { return _messageText; } set { this.RaiseAndSetIfChanged(ref _messageText, value); } } - private string _positiveButtonText; + private string _positiveButtonText = null!; public string PositiveButtonText { get { return _positiveButtonText; } set { this.RaiseAndSetIfChanged(ref _positiveButtonText, value); } } - private string _negativeButtonText; + private string _negativeButtonText = null!; public string NegativeButtonText { get { return _negativeButtonText; } set { this.RaiseAndSetIfChanged(ref _negativeButtonText, value); } } } } diff --git a/Stardrop/ViewModels/MissingModsWindowViewModel.cs b/Stardrop/ViewModels/MissingModsWindowViewModel.cs index 6ae8777c..8635ca8f 100644 --- a/Stardrop/ViewModels/MissingModsWindowViewModel.cs +++ b/Stardrop/ViewModels/MissingModsWindowViewModel.cs @@ -1,4 +1,5 @@ using Avalonia.Controls; +using ReactiveUI.Reactive; using Stardrop.Models; using System.Collections.ObjectModel; @@ -6,11 +7,16 @@ namespace Stardrop.ViewModels { public class MissingModsWindowViewModel : ViewModelBase { - public ObservableCollection MissingMods { get; set; } + private ObservableCollection _missingMods = []; + public ObservableCollection MissingMods + { + get { return _missingMods; } + set { this.RaiseAndSetIfChanged(ref _missingMods, value); } + } public MissingModsWindowViewModel() { - MissingMods = new ObservableCollection(); + MissingMods = []; if (Design.IsDesignMode) { MissingMods = diff --git a/Stardrop/ViewModels/ModDownloadViewModel.cs b/Stardrop/ViewModels/ModDownloadViewModel.cs index f24b03e7..6cb9122d 100644 --- a/Stardrop/ViewModels/ModDownloadViewModel.cs +++ b/Stardrop/ViewModels/ModDownloadViewModel.cs @@ -1,9 +1,9 @@ -using ReactiveUI; +using ReactiveUI.Reactive; using System; using System.Linq; +using System.Threading; using System.Reactive; using System.Reactive.Linq; -using System.Threading; namespace Stardrop.ViewModels { @@ -74,24 +74,24 @@ public ModDownloadViewModel(Uri modUri, string name, long? sizeInBytes, Cancella RemoveCommand = ReactiveCommand.Create(Remove); // SizeBytes null-ness to IsSizeUnknown converison - this.WhenAnyValue(x => x.SizeBytes) + this.WhenAnyValueUnsafe(x => x.SizeBytes) .Select(x => x.HasValue is false) .ToProperty(this, x => x.IsSizeUnknown, out _isSizeUnknown); // DownloadedBytes to DownloadSpeedLabel conversion - this.WhenAnyValue(x => x.DownloadedBytes) - .Sample(TimeSpan.FromMilliseconds(500), RxApp.MainThreadScheduler) + this.WhenAnyValueUnsafe(x => x.DownloadedBytes) + .Sample(TimeSpan.FromMilliseconds(500), RxSchedulers.MainThreadScheduler) .Select(bytes => { double elapsedSeconds = (DateTimeOffset.UtcNow - _startTime).TotalSeconds; double bytesPerSecond = bytes / elapsedSeconds; if (bytesPerSecond > 1024 * 1024) // MB { - return $"{(bytesPerSecond / (1024 * 1024)):N2} {Program.translation.Get("internal.measurements.megabytes_per_second")}"; + return $"{bytesPerSecond / (1024 * 1024):N2} {Program.translation.Get("internal.measurements.megabytes_per_second")}"; } else if (bytesPerSecond > 1024) // KB { - return $"{(bytesPerSecond / 1024):N2} {Program.translation.Get("internal.measurements.kilobytes_per_second")}"; + return $"{bytesPerSecond / 1024:N2} {Program.translation.Get("internal.measurements.kilobytes_per_second")}"; } else // Bytes { @@ -100,9 +100,12 @@ public ModDownloadViewModel(Uri modUri, string name, long? sizeInBytes, Cancella }).ToProperty(this, x => x.DownloadSpeedLabel, out _downloadSpeedLabel); // DownloadedBytes and SizeBytes to DownloadProgressLabel conversion - this.WhenAnyValue(x => x.DownloadedBytes, x => x.SizeBytes) - .Sample(TimeSpan.FromMilliseconds(500), RxApp.MainThreadScheduler) - .Select(((long Bytes, long? Total) x) => + this.WhenAnyValueUnsafe( + x => x.DownloadedBytes, + x => x.SizeBytes, + (bytes, total) => (bytes, total)) // 选择器直接产出元组 + .Sample(TimeSpan.FromMilliseconds(500), RxSchedulers.MainThreadScheduler) + .Select(((long Bytes, long? Total) x) => { string bytesString = ToHumanReadable(x.Bytes); if (x.Total is null) @@ -119,11 +122,11 @@ static string ToHumanReadable(long bytes) { if (bytes > 1024 * 1024) // MB { - return $"{(bytes / (1024.0 * 1024.0)):N2} {Program.translation.Get("internal.measurements.megabytes_size")}"; + return $"{bytes / (1024.0 * 1024.0):N2} {Program.translation.Get("internal.measurements.megabytes_size")}"; } else if (bytes > 1024) // KB { - return $"{(bytes / 1024.0):N2} {Program.translation.Get("internal.measurements.kilobytes_size")}"; + return $"{bytes / 1024.0:N2} {Program.translation.Get("internal.measurements.kilobytes_size")}"; } else { @@ -136,8 +139,8 @@ static string ToHumanReadable(long bytes) { // DownloadedBytes to Completion conversion this.WhenAnyValue(x => x.DownloadedBytes) - .Sample(TimeSpan.FromMilliseconds(500), RxApp.MainThreadScheduler) - .Select(x => (DownloadedBytes / (double)SizeBytes) * 100) + .Sample(TimeSpan.FromMilliseconds(500), RxSchedulers.MainThreadScheduler) + .Select(x => DownloadedBytes / (double)SizeBytes * 100) .ToProperty(this, x => x.Completion, out _completion); } } diff --git a/Stardrop/ViewModels/ProfileEditorViewModel.cs b/Stardrop/ViewModels/ProfileEditorViewModel.cs index 9c13a815..1a1dcd7e 100644 --- a/Stardrop/ViewModels/ProfileEditorViewModel.cs +++ b/Stardrop/ViewModels/ProfileEditorViewModel.cs @@ -16,8 +16,8 @@ public class ProfileEditorViewModel : ViewModelBase { public ObservableCollection Profiles { get; set; } public List OldProfiles { get; set; } - public string ToolTip_Save { get; set; } - public string ToolTip_Cancel { get; set; } + public string ToolTip_Save { get; set; } = null!; + public string ToolTip_Cancel { get; set; } = null!; private readonly string _profileFilePath; private List _mods; @@ -29,13 +29,13 @@ public class ProfileEditorViewModel : ViewModelBase public ProfileEditorViewModel(string profilesFilePath, List mods) { - OldProfiles = new List(); - Profiles = new ObservableCollection(); + OldProfiles = []; + Profiles = []; _profileFilePath = profilesFilePath; _mods = mods; - DirectoryInfo profileDirectory = new DirectoryInfo(_profileFilePath); + DirectoryInfo profileDirectory = new(_profileFilePath); foreach (var fileInfo in profileDirectory.GetFiles("*.json", SearchOption.AllDirectories)) { if (fileInfo.DirectoryName is null) @@ -48,7 +48,7 @@ public ProfileEditorViewModel(string profilesFilePath, List mods) var profile = JsonSerializer.Deserialize(File.ReadAllText(fileInfo.FullName), new JsonSerializerOptions { AllowTrailingCommas = true }); if (profile is null) { - Program.helper.Log($"The profile file {fileInfo.Name} was empty or not deserializable from {fileInfo.DirectoryName}", Utilities.Helper.Status.Alert); + Program.helper.Log($"The profile file {fileInfo.Name} was empty or not deserializable from {fileInfo.DirectoryName}", Helper.Status.Alert); continue; } @@ -56,7 +56,7 @@ public ProfileEditorViewModel(string profilesFilePath, List mods) } catch (Exception ex) { - Program.helper.Log($"Unable to load the profile file {fileInfo.Name} from {fileInfo.DirectoryName}: {ex}", Utilities.Helper.Status.Alert); + Program.helper.Log($"Unable to load the profile file {fileInfo.Name} from {fileInfo.DirectoryName}: {ex}", Helper.Status.Alert); } } @@ -193,7 +193,7 @@ internal void CreateProfile(Profile profile, bool force = false) string fileFullName = GetProfileFilePath(profile.Name); if (File.Exists(fileFullName) && !force) { - Program.helper.Log($"Attempted to create an already existing profile file ({profile.Name}) at the path {fileFullName}", Utilities.Helper.Status.Warning); + Program.helper.Log($"Attempted to create an already existing profile file ({profile.Name}) at the path {fileFullName}", Helper.Status.Warning); return; } @@ -218,7 +218,7 @@ internal void DeleteProfile(Profile profile) string fileFullName = GetProfileFilePath(profile.Name); if (File.Exists(fileFullName) is false) { - Program.helper.Log($"Attempted to delete a non-existent profile file ({profile.Name}) at the path {fileFullName}", Utilities.Helper.Status.Warning); + Program.helper.Log($"Attempted to delete a non-existent profile file ({profile.Name}) at the path {fileFullName}", Helper.Status.Warning); } else { diff --git a/Stardrop/ViewModels/ProfileExportWindowViewModel.cs b/Stardrop/ViewModels/ProfileExportWindowViewModel.cs index fa5082af..dff4f27e 100644 --- a/Stardrop/ViewModels/ProfileExportWindowViewModel.cs +++ b/Stardrop/ViewModels/ProfileExportWindowViewModel.cs @@ -12,7 +12,9 @@ public ProfileExportWindowViewModel() { if (Design.IsDesignMode) { - + IncludeModConfigs = true; + IncludeDisabledMods = false; + IncludeModNotes = true; } } } diff --git a/Stardrop/ViewModels/SettingsWindowViewModel.cs b/Stardrop/ViewModels/SettingsWindowViewModel.cs index 961b9f79..b7e899bc 100644 --- a/Stardrop/ViewModels/SettingsWindowViewModel.cs +++ b/Stardrop/ViewModels/SettingsWindowViewModel.cs @@ -1,6 +1,6 @@ using Stardrop.Models; using Stardrop.Utilities; -using System; +using ReactiveUI.Reactive; using System.Collections.Generic; using System.Runtime.InteropServices; @@ -9,7 +9,7 @@ namespace Stardrop.ViewModels public class SettingsWindowViewModel : ViewModelBase { // Setting bindings - public string SMAPIPath { get { return Program.settings.SMAPIFolderPath; } set { Program.settings.SMAPIFolderPath = value; Pathing.SetSmapiPath(Program.settings.SMAPIFolderPath, String.IsNullOrEmpty(Program.settings.ModFolderPath)); } } + public string SMAPIPath { get { return Program.settings.SMAPIFolderPath; } set { Program.settings.SMAPIFolderPath = value; Pathing.SetSmapiPath(Program.settings.SMAPIFolderPath, string.IsNullOrEmpty(Program.settings.ModFolderPath)); } } public string ModFolderPath { get { return Program.settings.ModFolderPath; } set { Program.settings.ModFolderPath = value; Pathing.SetModPath(Program.settings.ModFolderPath); } } public string ModInstallPath { get { return Program.settings.ModInstallPath; } set { Program.settings.ModInstallPath = value; } } public string CollectionInstallPath { get { return Program.settings.CollectionInstallPath; } set { Program.settings.CollectionInstallPath = value; } } @@ -22,62 +22,20 @@ public class SettingsWindowViewModel : ViewModelBase public bool CollectionsSkipSMAPIUpdateCheck { get { return Program.settings.CollectionsSkipSMAPIUpdateCheck; } set { Program.settings.CollectionsSkipSMAPIUpdateCheck = value; } } public bool ShouldAutomaticallySaveProfileChanges { get { return Program.settings.ShouldAutomaticallySaveProfileChanges; } set { Program.settings.ShouldAutomaticallySaveProfileChanges = value; } } public bool ShowModThumbnails { get { return Program.settings.ShowModThumbnails; } set { Program.settings.ShowModThumbnails = value; } } - public List Themes { get; set; } = new List(); - - // Tooltips - public string ToolTip_SMAPI { get; set; } - public string ToolTip_ModFolder { get; set; } - public string ToolTip_ModInstall { get; set; } - public string ToolTip_CollectionInstall { get; set; } - public string ToolTip_Theme { get; set; } - public string ToolTip_RefreshThemes { get; set; } - public string ToolTip_Language { get; set; } - public string ToolTip_Grouping { get; set; } - public string ToolTip_IgnoreHiddenFolders { get; set; } - public string ToolTip_PreferredServer { get; set; } - public string ToolTip_NXMAssociation { get; set; } - public string ToolTip_RemoveNXMAssociation { get; set; } - public string ToolTip_AlwaysAskNXMFiles { get; set; } - public string ToolTip_AlwaysAskToDelete { get; set; } - public string ToolTip_AlwaysAskForCollectionInstallTarget { get; set; } - public string ToolTip_CollectionsSkipSMAPIUpdateCheck { get; set; } - public string ToolTip_EnableProfileSpecificModConfigs { get; set; } - public string ToolTip_EnableModsOnAdd { get; set; } - public string ToolTip_ShouldAutomaticallySaveProfileChanges { get; set; } - public string ToolTip_ShowModThumbnails { get; set; } - public string ToolTip_Save { get; set; } - public string ToolTip_Cancel { get; set; } + private List _themes = []; + public List Themes + { + get => _themes; + set => this.RaiseAndSetIfChanged(ref _themes, value); + } // Other UI controls - public bool ShowMainMenu { get; set; } - public bool ShowNXMAssociationButton { get; set; } - public bool ShowNexusServers { get; set; } + public bool ShowMainMenu { get; } + public bool ShowNXMAssociationButton { get; } + public bool ShowNexusServers { get; } public SettingsWindowViewModel() { - ToolTip_SMAPI = Program.translation.Get("ui.settings_window.tooltips.smapi"); - ToolTip_ModFolder = Program.translation.Get("ui.settings_window.tooltips.mod_folder_path"); - ToolTip_ModInstall = Program.translation.Get("ui.settings_window.tooltips.mod_install_path"); - ToolTip_CollectionInstall = Program.translation.Get("ui.settings_window.tooltips.collection_install_path"); - ToolTip_Theme = Program.translation.Get("ui.settings_window.tooltips.theme"); - ToolTip_RefreshThemes = Program.translation.Get("ui.settings_window.tooltips.refresh_themes"); - ToolTip_Language = Program.translation.Get("ui.settings_window.tooltips.language"); - ToolTip_Grouping = Program.translation.Get("ui.settings_window.tooltips.grouping"); - ToolTip_IgnoreHiddenFolders = Program.translation.Get("ui.settings_window.tooltips.ignore_hidden_folders"); - ToolTip_PreferredServer = Program.translation.Get("ui.settings_window.tooltips.preferred_server"); - ToolTip_NXMAssociation = Program.translation.Get("ui.settings_window.tooltips.nxm_file_association"); - ToolTip_RemoveNXMAssociation = Program.translation.Get("ui.settings_window.tooltips.remove_nxm_file_association"); - ToolTip_AlwaysAskNXMFiles = Program.translation.Get("ui.settings_window.tooltips.always_ask_nxm_files"); - ToolTip_AlwaysAskToDelete = Program.translation.Get("ui.settings_window.tooltips.always_ask_to_delete"); - ToolTip_AlwaysAskForCollectionInstallTarget = Program.translation.Get("ui.settings_window.tooltips.always_ask_for_collection_install_target"); - ToolTip_CollectionsSkipSMAPIUpdateCheck = Program.translation.Get("ui.settings_window.tooltips.collections_skip_smapi_update_check"); - ToolTip_EnableProfileSpecificModConfigs = Program.translation.Get("ui.settings_window.tooltips.enable_profile_specific_configs"); - ToolTip_EnableModsOnAdd = Program.translation.Get("ui.settings_window.tooltips.enable_mods_on_add"); - ToolTip_ShouldAutomaticallySaveProfileChanges = Program.translation.Get("ui.settings_window.tooltips.automatically_save_profile_changes"); - ToolTip_ShowModThumbnails = Program.translation.Get("ui.settings_window.tooltips.show_mod_thumbnails"); - ToolTip_Save = Program.translation.Get("ui.settings_window.tooltips.save_changes"); - ToolTip_Cancel = Program.translation.Get("ui.settings_window.tooltips.cancel_changes"); - ShowMainMenu = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); ShowNXMAssociationButton = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); ShowNexusServers = Program.settings.NexusDetails is not null && Program.settings.NexusDetails.IsPremium; diff --git a/Stardrop/ViewModels/ViewModelBase.cs b/Stardrop/ViewModels/ViewModelBase.cs index c6d837eb..65170de9 100644 --- a/Stardrop/ViewModels/ViewModelBase.cs +++ b/Stardrop/ViewModels/ViewModelBase.cs @@ -1,4 +1,4 @@ -using ReactiveUI; +using ReactiveUI.Reactive; namespace Stardrop.ViewModels { diff --git a/Stardrop/ViewModels/WarningWindowViewModel.cs b/Stardrop/ViewModels/WarningWindowViewModel.cs index d51ae4db..f87b757f 100644 --- a/Stardrop/ViewModels/WarningWindowViewModel.cs +++ b/Stardrop/ViewModels/WarningWindowViewModel.cs @@ -1,6 +1,6 @@ using Avalonia.Layout; using Avalonia.Media; -using ReactiveUI; +using ReactiveUI.Reactive; using Stardrop.Models.Data; using Stardrop.Utilities; using Stardrop.Utilities.Internal; @@ -10,9 +10,9 @@ namespace Stardrop.ViewModels { public class WarningWindowViewModel : ViewModelBase { - private string _warningText; + private string _warningText = null!; public string WarningText { get { return _warningText; } set { this.RaiseAndSetIfChanged(ref _warningText, value); } } - private string _buttonText; + private string _buttonText = null!; public string ButtonText { get { return _buttonText; } set { this.RaiseAndSetIfChanged(ref _buttonText, value); } } private bool _isButtonVisible; public bool IsButtonVisible { get { return _isButtonVisible; } set { this.RaiseAndSetIfChanged(ref _isButtonVisible, value); } } @@ -42,7 +42,7 @@ public double WindowWidth private bool _isRichTextVisible; /// Swaps the plain text block out for the segment based display, which can render links public bool IsRichTextVisible { get { return _isRichTextVisible; } set { this.RaiseAndSetIfChanged(ref _isRichTextVisible, value); } } - private ObservableCollection _warningLines = new ObservableCollection(); + private ObservableCollection _warningLines = []; public ObservableCollection WarningLines { get { return _warningLines; } set { this.RaiseAndSetIfChanged(ref _warningLines, value); } } /// Padding kept clear on either side of a link, covering the window border and the scroll bar diff --git a/Stardrop/Views/BaseWindow.axaml.cs b/Stardrop/Views/BaseWindow.axaml.cs index adc9de78..f61e1a70 100644 --- a/Stardrop/Views/BaseWindow.axaml.cs +++ b/Stardrop/Views/BaseWindow.axaml.cs @@ -1,4 +1,3 @@ -using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; @@ -8,10 +7,6 @@ public partial class BaseWindow : Window { public BaseWindow() { - AvaloniaXamlLoader.Load(this); - -#if DEBUG - this.AttachDevTools(); -#endif + // AvaloniaXamlLoader.Load(this); } } \ No newline at end of file diff --git a/Stardrop/Views/ChangelogWindow.axaml b/Stardrop/Views/ChangelogWindow.axaml index a6cdc6be..5c459e20 100644 --- a/Stardrop/Views/ChangelogWindow.axaml +++ b/Stardrop/Views/ChangelogWindow.axaml @@ -3,10 +3,12 @@ xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - xmlns:i="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia" + xmlns:i="clr-namespace:Optris.Icons.Avalonia;assembly=Optris.Icons.Avalonia" xmlns:i18n="clr-namespace:Stardrop.Utilities.Extension" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="using:Stardrop.ViewModels" + xmlns:models="using:Stardrop.Models.Nexus.Web" + x:DataType="vm:ChangelogWindowViewModel" Title="{i18n:Translate ui.window.changelog.name}" Width="600" Height="500" @@ -16,10 +18,9 @@ d:DesignWidth="600" Background="{DynamicResource ThemeBackgroundBrush}" CanResize="True" - ExtendClientAreaChromeHints="NoChrome" ExtendClientAreaTitleBarHeightHint="-1" - ExtendClientAreaToDecorationsHint="true" - HasSystemDecorations="true" + ExtendClientAreaToDecorationsHint="True" + WindowDecorations="BorderOnly" Icon="/Assets/icon.ico" mc:Ignorable="d"> @@ -91,17 +92,17 @@ Text="{Binding EmptyMessage}" TextWrapping="Wrap" /> - + - + - + - + ("closeButton").Click += delegate { this.Close(); }; - this.FindControl - + - - - + - + - - + + @@ -658,7 +689,7 @@ - + - - - - - - + - - - private async void ModGridMenuRow_IgnoreUpdate(object? sender, Avalonia.Interactivity.RoutedEventArgs e) + private async void ModGridMenuRow_IgnoreUpdate(object? sender, RoutedEventArgs e) { if ((sender as MenuItem)?.DataContext is not Mod selectedMod) { @@ -894,12 +916,12 @@ private async void ModGridMenuRow_IgnoreUpdate(object? sender, Avalonia.Interact // profile scoped, so nothing here should mark the profile as having unsaved changes try { - ClientData clientData = new ClientData(); + ClientData clientData = new(); if (File.Exists(Pathing.GetDataCachePath())) { try { - clientData = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), new JsonSerializerOptions { AllowTrailingCommas = true }) ?? new ClientData(); + clientData = JsonSerializer.Deserialize(File.ReadAllText(Pathing.GetDataCachePath()), ReadOptions) ?? new ClientData(); } catch { @@ -907,7 +929,7 @@ private async void ModGridMenuRow_IgnoreUpdate(object? sender, Avalonia.Interact } } - if (String.IsNullOrEmpty(selectedMod.IgnoredVersion)) + if (string.IsNullOrEmpty(selectedMod.IgnoredVersion)) { if (clientData.IgnoredUpdates.ContainsKey(selectedMod.UniqueId)) { @@ -919,7 +941,7 @@ private async void ModGridMenuRow_IgnoreUpdate(object? sender, Avalonia.Interact clientData.IgnoredUpdates[selectedMod.UniqueId] = selectedMod.IgnoredVersion; } - File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(clientData, new JsonSerializerOptions() { WriteIndented = true })); + File.WriteAllText(Pathing.GetDataCachePath(), JsonSerializer.Serialize(clientData, WriteOptions)); } catch (Exception ex) { @@ -941,8 +963,10 @@ private void SearchBox_KeyUp(object? sender, KeyEventArgs e) { if (_searchBoxTimer is null) { - _searchBoxTimer = new DispatcherTimer(); - _searchBoxTimer.Interval = new TimeSpan(TimeSpan.TicksPerMillisecond / 2); + _searchBoxTimer = new DispatcherTimer + { + Interval = new TimeSpan(TimeSpan.TicksPerMillisecond / 2) + }; _searchBoxTimer.Tick += SearchBoxTimer_Tick; _searchBoxTimer.Start(); } @@ -950,7 +974,7 @@ private void SearchBox_KeyUp(object? sender, KeyEventArgs e) private void SearchBoxTimer_Tick(object? sender, EventArgs e) { - var filterText = this.FindControl("searchBox").Text; + var filterText = this.FindControl("searchBox")!.Text ?? string.Empty; if (_viewModel.FilterText == filterText) { return; @@ -960,53 +984,68 @@ private void SearchBoxTimer_Tick(object? sender, EventArgs e) // Ensure the ColumnFilter is set if (_viewModel.ColumnFilter is null || _viewModel.ColumnFilter.Any() is false) { - var searchFilterColumnBox = this.FindControl("searchFilterColumnBox"); - _viewModel.ColumnFilter = searchFilterColumnBox.SelectedItems.Cast().Select(i => i.Content.ToString()).ToList(); + var searchFilterColumnBox = this.FindControl("searchFilterColumnBox")!; + _viewModel.ColumnFilter = [.. (searchFilterColumnBox.SelectedItems ?? Array.Empty()) + .Cast() + .Select(i => i.Content?.ToString() ?? string.Empty)]; } } private void FilterListBox_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - var searchFilterColumnBox = (e.Source as ListBox); - _viewModel.ColumnFilter = searchFilterColumnBox.SelectedItems.Cast().Select(i => i.Content.ToString()).ToList(); + if (e.Source is not ListBox searchFilterColumnBox) + { + return; + } + _viewModel.ColumnFilter = [.. (searchFilterColumnBox.SelectedItems ?? Array.Empty()) + .Cast() + .Select(i => i.Content?.ToString() ?? string.Empty)]; - int selectedItemCount = searchFilterColumnBox.SelectedItems.Count; - this.FindControl