Browse Source

code cleaning

Veloe 2 years ago
parent
commit
14c9f34d92

+ 5 - 5
VeloeMinecraftLauncher/Models/Entity/DownloadedVersion.cs

@@ -1,17 +1,17 @@
 namespace VeloeMinecraftLauncher.Models.Entity;
 public class DownloadedVersion
 {
-    public string path;
-    public string version;
+    public string Path { get; set; }
+    public string Version { get; set; }
 
     public DownloadedVersion(string path, string version)
     {
-        this.path = path;
-        this.version = version;
+        Path = path;
+        Version = version;
     }
 
     public override string ToString()
     {
-        return version;
+        return Version;
     }
 }

+ 7 - 7
VeloeMinecraftLauncher/Utils/Downloader.cs

@@ -17,7 +17,7 @@ namespace VeloeMinecraftLauncher.Utils;
 
 internal static class Downloader
 {
-    static HttpClient _httpClient = new HttpClient();
+    static HttpClient _httpClient = new();
 
     public static async Task<TaskStatus> StartDownload(
         Action<string> DownloadingFileName, //status text showing on ui
@@ -437,13 +437,13 @@ internal static class Downloader
             var assetsIterator = 1;
 
             List<Task> assetsDownloadTasks = new();
-            using SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(0,40);
+            using SemaphoreSlim concurrencySemaphore = new(0, 40);
 
             foreach (var asset in assetsJson?.Objects?.DistinctBy(a => a.Value.Hash) ?? new Dictionary<string,Asset>())
             {
                 assetsDownloadTasks.Add(Task.Run(async () => {
                     
-                    var folder = asset.Value.Hash.Substring(0, 2);
+                    var folder = asset.Value.Hash[..2];
 
                     var chksum = String.Empty;
                     //here hash check
@@ -473,8 +473,9 @@ internal static class Downloader
                     
                 }));
             }
-            concurrencySemaphore.Release(40);
+            
             Task.WaitAll(assetsDownloadTasks.ToArray());
+            concurrencySemaphore.Release(40);
 
             SetProgress(100);
             tasksIterator++;
@@ -654,8 +655,7 @@ internal static class Downloader
 
     public static async Task<T?> DownloadAndDeserializeJsonData<T>(string url, string path = "", string filename = "") where T : new()
     {
-        var jsonData = string.Empty;
-
+        string jsonData;
         try
         {
             Settings.logger.Debug($"Downloading: {url.Split('/').Last()}");
@@ -689,7 +689,7 @@ internal static class Downloader
 
     public static async Task DownloadFileAsync(string url, string path, CancellationToken ct, HttpClient? client = null)
     {
-        if (client == null) client = _httpClient;
+        client ??= _httpClient;
         using HttpResponseMessage response = await client.GetAsync(new System.Uri(url),HttpCompletionOption.ResponseHeadersRead, ct);
         response.EnsureSuccessStatusCode();
         using Stream contentStream = await response.Content.ReadAsStreamAsync(ct);

+ 2 - 2
VeloeMinecraftLauncher/Utils/EventSink.cs

@@ -15,12 +15,12 @@ public class EventSink : Serilog.Core.ILogEventSink
 
     public void Emit(LogEvent logEvent)
     {
-        var message = "";
+        string message;
         if (_formatProvider is not null)
             message = logEvent.RenderMessage(_formatProvider);
         else
         {
-            message = $"[{logEvent.Timestamp.ToString("HH:mm:ss")} {logEvent.Level.ToString()}] {logEvent.RenderMessage()}{logEvent.Exception}\n";
+            message = $"[{logEvent.Timestamp:HH:mm:ss} {logEvent.Level.ToString()}] {logEvent.RenderMessage()}{logEvent.Exception}\n";
         }
         if (DataReceived != null)
         {

+ 1 - 1
VeloeMinecraftLauncher/Utils/Settings.cs

@@ -81,7 +81,7 @@ internal static class Settings
             minecraftForlderPath = Directory.GetCurrentDirectory();
 
         if(minecraftForlderPath.Last() is not ('/' or '\\'))
-            minecraftForlderPath = minecraftForlderPath + "/";
+            minecraftForlderPath += "/";
 
         if (!Directory.Exists(minecraftForlderPath))
             Directory.CreateDirectory(minecraftForlderPath);

+ 29 - 55
VeloeMinecraftLauncher/Utils/StartCommandBuilder.cs

@@ -45,24 +45,20 @@ internal static class StartCommandBuilder
                 rulesVaild = false;
                 foreach (var rule in library.Rules)
                 {
-                    bool isRuleOsExist = rule.Os is not null;
-
-
                     if (rule.Action == "allow" && rule.Os is null)
                     {
                         rulesVaild = true;
                         continue;
                     }
 
-                    if (rule.Os is not null)
-                        if (rule.Action == "allow" &&
-                                (rule.Os.Name == "linux" && OperatingSystem.IsLinux() ||
-                                rule.Os.Name == "windows" && OperatingSystem.IsWindows())
-                            )
-                        {
-                            rulesVaild = true;
-                            continue;
-                        }
+                    if (rule.Os is not null && 
+                        rule.Action == "allow" &&
+                            (rule.Os.Name == "linux" && OperatingSystem.IsLinux() ||
+                            rule.Os.Name == "windows" && OperatingSystem.IsWindows()))
+                    {
+                        rulesVaild = true;
+                        continue;
+                    }
                 }
             }
 
@@ -140,7 +136,7 @@ internal static class StartCommandBuilder
                 returnString.Append(Path.GetFullPath(Settings.minecraftForlderPath + "versions/" + version.InheritsFrom + "/" + version.InheritsFrom + ".jar"));//for forge
         }
 
-        returnString.Append("\"");
+        returnString.Append('"');
 
         //check for jvm fabric options
 
@@ -154,15 +150,13 @@ internal static class StartCommandBuilder
 
                     var type = argument.GetType();
 
-                    if (!(argument is JsonElement))
+                    if (argument is not JsonElement)
                         continue;
 
                     if (!(((JsonElement)argument).ValueKind == JsonValueKind.String))
                         continue;
 
-                    var value = ((JsonElement)argument).Deserialize(typeof(string)) as string;
-
-                    if (value is null) continue;
+                    if (((JsonElement)argument).Deserialize(typeof(string)) is not string value) continue;
 
                     //for new forge versions (1.18, 1.19)
                     if (value.Contains("${version_name}"))
@@ -183,12 +177,12 @@ internal static class StartCommandBuilder
                     //value = value.Replace(" ", "");
                     if (containsArgWithValue)
                         value = value.Replace("=", "=\"");
-                    returnString.Append(" ");
+                    returnString.Append(' ');
                     if (containsPathValueOnly)
-                        returnString.Append("\"");
+                        returnString.Append('"');
                     returnString.Append(value);
                     if (containsArgWithValue || containsPathValueOnly)
-                        returnString.Append("\"");
+                        returnString.Append('"');
                 }
         }
 
@@ -199,27 +193,17 @@ internal static class StartCommandBuilder
 
         returnString.Append(" " + version.MainClass);
 
-        List<string> args = new List<string>();
-        List<string> argsValues = new List<string>();
+        List<string> args = new();
+        List<string> argsValues = new();
        
         if (version.Arguments is not null)
         {
             foreach (var argument in version.Arguments.Game)
             {
-                if (argument is null)
-                    continue;
-
-                var type = argument.GetType();
-
-                if (!(argument is JsonElement))
-                    continue;
-
-                if (!(((JsonElement)argument).ValueKind == JsonValueKind.String))
-                    continue;
-
-                var value = ((JsonElement)argument).Deserialize(typeof(string)) as string;
-
-                if (value is null) continue;
+                if (argument is null ||
+                    argument is not JsonElement jsonArgument || 
+                    jsonArgument.ValueKind != JsonValueKind.String || 
+                    jsonArgument.Deserialize(typeof(string)) is not string value) continue;
 
                 if (!(value).Contains("--"))
                 {
@@ -234,7 +218,7 @@ internal static class StartCommandBuilder
         {
             var minecraftArguments = version.MinecraftArguments.Split(' ');
             //args = version.minecraftArguments.Split(' ').Where(x=> x.Contains("--")).ToList();
-            for (int i = 0; i < minecraftArguments.Count(); i++)
+            for (int i = 0; i < minecraftArguments.Length; i++)
             {
                 if (minecraftArguments[i].Contains("--"))
                 {
@@ -248,7 +232,7 @@ internal static class StartCommandBuilder
         }
 
 
-        Dictionary<string, bool> argsProvided = new Dictionary<string, bool>()
+        Dictionary<string, bool> argsProvided = new()
         {
             { "--username", false },
             { "--version", false },
@@ -273,21 +257,11 @@ internal static class StartCommandBuilder
             {
                 foreach (var argument in inheritsFrom.Arguments.Game)
                 {
-                    if (argument is null)
-                        continue;
-
-                    var type = argument.GetType();
-
-                    if (!(argument is JsonElement))
-                        continue;
-
-                    if (!(((JsonElement)argument).ValueKind == JsonValueKind.String))
-                        continue;
-
-                    var value = ((JsonElement)argument).Deserialize(typeof(string)) as string;
+                    if (argument is null ||
+                        argument is not JsonElement jsonArgument ||
+                        jsonArgument.ValueKind != JsonValueKind.String ||
+                        jsonArgument.Deserialize(typeof(string)) is not string value) continue;
 
-                    if (value is null) continue;
-                         
                     if (!(value).Contains("--"))
                     {
                         argsValues.Add(value);
@@ -304,7 +278,7 @@ internal static class StartCommandBuilder
             {
                 var minecraftArguments = inheritsFrom.MinecraftArguments.Split(' ');
                 //args = version.minecraftArguments.Split(' ').Where(x=> x.Contains("--")).ToList();
-                for (int i = 0; i < minecraftArguments.Count(); i++)
+                for (int i = 0; i < minecraftArguments.Length; i++)
                 {
                     if (minecraftArguments[i].Contains("--"))
                     {
@@ -329,7 +303,7 @@ internal static class StartCommandBuilder
                     break;
                 case "--gameDir":
                     //for forge
-                    if (!(argsValues.Where(x => x.Contains("forge")).Count() > 0 || version.Id.ToLower().Contains("fabric")))
+                    if (!(argsValues.Where(x => x.Contains("forge")).Any() || version.Id.ToLower().Contains("fabric")))
                         returnString.Append(" --gameDir " + "\"" + Path.GetDirectoryName(Settings.minecraftForlderPath) + "\"");
                     else
                         returnString.Append(" --gameDir " + "\"" + Path.GetDirectoryName(Settings.minecraftForlderPath + "versions/" + version.Id + "/") + "\"");
@@ -392,7 +366,7 @@ internal static class StartCommandBuilder
             libPath += dir + "/";
         }
 
-        libPath += dirs[dirs.Length - 2] + "-" + dirs[dirs.Length - 1] + ".jar";
+        libPath += dirs[^2] + "-" + dirs[^1] + ".jar";
 
 #if DEBUG
         if (File.Exists(Settings.minecraftForlderPath + "libraries/" + libPath))

+ 40 - 46
VeloeMinecraftLauncher/ViewModels/MainWindowViewModel.cs

@@ -55,15 +55,12 @@ public class MainWindowViewModel : ViewModelBase
 
             //loading local verions
             _logger.Debug("Loading local versions.");
-            updateAvailable();
+            ScanForDownloadedVersions();
         }
         catch (Exception ex)
         {
             OpenErrorWindow(ex);
-            if (_logger is null)
-            {
-                _logger = new LoggerConfiguration().MinimumLevel.Debug().CreateLogger();
-            }
+            _logger ??= new LoggerConfiguration().MinimumLevel.Debug().CreateLogger();
         }
         finally
         {
@@ -166,12 +163,12 @@ public class MainWindowViewModel : ViewModelBase
                 var modpacksInfo = await Downloader.DownloadAndDeserializeJsonData<List<Modpack>>("https://files.veloe.link/launcher/modpacks.json") ?? new List<Modpack>();
                 var installedModpacks = //DownloadedVersions.Where(v => modpacksInfo.Select(m => m.Name).Contains(v.version)).Join(modpacksInfo, (v, m) => v.version == m.);
                     from downloadedVersion in DownloadedVersions
-                    join modpack in modpacksInfo on downloadedVersion.version equals modpack.Name
+                    join modpack in modpacksInfo on downloadedVersion.Version equals modpack.Name
                     select new
                     {
-                        Name = downloadedVersion.version,
-                        Path = downloadedVersion.path,
-                        Revision = modpack.Revision
+                        Name = downloadedVersion.Version,
+                        downloadedVersion.Path,
+                        modpack.Revision
                     };
                 var modpacksToUpdate = new List<string>();
                 var modpacksRevsionUnknown = new List<string>();
@@ -271,7 +268,6 @@ public class MainWindowViewModel : ViewModelBase
                 DownloadedVersion = DownloadedVersions[value];
         }
     }
-    public string Greeting => "Welcome to Cringe Launcher!";
     public string DownloadButton {
         get => _downloadButton;
         set => this.RaiseAndSetIfChanged(ref _downloadButton, value);
@@ -368,7 +364,7 @@ public class MainWindowViewModel : ViewModelBase
         {
             try
             {
-                versionsDownloader.Closed += updateAvailable;
+                versionsDownloader.Closed += OnDialogWindowCloseVersionsScan;
                 await versionsDownloader.ShowDialog(desktop.MainWindow);
             }
             catch (Exception ex)
@@ -394,7 +390,7 @@ public class MainWindowViewModel : ViewModelBase
 
                 int version = 0;
 
-                using (StreamReader reader = new StreamReader(DownloadedVersion.path))
+                using (StreamReader reader = new(DownloadedVersion.Path))
                 {
                     string json = reader.ReadToEnd();
 
@@ -411,16 +407,14 @@ public class MainWindowViewModel : ViewModelBase
                             result = await Downloader.StartDownload(value => StartButtonOutput = value, value => { } ,value => IsNoGameRunning = value, value => { }, versionJson, _tokenSource.Token);
                         else
                         {
-                            using (StreamReader inheritsFromReader = new StreamReader(Settings.minecraftForlderPath + "versions/" + versionJson.InheritsFrom + "/" + versionJson.InheritsFrom + ".json"))
-                            {
-                                string jsonInheritsFrom = inheritsFromReader.ReadToEnd();
-                                var inheritsFromJson = JsonSerializer.Deserialize<Entity.Version.Version>(jsonInheritsFrom, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+                            using StreamReader inheritsFromReader = new(Settings.minecraftForlderPath + "versions/" + versionJson.InheritsFrom + "/" + versionJson.InheritsFrom + ".json");
+                            string jsonInheritsFrom = inheritsFromReader.ReadToEnd();
+                            var inheritsFromJson = JsonSerializer.Deserialize<Entity.Version.Version>(jsonInheritsFrom, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
 
-                                if (inheritsFromJson is not null)
-                                    result = await Downloader.StartDownload(value => StartButtonOutput = value, value => { }, value => IsNoGameRunning = value, value => { }, inheritsFromJson, _tokenSource.Token);
-                                else
-                                    result = TaskStatus.Faulted;
-                            }
+                            if (inheritsFromJson is not null)
+                                result = await Downloader.StartDownload(value => StartButtonOutput = value, value => { }, value => IsNoGameRunning = value, value => { }, inheritsFromJson, _tokenSource.Token);
+                            else
+                                result = TaskStatus.Faulted;
                         }
 
                         if (result != TaskStatus.RanToCompletion)
@@ -444,15 +438,13 @@ public class MainWindowViewModel : ViewModelBase
                         {
                             if (!string.IsNullOrEmpty(versionJson?.InheritsFrom))
                             {
-                                using (StreamReader inheritsFromReader = new StreamReader(Settings.minecraftForlderPath + "versions/" + versionJson.InheritsFrom + "/" + versionJson.InheritsFrom + ".json"))
+                                using StreamReader inheritsFromReader = new(Settings.minecraftForlderPath + "versions/" + versionJson.InheritsFrom + "/" + versionJson.InheritsFrom + ".json");
+                                string jsonInheritsFrom = inheritsFromReader.ReadToEnd();
+                                var inheritsFromJson = JsonSerializer.Deserialize<Entity.Version.Version>(jsonInheritsFrom, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+                                if (inheritsFromJson?.JavaVersion?.MajorVersion is not null)
                                 {
-                                    string jsonInheritsFrom = inheritsFromReader.ReadToEnd();
-                                    var inheritsFromJson = JsonSerializer.Deserialize<Entity.Version.Version>(jsonInheritsFrom, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
-                                    if (inheritsFromJson?.JavaVersion?.MajorVersion is not null)
-                                    {
-                                        _logger.Debug("Java version required: {0}", inheritsFromJson.JavaVersion.MajorVersion);
-                                        version = inheritsFromJson.JavaVersion.MajorVersion.Value;
-                                    }
+                                    _logger.Debug("Java version required: {0}", inheritsFromJson.JavaVersion.MajorVersion);
+                                    version = inheritsFromJson.JavaVersion.MajorVersion.Value;
                                 }
                             }
                             else
@@ -501,9 +493,10 @@ public class MainWindowViewModel : ViewModelBase
                     Arguments = ArgumentsBox
                 };
 
-                Process minecraft = new Process();
-
-                minecraft.StartInfo = proc;
+                Process minecraft = new()
+                {
+                    StartInfo = proc
+                };
 
                 if (!Settings.useCustomJava)
                     minecraft.StartInfo.EnvironmentVariables["JAVA_HOME"] = $"{Settings.minecraftForlderPath}javaruntime/{version}";
@@ -552,7 +545,7 @@ public class MainWindowViewModel : ViewModelBase
 #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                 _logger.Debug("Updating Settings");
                 Settings.username = _username;
-                Settings.lastChosenVersion = DownloadedVersion.version;
+                Settings.lastChosenVersion = DownloadedVersion.Version;
                 Settings.SaveSettings();
 
             }
@@ -619,7 +612,7 @@ public class MainWindowViewModel : ViewModelBase
             StartButtonOutput = "";
             IsNoGameRunning = true;
             if (minecraftProcess.ExitCode is not (0 or 2))
-                OpenErrorWindow(new JavaProcessException($"Minecraft process exited with an error code {minecraftProcess.ExitCode}.\nCheck log in game folder or launcher console.", $"{Settings.minecraftForlderPath}versions/{_startedVersion.version}/crash-reports"));
+                OpenErrorWindow(new JavaProcessException($"Minecraft process exited with an error code {minecraftProcess.ExitCode}.\nCheck log in game folder or launcher console.", $"{Settings.minecraftForlderPath}versions/{_startedVersion.Version}/crash-reports"));
             else if (minecraftProcess.ExitCode is 2)
             {
                 OpenErrorWindow(new Exception("JVM exited on the startup (Exit code 2). Check your Java installation. Get more info in the laucher console."));
@@ -630,18 +623,19 @@ public class MainWindowViewModel : ViewModelBase
 
 
 
-    public void updateAvailable()
+    public void ScanForDownloadedVersions()
     {
-        if (DownloadedVersions is null)
-            DownloadedVersions = new();
+        DownloadedVersions ??= new();
 
         DownloadedVersions.Clear();
         DirectoryInfo versions = new( Settings.minecraftForlderPath + "versions");
         try
         {
             var dirs = versions.GetDirectories("*", SearchOption.TopDirectoryOnly);
-            LauncherProfiles profiles = new LauncherProfiles();
-            profiles.SelectedProfile = "NotImplemented";
+            LauncherProfiles profiles = new()
+            {
+                SelectedProfile = "NotImplemented"
+            };
 
             foreach (var dir in dirs)
             {
@@ -661,7 +655,7 @@ public class MainWindowViewModel : ViewModelBase
                 DownloadedIndex = 0;
                 for (int i = 0; i < DownloadedVersions.Count; i++)
                 {
-                    if (DownloadedVersions[i].version == Settings.lastChosenVersion)
+                    if (DownloadedVersions[i].Version == Settings.lastChosenVersion)
                     {
                         DownloadedIndex = i;
                         break;
@@ -686,11 +680,11 @@ public class MainWindowViewModel : ViewModelBase
         
     }
 
-    public void updateAvailable(object? sendingObject, EventArgs e)
+    public void OnDialogWindowCloseVersionsScan(object? sendingObject, EventArgs e)
     {
         try
         {
-            updateAvailable();
+            ScanForDownloadedVersions();
         }
         catch (Exception ex)
         {
@@ -700,11 +694,11 @@ public class MainWindowViewModel : ViewModelBase
         switch (sendingObject)
         {
             case VersionsDownloader:
-                ((VersionsDownloader)sendingObject).Closed -= updateAvailable;
+                ((VersionsDownloader)sendingObject).Closed -= OnDialogWindowCloseVersionsScan;
                 break;
 
             case SettingsWindow:
-                ((SettingsWindow)sendingObject).Closed -= updateAvailable;
+                ((SettingsWindow)sendingObject).Closed -= OnDialogWindowCloseVersionsScan;
                 break;
         }
 
@@ -716,7 +710,7 @@ public class MainWindowViewModel : ViewModelBase
 
         if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow is not null)
         {
-            settingsWindow.Closed += updateAvailable;
+            settingsWindow.Closed += OnDialogWindowCloseVersionsScan;
             settingsWindow.ShowDialog(desktop.MainWindow);
         }
     }
@@ -724,7 +718,7 @@ public class MainWindowViewModel : ViewModelBase
     public void DownloadUpdate()
     {
         _logger.Debug("Started updater.exe");
-        Process updater = new Process();
+        Process updater = new();
         updater.StartInfo.FileName = "Updater";
         if (OperatingSystem.IsWindows())
             updater.StartInfo.FileName += ".exe";

+ 75 - 68
VeloeMinecraftLauncher/ViewModels/VersionsDownloaderViewModel.cs

@@ -16,6 +16,7 @@ using VeloeMinecraftLauncher.Models.Entity;
 using VeloeMinecraftLauncher.Entity.Version;
 using System.Diagnostics;
 using System.Linq.Expressions;
+using System.Globalization;
 
 namespace VeloeMinecraftLauncher.ViewModels;
 
@@ -74,24 +75,23 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
         ArgumentNullException.ThrowIfNull(_logger);
 
-        if (_versionManifest is null) _versionManifest = new();
-
-        if (_filteredVersions is null) _filteredVersions = new();
-        if (_modpackVersions is null) _modpackVersions = new();
-        if (_modpackVersionsAsVersion is null) 
-            _modpackVersionsAsVersion = _modpackVersions
-                                            .Select(v => new Entity.VersionManifest.Version() 
-                                            { 
-                                                Id = v.Name, 
-                                                Type = "modpack", 
-                                                ComplianceLevel = v.Revision 
-                                            })
-                                            .ToList();
-
-        if (_libraries is null) _libraries = new();
-        if (_downloadedVersions is null) _downloadedVersions = new();
-        if (_downloadedVersionTree is null) _downloadedVersionTree = new();
-        if (DownloadedVersionsDictionary is null) DownloadedVersionsDictionary = new();
+        _versionManifest ??= new();
+
+        _filteredVersions ??= new();
+        _modpackVersions ??= new();
+        _modpackVersionsAsVersion ??= _modpackVersions
+                                        .Select(v => new Entity.VersionManifest.Version() 
+                                        { 
+                                            Id = v.Name, 
+                                            Type = "modpack", 
+                                            ComplianceLevel = v.Revision 
+                                        })
+                                        .ToList();
+
+        _libraries ??= new();
+        _downloadedVersions ??= new();
+        _downloadedVersionTree ??= new();
+        DownloadedVersionsDictionary ??= new();
 
         try
         {
@@ -210,7 +210,6 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
         set
         {
             this.RaiseAndSetIfChanged(ref _installForge, value);
-
             if (InstallFabric)
                 InstallFabric = false;
         }
@@ -436,6 +435,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
     {
         await Task.Run(async() =>
         {
+            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
             try
             {
                 IsControlsEnabled = false;
@@ -454,10 +454,10 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
                 foreach (var dversion in DownloadedVersions)
                 {
-                    using StreamReader reader = new StreamReader(dversion.path);
+                    using StreamReader reader = new(dversion.Path);
 
                     Entity.Version.Version versionObject = await JsonSerializer.DeserializeAsync<Entity.Version.Version>(reader.BaseStream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
-                    DownloadedVersionsDictionary.Add(dversion.version, versionObject);
+                    DownloadedVersionsDictionary.Add(dversion.Version, versionObject);
 
                     if (dversion == _downloadedVersion)
                     {
@@ -471,7 +471,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
                     return;
                 }
 
-                var versionDir = new FileInfo(value.path)?.Directory?.FullName;
+                var versionDir = new FileInfo(value.Path)?.Directory?.FullName;
 
                 if (versionDir is null)
                 {
@@ -503,19 +503,19 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
                         DirectoryToTreeNode(
                             dirInfo,
                             out dirSize,
-                            (dir) => dir.Name == ".mixin.out" ||
-                                dir.Name == "assets" ||
-                                dir.Name == "javaruntime" ||
-                                dir.Name == "libraries" ||
-                                dir.Name == "logs" ||
-                                dir.Name == "versions",
-                            (file) => file.Name.Contains("Veloe") ||
-                                file.Name.Contains("log") ||
-                                file.Name.Contains("exe") ||
-                                file.Name == "launcher_profiles.json" ||
-                                file.Name == "libHarfBuzzSharp.dll" ||
-                                file.Name == "libSkiaSharp.dll" ||
-                                file.Name == "settings.json")
+                            (dir) => dir.Name.Equals(".mixin.out",StringComparison.Ordinal) ||
+                                dir.Name.Equals("assets",StringComparison.Ordinal) ||
+                                dir.Name.Equals("javaruntime", StringComparison.Ordinal) ||
+                                dir.Name.Equals("libraries", StringComparison.Ordinal) ||
+                                dir.Name.Equals("logs", StringComparison.Ordinal) ||
+                                dir.Name.Equals("versions", StringComparison.Ordinal),
+                            (file) => file.Name.Contains("Veloe",StringComparison.Ordinal) ||
+                                file.Name.Contains("log", StringComparison.Ordinal) ||
+                                file.Name.Contains("exe", StringComparison.Ordinal) ||
+                                file.Name.Equals("launcher_profiles.json", StringComparison.Ordinal) ||
+                                file.Name.Equals("libHarfBuzzSharp.dll", StringComparison.Ordinal) ||
+                                file.Name.Equals("libSkiaSharp.dll", StringComparison.Ordinal) ||
+                                file.Name.Equals("settings.json", StringComparison.Ordinal))
                         );
                     allSize += dirSize;
                 }
@@ -535,7 +535,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
                 if (dirInfo is not null)
                 {
-                    var worldsTreeNode = new TreeNode() { Title = "Worlds: " + dirInfo.GetDirectories().Count() };
+                    var worldsTreeNode = new TreeNode() { Title = "Worlds: " + dirInfo.GetDirectories().Length };
 
                     foreach (var world in dirInfo.GetDirectories())
                     { worldsTreeNode.SubNode.Add(new TreeNode() { Title = world.Name }); }
@@ -545,18 +545,19 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
                 //check modloader
 
-                var modsTreeNode = new TreeNode();
-
-                if (version.InheritsFrom is null)
-                    modsTreeNode.Title = "Modloader: No";
-                else if (version.Libraries.Any(l => l.Downloads?.Artifact?.Url?.Contains("forge") ?? false))
-                {
-                    modsTreeNode.Title = "Modloader: Forge";
-                    OpenErrorWindow("This version contains forge modloader, it installs some libraries that can't be displayed and deleted in current launcher versions manager.");
-                }
-                else if (version.Libraries.Any(l => l.Name.Contains("fabric")))
-                    modsTreeNode.Title = "Modloader: Fabric";
+                var modsTreeNode = new TreeNode() { Title = "Unknown" };
 
+            if (version.InheritsFrom is null)
+                modsTreeNode.Title = "Modloader: No";
+            else if (version.Libraries.Any(l => l.Downloads?.Artifact?.Url?.Contains("forge", StringComparison.OrdinalIgnoreCase) ?? false))
+            {
+                modsTreeNode.Title = "Modloader: Forge";
+                OpenErrorWindow("This version contains forge modloader, it installs some libraries that can't be displayed and deleted in current launcher versions manager.");
+            }
+            else if (version.Libraries.Any(l => l.Name.Contains("fabric", StringComparison.OrdinalIgnoreCase)))
+                modsTreeNode.Title = "Modloader: Fabric";
+            else if (version.Libraries.Any(l => l.Name.Contains("optifine",StringComparison.OrdinalIgnoreCase)))
+                    modsTreeNode.Title = "Modloader: Optifine modified";
                 //get mods list
 
                 if (modsTreeNode.Title != "No" && Directory.Exists(versionDir + "/mods"))
@@ -583,9 +584,10 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
                 if (dirInfo is not null)
                 {
-                    var resourcepacksTreeNode = new TreeNode();
-
-                    resourcepacksTreeNode.Title = "Resoursepacks: " + (dirInfo?.GetDirectories()?.Count() + dirInfo?.GetFiles().Count() ?? 0).ToString();
+                    var resourcepacksTreeNode = new TreeNode
+                    {
+                        Title = "Resoursepacks: " + (dirInfo?.GetDirectories()?.Length + dirInfo?.GetFiles().Length ?? 0).ToString()
+                    };
                     foreach (var resourcepack in dirInfo?.GetFileSystemInfos())
                     { resourcepacksTreeNode.SubNode.Add(new TreeNode() { Title = resourcepack.Name }); }
 
@@ -635,8 +637,10 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
                 var usedLibraries = version.Libraries;
 
-                var libTreeNode = new TreeNode();
-                libTreeNode.Title = "Libraries";
+                var libTreeNode = new TreeNode
+                {
+                    Title = "Libraries"
+                };
 
                 if (version.InheritsFrom is not null && DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out outVersion) && outVersion is not null)
                 {
@@ -772,13 +776,13 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
                 foreach (var dversion in DownloadedVersions)
                 {
                     string json;
-                    using (StreamReader reader = new StreamReader(dversion.path))
+                    using (StreamReader reader = new(dversion.Path))
                     {
                         json = reader.ReadToEnd();
                     }
 
                     var versionObject = JsonSerializer.Deserialize<Entity.Version.Version>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
-                    DownloadedVersionsDictionary.Add(dversion.version, versionObject);
+                    DownloadedVersionsDictionary.Add(dversion.Version, versionObject);
 
                     if (dversion == _downloadedVersion)
                     {
@@ -792,7 +796,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
                     return;
                 }
 
-                var versionDir = new FileInfo(DownloadedVersion.path)?.Directory?.FullName;
+                var versionDir = new FileInfo(DownloadedVersion.Path)?.Directory?.FullName;
 
                 if (versionDir is null)
                 {
@@ -882,7 +886,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
         var result = (double)size;
         while (j < _size_label.Length && result > 1024)
         {
-            result = result / 1024;
+            result /= 1024;
             j++;
         }
         return string.Format("{0:N2}", result) + " " + _size_label[j];
@@ -895,11 +899,9 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
         if (!(dirInfo is not null && dirInfo.Exists)) return nodes;
 
-        if (dirExpression is null)
-            dirExpression = (x) => false;
+        dirExpression ??= (x) => false;
 
-        if (fileExpression is null)
-            fileExpression = (x) => false;
+        fileExpression ??= (x) => false;
 
         var dirDelegate = dirExpression.Compile();
         var fileDelegate = fileExpression.Compile();
@@ -943,7 +945,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
                 return;
             }
 
-            if (libDir?.GetFileSystemInfos().Count() > 1)
+            if (libDir?.GetFileSystemInfos().Length > 1)
             {
                 Debug.WriteLine(libFileInfo.FullName);
                 libFileInfo.Delete();
@@ -978,16 +980,20 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
     {
         if (DownloadedVersions is null)
             DownloadedVersions = new();
-
-        DownloadedVersions.Clear();
-        DownloadedVersions = new();
+        else
+        {
+            DownloadedVersions.Clear();
+            DownloadedVersions = new();
+        }
 
         DirectoryInfo versions = new(Settings.minecraftForlderPath + "versions");
         try
         {
             var dirs = versions.GetDirectories("*", SearchOption.TopDirectoryOnly);
-            LauncherProfiles profiles = new LauncherProfiles();
-            profiles.SelectedProfile = "NotImplemented";
+            LauncherProfiles profiles = new()
+            {
+                SelectedProfile = "NotImplemented"
+            };
 
             foreach (var dir in dirs)
             {
@@ -1011,8 +1017,8 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
 
     public void OnOpenForlder()
     {       
-        if (DownloadedVersion?.version is not null && Path.Exists(Settings.minecraftForlderPath + "versions/" + DownloadedVersion.version))
-            Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = Settings.minecraftForlderPath + "versions/" + DownloadedVersion.version, UseShellExecute = true });   
+        if (DownloadedVersion?.Version is not null && Path.Exists(Settings.minecraftForlderPath + "versions/" + DownloadedVersion.Version))
+            Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = Settings.minecraftForlderPath + "versions/" + DownloadedVersion.Version, UseShellExecute = true });   
     }
 
     public void OnClosing(object sender, CancelEventArgs args)
@@ -1044,6 +1050,7 @@ public class VersionsDownloaderViewModel : ViewModelBase, IDisposable
     {
         this.PropertyChanged -= OnFilteredVersionPropertyChanged;
         this.PropertyChanged -= OnDownloadedVersionPropertyChanged;
+        GC.SuppressFinalize(this);
     }
 }
 

+ 10 - 14
VeloeMinecraftLauncher/Views/TitleBar/TitleBarWindow.axaml.cs

@@ -75,10 +75,10 @@ namespace VeloeMinecraftLauncher.Views.TitleBar
                     seamlessMenuBar != null &&
                     defaultMenuBar != null)
                 {
-                    titleBarBackground.IsVisible = IsSeamless ? false : true;
-                    systemChromeTitle.IsVisible = IsSeamless ? false : true;
-                    seamlessMenuBar.IsVisible = IsSeamless ? true : false;
-                    defaultMenuBar.IsVisible = IsSeamless ? false : true;
+                    titleBarBackground.IsVisible = !IsSeamless;
+                    systemChromeTitle.IsVisible = !IsSeamless;
+                    seamlessMenuBar.IsVisible = IsSeamless;
+                    defaultMenuBar.IsVisible = !IsSeamless;
 
                     if (IsSeamless == false)
                     {
@@ -97,7 +97,7 @@ namespace VeloeMinecraftLauncher.Views.TitleBar
                 if (windowIcon != null
                     )
                 {
-                    windowIcon.IsVisible = IsIconVisible ? true : false;
+                    windowIcon.IsVisible = IsIconVisible;
                     //systemChromeTitle.IsVisible = IsIconVisible ? true : false;
                 }
             }
@@ -113,9 +113,9 @@ namespace VeloeMinecraftLauncher.Views.TitleBar
                     maximizeIcon != null &&
                     maximizeToolTip != null)
                 {
-                    maximizeButton.IsVisible = IsIconVisible ? true : false;
-                    maximizeIcon.IsVisible = IsIconVisible ? true : false;
-                    maximizeToolTip.IsVisible = IsIconVisible ? true : false;
+                    maximizeButton.IsVisible = IsIconVisible;
+                    maximizeIcon.IsVisible = IsIconVisible;
+                    maximizeToolTip.IsVisible = IsIconVisible;
                 }
             }
         }
@@ -175,9 +175,7 @@ namespace VeloeMinecraftLauncher.Views.TitleBar
 
         private void MaximizeWindow(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
         {
-            Window? hostWindow = this.GetVisualRoot() as Window;
-
-            if (hostWindow is null) return;
+            if (this.GetVisualRoot() is not Window hostWindow) return;
 
             if (hostWindow.WindowState == WindowState.Normal)
             {
@@ -191,9 +189,7 @@ namespace VeloeMinecraftLauncher.Views.TitleBar
 
         private void MinimizeWindow(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
         {
-            Window? hostWindow = this.GetVisualRoot() as Window;
-
-            if (hostWindow is null) return;
+            if (this.GetVisualRoot() is not Window hostWindow) return;
 
             hostWindow.WindowState = WindowState.Minimized;
         }