diff --git a/src/UniGetUI.Core.IconStore/IconDatabase.cs b/src/UniGetUI.Core.IconStore/IconDatabase.cs index dfc0500ca3..9880fa4620 100644 --- a/src/UniGetUI.Core.IconStore/IconDatabase.cs +++ b/src/UniGetUI.Core.IconStore/IconDatabase.cs @@ -60,9 +60,9 @@ public async Task LoadIconAndScreenshotsDatabaseAsync() try { Uri DownloadUrl = new("https://raw.githubusercontent.com/marticliment/UniGetUI/main/WebBasedData/screenshot-database-v2.json"); - if (Settings.Get("IconDataBaseURL")) + if (Settings.Get(Settings.K.IconDataBaseURL)) { - DownloadUrl = new Uri(Settings.GetValue("IconDataBaseURL")); + DownloadUrl = new Uri(Settings.GetValue(Settings.K.IconDataBaseURL)); } using (HttpClient client = new(CoreTools.GenericHttpClientParameters)) diff --git a/src/UniGetUI.Core.LanguageEngine/LanguageData.cs b/src/UniGetUI.Core.LanguageEngine/LanguageData.cs index 9b3206b4de..8c374f7e64 100644 --- a/src/UniGetUI.Core.LanguageEngine/LanguageData.cs +++ b/src/UniGetUI.Core.LanguageEngine/LanguageData.cs @@ -132,7 +132,7 @@ private static Person[] LoadLanguageTranslatorList() Name: (url is not null ? "@" : "") + (translator["name"] ?? "").ToString(), ProfilePicture: url is not null ? new Uri(url.ToString() + ".png") : null, GitHubUrl: url, - Language: !LangShown ? LanguageData.LanguageReference[langKey.Key] : "" + Language: !LangShown ? LanguageReference[langKey.Key] : "" ); LangShown = true; result.Add(person); diff --git a/src/UniGetUI.Core.LanguageEngine/LanguageEngine.cs b/src/UniGetUI.Core.LanguageEngine/LanguageEngine.cs index a8721d5afb..80d28d5b51 100644 --- a/src/UniGetUI.Core.LanguageEngine/LanguageEngine.cs +++ b/src/UniGetUI.Core.LanguageEngine/LanguageEngine.cs @@ -21,7 +21,7 @@ public class LanguageEngine public LanguageEngine(string ForceLanguage = "") { - string LangName = Settings.GetValue("PreferredLanguage"); + string LangName = Settings.GetValue(Settings.K.PreferredLanguage); if (LangName is "default" or "") { LangName = CultureInfo.CurrentUICulture.ToString().Replace("-", "_"); @@ -93,7 +93,7 @@ public Dictionary LoadLanguageFile(string LangKey) string CachedLangFileToLoad = Path.Join(CoreData.UniGetUICacheDirectory_Lang, "lang_" + LangKey + ".json"); - if (Settings.Get("DisableLangAutoUpdater")) + if (Settings.Get(Settings.K.DisableLangAutoUpdater)) { Logger.Warn("User has updated translations disabled"); } @@ -120,7 +120,7 @@ public Dictionary LoadLanguageFile(string LangKey) } } - if (!Settings.Get("DisableLangAutoUpdater")) + if (!Settings.Get(Settings.K.DisableLangAutoUpdater)) _ = DownloadUpdatedLanguageFile(LangKey); return LangDict; diff --git a/src/UniGetUI.Core.SecureSettings/SecureSettings.cs b/src/UniGetUI.Core.SecureSettings/SecureSettings.cs index c2dd1a1b62..11b2d0044e 100644 --- a/src/UniGetUI.Core.SecureSettings/SecureSettings.cs +++ b/src/UniGetUI.Core.SecureSettings/SecureSettings.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using UniGetUI.Core.Data; using UniGetUI.Core.Tools; +using YamlDotNet.Core.Tokens; using YamlDotNet.Serialization; namespace UniGetUI.Core.SettingsEngine.SecureSettings; @@ -8,11 +9,30 @@ namespace UniGetUI.Core.SettingsEngine.SecureSettings; public static class SecureSettings { // Various predefined secure settings keys - public const string ALLOW_CLI_ARGUMENTS = "AllowCLIArguments"; - public const string ALLOW_IMPORTING_CLI_ARGUMENTS = "AllowImportingCLIArguments"; - public const string ALLOW_PREPOST_OPERATIONS = "AllowPrePostInstallCommands"; - public const string ALLOW_IMPORT_PREPOST_OPERATIONS = "AllowImportingPrePostInstallCommands"; - public const string FORCE_USER_GSUDO = "ForceUserGSudo"; + public enum K + { + AllowCLIArguments, + AllowImportingCLIArguments, + AllowPrePostOpCommand, + AllowImportPrePostOpCommands, + ForceUserGSudo, + Unset + }; + + public static string ResolveKey(K key) + { + return key switch + { + K.AllowCLIArguments => "AllowCLIArguments", + K.AllowImportingCLIArguments => "AllowImportingCLIArguments", + K.AllowPrePostOpCommand => "AllowPrePostInstallCommands", + K.AllowImportPrePostOpCommands => "AllowImportingPrePostInstallCommands", + K.ForceUserGSudo => "ForceUserGSudo", + + K.Unset => throw new InvalidDataException("SecureSettings key was unset!"), + _ => throw new KeyNotFoundException($"The SecureSettings key {key} was not found on the ResolveKey map") + }; + } private static readonly Dictionary _cache = new(); @@ -23,9 +43,9 @@ public static class Args public const string DISABLE_FOR_USER = "--disable-secure-setting-for-user"; } - public static bool Get(string setting) + public static bool Get(K key) { - string purifiedSetting = CoreTools.MakeValidFileName(setting); + string purifiedSetting = CoreTools.MakeValidFileName(ResolveKey(key)); if (_cache.TryGetValue(purifiedSetting, out var value)) { return value; @@ -48,9 +68,9 @@ public static bool Get(string setting) return exists; } - public static async Task TrySet(string setting, bool enabled) + public static async Task TrySet(K key, bool enabled) { - string purifiedSetting = CoreTools.MakeValidFileName(setting); + string purifiedSetting = CoreTools.MakeValidFileName(ResolveKey(key)); _cache.Remove(purifiedSetting); string purifiedUser = CoreTools.MakeValidFileName(Environment.UserName); diff --git a/src/UniGetUI.Core.Settings.Tests/SettingsTest.cs b/src/UniGetUI.Core.Settings.Tests/SettingsTest.cs index dd572781bf..ede74dc344 100644 --- a/src/UniGetUI.Core.Settings.Tests/SettingsTest.cs +++ b/src/UniGetUI.Core.Settings.Tests/SettingsTest.cs @@ -54,8 +54,8 @@ public void Dispose() [Fact] public void TestSettingsSaveToNewDirectory() { - Settings.Set("FreshBoolSetting", true); - Settings.SetValue("FreshValue", "test"); + Settings.Set(Settings.K.FreshBoolSetting, true); + Settings.SetValue(Settings.K.FreshValue, "test"); Assert.True(File.Exists(GetNewSettingPath("FreshBoolSetting"))); Assert.True(File.Exists(GetNewSettingPath("FreshValue"))); @@ -64,13 +64,13 @@ public void TestSettingsSaveToNewDirectory() [Fact] public void TestExistingSettingsMigrateToNewDirectory() { - string settingName = "LegacyBoolSetting"; + string settingName = Settings.ResolveKey(Settings.K.Test7_Legacy); var oldPath = GetOldSettingsPath(settingName); File.WriteAllText(oldPath, ""); - var migratedValue = Settings.Get(settingName); + var migratedValue = Settings.Get(Settings.K.Test7_Legacy); var newPath = GetNewSettingPath(settingName); - var valueAfterMigration = Settings.Get(settingName); + var valueAfterMigration = Settings.Get(Settings.K.Test7_Legacy); Assert.True(migratedValue); Assert.True(valueAfterMigration); @@ -80,71 +80,73 @@ public void TestExistingSettingsMigrateToNewDirectory() } [Theory] - [InlineData("TestSetting1", true, false, false, true)] - [InlineData("TestSetting2", true, false, false, false)] - [InlineData("Test.Settings_with", true, false, true, true)] - [InlineData("TestSettingEntry With A Space", false, true, false, false)] - [InlineData("ª", false, false, false, false)] - [InlineData("VeryVeryLongTestSettingEntrySoTheClassCanReallyBeStressedOut", true, false, true, true)] - public void TestBooleanSettings(string SettingName, bool st1, bool st2, bool st3, bool st4) + [InlineData(Settings.K.Test1, true, false, false, true)] + [InlineData(Settings.K.Test2, true, false, false, false)] + [InlineData(Settings.K.Test3, true, false, true, true)] + [InlineData(Settings.K.Test4, false, true, false, false)] + [InlineData(Settings.K.Test5, false, false, false, false)] + [InlineData(Settings.K.Test6, true, false, true, true)] + public void TestBooleanSettings(Settings.K key, bool st1, bool st2, bool st3, bool st4) { - Settings.Set(SettingName, st1); - Assert.Equal(st1, Settings.Get(SettingName)); - Assert.Equal(st1, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.Set(SettingName, st2); - Assert.Equal(st2, Settings.Get(SettingName)); - Assert.Equal(st2, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.Set(SettingName, st3); - Assert.Equal(st3, Settings.Get(SettingName)); - Assert.Equal(st3, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.Set(SettingName, st4); - Assert.Equal(st4, Settings.Get(SettingName)); - Assert.Equal(st4, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.Set(SettingName, false); // Cleanup - Assert.False(Settings.Get(SettingName)); - Assert.False(File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); + string sName = Settings.ResolveKey(key); + Settings.Set(key, st1); + Assert.Equal(st1, Settings.Get(key)); + Assert.Equal(st1, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.Set(key, st2); + Assert.Equal(st2, Settings.Get(key)); + Assert.Equal(st2, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.Set(key, st3); + Assert.Equal(st3, Settings.Get(key)); + Assert.Equal(st3, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.Set(key, st4); + Assert.Equal(st4, Settings.Get(key)); + Assert.Equal(st4, File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.Set(key, false); // Cleanup + Assert.False(Settings.Get(key)); + Assert.False(File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); } [Theory] - [InlineData("TestSetting1", "RandomFirstValue", "RandomSecondValue", "", "RandomThirdValue")] - [InlineData("ktjgshdfsd", "", "", "", "RandomThirdValue")] - [InlineData("ª", "RandomFirstValue", " ", "\t", "RandomThirdValue")] - [InlineData("TestSettingEntry With A Space", "RandomFirstValue", "", "", "")] - [InlineData("VeryVeryLongTestSettingEntrySoTheClassCanReallyBeStressedOut", "\x00\x01\x02\u0003", "", "", "RandomThirdValue")] - public void TestValueSettings(string SettingName, string st1, string st2, string st3, string st4) + [InlineData(Settings.K.Test1, "RandomFirstValue", "RandomSecondValue", "", "RandomThirdValue")] + [InlineData(Settings.K.Test2, "", "", "", "RandomThirdValue")] + [InlineData(Settings.K.Test3, "RandomFirstValue", " ", "\t", "RandomThirdValue")] + [InlineData(Settings.K.Test4, "RandomFirstValue", "", "", "")] + [InlineData(Settings.K.Test5, "\x00\x01\x02\u0003", "", "", "RandomThirdValue")] + public void TestValueSettings(Settings.K key, string st1, string st2, string st3, string st4) { - Settings.SetValue(SettingName, st1); - Assert.Equal(st1, Settings.GetValue(SettingName)); - Assert.Equal(st1 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.SetValue(SettingName, st2); - Assert.Equal(st2, Settings.GetValue(SettingName)); - Assert.Equal(st2 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.SetValue(SettingName, st3); - Assert.Equal(st3, Settings.GetValue(SettingName)); - Assert.Equal(st3 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.SetValue(SettingName, st4); - Assert.Equal(st4, Settings.GetValue(SettingName)); - Assert.Equal(st4 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); - - Settings.Set(SettingName, false); // Cleanup - Assert.False(Settings.Get(SettingName)); - Assert.Equal("", Settings.GetValue(SettingName)); - Assert.False(File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, SettingName))); + string sName = Settings.ResolveKey(key); + Settings.SetValue(key, st1); + Assert.Equal(st1, Settings.GetValue(key)); + Assert.Equal(st1 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.SetValue(key, st2); + Assert.Equal(st2, Settings.GetValue(key)); + Assert.Equal(st2 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.SetValue(key, st3); + Assert.Equal(st3, Settings.GetValue(key)); + Assert.Equal(st3 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.SetValue(key, st4); + Assert.Equal(st4, Settings.GetValue(key)); + Assert.Equal(st4 != "", File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); + + Settings.Set(key, false); // Cleanup + Assert.False(Settings.Get(key)); + Assert.Equal("", Settings.GetValue(key)); + Assert.False(File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, sName))); } [Theory] - [InlineData("lsTestSetting1", new string[] { "UpdatedFirstValue", "RandomString1", "RandomTestValue", "AnotherRandomValue" }, new int[] { 9, 15, 21, 1001, 4567 }, new string[] { "itemA", "itemB", "itemC" })] - [InlineData("lsktjgshdfsd", new string[] { "newValue1", "updatedString", "emptyString", "randomSymbols@123" }, new int[] { 42, 23, 17, 98765, 3482 }, new string[] { "itemX", "itemY", "itemZ" })] - [InlineData("lsª", new string[] { "UniqueVal1", "NewVal2", "AnotherVal3", "TestVal4" }, new int[] { 123, 456, 789, 321, 654 }, new string[] { "item1", "item2", "item3" })] - [InlineData("lsTestSettingEntry With A Space", new string[] { "ChangedFirstValue", "AlteredSecondVal", "TestedValue", "FinalVal" }, new int[] { 23, 98, 456, 753, 951 }, new string[] { "testA", "testB", "testC" })] - [InlineData("lsVeryVeryLongTestSettingEntrySoTheClassCanReallyBeStressedOut", new string[] { "newCharacterSet\x99\x01\x02", "UpdatedRandomValue", "TestEmptyString", "FinalTestValue" }, new int[] { 0b11001100, 1234, 5678, 1000000 }, new string[] { "finalTest1", "finalTest2", "finalTest3" })] + [InlineData("lsTestSetting1", new[] { "UpdatedFirstValue", "RandomString1", "RandomTestValue", "AnotherRandomValue" }, new[] { 9, 15, 21, 1001, 4567 }, new[] { "itemA", "itemB", "itemC" })] + [InlineData("lsktjgshdfsd", new[] { "newValue1", "updatedString", "emptyString", "randomSymbols@123" }, new[] { 42, 23, 17, 98765, 3482 }, new[] { "itemX", "itemY", "itemZ" })] + [InlineData("lsª", new[] { "UniqueVal1", "NewVal2", "AnotherVal3", "TestVal4" }, new[] { 123, 456, 789, 321, 654 }, new[] { "item1", "item2", "item3" })] + [InlineData("lsTestSettingEntry With A Space", new[] { "ChangedFirstValue", "AlteredSecondVal", "TestedValue", "FinalVal" }, new[] { 23, 98, 456, 753, 951 }, new[] { "testA", "testB", "testC" })] + [InlineData("lsVeryVeryLongTestSettingEntrySoTheClassCanReallyBeStressedOut", new[] { "newCharacterSet\x99\x01\x02", "UpdatedRandomValue", "TestEmptyString", "FinalTestValue" }, new[] { 0b11001100, 1234, 5678, 1000000 }, new[] { "finalTest1", "finalTest2", "finalTest3" })] public void TestListSettings(string SettingName, string[] ls1Array, int[] ls2Array, string[] ls3Array) { // Convert arrays to Lists manually @@ -199,12 +201,12 @@ public void TestListSettings(string SettingName, string[] ls1Array, int[] ls2Arr } [Theory] - [InlineData("dTestSetting1", new string[] { "UpdatedFirstValue", "RandomString1", "RandomTestValue", "AnotherRandomValue" }, new int[] { 9, 15, 21, 1001, 4567 }, new string[] { "itemA", "itemB", "itemC" })] - [InlineData("dktjgshdfsd", new string[] { "newValue1", "updatedString", "emptyString", "randomSymbols@123" }, new int[] { 42, 23, 17, 98765, 3482 }, new string[] { "itemX", "itemY", "itemZ" })] - [InlineData("dª", new string[] { "UniqueVal1", "NewVal2", "AnotherVal3", "TestVal4" }, new int[] { 123, 456, 789, 321, 654 }, new string[] { "item1", "item2", "item3" })] - [InlineData("dTestSettingEntry With A Space", new string[] { "ChangedFirstValue", "AlteredSecondVal", "TestedValue", "FinalVal" }, new int[] { 23, 98, 456, 753, 951 }, new string[] { "testA", "testB", "testC" })] - [InlineData("dVeryVeryLongTestSettingEntrySoTheClassCanReallyBeStressedOut", new string[] { "newCharacterSet\x99\x01\x02", "UpdatedRandomValue", "TestEmptyString", "FinalTestValue" }, new int[] { 0b11001100, 1234, 5678, 1000000 }, new string[] { "finalTest1", "finalTest2", "finalTest3" })] - public void TestDictionarySettings(string SettingName, string[] keyArray, int[] intArray, string[] strArray) + [InlineData(Settings.K.Test2, new[] { "UpdatedFirstValue", "RandomString1", "RandomTestValue", "AnotherRandomValue" }, new[] { 9, 15, 21, 1001, 4567 }, new[] { "itemA", "itemB", "itemC" })] + [InlineData(Settings.K.Test3, new[] { "newValue1", "updatedString", "emptyString", "randomSymbols@123" }, new[] { 42, 23, 17, 98765, 3482 }, new[] { "itemX", "itemY", "itemZ" })] + [InlineData(Settings.K.Test4, new[] { "UniqueVal1", "NewVal2", "AnotherVal3", "TestVal4" }, new[] { 123, 456, 789, 321, 654 }, new[] { "item1", "item2", "item3" })] + [InlineData(Settings.K.Test5, new[] { "ChangedFirstValue", "AlteredSecondVal", "TestedValue", "FinalVal" }, new[] { 23, 98, 456, 753, 951 }, new[] { "testA", "testB", "testC" })] + [InlineData(Settings.K.Test6, new[] { "newCharacterSet\x99\x01\x02", "UpdatedRandomValue", "TestEmptyString", "FinalTestValue" }, new[] { 0b11001100, 1234, 5678, 1000000 }, new[] { "finalTest1", "finalTest2", "finalTest3" })] + public void TestDictionarySettings(Settings.K SettingName, string[] keyArray, int[] intArray, string[] strArray) { Dictionary test = []; Dictionary nonEmptyDictionary = []; @@ -222,11 +224,10 @@ public void TestDictionarySettings(string SettingName, string[] keyArray, int[] ); } - string randStr = new Random().Next().ToString(); - Settings.SetDictionaryItem(randStr, "key", 12); - Assert.Equal(12, Settings.GetDictionaryItem(randStr, "key")); + Settings.SetDictionaryItem(SettingName, "key", 12); + Assert.Equal(12, Settings.GetDictionaryItem(SettingName, "key")); Settings.SetDictionary(SettingName, test); - Assert.Equal(JsonSerializer.Serialize(test, Settings.SerializationOptions), File.ReadAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{SettingName}.json"))); + Assert.Equal(JsonSerializer.Serialize(test, Settings.SerializationOptions), File.ReadAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{Settings.ResolveKey(SettingName)}.json"))); Assert.Equal(test[keyArray[0]]?.sub.count, Settings.GetDictionary(SettingName)?[keyArray[0]]?.sub.count); Assert.Equal(test[keyArray[1]]?.sub.count, Settings.GetDictionaryItem(SettingName, keyArray[1])?.sub.count); Settings.SetDictionaryItem(SettingName, keyArray[0], test[keyArray[1]]); @@ -258,12 +259,22 @@ public void TestDictionarySettings(string SettingName, string[] keyArray, int[] Assert.Equal( JsonSerializer.Serialize(Settings.GetDictionary(SettingName), Settings.SerializationOptions), - File.ReadAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{SettingName}.json")) + File.ReadAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{Settings.ResolveKey(SettingName)}.json")) ); Settings.ClearDictionary(SettingName); // Cleanup Assert.Empty(Settings.GetDictionary(SettingName) ?? nonEmptyDictionary); - Assert.False(File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{SettingName}.json"))); + Assert.False(File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{Settings.ResolveKey(SettingName)}.json"))); + } + + [Fact] + public static void EnsureAllKeysResolve() + { + foreach (Settings.K key in Enum.GetValues(typeof(Settings.K))) + { + if(key is Settings.K.Unset) continue; + Assert.NotEmpty(Settings.ResolveKey(key)); + } } } } diff --git a/src/UniGetUI.Core.Settings/SettingsEngine.cs b/src/UniGetUI.Core.Settings/SettingsEngine.cs index f2861d92d2..8cc8aee80b 100644 --- a/src/UniGetUI.Core.Settings/SettingsEngine.cs +++ b/src/UniGetUI.Core.Settings/SettingsEngine.cs @@ -6,28 +6,30 @@ namespace UniGetUI.Core.SettingsEngine { public static partial class Settings { - private static readonly ConcurrentDictionary booleanSettings = new(); - private static readonly ConcurrentDictionary valueSettings = new(); + private static readonly ConcurrentDictionary booleanSettings = new(); + private static readonly ConcurrentDictionary valueSettings = new(); - public static bool Get(string setting, bool invert = false) + public static bool Get(K key, bool invert = false) { - if (booleanSettings.TryGetValue(setting, out bool result)) + string setting = ResolveKey(key); + if (booleanSettings.TryGetValue(key, out bool result)) { // If the setting was cached return result ^ invert; } // Otherwise, load the value from disk and cache that setting result = File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, setting)); - booleanSettings[setting] = result; + booleanSettings[key] = result; return result ^ invert; } - public static void Set(string setting, bool value) + public static void Set(K key, bool value) { + string setting = ResolveKey(key); try { // Cache that setting's new value - booleanSettings[setting] = value; + booleanSettings[key] = value; // Update changes on disk if applicable if (value && !File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, setting))) @@ -36,7 +38,7 @@ public static void Set(string setting, bool value) } else if (!value) { - valueSettings[setting] = ""; + valueSettings[key] = ""; if (File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, setting))) { @@ -52,9 +54,10 @@ public static void Set(string setting, bool value) } } - public static string GetValue(string setting) + public static string GetValue(K key) { - if (valueSettings.TryGetValue(setting, out string? value)) + string setting = ResolveKey(key); + if (valueSettings.TryGetValue(key, out string? value)) { // If the setting was cached return value; } @@ -66,26 +69,27 @@ public static string GetValue(string setting) value = File.ReadAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, setting)); } - valueSettings[setting] = value; + valueSettings[key] = value; return value; } - public static void SetValue(string setting, string value) + public static void SetValue(K key, string value) { + string setting = ResolveKey(key); try { if (value == String.Empty) { - Set(setting, false); - booleanSettings[setting] = false; - valueSettings[setting] = ""; + Set(key, false); + booleanSettings[key] = false; + valueSettings[key] = ""; } else { File.WriteAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, setting), value); - booleanSettings[setting] = true; - valueSettings[setting] = value; + booleanSettings[key] = true; + valueSettings[key] = value; } } catch (Exception e) diff --git a/src/UniGetUI.Core.Settings/SettingsEngine_Dictionaries.cs b/src/UniGetUI.Core.Settings/SettingsEngine_Dictionaries.cs index a187870cdd..6de0da2a4b 100644 --- a/src/UniGetUI.Core.Settings/SettingsEngine_Dictionaries.cs +++ b/src/UniGetUI.Core.Settings/SettingsEngine_Dictionaries.cs @@ -7,34 +7,35 @@ namespace UniGetUI.Core.SettingsEngine { public static partial class Settings { - private static readonly ConcurrentDictionary> _dictionarySettings = new(); + private static readonly ConcurrentDictionary> _dictionarySettings = new(); // Returns an empty dictionary if the setting doesn't exist and null if the types are invalid - private static Dictionary _getDictionary(string setting) - where K : notnull - { + private static Dictionary _getDictionary(K key) + where KeyT : notnull + { + string setting = ResolveKey(key); try { try { - if (_dictionarySettings.TryGetValue(setting, out Dictionary? result)) + if (_dictionarySettings.TryGetValue(key, out Dictionary? result)) { // If the setting was cached return result.ToDictionary( - kvp => (K)kvp.Key, - kvp => (V?)kvp.Value + kvp => (KeyT)kvp.Key, + kvp => (ValueT?)kvp.Value ); } } catch (InvalidCastException) { Logger.Error( - $"Tried to get a dictionary setting with a key of type {typeof(K)} and a value of type {typeof(V)}, which is not the type of the dictionary"); + $"Tried to get a dictionary setting with a key of type {typeof(KeyT)} and a value of type {typeof(ValueT)}, which is not the type of the dictionary"); return null; } // Otherwise, load the setting from disk and cache that setting - Dictionary value = []; + Dictionary value = []; if (File.Exists(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{setting}.json"))) { string result = File.ReadAllText(Path.Join(CoreData.UniGetUIUserConfigurationDirectory, $"{setting}.json")); @@ -43,7 +44,7 @@ public static partial class Settings if (result != "") { - Dictionary? item = JsonSerializer.Deserialize>(result, SerializationOptions); + Dictionary? item = JsonSerializer.Deserialize>(result, SerializationOptions); if (item is not null) { value = item; @@ -53,11 +54,11 @@ public static partial class Settings catch (InvalidCastException) { Logger.Error( - $"Tried to get a dictionary setting with a key of type {typeof(K)} and a value of type {typeof(V)}, but the setting on disk ({result}) cannot be deserialized to that"); + $"Tried to get a dictionary setting with a key of type {typeof(KeyT)} and a value of type {typeof(ValueT)}, but the setting on disk ({result}) cannot be deserialized to that"); } } - _dictionarySettings[setting] = value.ToDictionary( + _dictionarySettings[key] = value.ToDictionary( kvp => (object)kvp.Key, kvp => (object?)kvp.Value ); @@ -72,16 +73,17 @@ public static partial class Settings } // Returns an empty dictionary if the setting doesn't exist and null if the types are invalid - public static IReadOnlyDictionary GetDictionary(string setting) - where K : notnull + public static IReadOnlyDictionary GetDictionary(K settingsKey) + where KeyT : notnull { - return _getDictionary(setting); + return _getDictionary(settingsKey); } - public static void SetDictionary(string setting, Dictionary value) - where K : notnull + public static void SetDictionary(K settingsKey, Dictionary value) + where KeyT : notnull { - _dictionarySettings[setting] = value.ToDictionary( + string setting = ResolveKey(settingsKey); + _dictionarySettings[settingsKey] = value.ToDictionary( kvp => (object)kvp.Key, kvp => (object?)kvp.Value ); @@ -100,80 +102,80 @@ public static void SetDictionary(string setting, Dictionary value) } } - public static V? GetDictionaryItem(string setting, K key) - where K : notnull + public static ValueT? GetDictionaryItem(K settingsKey, KeyT key) + where KeyT : notnull { - Dictionary? dictionary = _getDictionary(setting); - if (dictionary == null || !dictionary.TryGetValue(key, out V? value)) return default; + Dictionary? dictionary = _getDictionary(settingsKey); + if (dictionary == null || !dictionary.TryGetValue(key, out ValueT? value)) return default; return value; } // Also works as `Add` - public static V? SetDictionaryItem(string setting, K key, V value) - where K : notnull + public static ValueT? SetDictionaryItem(K settingsKey, KeyT key, ValueT value) + where KeyT : notnull { - Dictionary? dictionary = _getDictionary(setting); + Dictionary? dictionary = _getDictionary(settingsKey); if (dictionary == null) { dictionary = new() { { key, value } }; - SetDictionary(setting, dictionary); + SetDictionary(settingsKey, dictionary); return default; } - if (dictionary.TryGetValue(key, out V? oldValue)) + if (dictionary.TryGetValue(key, out ValueT? oldValue)) { dictionary[key] = value; - SetDictionary(setting, dictionary); + SetDictionary(settingsKey, dictionary); return oldValue; } dictionary.Add(key, value); - SetDictionary(setting, dictionary); + SetDictionary(settingsKey, dictionary); return default; } - public static V? RemoveDictionaryKey(string setting, K key) - where K : notnull + public static ValueT? RemoveDictionaryKey(K settingsKey, KeyT key) + where KeyT : notnull { - Dictionary? dictionary = _getDictionary(setting); + Dictionary? dictionary = _getDictionary(settingsKey); if (dictionary == null) return default; bool success = false; - if (dictionary.TryGetValue(key, out V? value)) + if (dictionary.TryGetValue(key, out ValueT? value)) { success = dictionary.Remove(key); - SetDictionary(setting, dictionary); + SetDictionary(settingsKey, dictionary); } if (!success) return default; return value; } - public static bool DictionaryContainsKey(string setting, K key) - where K : notnull + public static bool DictionaryContainsKey(K settingsKey, KeyT key) + where KeyT : notnull { - Dictionary? dictionary = _getDictionary(setting); + Dictionary? dictionary = _getDictionary(settingsKey); if (dictionary == null) return false; return dictionary.ContainsKey(key); } - public static bool DictionaryContainsValue(string setting, V value) - where K : notnull + public static bool DictionaryContainsValue(K settingsKey, ValueT value) + where KeyT : notnull { - Dictionary? dictionary = _getDictionary(setting); + Dictionary? dictionary = _getDictionary(settingsKey); if (dictionary == null) return false; return dictionary.ContainsValue(value); } - public static void ClearDictionary(string setting) + public static void ClearDictionary(K settingsKey) { - SetDictionary(setting, new Dictionary()); + SetDictionary(settingsKey, new Dictionary()); } } } diff --git a/src/UniGetUI.Core.Settings/SettingsEngine_Extras.cs b/src/UniGetUI.Core.Settings/SettingsEngine_Extras.cs index 19d1587533..dc63aaaf02 100644 --- a/src/UniGetUI.Core.Settings/SettingsEngine_Extras.cs +++ b/src/UniGetUI.Core.Settings/SettingsEngine_Extras.cs @@ -14,37 +14,27 @@ public partial class Settings */ public static bool AreNotificationsDisabled() - { - return Get("DisableSystemTray") || Get("DisableNotifications"); - } + => Get(K.DisableSystemTray) || Get(K.DisableNotifications); public static bool AreUpdatesNotificationsDisabled() - { - return AreNotificationsDisabled() || Get("DisableUpdatesNotifications"); - } + => AreNotificationsDisabled() || Get(K.DisableUpdatesNotifications); public static bool AreErrorNotificationsDisabled() - { - return AreNotificationsDisabled() || Get("DisableErrorNotifications"); - } + => AreNotificationsDisabled() || Get(K.DisableErrorNotifications); public static bool AreSuccessNotificationsDisabled() - { - return AreNotificationsDisabled() || Get("DisableSuccessNotifications"); - } + => AreNotificationsDisabled() || Get(K.DisableSuccessNotifications); public static bool AreProgressNotificationsDisabled() - { - return AreNotificationsDisabled() || Get("DisableProgressNotifications"); - } + => AreNotificationsDisabled() || Get(K.DisableProgressNotifications); public static Uri? GetProxyUrl() { - if (!Settings.Get("EnableProxy")) return null; + if (!Get(K.EnableProxy)) return null; - string plainUrl = Settings.GetValue("ProxyURL"); + string plainUrl = GetValue(K.ProxyURL); Uri.TryCreate(plainUrl, UriKind.RelativeOrAbsolute, out Uri? var); - if(Settings.Get("EnableProxy") && var is null) Logger.Warn($"Proxy setting {plainUrl} is not valid"); + if(Get(K.EnableProxy) && var is null) Logger.Warn($"Proxy setting {plainUrl} is not valid"); return var; } @@ -55,7 +45,7 @@ public static bool AreProgressNotificationsDisabled() try { var vault = new PasswordVault(); - var credentials = vault.Retrieve(PROXY_RES_ID, Settings.GetValue("ProxyUsername")); + var credentials = vault.Retrieve(PROXY_RES_ID, GetValue(K.ProxyUsername)); return new NetworkCredential() { @@ -76,7 +66,7 @@ public static void SetProxyCredentials(string username, string password) try { var vault = new PasswordVault(); - Settings.SetValue("ProxyUsername", username); + SetValue(K.ProxyUsername, username); vault.Add(new PasswordCredential(PROXY_RES_ID, username, password)); } catch (Exception ex) diff --git a/src/UniGetUI.Core.Settings/SettingsEngine_Names.cs b/src/UniGetUI.Core.Settings/SettingsEngine_Names.cs new file mode 100644 index 0000000000..e9a5054fea --- /dev/null +++ b/src/UniGetUI.Core.Settings/SettingsEngine_Names.cs @@ -0,0 +1,174 @@ +namespace UniGetUI.Core.SettingsEngine; + +public static partial class Settings +{ + public enum K + { + EnableProxy, + EnableProxyAuth, + DisableWaitForInternetConnection, + IconDataBaseURL, + DisableLangAutoUpdater, + DisableDMWThreadOptimizations, + DisableTelemetry, + DisableTimeoutOnPackageListingTasks, + RemoveAllDesktopShortcuts, + EnableScoopCleanup, + IgnoreUpdatesNotApplicable, + ForceLegacyBundledWinGet, + DisableNewWinGetTroubleshooter, + DisableUpdateVcpkgGitPorts, + ChocolateySymbolicLinkCreated, + UseSystemChocolatey, + DisableSelectingUpdatesByDefault, + DisableAutoCheckforUpdates, + AskToDeleteNewDesktopShortcuts, + DoCacheAdminRights, + DoCacheAdminRightsForBatches, + DisableAutoUpdateWingetUI, + EnableUniGetUIBeta, + ShowVersionNumberOnTitlebar, + TransferredOldSettings, + DisableApi, + DisableSystemTray, + MaintainSuccessfulInstalls, + AutomaticallyUpdatePackages, + DisableAUPOnMeteredConnections, + DisableAUPOnBatterySaver, + CustomVcpkgRoot, + AlreadyWarnedAboutAdmin, + ShownTelemetryBanner, + CollapseNavMenuOnWideScreen, + EnablePackageBackup, + ChangeBackupOutputDirectory, + DisableWinGetMalfunctionDetector, + EnableBackupTimestamping, + DisableIconsOnPackageLists, + ProxyURL, + ProxyUsername, + PreferredLanguage, + DefaultVcpkgTriplet, + UpdatesCheckInterval, + ParallelOperationCount, + TelemetryClientToken, + PreferredTheme, + OperationHistory, + StartupPage, + WindowGeometry, + ChangeBackupFileName, + CurrentSessionToken, + IgnoredPackageUpdates, + DisabledManagers, + DeletableDesktopShortcuts, + WinGetAlreadyUpgradedPackages, + DependencyManagement, + DisabledPackageManagerNotifications, + PackageListViewMode, + DisableInstantSearch, + SidepanelWidths, + HideToggleFilters, + FreshBoolSetting, + FreshValue, + DisableNotifications, + DisableUpdatesNotifications, + DisableErrorNotifications, + DisableSuccessNotifications, + DisableProgressNotifications, + + Test1, + Test2, + Test3, + Test4, + Test5, + Test6, + Test7_Legacy, + Unset + }; + + public static string ResolveKey(K key) + { + return key switch + { + K.EnableProxy => "EnableProxy", + K.EnableProxyAuth => "EnableProxyAuth", + K.DisableWaitForInternetConnection => "DisableWaitForInternetConnection", + K.IconDataBaseURL => "IconDataBaseURL", + K.DisableLangAutoUpdater => "DisableLangAutoUpdater", + K.DisableDMWThreadOptimizations => "DisableDMWThreadOptimizations", + K.DisableTelemetry => "DisableTelemetry", + K.DisableTimeoutOnPackageListingTasks => "DisableTimeoutOnPackageListingTasks", + K.RemoveAllDesktopShortcuts => "RemoveAllDesktopShortcuts", + K.EnableScoopCleanup => "EnableScoopCleanup", + K.IgnoreUpdatesNotApplicable => "IgnoreUpdatesNotApplicable", + K.ForceLegacyBundledWinGet => "ForceLegacyBundledWinGet", + K.DisableNewWinGetTroubleshooter => "DisableNewWinGetTroubleshooter", + K.DisableUpdateVcpkgGitPorts => "DisableUpdateVcpkgGitPorts", + K.ChocolateySymbolicLinkCreated => "ChocolateySymbolicLinkCreated", + K.UseSystemChocolatey => "UseSystemChocolatey", + K.DisableSelectingUpdatesByDefault => "DisableSelectingUpdatesByDefault", + K.DisableAutoCheckforUpdates => "DisableAutoCheckforUpdates", + K.AskToDeleteNewDesktopShortcuts => "AskToDeleteNewDesktopShortcuts", + K.DoCacheAdminRights => "DoCacheAdminRights", + K.DoCacheAdminRightsForBatches => "DoCacheAdminRightsForBatches", + K.DisableAutoUpdateWingetUI => "DisableAutoUpdateWingetUI", + K.EnableUniGetUIBeta => "EnableUniGetUIBeta", + K.ShowVersionNumberOnTitlebar => "ShowVersionNumberOnTitlebar", + K.TransferredOldSettings => "TransferredOldSettings", + K.DisableApi => "DisableApi", + K.DisableSystemTray => "DisableSystemTray", + K.MaintainSuccessfulInstalls => "MaintainSuccessfulInstalls", + K.AutomaticallyUpdatePackages => "AutomaticallyUpdatePackages", + K.DisableAUPOnMeteredConnections => "DisableAUPOnMeteredConnections", + K.DisableAUPOnBatterySaver => "DisableAUPOnBatterySaver", + K.CustomVcpkgRoot => "CustomVcpkgRoot", + K.AlreadyWarnedAboutAdmin => "AlreadyWarnedAboutAdmin", + K.ShownTelemetryBanner => "ShownTelemetryBanner", + K.CollapseNavMenuOnWideScreen => "CollapseNavMenuOnWideScreen", + K.EnablePackageBackup => "EnablePackageBackup", + K.ChangeBackupOutputDirectory => "ChangeBackupOutputDirectory", + K.DisableWinGetMalfunctionDetector => "DisableWinGetMalfunctionDetector", + K.EnableBackupTimestamping => "EnableBackupTimestamping", + K.DisableIconsOnPackageLists => "DisableIconsOnPackageLists", + K.ProxyURL => "ProxyURL", + K.ProxyUsername => "ProxyUsername", + K.PreferredLanguage => "PreferredLanguage", + K.DefaultVcpkgTriplet => "DefaultVcpkgTriplet", + K.UpdatesCheckInterval => "UpdatesCheckInterval", + K.ParallelOperationCount => "ParallelOperationCount", + K.TelemetryClientToken => "TelemetryClientToken", + K.PreferredTheme => "PreferredTheme", + K.OperationHistory => "OperationHistory", + K.StartupPage => "StartupPage", + K.WindowGeometry => "WindowGeometry", + K.ChangeBackupFileName => "ChangeBackupFileName", + K.CurrentSessionToken => "CurrentSessionToken", + K.IgnoredPackageUpdates => "IgnoredPackageUpdates", + K.DisabledManagers => "DisabledManagers", + K.DeletableDesktopShortcuts => "DeletableDesktopShortcuts", + K.WinGetAlreadyUpgradedPackages => "WinGetAlreadyUpgradedPackages", + K.DependencyManagement => "DependencyManagement", + K.DisabledPackageManagerNotifications => "DisabledPackageManagerNotifications", + K.PackageListViewMode => "PackageListViewMode", + K.DisableInstantSearch => "DisableInstantSearch", + K.SidepanelWidths => "SidepanelWidths", + K.HideToggleFilters => "HideToggleFilters", + K.FreshBoolSetting => "FreshBoolSetting", + K.FreshValue => "FreshValue", + K.DisableNotifications => "DisableNotifications", + K.DisableUpdatesNotifications => "DisableUpdatesNotifications", + K.DisableErrorNotifications => "DisableErrorNotifications", + K.DisableSuccessNotifications => "DisableSuccessNotifications", + K.DisableProgressNotifications => "DisableProgressNotifications", + + K.Test1 => "TestSetting1", + K.Test2 => "TestSetting2", + K.Test3 => "Test.Settings_with", + K.Test4 => "TestSettingEntry With A Space", + K.Test5 => "ª", + K.Test6 => "VeryVeryLongTestSettingEntrySoTheClassCanReallyBeStressedOut", + K.Test7_Legacy => "LegacyBoolSetting", + K.Unset => throw new InvalidDataException("Setting key was unset!"), + _ => throw new KeyNotFoundException($"The settings key {key} was not found on the ResolveKey map") + }; + } +} diff --git a/src/UniGetUI.Core.Tools.Tests/MetaTests.cs b/src/UniGetUI.Core.Tools.Tests/MetaTests.cs index 8259da2e57..0594d65a5e 100644 --- a/src/UniGetUI.Core.Tools.Tests/MetaTests.cs +++ b/src/UniGetUI.Core.Tools.Tests/MetaTests.cs @@ -22,7 +22,7 @@ public void TestJsonSerializationOptions() var serialOptionsCount3 = lines.Count(x => x.Contains("SerializationOptions")); Assert.True((jsonSerCount + jsonDeserCount) <= serialOptionsCount1 + serialOptionsCount2 + serialOptionsCount3, $"Failing on {file}. The specified file does not serialize and/or deserialize JSON with" + - $" the proper CoreData.DefaultOptions set"); + $" the proper SerializationHelpers.DefaultOptions set"); } } diff --git a/src/UniGetUI.Core.Tools/DWMThreadHelper.cs b/src/UniGetUI.Core.Tools/DWMThreadHelper.cs index 2b14cd8a24..9ef12a2b49 100644 --- a/src/UniGetUI.Core.Tools/DWMThreadHelper.cs +++ b/src/UniGetUI.Core.Tools/DWMThreadHelper.cs @@ -41,7 +41,7 @@ private enum ThreadAccess : uint public static void ChangeState_DWM(bool suspend) { - if (Settings.Get("DisableDMWThreadOptimizations")) return; + if (Settings.Get(Settings.K.DisableDMWThreadOptimizations)) return; if (DWM_IsSuspended && suspend) { @@ -63,7 +63,7 @@ public static void ChangeState_DWM(bool suspend) public static void ChangeState_XAML(bool suspend) { - if (Settings.Get("DisableDMWThreadOptimizations")) return; + if (Settings.Get(Settings.K.DisableDMWThreadOptimizations)) return; if (XAML_IsSuspended && suspend) { diff --git a/src/UniGetUI.Core.Tools/Tools.cs b/src/UniGetUI.Core.Tools/Tools.cs index 5d97385236..231e7f6aef 100644 --- a/src/UniGetUI.Core.Tools/Tools.cs +++ b/src/UniGetUI.Core.Tools/Tools.cs @@ -29,8 +29,8 @@ public static HttpClientHandler GenericHttpClientParameters IWebProxy? proxy = null; ICredentials? creds = null; - if (Settings.Get("EnableProxy")) proxyUri = Settings.GetProxyUrl(); - if (Settings.Get("EnableProxyAuth")) creds = Settings.GetProxyCredentials(); + if (Settings.Get(Settings.K.EnableProxy)) proxyUri = Settings.GetProxyUrl(); + if (Settings.Get(Settings.K.EnableProxyAuth)) creds = Settings.GetProxyCredentials(); if (proxyUri is not null) proxy = new WebProxy() { Address = proxyUri, @@ -608,7 +608,7 @@ public static async Task WaitForInternetConnection() public static void _waitForInternetConnection() { - if (Settings.Get("DisableWaitForInternetConnection")) return; + if (Settings.Get(Settings.K.DisableWaitForInternetConnection)) return; Logger.Debug("Checking for internet connectivity..."); bool internetLost = false; diff --git a/src/UniGetUI.Interface.BackgroundApi/BackgroundApi.cs b/src/UniGetUI.Interface.BackgroundApi/BackgroundApi.cs index ff0df44156..3b8653fb98 100644 --- a/src/UniGetUI.Interface.BackgroundApi/BackgroundApi.cs +++ b/src/UniGetUI.Interface.BackgroundApi/BackgroundApi.cs @@ -43,15 +43,8 @@ public static bool AuthenticateToken(string? token) public async Task Start() { - - if (Settings.Get("DisableWidgetsApi")) - { - Logger.Warn("Widgets API is disabled"); - return; - } - ApiTokenHolder.Token = CoreTools.RandomString(64); - Settings.SetValue("CurrentSessionToken", ApiTokenHolder.Token); + Settings.SetValue(Settings.K.CurrentSessionToken, ApiTokenHolder.Token); Logger.Info("Randomly-generated background API auth token: " + ApiTokenHolder.Token); var builder = Host.CreateDefaultBuilder(); diff --git a/src/UniGetUI.Interface.Telemetry/TelemetryHandler.cs b/src/UniGetUI.Interface.Telemetry/TelemetryHandler.cs index c6850234a5..0531236fef 100644 --- a/src/UniGetUI.Interface.Telemetry/TelemetryHandler.cs +++ b/src/UniGetUI.Interface.Telemetry/TelemetryHandler.cs @@ -32,31 +32,28 @@ public static class TelemetryHandler private const string HOST = "https://marticliment.com/unigetui/statistics"; #endif - private static readonly string[] SettingsToSend = + private static readonly Settings.K[] SettingsToSend = [ - "DisableAutoUpdateWingetUI", - "EnableUniGetUIBeta", - "DisableSystemTray", - "DisableNotifications", - "DisableAutoCheckforUpdates", - "AutomaticallyUpdatePackages", - "AskToDeleteNewDesktopShortcuts", - "EnablePackageBackup", - "DoCacheAdminRights", - "DoCacheAdminRightsForBatches", - "ForceLegacyBundledWinGet", - "UseSystemChocolatey", - "SP1", // UniGetUI is portable - "SP2", // UniGetUI was started as daemon + Settings.K.DisableAutoUpdateWingetUI, + Settings.K.EnableUniGetUIBeta, + Settings.K.DisableSystemTray, + Settings.K.DisableNotifications, + Settings.K.DisableAutoCheckforUpdates, + Settings.K.AutomaticallyUpdatePackages, + Settings.K.AskToDeleteNewDesktopShortcuts, + Settings.K.EnablePackageBackup, + Settings.K.DoCacheAdminRights, + Settings.K.DoCacheAdminRightsForBatches, + Settings.K.ForceLegacyBundledWinGet, + Settings.K.UseSystemChocolatey ]; - // ------------------------------------------------------------------------- public static async void Initialize() { try { - if (Settings.Get("DisableTelemetry")) return; + if (Settings.Get(Settings.K.DisableTelemetry)) return; await CoreTools.WaitForInternetConnection(); string ID = GetRandomizedId(); @@ -77,12 +74,24 @@ public static async void Initialize() int SettingsMagicValue = 0; mask = 0x1; foreach (var setting in SettingsToSend) + { + bool enabled = Settings.Get( + key: setting, + invert: Settings.ResolveKey(setting).StartsWith("Disable") + ); + + if (enabled) SettingsMagicValue |= mask; + mask = mask << 1; + + if (mask == 0x1) + throw new OverflowException(); + } + foreach (var setting in new []{"SP1", "SP2"}) { bool enabled; if (setting == "SP1") enabled = File.Exists("ForceUniGetUIPortable"); else if (setting == "SP2") enabled = CoreData.WasDaemon; - else if (setting.StartsWith("Disable")) enabled = !Settings.Get(setting); - else enabled = Settings.Get(setting); + else throw new NotImplementedException(); if (enabled) SettingsMagicValue |= mask; mask = mask << 1; @@ -144,7 +153,7 @@ private static async void PackageEndpoint(IPackage package, string endpoint, TEL try { - if (Settings.Get("DisableTelemetry")) return; + if (Settings.Get(Settings.K.DisableTelemetry)) return; await CoreTools.WaitForInternetConnection(); string ID = GetRandomizedId(); @@ -189,7 +198,7 @@ private static async void BundlesEndpoint(string endpoint, BundleFormatType type { try { - if (Settings.Get("DisableTelemetry")) return; + if (Settings.Get(Settings.K.DisableTelemetry)) return; await CoreTools.WaitForInternetConnection(); string ID = GetRandomizedId(); @@ -219,11 +228,11 @@ private static async void BundlesEndpoint(string endpoint, BundleFormatType type private static string GetRandomizedId() { - string ID = Settings.GetValue("TelemetryClientToken"); + string ID = Settings.GetValue(Settings.K.TelemetryClientToken); if (ID.Length != 64) { ID = CoreTools.RandomString(64); - Settings.SetValue("TelemetryClientToken", ID); + Settings.SetValue(Settings.K.TelemetryClientToken, ID); } return ID; diff --git a/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs b/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs index d81d4ece4c..d76cbe26e8 100644 --- a/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs +++ b/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs @@ -68,11 +68,11 @@ public Chocolatey() public static string GetProxyArgument() { - if (!Settings.Get("EnableProxy")) return ""; + if (!Settings.Get(Settings.K.EnableProxy)) return ""; var proxyUri = Settings.GetProxyUrl(); if (proxyUri is null) return ""; - if (Settings.Get("EnableProxyAuth") is false) + if (Settings.Get(Settings.K.EnableProxyAuth) is false) return $"--proxy {proxyUri.ToString()}"; var creds = Settings.GetProxyCredentials(); @@ -206,7 +206,7 @@ protected override ManagerStatus LoadManager() { Logger.ImportantInfo("Old chocolatey path is a symbolic link, not migrating Chocolatey..."); } - else if (Settings.Get("ChocolateySymbolicLinkCreated")) + else if (Settings.Get(Settings.K.ChocolateySymbolicLinkCreated)) { Logger.Warn("The Choco path symbolic link has already been set to created!"); } @@ -274,7 +274,7 @@ protected override ManagerStatus LoadManager() } CoreTools.CreateSymbolicLinkDir(old_choco_path, new_choco_path); - Settings.Set("ChocolateySymbolicLinkCreated", true); + Settings.Set(Settings.K.ChocolateySymbolicLinkCreated, true); Logger.Info($"Symbolic link created successfully from {old_choco_path} to {new_choco_path}."); } @@ -285,7 +285,7 @@ protected override ManagerStatus LoadManager() } } - if (Settings.Get("UseSystemChocolatey")) + if (Settings.Get(Settings.K.UseSystemChocolatey)) { status.ExecutablePath = CoreTools.Which("choco.exe").Item2; } @@ -323,9 +323,9 @@ protected override ManagerStatus LoadManager() status.Version = process.StandardOutput.ReadToEnd().Trim(); // If the user is running bundled chocolatey and chocolatey is not in path, add chocolatey to path - if (!Settings.Get("UseSystemChocolatey") + if (!Settings.Get(Settings.K.UseSystemChocolatey) && !File.Exists("C:\\ProgramData\\Chocolatey\\bin\\choco.exe")) - /* && Settings.Get("ShownWelcomeWizard")) */ + /* && Settings.Get(Settings.K.ShownWelcomeWizard)) */ { string? path = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User); if (!path?.Contains(status.ExecutablePath.Replace("\\choco.exe", "\\bin")) ?? false) diff --git a/src/UniGetUI.PackageEngine.Managers.Chocolatey/Helpers/ChocolateyDetailsHelper.cs b/src/UniGetUI.PackageEngine.Managers.Chocolatey/Helpers/ChocolateyDetailsHelper.cs index 89c804be9d..762f8f19d4 100644 --- a/src/UniGetUI.PackageEngine.Managers.Chocolatey/Helpers/ChocolateyDetailsHelper.cs +++ b/src/UniGetUI.PackageEngine.Managers.Chocolatey/Helpers/ChocolateyDetailsHelper.cs @@ -56,7 +56,7 @@ protected override IReadOnlyList GetInstallableVersions_UnSafe(IPackage if (File.Exists(portable_path)) return Path.GetDirectoryName(portable_path); - foreach (var base_path in new string[] + foreach (var base_path in new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), diff --git a/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs b/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs index c1d9be7829..fd6d36351b 100644 --- a/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs +++ b/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs @@ -47,7 +47,7 @@ private struct SearchResult protected sealed override IReadOnlyList FindPackages_UnSafe(string query) { List Packages = []; - INativeTaskLogger logger = TaskLogger.CreateNew(Enums.LoggableTaskType.FindPackages); + INativeTaskLogger logger = TaskLogger.CreateNew(LoggableTaskType.FindPackages); IReadOnlyList sources; if (Capabilities.SupportsCustomSources) diff --git a/src/UniGetUI.PackageEngine.Managers.Pip/Helpers/PipPkgDetailsHelper.cs b/src/UniGetUI.PackageEngine.Managers.Pip/Helpers/PipPkgDetailsHelper.cs index 21d32b4883..525980ccbb 100644 --- a/src/UniGetUI.PackageEngine.Managers.Pip/Helpers/PipPkgDetailsHelper.cs +++ b/src/UniGetUI.PackageEngine.Managers.Pip/Helpers/PipPkgDetailsHelper.cs @@ -111,7 +111,7 @@ protected override IReadOnlyList GetInstallableVersions_UnSafe(IPackage } }; - IProcessTaskLogger logger = Manager.TaskLogger.CreateNew(Enums.LoggableTaskType.LoadPackageVersions, p); + IProcessTaskLogger logger = Manager.TaskLogger.CreateNew(LoggableTaskType.LoadPackageVersions, p); p.Start(); string? line; diff --git a/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs b/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs index f8d1c2ef3d..7315c19d2d 100644 --- a/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs +++ b/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs @@ -76,11 +76,11 @@ public Pip() public static string GetProxyArgument() { - if (!Settings.Get("EnableProxy")) return ""; + if (!Settings.Get(Settings.K.EnableProxy)) return ""; var proxyUri = Settings.GetProxyUrl(); if (proxyUri is null) return ""; - if (Settings.Get("EnableProxyAuth") is false) + if (Settings.Get(Settings.K.EnableProxyAuth) is false) return $"--proxy {proxyUri.ToString()}"; var creds = Settings.GetProxyCredentials(); diff --git a/src/UniGetUI.PackageEngine.Managers.PowerShell7/PowerShell7.cs b/src/UniGetUI.PackageEngine.Managers.PowerShell7/PowerShell7.cs index d8456ae9d0..2891b642ed 100644 --- a/src/UniGetUI.PackageEngine.Managers.PowerShell7/PowerShell7.cs +++ b/src/UniGetUI.PackageEngine.Managers.PowerShell7/PowerShell7.cs @@ -140,7 +140,7 @@ protected override ManagerStatus LoadManager() RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 } }; process.Start(); diff --git a/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs b/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs index 09738a717c..049ae08f65 100644 --- a/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs +++ b/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs @@ -398,7 +398,7 @@ protected override ManagerStatus LoadManager() status.Found = CoreTools.Which("scoop").Item1; Status = status; // Wee need this for the RunCleanup method to get the executable path - if (status.Found && IsEnabled() && Settings.Get("EnableScoopCleanup")) + if (status.Found && IsEnabled() && Settings.Get(Settings.K.EnableScoopCleanup)) { RunCleanup(); } diff --git a/src/UniGetUI.PackageEngine.Managers.Vcpkg/Vcpkg.cs b/src/UniGetUI.PackageEngine.Managers.Vcpkg/Vcpkg.cs index b1262b04ad..0f84462324 100644 --- a/src/UniGetUI.PackageEngine.Managers.Vcpkg/Vcpkg.cs +++ b/src/UniGetUI.PackageEngine.Managers.Vcpkg/Vcpkg.cs @@ -62,7 +62,7 @@ public Vcpkg() { "x86-windows", new ManagerSource(this, "x86-windows", URI_VCPKG_IO) } }; - string vcpkgRoot = Settings.GetValue("CustomVcpkgRoot"); + string vcpkgRoot = Settings.GetValue(Settings.K.CustomVcpkgRoot); Properties = new ManagerProperties { Name = "vcpkg", @@ -351,11 +351,11 @@ public override void RefreshPackageIndexes() if (!found || !gitFound || !vcpkgRootFound) { INativeTaskLogger logger = TaskLogger.CreateNew(LoggableTaskType.RefreshIndexes); - if (Settings.Get("DisableUpdateVcpkgGitPorts")) logger.Error("User has disabled updating sources"); + if (Settings.Get(Settings.K.DisableUpdateVcpkgGitPorts)) logger.Error("User has disabled updating sources"); if (!found) logger.Error("Vcpkg was not found???"); if (!gitFound) logger.Error("Vcpkg sources won't be updated since git was not found"); if (!vcpkgRootFound) logger.Error("Cannot update vcpkg port files as requested: the VCPKG_ROOT environment variable or custom vcpkg root setting was not set"); - logger.Close(Settings.Get("DisableUpdateVcpkgGitPorts") ? 0 : 1); + logger.Close(Settings.Get(Settings.K.DisableUpdateVcpkgGitPorts) ? 0 : 1); return; } @@ -428,7 +428,7 @@ public static Tuple GetVcpkgPath() public static Tuple GetVcpkgRoot() { - string? vcpkgRoot = Settings.GetValue("CustomVcpkgRoot"); + string? vcpkgRoot = Settings.GetValue(Settings.K.CustomVcpkgRoot); if (vcpkgRoot == "") { vcpkgRoot = Environment.GetEnvironmentVariable("VCPKG_ROOT"); @@ -452,7 +452,7 @@ public static Tuple GetVcpkgRoot() public static string GetDefaultTriplet() { - string DefaultTriplet = Settings.GetValue("DefaultVcpkgTriplet"); + string DefaultTriplet = Settings.GetValue(Settings.K.DefaultVcpkgTriplet); if (DefaultTriplet == "") { DefaultTriplet = Environment.GetEnvironmentVariable("VCPKG_DEFAULT_TRIPLET") ?? ""; diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/BundledWinGetHelper.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/BundledWinGetHelper.cs index f6142d8ac6..f00d85c1eb 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/BundledWinGetHelper.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/BundledWinGetHelper.cs @@ -34,7 +34,7 @@ public IReadOnlyList GetAvailableUpdates_UnSafe() RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 } }; @@ -145,7 +145,7 @@ public IReadOnlyList GetInstalledPackages_UnSafe() RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 } }; @@ -245,7 +245,7 @@ public IReadOnlyList FindPackages_UnSafe(string query) RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 } }; @@ -392,7 +392,7 @@ public void GetPackageDetails_UnSafe(IPackageDetails details) RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 }; process.StartInfo = startInfo; if (CoreTools.IsAdministrator()) @@ -436,7 +436,7 @@ public void GetPackageDetails_UnSafe(IPackageDetails details) RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 }; process.StartInfo = startInfo; if (CoreTools.IsAdministrator()) @@ -581,7 +581,7 @@ public IReadOnlyList GetInstallableVersions_Unsafe(IPackage package) RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 + StandardOutputEncoding = Encoding.UTF8 } }; diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/NativeWinGetHelper.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/NativeWinGetHelper.cs index f15a88420c..763fb77c58 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/NativeWinGetHelper.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/NativeWinGetHelper.cs @@ -66,7 +66,7 @@ public IReadOnlyList FindPackages_UnSafe(string query) ConnectResult result = CatalogReference.Connect(); if (result.Status == ConnectResultStatus.Ok) { - foreach (var filter_type in new PackageMatchField[] { PackageMatchField.Name, PackageMatchField.Id, PackageMatchField.Moniker }) + foreach (var filter_type in new[] { PackageMatchField.Name, PackageMatchField.Id, PackageMatchField.Moniker }) { FindPackagesOptions PackageFilters = Factory.CreateFindPackagesOptions(); diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/Helpers/WinGetPkgOperationHelper.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/Helpers/WinGetPkgOperationHelper.cs index 21c36b13a6..e1e8b0b47d 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/Helpers/WinGetPkgOperationHelper.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/Helpers/WinGetPkgOperationHelper.cs @@ -171,7 +171,7 @@ protected override OperationVeredict _getOperationResult( if (uintCode is 0x8A15002B) { - if (Settings.Get("IgnoreUpdatesNotApplicable")) + if (Settings.Get(Settings.K.IgnoreUpdatesNotApplicable)) { Logger.Warn($"Ignoring update {package.Id} as the update is not applicable to the platform, and the user has enabled IgnoreUpdatesNotApplicable"); IgnoredUpdatesDatabase.Add(IgnoredUpdatesDatabase.GetIgnoredIdForPackage(package), package.VersionString); @@ -210,11 +210,11 @@ protected override OperationVeredict _getOperationResult( private static void MarkUpgradeAsDone(IPackage package) { - Settings.SetDictionaryItem("WinGetAlreadyUpgradedPackages", package.Id, package.NewVersionString); + Settings.SetDictionaryItem(Settings.K.WinGetAlreadyUpgradedPackages, package.Id, package.NewVersionString); } public static bool UpdateAlreadyInstalled(IPackage package) { - return Settings.GetDictionaryItem("WinGetAlreadyUpgradedPackages", package.Id) == package.NewVersionString; + return Settings.GetDictionaryItem(Settings.K.WinGetAlreadyUpgradedPackages, package.Id) == package.NewVersionString; } } diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs index 3f035d4a6d..353f50b248 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs @@ -93,11 +93,11 @@ public WinGet() public static string GetProxyArgument() { - if (!Settings.Get("EnableProxy")) return ""; + if (!Settings.Get(Settings.K.EnableProxy)) return ""; var proxyUri = Settings.GetProxyUrl(); if (proxyUri is null) return ""; - if (Settings.Get("EnableProxyAuth")) + if (Settings.Get(Settings.K.EnableProxyAuth)) { Logger.Warn("Proxy is enabled, but WinGet does not support proxy authentication, so the proxy setting will be ignored"); return ""; @@ -179,7 +179,7 @@ protected override ManagerStatus LoadManager() { ManagerStatus status = new(); - bool FORCE_BUNDLED = Settings.Get("ForceLegacyBundledWinGet"); + bool FORCE_BUNDLED = Settings.Get(Settings.K.ForceLegacyBundledWinGet); var (found, path) = CoreTools.Which("winget.exe"); status.ExecutablePath = path; @@ -292,7 +292,7 @@ public override void AttemptFastRepair() private static void TryRepairTempFolderPermissions() { - if (Settings.Get("DisableNewWinGetTroubleshooter")) return; + if (Settings.Get(Settings.K.DisableNewWinGetTroubleshooter)) return; try { @@ -350,7 +350,7 @@ public override void RefreshPackageIndexes() StartInfo = new ProcessStartInfo { FileName = Status.ExecutablePath, - Arguments = Properties.ExecutableCallArgs + " source update --disable-interactivity " + WinGet.GetProxyArgument(), + Arguments = Properties.ExecutableCallArgs + " source update --disable-interactivity " + GetProxyArgument(), UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, diff --git a/src/UniGetUI.PackageEngine.Operations/AbstractOperation.cs b/src/UniGetUI.PackageEngine.Operations/AbstractOperation.cs index 340169c53a..f19bc881ce 100644 --- a/src/UniGetUI.PackageEngine.Operations/AbstractOperation.cs +++ b/src/UniGetUI.PackageEngine.Operations/AbstractOperation.cs @@ -131,7 +131,7 @@ public AbstractOperation(bool queue_enabled, AbstractOperation? req) Status = OperationStatus.InQueue; Line("Please wait...", LineType.ProgressIndicator); - if (int.TryParse(Settings.GetValue("ParallelOperationCount"), out int _maxPps)) + if (int.TryParse(Settings.GetValue(Settings.K.ParallelOperationCount), out int _maxPps)) { MAX_OPERATIONS = _maxPps; Logger.Debug($"Parallel operation limit set to {MAX_OPERATIONS}"); diff --git a/src/UniGetUI.PackageEngine.Operations/PackageOperations.cs b/src/UniGetUI.PackageEngine.Operations/PackageOperations.cs index 80c75372f6..85baf8c142 100644 --- a/src/UniGetUI.PackageEngine.Operations/PackageOperations.cs +++ b/src/UniGetUI.PackageEngine.Operations/PackageOperations.cs @@ -89,7 +89,7 @@ protected sealed override void PrepareProcessStartInfo() if (RequiresAdminRights() && IsAdmin is false) { IsAdmin = true; - if (Settings.Get("DoCacheAdminRights") || Settings.Get("DoCacheAdminRightsForBatches")) + if (Settings.Get(Settings.K.DoCacheAdminRights) || Settings.Get(Settings.K.DoCacheAdminRightsForBatches)) { RequestCachingOfUACPrompt(); } @@ -152,7 +152,7 @@ protected override Task HandleSuccess() Package.SetTag(PackageTag.AlreadyInstalled); InstalledPackagesLoader.Instance.AddForeign(Package); - if (Settings.Get("AskToDeleteNewDesktopShortcuts")) + if (Settings.Get(Settings.K.AskToDeleteNewDesktopShortcuts)) { DesktopShortcutsDatabase.HandleNewShortcuts(DesktopShortcutsBeforeStart); } @@ -172,7 +172,7 @@ protected override void Initialize() Metadata.FailureTitle = CoreTools.Translate("Installation failed", new Dictionary { { "package", Package.Name } }); Metadata.FailureMessage = CoreTools.Translate("{package} could not be installed", new Dictionary { { "package", Package.Name } }); - if (Settings.Get("AskToDeleteNewDesktopShortcuts")) + if (Settings.Get(Settings.K.AskToDeleteNewDesktopShortcuts)) { DesktopShortcutsBeforeStart = DesktopShortcutsDatabase.GetShortcutsOnDisk(); } @@ -204,7 +204,7 @@ protected override async Task HandleSuccess() UpgradablePackagesLoader.Instance.Remove(Package); - if (Settings.Get("AskToDeleteNewDesktopShortcuts")) + if (Settings.Get(Settings.K.AskToDeleteNewDesktopShortcuts)) { DesktopShortcutsDatabase.HandleNewShortcuts(DesktopShortcutsBeforeStart); } @@ -226,7 +226,7 @@ protected override void Initialize() Metadata.FailureTitle = CoreTools.Translate("Update failed", new Dictionary { { "package", Package.Name } }); Metadata.FailureMessage = CoreTools.Translate("{package} could not be updated", new Dictionary { { "package", Package.Name } }); - if (Settings.Get("AskToDeleteNewDesktopShortcuts")) + if (Settings.Get(Settings.K.AskToDeleteNewDesktopShortcuts)) { DesktopShortcutsBeforeStart = DesktopShortcutsDatabase.GetShortcutsOnDisk(); } diff --git a/src/UniGetUI.PackageEngine.Operations/SourceOperations.cs b/src/UniGetUI.PackageEngine.Operations/SourceOperations.cs index 5d43be157d..0bd01ed287 100644 --- a/src/UniGetUI.PackageEngine.Operations/SourceOperations.cs +++ b/src/UniGetUI.PackageEngine.Operations/SourceOperations.cs @@ -52,7 +52,7 @@ protected override void PrepareProcessStartInfo() bool admin = false; if (ForceAsAdministrator || Source.Manager.Capabilities.Sources.MustBeInstalledAsAdmin) { - if (Settings.Get("DoCacheAdminRights") || Settings.Get("DoCacheAdminRightsForBatches")) + if (Settings.Get(Settings.K.DoCacheAdminRights) || Settings.Get(Settings.K.DoCacheAdminRightsForBatches)) { CoreTools.CacheUACForCurrentProcess().GetAwaiter().GetResult(); } @@ -105,7 +105,7 @@ protected override void PrepareProcessStartInfo() bool admin = false; if (ForceAsAdministrator || Source.Manager.Capabilities.Sources.MustBeInstalledAsAdmin) { - if (Settings.Get("DoCacheAdminRights") || Settings.Get("DoCacheAdminRightsForBatches")) + if (Settings.Get(Settings.K.DoCacheAdminRights) || Settings.Get(Settings.K.DoCacheAdminRightsForBatches)) { CoreTools.CacheUACForCurrentProcess().GetAwaiter().GetResult(); } diff --git a/src/UniGetUI.PackageEngine.PackageLoader/UpgradablePackagesLoader.cs b/src/UniGetUI.PackageEngine.PackageLoader/UpgradablePackagesLoader.cs index 6d524df40e..b060e1f2bf 100644 --- a/src/UniGetUI.PackageEngine.PackageLoader/UpgradablePackagesLoader.cs +++ b/src/UniGetUI.PackageEngine.PackageLoader/UpgradablePackagesLoader.cs @@ -22,7 +22,7 @@ public UpgradablePackagesLoader(IReadOnlyList managers) identifier: "UPGRADABLE_PACKAGES", AllowMultiplePackageVersions: false, DisableReload: false, - CheckedBydefault: !Settings.Get("DisableSelectingUpdatesByDefault"), + CheckedBydefault: !Settings.Get(Settings.K.DisableSelectingUpdatesByDefault), RequiresInternet: true) { Instance = this; @@ -60,12 +60,12 @@ protected override Task WhenAddingPackage(IPackage package) protected void StartAutoCheckTimeout() { - if (!Settings.Get("DisableAutoCheckforUpdates")) + if (!Settings.Get(Settings.K.DisableAutoCheckforUpdates)) { long waitTime = 3600; try { - waitTime = long.Parse(Settings.GetValue("UpdatesCheckInterval")); + waitTime = long.Parse(Settings.GetValue(Settings.K.UpdatesCheckInterval)); Logger.Debug($"Starting check for updates wait interval with waitTime={waitTime}"); } catch diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs index 1e78b4f780..5a3068c019 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs @@ -126,7 +126,7 @@ public virtual void Initialize() /// public bool IsEnabled() { - return !Settings.GetDictionaryItem("DisabledManagers", Name); + return !Settings.GetDictionaryItem(Settings.K.DisabledManagers, Name); } /// @@ -152,7 +152,7 @@ private IReadOnlyList _findPackages(string query, bool SecondAttempt) var task = Task.Run(() => FindPackages_UnSafe(query)); if (!task.Wait(TimeSpan.FromSeconds(PackageListingTaskTimeout))) { - if (!Settings.Get("DisableTimeoutOnPackageListingTasks")) + if (!Settings.Get(Settings.K.DisableTimeoutOnPackageListingTasks)) throw new TimeoutException($"Task _getInstalledPackages for manager {Name} did not finish after " + $"{PackageListingTaskTimeout} seconds, aborting. You may disable " + $"timeouts from UniGetUI Advanced Settings"); @@ -202,7 +202,7 @@ private IReadOnlyList _getAvailableUpdates(bool SecondAttempt) var task = Task.Run(GetAvailableUpdates_UnSafe); if (!task.Wait(TimeSpan.FromSeconds(PackageListingTaskTimeout))) { - if (!Settings.Get("DisableTimeoutOnPackageListingTasks")) + if (!Settings.Get(Settings.K.DisableTimeoutOnPackageListingTasks)) throw new TimeoutException($"Task _getInstalledPackages for manager {Name} did not finish after " + $"{PackageListingTaskTimeout} seconds, aborting. You may disable " + $"timeouts from UniGetUI Advanced Settings"); @@ -251,7 +251,7 @@ private IReadOnlyList _getInstalledPackages(bool SecondAttempt) var task = Task.Run(GetInstalledPackages_UnSafe); if (!task.Wait(TimeSpan.FromSeconds(PackageListingTaskTimeout))) { - if (!Settings.Get("DisableTimeoutOnPackageListingTasks")) + if (!Settings.Get(Settings.K.DisableTimeoutOnPackageListingTasks)) throw new TimeoutException($"Task _getInstalledPackages for manager {Name} did not finish after " + $"{PackageListingTaskTimeout} seconds, aborting. You may disable " + $"timeouts from UniGetUI Advanced Settings"); diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/DesktopShortcutsDatabase.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/DesktopShortcutsDatabase.cs index 3eb80d43a6..7131fe2aee 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/DesktopShortcutsDatabase.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/DesktopShortcutsDatabase.cs @@ -16,12 +16,12 @@ public enum Status public static IReadOnlyDictionary GetDatabase() { - return Settings.GetDictionary("DeletableDesktopShortcuts") ?? new Dictionary(); + return Settings.GetDictionary(Settings.K.DeletableDesktopShortcuts) ?? new Dictionary(); } public static void ResetDatabase() { - Settings.ClearDictionary("DeletableDesktopShortcuts"); + Settings.ClearDictionary(Settings.K.DeletableDesktopShortcuts); } /// @@ -32,9 +32,9 @@ public static void ResetDatabase() public static void AddToDatabase(string shortcutPath, Status shortcutStatus) { if (shortcutStatus is Status.Unknown) - Settings.RemoveDictionaryKey("DeletableDesktopShortcuts", shortcutPath); + Settings.RemoveDictionaryKey(Settings.K.DeletableDesktopShortcuts, shortcutPath); else - Settings.SetDictionaryItem("DeletableDesktopShortcuts", shortcutPath, shortcutStatus is Status.Delete); + Settings.SetDictionaryItem(Settings.K.DeletableDesktopShortcuts, shortcutPath, shortcutStatus is Status.Delete); } /// @@ -45,10 +45,10 @@ public static void AddToDatabase(string shortcutPath, Status shortcutStatus) public static bool Remove(string shortcutPath) { // Remove the entry if present - if (Settings.DictionaryContainsKey("DeletableDesktopShortcuts", shortcutPath)) + if (Settings.DictionaryContainsKey(Settings.K.DeletableDesktopShortcuts, shortcutPath)) { // Remove the entry and propagate changes to disk - Settings.SetDictionaryItem("DeletableDesktopShortcuts", shortcutPath, false); + Settings.SetDictionaryItem(Settings.K.DeletableDesktopShortcuts, shortcutPath, false); return true; } @@ -88,9 +88,9 @@ public static bool DeleteFromDisk(string shortcutPath) public static Status GetStatus(string shortcutPath) { // Check if the package is ignored - if (Settings.DictionaryContainsKey("DeletableDesktopShortcuts", shortcutPath)) + if (Settings.DictionaryContainsKey(Settings.K.DeletableDesktopShortcuts, shortcutPath)) { - bool canDelete = Settings.GetDictionaryItem("DeletableDesktopShortcuts", shortcutPath); + bool canDelete = Settings.GetDictionaryItem(Settings.K.DeletableDesktopShortcuts, shortcutPath); return canDelete ? Status.Delete : Status.Maintain; } @@ -119,7 +119,7 @@ public static List GetAllShortcuts() { var shortcuts = GetShortcutsOnDisk(); - foreach (var item in Settings.GetDictionary("DeletableDesktopShortcuts")) + foreach (var item in Settings.GetDictionary(Settings.K.DeletableDesktopShortcuts)) { if (!shortcuts.Contains(item.Key)) shortcuts.Add(item.Key); @@ -153,7 +153,7 @@ public static List GetUnknownShortcuts() /// The shortcuts that already existed public static void HandleNewShortcuts(IReadOnlyList PreviousShortCutList) { - bool DeleteUnknownShortcuts = Settings.Get("RemoveAllDesktopShortcuts"); + bool DeleteUnknownShortcuts = Settings.Get(Settings.K.RemoveAllDesktopShortcuts); HashSet PreviousShortcuts = [.. PreviousShortCutList]; List CurrentShortcuts = GetShortcutsOnDisk(); diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/IgnoredUpdatesDatabase.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/IgnoredUpdatesDatabase.cs index 511ddcab0e..b237cafa85 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/IgnoredUpdatesDatabase.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/IgnoredUpdatesDatabase.cs @@ -70,7 +70,7 @@ public string StringRepresentation() public static IReadOnlyDictionary GetDatabase() { - return Settings.GetDictionary("IgnoredPackageUpdates") ?? new Dictionary(); + return Settings.GetDictionary(Settings.K.IgnoredPackageUpdates) ?? new Dictionary(); } public static string GetIgnoredIdForPackage(IPackage package) @@ -85,7 +85,7 @@ public static string GetIgnoredIdForPackage(IPackage package) /// The version to ignore. Use wildcard (`*`) to ignore all versions public static void Add(string ignoredId, string version = "*") { - Settings.SetDictionaryItem("IgnoredPackageUpdates", ignoredId, version); + Settings.SetDictionaryItem(Settings.K.IgnoredPackageUpdates, ignoredId, version); } /// @@ -96,10 +96,10 @@ public static void Add(string ignoredId, string version = "*") public static bool Remove(string ignoredId) { // Remove the entry if present - if (Settings.DictionaryContainsKey("IgnoredPackageUpdates", ignoredId)) + if (Settings.DictionaryContainsKey(Settings.K.IgnoredPackageUpdates, ignoredId)) { // Remove the entry and propagate changes to disk - return Settings.RemoveDictionaryKey("IgnoredPackageUpdates", ignoredId) != null; + return Settings.RemoveDictionaryKey(Settings.K.IgnoredPackageUpdates, ignoredId) != null; } // Do nothing if the entry was not there @@ -121,7 +121,7 @@ public static bool Remove(string ignoredId) /// True if the package is ignored, false otherwise public static bool HasUpdatesIgnored(string ignoredId, string version = "*") { - string? ignoredVersion = Settings.GetDictionaryItem("IgnoredPackageUpdates", ignoredId); + string? ignoredVersion = Settings.GetDictionaryItem(Settings.K.IgnoredPackageUpdates, ignoredId); if (ignoredVersion != null && ignoredVersion.StartsWith("<")) { @@ -151,6 +151,6 @@ public static bool HasUpdatesIgnored(string ignoredId, string version = "*") /// If **no** versions are ignored, null will be returned. public static string? GetIgnoredVersion(string ignoredId) { - return Settings.GetDictionaryItem("IgnoredPackageUpdates", ignoredId); + return Settings.GetDictionaryItem(Settings.K.IgnoredPackageUpdates, ignoredId); } } diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/InstallOptionsFactory.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/InstallOptionsFactory.cs index 81b397f45f..f3b4254d7b 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/InstallOptionsFactory.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Packages/Classes/InstallOptionsFactory.cs @@ -186,7 +186,7 @@ private static InstallOptions _loadFromDisk(string key) private static InstallOptions EnsureSecureOptions(InstallOptions options) { - if (SecureSettings.Get(SecureSettings.ALLOW_CLI_ARGUMENTS)) + if (SecureSettings.Get(SecureSettings.K.AllowCLIArguments)) { // If CLI arguments are allowed, sanitize them for (int i = 0; i < options.CustomParameters_Install.Count; i++) diff --git a/src/UniGetUI.PackageEngine.Serializable.Tests/TestInstallOptions.cs b/src/UniGetUI.PackageEngine.Serializable.Tests/TestInstallOptions.cs index 7ecfca47f9..30bdc3d91a 100644 --- a/src/UniGetUI.PackageEngine.Serializable.Tests/TestInstallOptions.cs +++ b/src/UniGetUI.PackageEngine.Serializable.Tests/TestInstallOptions.cs @@ -88,9 +88,9 @@ public void FromJson(string JSON, bool hash, bool inter, string installLoc, stri Assert.Equal(hash, o2.SkipHashCheck); Assert.Equal(arch, o2.Architecture); Assert.Equal(installLoc, o2.CustomInstallLocation); - Assert.Equal(list, o2.CustomParameters_Install); - Assert.Equal(list, o2.CustomParameters_Update); - Assert.Equal(list, o2.CustomParameters_Uninstall); + Assert.Equal(list.Where(x => x.Any()).ToList(), o2.CustomParameters_Install.Where(x => x.Any()).ToList()); + Assert.Equal(list.Where(x => x.Any()).ToList(), o2.CustomParameters_Update.Where(x => x.Any()).ToList()); + Assert.Equal(list.Where(x => x.Any()).ToList(), o2.CustomParameters_Uninstall.Where(x => x.Any()).ToList()); Assert.Equal(scope, o2.InstallationScope); Assert.Equal(inter, o2.InteractiveInstallation); Assert.Equal(pre, o2.PreRelease); @@ -104,9 +104,9 @@ internal static void AreEqual(InstallOptions o1, InstallOptions o2) Assert.Equal(o1.SkipHashCheck, o2.SkipHashCheck); Assert.Equal(o1.Architecture, o2.Architecture); Assert.Equal(o1.CustomInstallLocation, o2.CustomInstallLocation); - Assert.Equal(o1.CustomParameters_Install, o2.CustomParameters_Install); - Assert.Equal(o1.CustomParameters_Uninstall, o2.CustomParameters_Uninstall); - Assert.Equal(o1.CustomParameters_Update, o2.CustomParameters_Update); + Assert.Equal(o1.CustomParameters_Install.Where(x => x.Any()).ToList(), o2.CustomParameters_Install.Where(x => x.Any()).ToList()); + Assert.Equal(o1.CustomParameters_Uninstall.Where(x => x.Any()).ToList(), o2.CustomParameters_Uninstall.Where(x => x.Any()).ToList()); + Assert.Equal(o1.CustomParameters_Update.Where(x => x.Any()).ToList(), o2.CustomParameters_Update.Where(x => x.Any()).ToList()); Assert.Equal(o1.InstallationScope, o2.InstallationScope); Assert.Equal(o1.InteractiveInstallation, o2.InteractiveInstallation); Assert.Equal(o1.PreRelease, o2.PreRelease); diff --git a/src/UniGetUI/App.xaml.cs b/src/UniGetUI/App.xaml.cs index bdedbb673b..347912e14f 100644 --- a/src/UniGetUI/App.xaml.cs +++ b/src/UniGetUI/App.xaml.cs @@ -68,7 +68,7 @@ public MainApp() InitializeComponent(); - string preferredTheme = Settings.GetValue("PreferredTheme"); + string preferredTheme = Settings.GetValue(Settings.K.PreferredTheme); if (preferredTheme == "dark") { RequestedTheme = ApplicationTheme.Dark; @@ -99,7 +99,7 @@ private static async void LoadGSudo() Logger.Warn($"Using bundled GSudo at {CoreData.ElevatorPath} since UniGetUI Elevator is not available!"); CoreData.ElevatorPath = (await CoreTools.WhichAsync("gsudo.exe")).Item2; #else - if (SecureSettings.Get(SecureSettings.FORCE_USER_GSUDO)) + if (SecureSettings.Get(SecureSettings.K.ForceUserGSudo)) { var res = await CoreTools.WhichAsync("gsudo.exe"); if (res.Item1) @@ -254,7 +254,7 @@ private async Task LoadComponentsAsync() private async Task InitializeBackgroundAPI() { // Bind the background api to the main interface - if (!Settings.Get("DisableApi")) + if (!Settings.Get(Settings.K.DisableApi)) { try { @@ -325,7 +325,7 @@ private async Task CheckForMissingDependencies() if (!isInstalled) { - if (Settings.GetDictionaryItem("DependencyManagement", dependency.Name) == "skipped") + if (Settings.GetDictionaryItem(Settings.K.DependencyManagement, dependency.Name) == "skipped") { Logger.Error($"Dependency {dependency.Name} was not found, and the user set it to not be reminded of the missing dependency"); } @@ -395,7 +395,7 @@ public async void DisposeAndQuit(int outputCode = 0) public void KillAndRestart() { Process.Start(CoreData.UniGetUIExecutableFile); - MainApp.Instance.MainWindow?.Close(); + Instance.MainWindow?.Close(); Environment.Exit(0); } } diff --git a/src/UniGetUI/AppOperationHelper.cs b/src/UniGetUI/AppOperationHelper.cs index 9346dca993..4ef6f908e3 100644 --- a/src/UniGetUI/AppOperationHelper.cs +++ b/src/UniGetUI/AppOperationHelper.cs @@ -68,14 +68,14 @@ public static void Remove(AbstractOperation op) Content = CoreTools.Translate("No applicable installer was found for the package {0}", package.Name), PrimaryButtonText = CoreTools.Translate("Ok"), DefaultButton = ContentDialogButton.Primary, - XamlRoot = MainApp.Instance.MainWindow.Content.XamlRoot, + XamlRoot = Instance.MainWindow.Content.XamlRoot, }; - await MainApp.Instance.MainWindow.ShowDialogAsync(dialog); + await Instance.MainWindow.ShowDialogAsync(dialog); return null; } FileSavePicker savePicker = new(); - MainWindow window = MainApp.Instance.MainWindow; + MainWindow window = Instance.MainWindow; IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window); WinRT.Interop.InitializeWithWindow.Initialize(savePicker, hWnd); savePicker.SuggestedStartLocation = PickerLocationId.Downloads; diff --git a/src/UniGetUI/AutoUpdater.cs b/src/UniGetUI/AutoUpdater.cs index 9742744395..51d92b6497 100644 --- a/src/UniGetUI/AutoUpdater.cs +++ b/src/UniGetUI/AutoUpdater.cs @@ -30,7 +30,7 @@ public class AutoUpdater public static async Task UpdateCheckLoop(Window window, InfoBar banner) { - if (Settings.Get("DisableAutoUpdateWingetUI")) + if (Settings.Get(Settings.K.DisableAutoUpdateWingetUI)) { Logger.Warn("User has disabled updates"); return; @@ -44,7 +44,7 @@ public static async Task UpdateCheckLoop(Window window, InfoBar banner) while (true) { // User could have disabled updates on runtime - if (Settings.Get("DisableAutoUpdateWingetUI")) + if (Settings.Get(Settings.K.DisableAutoUpdateWingetUI)) { Logger.Warn("User has disabled updates"); return; @@ -74,8 +74,8 @@ public static async Task CheckAndInstallUpdates(Window window, InfoBar ban ); // Check for updates - string UpdatesEndpoint = Settings.Get("EnableUniGetUIBeta") ? BETA_ENDPOINT : STABLE_ENDPOINT; - string InstallerDownloadUrl = Settings.Get("EnableUniGetUIBeta") ? BETA_INSTALLER_URL : STABLE_INSTALLER_URL; + string UpdatesEndpoint = Settings.Get(Settings.K.EnableUniGetUIBeta) ? BETA_ENDPOINT : STABLE_ENDPOINT; + string InstallerDownloadUrl = Settings.Get(Settings.K.EnableUniGetUIBeta) ? BETA_INSTALLER_URL : STABLE_INSTALLER_URL; var (IsUpgradable, LatestVersion, InstallerHash) = await CheckForUpdates(UpdatesEndpoint); if (IsUpgradable) @@ -221,7 +221,7 @@ private static async Task PrepairToLaunchInstaller(string installerLocatio ReleaseLockForAutoupdate_UpdateBanner = false; // Check if the user has disabled updates - if (!ManualCheck && Settings.Get("DisableAutoUpdateWingetUI")) + if (!ManualCheck && Settings.Get(Settings.K.DisableAutoUpdateWingetUI)) { Banner.IsOpen = false; Logger.Warn("User disabled updates!"); @@ -273,7 +273,7 @@ private static async Task PrepairToLaunchInstaller(string installerLocatio Logger.Debug("Autoupdater lock released, launching installer..."); } - if (!ManualCheck && Settings.Get("DisableAutoUpdateWingetUI")) + if (!ManualCheck && Settings.Get(Settings.K.DisableAutoUpdateWingetUI)) { Logger.Warn("User has disabled updates"); return true; diff --git a/src/UniGetUI/CLIHandler.cs b/src/UniGetUI/CLIHandler.cs index d917e4e259..8961a99ef1 100644 --- a/src/UniGetUI/CLIHandler.cs +++ b/src/UniGetUI/CLIHandler.cs @@ -32,6 +32,7 @@ private enum HRESULT STATUS_FAILED = -1, STATUS_INVALID_PARAMETER = -1073741811, STATUS_NO_SUCH_FILE = -1073741809, + STATUS_UNKNOWN__SETTINGS_KEY = -2, } public static int Help() @@ -108,10 +109,12 @@ public static int EnableSetting() return (int)HRESULT.STATUS_INVALID_PARAMETER; // The file parameter does not exist (export settings requires "--export-settings file") var setting = args[basePos + 1].Trim('"').Trim('\''); + if (!Enum.TryParse(setting, out Settings.K validKey)) + return (int)HRESULT.STATUS_UNKNOWN__SETTINGS_KEY; try { - Settings.Set(setting, true); + Settings.Set(validKey, true); } catch (Exception ex) { @@ -133,10 +136,11 @@ public static int DisableSetting() return (int)HRESULT.STATUS_INVALID_PARAMETER; // The file parameter does not exist (export settings requires "--export-settings file") var setting = args[basePos + 1].Trim('"').Trim('\''); - + if (!Enum.TryParse(setting, out Settings.K validKey)) + return (int)HRESULT.STATUS_UNKNOWN__SETTINGS_KEY; try { - Settings.Set(setting, false); + Settings.Set(validKey, false); } catch (Exception ex) { @@ -159,10 +163,12 @@ public static int SetSettingsValue() var setting = args[basePos + 1].Trim('"').Trim('\''); var value = args[basePos + 2]; + if (!Enum.TryParse(setting, out Settings.K validKey)) + return (int)HRESULT.STATUS_UNKNOWN__SETTINGS_KEY; try { - Settings.SetValue(setting, value); + Settings.SetValue(validKey, value); } catch (Exception ex) { @@ -250,10 +256,12 @@ public static int EnableSecureSetting() return (int)HRESULT.STATUS_INVALID_PARAMETER; // The file parameter does not exist (export settings requires "--export-settings file") var setting = args[basePos + 1].Trim('"').Trim('\''); + if (!Enum.TryParse(setting, out SecureSettings.K validKey)) + return (int)HRESULT.STATUS_UNKNOWN__SETTINGS_KEY; try { - bool success = SecureSettings.TrySet(setting, true).GetAwaiter().GetResult(); + bool success = SecureSettings.TrySet(validKey, true).GetAwaiter().GetResult(); if (!success) return (int)HRESULT.STATUS_FAILED; else return (int)HRESULT.SUCCESS; } @@ -275,10 +283,12 @@ public static int DisableSecureSetting() return (int)HRESULT.STATUS_INVALID_PARAMETER; // The first positional argument does not exist var setting = args[basePos + 1].Trim('"').Trim('\''); + if (!Enum.TryParse(setting, out SecureSettings.K validKey)) + return (int)HRESULT.STATUS_UNKNOWN__SETTINGS_KEY; try { - bool success = SecureSettings.TrySet(setting, false).GetAwaiter().GetResult(); + bool success = SecureSettings.TrySet(validKey, false).GetAwaiter().GetResult(); if (!success) return (int)HRESULT.STATUS_FAILED; else return (int)HRESULT.SUCCESS; } diff --git a/src/UniGetUI/Controls/OperationWidgets/OperationControl.cs b/src/UniGetUI/Controls/OperationWidgets/OperationControl.cs index 205d18c2bd..ca6890f168 100644 --- a/src/UniGetUI/Controls/OperationWidgets/OperationControl.cs +++ b/src/UniGetUI/Controls/OperationWidgets/OperationControl.cs @@ -107,7 +107,7 @@ private async void OnOperationSucceeded(object? sender, EventArgs e) ShowSuccessToast(); // Clean succesful operation from list - if (!Settings.Get("MaintainSuccessfulInstalls") && Operation is not DownloadOperation) + if (!Settings.Get(Settings.K.MaintainSuccessfulInstalls) && Operation is not DownloadOperation) { await TimeoutAndClose(); } @@ -146,17 +146,17 @@ private async void OnOperationFinished(object? sender, EventArgs e) rawOutput.Add(line.Item1); } - string[] oldHistory = Settings.GetValue("OperationHistory").Split("\n"); + string[] oldHistory = Settings.GetValue(Settings.K.OperationHistory).Split("\n"); if (oldHistory.Length > 300) oldHistory = oldHistory.Take(300).ToArray(); List newHistory = [.. rawOutput, .. oldHistory]; - Settings.SetValue("OperationHistory", string.Join('\n', newHistory)); + Settings.SetValue(Settings.K.OperationHistory, string.Join('\n', newHistory)); rawOutput.Add(""); rawOutput.Add(""); rawOutput.Add(""); // Handle UAC for batches - if (Settings.Get("DoCacheAdminRightsForBatches")) + if (Settings.Get(Settings.K.DoCacheAdminRightsForBatches)) { if (!MainApp.Operations.AreThereRunningOperations()) { @@ -166,7 +166,7 @@ private async void OnOperationFinished(object? sender, EventArgs e) } // Handle newly created shortcuts - if(Settings.Get("AskToDeleteNewDesktopShortcuts") + if(Settings.Get(Settings.K.AskToDeleteNewDesktopShortcuts) && !MainApp.Operations.AreThereRunningOperations() && DesktopShortcutsDatabase.GetUnknownShortcuts().Any()) { diff --git a/src/UniGetUI/Controls/SettingsWidgets/CheckboxButtonCard.cs b/src/UniGetUI/Controls/SettingsWidgets/CheckboxButtonCard.cs index cff66bc62b..31bba99397 100644 --- a/src/UniGetUI/Controls/SettingsWidgets/CheckboxButtonCard.cs +++ b/src/UniGetUI/Controls/SettingsWidgets/CheckboxButtonCard.cs @@ -19,12 +19,12 @@ public sealed partial class CheckboxButtonCard : SettingsCard public ButtonBase Button; private bool IS_INVERTED; - private string setting_name = ""; - public string SettingName + private Settings.K setting_name = Settings.K.Unset; + public Settings.K SettingName { set { setting_name = value; - IS_INVERTED = value.StartsWith("Disable"); + IS_INVERTED = Settings.ResolveKey(value).StartsWith("Disable"); _checkbox.IsOn = Settings.Get(setting_name) ^ IS_INVERTED ^ ForceInversion; _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; Button.IsEnabled = (_checkbox.IsOn) || _buttonAlwaysOn ; diff --git a/src/UniGetUI/Controls/SettingsWidgets/CheckboxCard.cs b/src/UniGetUI/Controls/SettingsWidgets/CheckboxCard.cs index c86d2a2208..81cd186a8f 100644 --- a/src/UniGetUI/Controls/SettingsWidgets/CheckboxCard.cs +++ b/src/UniGetUI/Controls/SettingsWidgets/CheckboxCard.cs @@ -17,13 +17,13 @@ public partial class CheckboxCard : SettingsCard public TextBlock _warningBlock; protected bool IS_INVERTED; - protected string setting_name = ""; - public virtual string SettingName + private Settings.K setting_name = Settings.K.Unset; + public Settings.K SettingName { set { setting_name = value; - IS_INVERTED = value.StartsWith("Disable"); + IS_INVERTED = Settings.ResolveKey(value).StartsWith("Disable"); _checkbox.IsOn = Settings.Get(setting_name) ^ IS_INVERTED ^ ForceInversion; _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; } @@ -100,29 +100,28 @@ public partial class CheckboxCard_Dict : CheckboxCard { public override event EventHandler? StateChanged; - private string _dictName = ""; - public string DictionaryName + private Settings.K _dictName = Settings.K.Unset; + + private string _keyName = ""; + public string KeyName { set { - set + _keyName = value; + if (_dictName != Settings.K.Unset && _keyName.Any()) { - _dictName = value; - IS_INVERTED = value.StartsWith("Disable"); - if (setting_name != "") - { - _checkbox.IsOn = Settings.GetDictionaryItem(_dictName, setting_name) ^ IS_INVERTED ^ ForceInversion; - _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; - } + _checkbox.IsOn = Settings.GetDictionaryItem(_dictName, _keyName) ^ IS_INVERTED ^ ForceInversion; + _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; } - } + } } - public override string SettingName + public Settings.K DictionaryName { set { - setting_name = value; - if (_dictName != "") + _dictName = value; + IS_INVERTED = Settings.ResolveKey(value).StartsWith("Disable"); + if (_dictName != Settings.K.Unset && _keyName.Any()) { - _checkbox.IsOn = Settings.GetDictionaryItem(_dictName, setting_name) ^ IS_INVERTED ^ ForceInversion; + _checkbox.IsOn = Settings.GetDictionaryItem(_dictName, _keyName) ^ IS_INVERTED ^ ForceInversion; _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; } } @@ -134,7 +133,7 @@ public CheckboxCard_Dict() : base() protected override void _checkbox_Toggled(object sender, RoutedEventArgs e) { - Settings.SetDictionaryItem(_dictName, setting_name, _checkbox.IsOn ^ IS_INVERTED ^ ForceInversion); + Settings.SetDictionaryItem(_dictName, _keyName, _checkbox.IsOn ^ IS_INVERTED ^ ForceInversion); StateChanged?.Invoke(this, EventArgs.Empty); _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; } diff --git a/src/UniGetUI/Controls/SettingsWidgets/ComboboxCard.cs b/src/UniGetUI/Controls/SettingsWidgets/ComboboxCard.cs index 13e057859e..a1d8755516 100644 --- a/src/UniGetUI/Controls/SettingsWidgets/ComboboxCard.cs +++ b/src/UniGetUI/Controls/SettingsWidgets/ComboboxCard.cs @@ -18,8 +18,8 @@ public sealed partial class ComboboxCard : SettingsCard private readonly Dictionary _values_ref = []; private readonly Dictionary _inverted_val_ref = []; - private string settings_name = ""; - public string SettingName + private Settings.K settings_name = Settings.K.Unset; + public Settings.K SettingName { set { diff --git a/src/UniGetUI/Controls/SettingsWidgets/SecureCheckboxCard.cs b/src/UniGetUI/Controls/SettingsWidgets/SecureCheckboxCard.cs index f0b3ce19b8..968b3ce59f 100644 --- a/src/UniGetUI/Controls/SettingsWidgets/SecureCheckboxCard.cs +++ b/src/UniGetUI/Controls/SettingsWidgets/SecureCheckboxCard.cs @@ -17,16 +17,16 @@ public partial class SecureCheckboxCard : SettingsCard public TextBlock _textblock; public TextBlock _warningBlock; public ProgressRing _loading; - protected bool IS_INVERTED; + private bool IS_INVERTED; - protected string setting_name = ""; - public virtual string SettingName + private SecureSettings.K setting_name = SecureSettings.K.Unset; + public SecureSettings.K SettingName { set { _checkbox.IsEnabled = false; setting_name = value; - IS_INVERTED = value.StartsWith("Disable"); + IS_INVERTED = SecureSettings.ResolveKey(value).StartsWith("Disable"); _checkbox.IsOn = SecureSettings.Get(setting_name) ^ IS_INVERTED ^ ForceInversion; _textblock.Opacity = _checkbox.IsOn ? 1 : 0.7; _checkbox.IsEnabled = true; diff --git a/src/UniGetUI/Controls/SettingsWidgets/TextboxCard.cs b/src/UniGetUI/Controls/SettingsWidgets/TextboxCard.cs index e0db71ddd9..bb6b4cce5b 100644 --- a/src/UniGetUI/Controls/SettingsWidgets/TextboxCard.cs +++ b/src/UniGetUI/Controls/SettingsWidgets/TextboxCard.cs @@ -11,11 +11,11 @@ namespace UniGetUI.Interface.Widgets { public sealed partial class TextboxCard : SettingsCard { - private readonly TextBox _textbox = new(); - private readonly HyperlinkButton _helpbutton = new(); + private readonly TextBox _textbox; + private readonly HyperlinkButton _helpbutton; - private string setting_name = ""; - public string SettingName + private Settings.K setting_name = Settings.K.Unset; + public Settings.K SettingName { set { setting_name = value; @@ -74,12 +74,9 @@ public void SaveValue() { string SanitizedText = _textbox.Text; - if (setting_name.Contains("File")) + if (Settings.ResolveKey(setting_name).Contains("File")) { - foreach (char rem in "#%&{}\\/<>*?$!'\":;@`|~") - { - SanitizedText = SanitizedText.Replace(rem.ToString(), ""); - } + SanitizedText = CoreTools.MakeValidFileName(SanitizedText); } if (SanitizedText != "") diff --git a/src/UniGetUI/MainWindow.xaml.cs b/src/UniGetUI/MainWindow.xaml.cs index 9794c95d79..c677b134c3 100644 --- a/src/UniGetUI/MainWindow.xaml.cs +++ b/src/UniGetUI/MainWindow.xaml.cs @@ -72,7 +72,7 @@ public MainWindow() LoadTrayMenu(); ApplyTheme(); - if (Settings.Get("ShowVersionNumberOnTitlebar")) + if (Settings.Get(Settings.K.ShowVersionNumberOnTitlebar)) { AddToSubtitle(CoreTools.Translate("version {0}", CoreData.VersionName)); } @@ -172,14 +172,14 @@ public static void ApplyProxyVariableToProcess() try { var proxyUri = Settings.GetProxyUrl(); - if (proxyUri is null || !Settings.Get("EnableProxy")) + if (proxyUri is null || !Settings.Get(Settings.K.EnableProxy)) { Environment.SetEnvironmentVariable("HTTP_PROXY", "", EnvironmentVariableTarget.Process); return; } string content; - if (Settings.Get("EnableProxyAuth") is false) + if (Settings.Get(Settings.K.EnableProxyAuth) is false) { content = proxyUri.ToString(); } @@ -223,14 +223,14 @@ private void ClearSubtitle() private static void TransferOldSettingsFormats() { - if (!Settings.Get("TransferredOldSettings")) + /*if (!Settings.Get(Settings.K.TransferredOldSettings)) { foreach (IPackageManager Manager in PEInterface.Managers) { string SettingName = "Disable" + Manager.Name; if (Settings.Get(SettingName)) { - Settings.SetDictionaryItem("DisabledManagers", Manager.Name, true); + Settings.SetDictionaryItem(Settings.K.DisabledManagers, Manager.Name, true); Settings.Set(SettingName, false); } } @@ -241,23 +241,23 @@ private static void TransferOldSettingsFormats() { if (Settings.Get($"HideToggleFilters{Page}Page")) { - Settings.SetDictionaryItem("HideToggleFilters", Page, true); + Settings.SetDictionaryItem(Settings.K.HideToggleFilters, Page, true); Settings.Set($"HideToggleFilters{Page}Page", false); } if (Settings.Get($"DisableInstantSearch{Page}Tab")) { - Settings.SetDictionaryItem("DisableInstantSearch", Page, true); + Settings.SetDictionaryItem(Settings.K.DisableInstantSearch, Page, true); Settings.Set($"DisableInstantSearch{Page}Tab", false); } if (!int.TryParse(Settings.GetValue($"SidepanelWidth{Page}Page"), out int sidepanelWidth)) sidepanelWidth = 250; - Settings.SetDictionaryItem("SidepanelWidths", Page, sidepanelWidth); + Settings.SetDictionaryItem(Settings.K.SidepanelWidths, Page, sidepanelWidth); Settings.Set($"SidepanelWidth{Page}Page", false); } - Settings.Set("TransferredOldSettings", true); - } + Settings.Set(Settings.K.TransferredOldSettings, true); + }*/ } public void HandleNotificationActivation(AppNotificationActivatedEventArgs args) @@ -298,7 +298,7 @@ public async void HandleClosingEvent(AppWindow sender, AppWindowClosingEventArgs { AutoUpdater.ReleaseLockForAutoupdate_Window = true; SaveGeometry(Force: true); - if (!Settings.Get("DisableSystemTray") || AutoUpdater.UpdateReadyToBeInstalled) + if (!Settings.Get(Settings.K.DisableSystemTray) || AutoUpdater.UpdateReadyToBeInstalled) { args.Cancel = true; DWMThreadHelper.ChangeState_DWM(true); @@ -662,7 +662,7 @@ public void UpdateSystemTrayStatus() } } - if (Settings.Get("DisableSystemTray")) + if (Settings.Get(Settings.K.DisableSystemTray)) { TrayIcon.Visibility = Visibility.Collapsed; } @@ -708,7 +708,7 @@ public void SwitchToInterface() public void ApplyTheme() { - string preferredTheme = Settings.GetValue("PreferredTheme"); + string preferredTheme = Settings.GetValue(Settings.K.PreferredTheme); if (preferredTheme == "dark") { MainApp.Instance.ThemeListener.CurrentTheme = ApplicationTheme.Dark; @@ -885,13 +885,13 @@ private async void SaveGeometry(bool Force = false) $"{AppWindow.Position.X},{AppWindow.Position.Y},{AppWindow.Size.Width},{AppWindow.Size.Height},{windowState}"; Logger.Debug($"Saving window geometry {geometry}"); - Settings.SetValue("WindowGeometry", geometry); + Settings.SetValue(Settings.K.WindowGeometry, geometry); } private void RestoreGeometry() { - string geometry = Settings.GetValue("WindowGeometry"); + string geometry = Settings.GetValue(Settings.K.WindowGeometry); string[] items = geometry.Split(","); if (items.Length != 5) { @@ -995,19 +995,19 @@ private static bool IsRectangleFullyVisible(int x, int y, int width, int height) return true; } - private void TitleBar_PaneToggleRequested(WinUIEx.TitleBar sender, object args) + private void TitleBar_PaneToggleRequested(TitleBar sender, object args) { if (NavigationPage is null) return; if(this.AppWindow.Size.Width >= 1600) { - Settings.Set("CollapseNavMenuOnWideScreen", NavigationPage.NavView.IsPaneOpen); + Settings.Set(Settings.K.CollapseNavMenuOnWideScreen, NavigationPage.NavView.IsPaneOpen); } NavigationPage.NavView.IsPaneOpen = !NavigationPage.NavView.IsPaneOpen; } - private void TitleBar_OnBackRequested(WinUIEx.TitleBar sender, object args) + private void TitleBar_OnBackRequested(TitleBar sender, object args) { NavigationPage?.NavigateBack(); } diff --git a/src/UniGetUI/Pages/DialogPages/DesktopShortcuts.xaml.cs b/src/UniGetUI/Pages/DialogPages/DesktopShortcuts.xaml.cs index f9ad33a90e..c22cb57df6 100644 --- a/src/UniGetUI/Pages/DialogPages/DesktopShortcuts.xaml.cs +++ b/src/UniGetUI/Pages/DialogPages/DesktopShortcuts.xaml.cs @@ -26,7 +26,7 @@ public DesktopShortcutsManager() InitializeComponent(); DeletableDesktopShortcutsList.ItemsSource = Shortcuts; - AutoDeleteShortcutsCheckbox.IsChecked = Settings.Get("RemoveAllDesktopShortcuts"); + AutoDeleteShortcutsCheckbox.IsChecked = Settings.Get(Settings.K.RemoveAllDesktopShortcuts); AutoDeleteShortcutsCheckbox.Checked += HandleAllDesktop_Checked; AutoDeleteShortcutsCheckbox.Unchecked += HandleAllDesktop_Unchecked; } @@ -104,7 +104,7 @@ private async void HandleAllDesktop_Checked(object sender, RoutedEventArgs e) private void HandleAllDesktop_Unchecked(object sender, RoutedEventArgs e) { - Settings.Set("RemoveAllDesktopShortcuts", false); + Settings.Set(Settings.K.RemoveAllDesktopShortcuts, false); } public void SaveChanges() diff --git a/src/UniGetUI/Pages/DialogPages/DialogHelper_Generic.cs b/src/UniGetUI/Pages/DialogPages/DialogHelper_Generic.cs index 5771dd394f..1ab9f7465f 100644 --- a/src/UniGetUI/Pages/DialogPages/DialogHelper_Generic.cs +++ b/src/UniGetUI/Pages/DialogPages/DialogHelper_Generic.cs @@ -101,15 +101,15 @@ public static async Task ShowMissingDependency(string dep_name, string exe_name, string fancy_command, int current, int total) { - if (Settings.GetDictionaryItem("DependencyManagement", dep_name) == "skipped") + if (Settings.GetDictionaryItem(Settings.K.DependencyManagement, dep_name) == "skipped") { Logger.Error( $"Dependency {dep_name} was not found, and the user set it to not be reminded of the missing dependency"); return; } - bool NotFirstTime = Settings.GetDictionaryItem("DependencyManagement", dep_name) == "attempted"; - Settings.SetDictionaryItem("DependencyManagement", dep_name, "attempted"); + bool NotFirstTime = Settings.GetDictionaryItem(Settings.K.DependencyManagement, dep_name) == "attempted"; + Settings.SetDictionaryItem(Settings.K.DependencyManagement, dep_name, "attempted"); var dialog = DialogFactory.Create(); dialog.Title = CoreTools.Translate("Missing dependency") + (total > 1 ? $" ({current}/{total})" : ""); @@ -168,8 +168,8 @@ public static async Task ShowMissingDependency(string dep_name, string exe_name, { c.Content = CoreTools.Translate("Do not show this dialog again for {0}", dep_name); c.IsChecked = false; - c.Checked += (_, _) => Settings.SetDictionaryItem("DependencyManagement", dep_name, "skipped"); - c.Unchecked += (_, _) => Settings.SetDictionaryItem("DependencyManagement", dep_name, "attempted"); + c.Checked += (_, _) => Settings.SetDictionaryItem(Settings.K.DependencyManagement, dep_name, "skipped"); + c.Unchecked += (_, _) => Settings.SetDictionaryItem(Settings.K.DependencyManagement, dep_name, "attempted"); p.Children.Add(c); } @@ -391,7 +391,7 @@ public static async void HandleBrokenWinGet() bool bannerWasOpen = false; try { - DialogHelper.ShowLoadingDialog("Attempting to repair WinGet...", + ShowLoadingDialog("Attempting to repair WinGet...", "WinGet is being repaired. Please wait until the process finishes."); bannerWasOpen = Window.WinGetWarningBanner.IsOpen; Window.WinGetWarningBanner.IsOpen = false; @@ -420,11 +420,11 @@ public static async void HandleBrokenWinGet() }; p.Start(); await p.WaitForExitAsync(); - DialogHelper.HideLoadingDialog(); + HideLoadingDialog(); // Toggle bundled WinGet - if (Settings.Get("ForceLegacyBundledWinGet")) - Settings.Set("ForceLegacyBundledWinGet", false); + if (Settings.Get(Settings.K.ForceLegacyBundledWinGet)) + Settings.Set(Settings.K.ForceLegacyBundledWinGet, false); var c = DialogFactory.Create(); c.Title = CoreTools.Translate("WinGet was repaired successfully"); @@ -453,7 +453,7 @@ public static async void HandleBrokenWinGet() Window.WinGetWarningBanner.IsOpen = bannerWasOpen; Logger.Error("An error occurred while trying to repair WinGet"); Logger.Error(ex); - DialogHelper.HideLoadingDialog(); + HideLoadingDialog(); var c = DialogFactory.Create(); c.Title = CoreTools.Translate("WinGet could not be repaired"); @@ -517,11 +517,11 @@ public static async void ShowTelemetryDialog() if (res is ContentDialogResult.Primary) { - Settings.Set("DisableTelemetry", false); + Settings.Set(Settings.K.DisableTelemetry, false); } else { - Settings.Set("DisableTelemetry", true); + Settings.Set(Settings.K.DisableTelemetry, true); } } @@ -543,7 +543,7 @@ public static void ShowTelemetryBanner() { Window.TelemetryWarner.Visibility = Visibility.Collapsed; Window.TelemetryWarner.IsOpen = false; - Settings.Set("ShownTelemetryBanner", true); + Settings.Set(Settings.K.ShownTelemetryBanner, true); }; var SettingsBtn = new Button() @@ -555,7 +555,7 @@ public static void ShowTelemetryBanner() Window.TelemetryWarner.Visibility = Visibility.Collapsed; Window.TelemetryWarner.IsOpen = false; ShowTelemetryDialog(); - Settings.Set("ShownTelemetryBanner", true); + Settings.Set(Settings.K.ShownTelemetryBanner, true); }; StackPanel btns = new() { Margin = new Thickness(4,0,4,0), Spacing = 4, Orientation = Orientation.Horizontal }; @@ -571,7 +571,7 @@ public static void ShowTelemetryBanner() }; mainButton.Resources["HyperlinkButtonBackgroundPointerOver"] = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); - Window.TelemetryWarner.CloseButtonClick += (_, _) => Settings.Set("ShownTelemetryBanner", true); + Window.TelemetryWarner.CloseButtonClick += (_, _) => Settings.Set(Settings.K.ShownTelemetryBanner, true); } @@ -587,9 +587,9 @@ public static async Task ConfirmSetDeleteAllShortcutsSetting() dialog.DefaultButton = ContentDialogButton.Close; if (await Window.ShowDialogAsync(dialog) is ContentDialogResult.Primary) { - Settings.Set("RemoveAllDesktopShortcuts", true); + Settings.Set(Settings.K.RemoveAllDesktopShortcuts, true); } - _ = DialogHelper.ManageDesktopShortcuts(); + _ = ManageDesktopShortcuts(); } /*public static async Task ManualScanDidNotFoundNewShortcuts() diff --git a/src/UniGetUI/Pages/DialogPages/InstallOptions_Manager.xaml.cs b/src/UniGetUI/Pages/DialogPages/InstallOptions_Manager.xaml.cs index 0193df957e..deeef6fd16 100644 --- a/src/UniGetUI/Pages/DialogPages/InstallOptions_Manager.xaml.cs +++ b/src/UniGetUI/Pages/DialogPages/InstallOptions_Manager.xaml.cs @@ -139,7 +139,7 @@ private async Task LoadOptions() CustomInstallLocation.Text = CoreTools.Translate("Install location can't be changed for {0} packages", Manager.DisplayName); } - bool IsCLIEnabled = SecureSettings.Get(SecureSettings.ALLOW_CLI_ARGUMENTS); + bool IsCLIEnabled = SecureSettings.Get(SecureSettings.K.AllowCLIArguments); CustomParameters1.IsEnabled = IsCLIEnabled; CustomParameters2.IsEnabled = IsCLIEnabled; CustomParameters3.IsEnabled = IsCLIEnabled; diff --git a/src/UniGetUI/Pages/DialogPages/InstallOptions_Package.xaml.cs b/src/UniGetUI/Pages/DialogPages/InstallOptions_Package.xaml.cs index b4325124f8..4f65948bd5 100644 --- a/src/UniGetUI/Pages/DialogPages/InstallOptions_Package.xaml.cs +++ b/src/UniGetUI/Pages/DialogPages/InstallOptions_Package.xaml.cs @@ -158,7 +158,7 @@ async Task LoadImage() if (Options.CustomInstallLocation == "") CustomInstallLocation.Text = packageInstallLocation; else CustomInstallLocation.Text = Options.CustomInstallLocation; - + CustomParameters1.Text = string.Join(' ', Options.CustomParameters_Install); CustomParameters2.Text = string.Join(' ', Options.CustomParameters_Update); CustomParameters3.Text = string.Join(' ', Options.CustomParameters_Uninstall); @@ -200,7 +200,7 @@ private void EnableDisableControls(OperationType operation) SelectDir.IsEnabled = Package.Manager.Capabilities.SupportsCustomLocations; } - bool IsCLIEnabled = SecureSettings.Get(SecureSettings.ALLOW_CLI_ARGUMENTS); + bool IsCLIEnabled = SecureSettings.Get(SecureSettings.K.AllowCLIArguments); CustomParameters1.IsEnabled = IsCLIEnabled; CustomParameters2.IsEnabled = IsCLIEnabled; CustomParameters3.IsEnabled = IsCLIEnabled; diff --git a/src/UniGetUI/Pages/LogPages/OperationHistoryPage.cs b/src/UniGetUI/Pages/LogPages/OperationHistoryPage.cs index 5de61ad236..7cb581e7f4 100644 --- a/src/UniGetUI/Pages/LogPages/OperationHistoryPage.cs +++ b/src/UniGetUI/Pages/LogPages/OperationHistoryPage.cs @@ -13,7 +13,7 @@ public OperationHistoryPage() : base(false) public override void LoadLog(bool isReload = false) { Paragraph paragraph = new(); - foreach (string line in Settings.GetValue("OperationHistory").Split("\n")) + foreach (string line in Settings.GetValue(Settings.K.OperationHistory).Split("\n")) { if (line.Replace("\r", "").Replace("\n", "").Trim() == "") { diff --git a/src/UniGetUI/Pages/MainView.xaml.cs b/src/UniGetUI/Pages/MainView.xaml.cs index 83ef7fc9ad..3c41c14eac 100644 --- a/src/UniGetUI/Pages/MainView.xaml.cs +++ b/src/UniGetUI/Pages/MainView.xaml.cs @@ -143,21 +143,21 @@ public MainView() LoadDefaultPage(); - if (CoreTools.IsAdministrator() && !Settings.Get("AlreadyWarnedAboutAdmin")) + if (CoreTools.IsAdministrator() && !Settings.Get(Settings.K.AlreadyWarnedAboutAdmin)) { - Settings.Set("AlreadyWarnedAboutAdmin", true); + Settings.Set(Settings.K.AlreadyWarnedAboutAdmin, true); DialogHelper.WarnAboutAdminRights(); } UpdateOperationsLayout(); MainApp.Operations._operationList.CollectionChanged += (_, _) => UpdateOperationsLayout(); - if (!Settings.Get("ShownTelemetryBanner")) + if (!Settings.Get(Settings.K.ShownTelemetryBanner)) { DialogHelper.ShowTelemetryBanner(); } - if (!Settings.Get("CollapseNavMenuOnWideScreen")) + if (!Settings.Get(Settings.K.CollapseNavMenuOnWideScreen)) { NavView.IsPaneOpen = true; } @@ -165,7 +165,7 @@ public MainView() public void LoadDefaultPage() { - PageType type = Settings.GetValue("StartupPage") switch + PageType type = Settings.GetValue(Settings.K.StartupPage) switch { "discover" => PageType.Discover, "updates" => PageType.Updates, diff --git a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Backup.xaml.cs b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Backup.xaml.cs index 81e0c5f4b4..e7babd4480 100644 --- a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Backup.xaml.cs +++ b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Backup.xaml.cs @@ -23,7 +23,7 @@ public Backup() { this.InitializeComponent(); - EnablePackageBackupUI(Settings.Get("EnablePackageBackup")); + EnablePackageBackupUI(Settings.Get(Settings.K.EnablePackageBackup)); ResetBackupDirectory.Content = CoreTools.Translate("Reset"); OpenBackupDirectory.Content = CoreTools.Translate("Open"); } @@ -44,7 +44,7 @@ private void ChangeBackupDirectory_Click(object sender, EventArgs e) string folder = openPicker.Show(); if (folder != string.Empty) { - Settings.SetValue("ChangeBackupOutputDirectory", folder); + Settings.SetValue(Settings.K.ChangeBackupOutputDirectory, folder); BackupDirectoryLabel.Text = folder; ResetBackupDirectory.IsEnabled = true; } @@ -59,14 +59,14 @@ public void EnablePackageBackupUI(bool enabled) if (enabled) { - if (!Settings.Get("ChangeBackupOutputDirectory")) + if (!Settings.Get(Settings.K.ChangeBackupOutputDirectory)) { BackupDirectoryLabel.Text = CoreData.UniGetUI_DefaultBackupDirectory; ResetBackupDirectory.IsEnabled = false; } else { - BackupDirectoryLabel.Text = Settings.GetValue("ChangeBackupOutputDirectory"); + BackupDirectoryLabel.Text = Settings.GetValue(Settings.K.ChangeBackupOutputDirectory); ResetBackupDirectory.IsEnabled = true; } } @@ -75,13 +75,13 @@ public void EnablePackageBackupUI(bool enabled) private void ResetBackupPath_Click(object sender, RoutedEventArgs e) { BackupDirectoryLabel.Text = CoreData.UniGetUI_DefaultBackupDirectory; - Settings.Set("ChangeBackupOutputDirectory", false); + Settings.Set(Settings.K.ChangeBackupOutputDirectory, false); ResetBackupDirectory.IsEnabled = false; } private void OpenBackupPath_Click(object sender, RoutedEventArgs e) { - string directory = Settings.GetValue("ChangeBackupOutputDirectory"); + string directory = Settings.GetValue(Settings.K.ChangeBackupOutputDirectory); if (directory == "") { directory = CoreData.UniGetUI_DefaultBackupDirectory; diff --git a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Interface_P.xaml.cs b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Interface_P.xaml.cs index aab3d2d9ee..b650846c4b 100644 --- a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Interface_P.xaml.cs +++ b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Interface_P.xaml.cs @@ -21,9 +21,9 @@ public Interface_P() { this.InitializeComponent(); - if (Settings.GetValue("PreferredTheme") == "") + if (Settings.GetValue(Settings.K.PreferredTheme) == "") { - Settings.SetValue("PreferredTheme", "auto"); + Settings.SetValue(Settings.K.PreferredTheme, "auto"); } ThemeSelector.AddItem(CoreTools.AutoTranslated("Light"), "light"); diff --git a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Notifications.xaml.cs b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Notifications.xaml.cs index 657baf517c..45ca0d5765 100644 --- a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Notifications.xaml.cs +++ b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Notifications.xaml.cs @@ -21,7 +21,7 @@ public Notifications() protected override void OnNavigatedTo(NavigationEventArgs e) { - if (Settings.Get("DisableSystemTray")) + if (Settings.Get(Settings.K.DisableSystemTray)) { ToolbarText.Visibility = Visibility.Visible; DisableNotifications.IsEnabled = false; diff --git a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Updates.xaml.cs b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Updates.xaml.cs index d6d4011094..4ef08b97eb 100644 --- a/src/UniGetUI/Pages/SettingsPages/GeneralPages/Updates.xaml.cs +++ b/src/UniGetUI/Pages/SettingsPages/GeneralPages/Updates.xaml.cs @@ -48,7 +48,7 @@ public Updates() public void ShowRestartBanner(object sender, EventArgs e) => RestartRequired?.Invoke(this, e); - private void OperationsSettingsButton_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) + private void OperationsSettingsButton_Click(object sender, RoutedEventArgs e) { NavigationRequested?.Invoke(this, typeof(Operations)); } diff --git a/src/UniGetUI/Pages/SettingsPages/ManagersPages/ManagersHomepage.xaml.cs b/src/UniGetUI/Pages/SettingsPages/ManagersPages/ManagersHomepage.xaml.cs index 8ffee91f86..334fa4c2b3 100644 --- a/src/UniGetUI/Pages/SettingsPages/ManagersPages/ManagersHomepage.xaml.cs +++ b/src/UniGetUI/Pages/SettingsPages/ManagersPages/ManagersHomepage.xaml.cs @@ -44,7 +44,7 @@ public ManagersHomepage() button.Click += (_, _) => NavigationRequested?.Invoke(this, manager.GetType()); var toggle = new ToggleSwitch(); - toggle.Toggled += (_, _) => Settings.SetDictionaryItem("DisabledManagers", manager.Name, !toggle.IsOn); + toggle.Toggled += (_, _) => Settings.SetDictionaryItem(Settings.K.DisabledManagers, manager.Name, !toggle.IsOn); button.Content = toggle; first = false; @@ -60,7 +60,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) for(int i = 0; i < managerControls.Count; i++) { var toggle = (ToggleSwitch)managerControls[i].Content; - toggle.IsOn = !Settings.GetDictionaryItem("DisabledManagers", PEInterface.Managers[i].Name); + toggle.IsOn = !Settings.GetDictionaryItem(Settings.K.DisabledManagers, PEInterface.Managers[i].Name); } base.OnNavigatedTo(e); diff --git a/src/UniGetUI/Pages/SettingsPages/ManagersPages/PackageManager.xaml.cs b/src/UniGetUI/Pages/SettingsPages/ManagersPages/PackageManager.xaml.cs index a23af8187a..d1b1959b6c 100644 --- a/src/UniGetUI/Pages/SettingsPages/ManagersPages/PackageManager.xaml.cs +++ b/src/UniGetUI/Pages/SettingsPages/ManagersPages/PackageManager.xaml.cs @@ -69,7 +69,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) LocationLabel.Text = Manager.Status.ExecutablePath + Manager.Properties.ExecutableCallArgs; if (LocationLabel.Text == "") LocationLabel.Text = CoreTools.Translate("The executable file for {0} was not found", Manager.DisplayName); - EnableManager.SettingName = Manager.Name; + EnableManager.KeyName = Manager.Name; EnableManager.Text = CoreTools.Translate("Enable {pm}").Replace("{pm}", Manager.DisplayName); InstallOptionsTitle.Text = CoreTools.Translate("Default installation options for {0} packages", Manager.DisplayName); @@ -79,9 +79,9 @@ protected override void OnNavigatedTo(NavigationEventArgs e) var DisableNotifsCard = new CheckboxCard_Dict() { Text = CoreTools.Translate("Ignore packages from {pm} when showing a notification about updates").Replace("{pm}", Manager.DisplayName), - DictionaryName = "DisabledPackageManagerNotifications", + DictionaryName = Settings.K.DisabledPackageManagerNotifications, ForceInversion = true, - SettingName = Manager.Name + KeyName = Manager.Name }; ManagerLogsLabel.Text = CoreTools.Translate("View {0} logs", Manager.DisplayName); @@ -126,7 +126,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) { Text = $"{CoreTools.Translate("Use bundled WinGet instead of system WinGet")} ({CoreTools.Translate("This may help if WinGet packages are not shown")})", - SettingName = "ForceLegacyBundledWinGet", + SettingName = Settings.K.ForceLegacyBundledWinGet, CornerRadius = new CornerRadius(0), BorderThickness = new Thickness(1, 0, 1, 0), }; @@ -136,7 +136,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) CheckboxCard WinGet_EnableTroubleshooter = new() { Text = CoreTools.Translate("Enable the automatic WinGet troubleshooter"), - SettingName = "DisableWinGetMalfunctionDetector", + SettingName = Settings.K.DisableWinGetMalfunctionDetector, CornerRadius = new CornerRadius(0), }; WinGet_EnableTroubleshooter.StateChanged += (_, _) => @@ -149,7 +149,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) CheckboxCard WinGet_EnableTroubleshooter_v2 = new() { Text = CoreTools.Translate("Enable an [experimental] improved WinGet troubleshooter"), - SettingName = "DisableNewWinGetTroubleshooter", + SettingName = Settings.K.DisableNewWinGetTroubleshooter, CornerRadius = new CornerRadius(0), BorderThickness = new Thickness(1, 0, 1, 0), }; @@ -163,7 +163,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) CheckboxCard WinGet_HideNonApplicableUpdates = new() { Text = CoreTools.Translate("Add updates that fail with a 'no applicable update found' to the ignored updates list"), - SettingName = "IgnoreUpdatesNotApplicable", + SettingName = Settings.K.IgnoreUpdatesNotApplicable, CornerRadius = new CornerRadius(0, 0, 8, 8) }; ExtraControls.Children.Add(WinGet_HideNonApplicableUpdates); @@ -226,7 +226,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) { CornerRadius = new CornerRadius(0, 0, 8, 8), BorderThickness = new Thickness(1, 0, 1, 1), - SettingName = "EnableScoopCleanup", + SettingName = Settings.K.EnableScoopCleanup, Text = "Enable Scoop cleanup on launch", }; ExtraControls.Children.Add(Scoop_CleanupOnStart); @@ -242,7 +242,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) CheckboxCard Chocolatey_SystemChoco = new() { Text = CoreTools.AutoTranslated("Use system Chocolatey"), - SettingName = "UseSystemChocolatey", + SettingName = Settings.K.UseSystemChocolatey, CornerRadius = new CornerRadius(0, 0, 8, 8) }; Chocolatey_SystemChoco.StateChanged += (_, _) => RestartRequired?.Invoke(this, new()); @@ -257,11 +257,11 @@ protected override void OnNavigatedTo(NavigationEventArgs e) DisableNotifsCard.BorderThickness = new Thickness(1, 1, 1, 0); ExtraControls.Children.Add(DisableNotifsCard); - Settings.SetValue("DefaultVcpkgTriplet", Vcpkg.GetDefaultTriplet()); + Settings.SetValue(Settings.K.DefaultVcpkgTriplet, Vcpkg.GetDefaultTriplet()); ComboboxCard Vcpkg_DefaultTriplet = new() { Text = CoreTools.Translate("Default vcpkg triplet"), - SettingName = "DefaultVcpkgTriplet", + SettingName = Settings.K.DefaultVcpkgTriplet, CornerRadius = new CornerRadius(0) }; foreach (string triplet in Vcpkg.GetSystemTriplets()) @@ -284,23 +284,23 @@ protected override void OnNavigatedTo(NavigationEventArgs e) var ResetVcPkgRootLabel = new HyperlinkButton { Content = CoreTools.Translate("Reset") }; var OpenVcPkgRootLabel = new HyperlinkButton { Content = CoreTools.Translate("Open") }; - VcPkgRootLabel.Text = Settings.Get("CustomVcpkgRoot") - ? Settings.GetValue("CustomVcpkgRoot") + VcPkgRootLabel.Text = Settings.Get(Settings.K.CustomVcpkgRoot) + ? Settings.GetValue(Settings.K.CustomVcpkgRoot) : "%VCPKG_ROOT%"; - OpenVcPkgRootLabel.IsEnabled = Settings.Get("CustomVcpkgRoot"); - ResetVcPkgRootLabel.IsEnabled = Settings.Get("CustomVcpkgRoot"); + OpenVcPkgRootLabel.IsEnabled = Settings.Get(Settings.K.CustomVcpkgRoot); + ResetVcPkgRootLabel.IsEnabled = Settings.Get(Settings.K.CustomVcpkgRoot); ResetVcPkgRootLabel.Click += (_, _) => { VcPkgRootLabel.Text = "%VCPKG_ROOT%"; - Settings.Set("CustomVcpkgRoot", false); + Settings.Set(Settings.K.CustomVcpkgRoot, false); ResetVcPkgRootLabel.IsEnabled = false; OpenVcPkgRootLabel.IsEnabled = false; }; OpenVcPkgRootLabel.Click += (_, _) => { - string directory = Settings.GetValue("CustomVcpkgRoot").Replace("/", "\\"); + string directory = Settings.GetValue(Settings.K.CustomVcpkgRoot).Replace("/", "\\"); if (directory.Any()) Process.Start("explorer.exe", directory); }; @@ -311,7 +311,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) string folder = openPicker.Show(); if (folder != string.Empty) { - Settings.SetValue("CustomVcpkgRoot", folder); + Settings.SetValue(Settings.K.CustomVcpkgRoot, folder); VcPkgRootLabel.Text = folder; ResetVcPkgRootLabel.IsEnabled = true; OpenVcPkgRootLabel.IsEnabled = true; diff --git a/src/UniGetUI/Pages/SoftwarePages/AbstractPackagesPage.xaml.cs b/src/UniGetUI/Pages/SoftwarePages/AbstractPackagesPage.xaml.cs index bdf65f491a..85d09a9407 100644 --- a/src/UniGetUI/Pages/SoftwarePages/AbstractPackagesPage.xaml.cs +++ b/src/UniGetUI/Pages/SoftwarePages/AbstractPackagesPage.xaml.cs @@ -218,7 +218,7 @@ protected AbstractPackagesPage(PackagesPageData data) InitializeComponent(); // Selection of grid view mode - int viewMode = Settings.GetDictionaryItem("PackageListViewMode", PAGE_NAME); + int viewMode = Settings.GetDictionaryItem(Settings.K.PackageListViewMode, PAGE_NAME); if (viewMode < 0 || viewMode >= ViewModeSelector.Items.Count) viewMode = 0; ViewModeSelector.SelectedIndex = viewMode; @@ -367,7 +367,7 @@ protected AbstractPackagesPage(PackagesPageData data) QueryBlock.PlaceholderText = CoreTools.Translate("Search for packages"); MegaQueryBlock.PlaceholderText = CoreTools.Translate("Search for packages"); - InstantSearchCheckbox.IsChecked = !Settings.GetDictionaryItem("DisableInstantSearch", PAGE_NAME); + InstantSearchCheckbox.IsChecked = !Settings.GetDictionaryItem(Settings.K.DisableInstantSearch, PAGE_NAME); HeaderIcon.FontWeight = new Windows.UI.Text.FontWeight(700); NameHeader.Content = CoreTools.Translate("Package Name"); @@ -569,7 +569,7 @@ private void FilterOptionsChanged(object sender, RoutedEventArgs e) } private void InstantSearchValueChanged(object sender, RoutedEventArgs e) - => Settings.SetDictionaryItem("DisableInstantSearch", PAGE_NAME, !InstantSearchCheckbox.IsChecked); + => Settings.SetDictionaryItem(Settings.K.DisableInstantSearch, PAGE_NAME, !InstantSearchCheckbox.IsChecked); private void SourcesTreeView_SelectionChanged(TreeView sender, TreeViewSelectionChangedEventArgs args) => FilterPackages(); @@ -849,7 +849,7 @@ public void FilterPackages(bool forceQueryUpdate = false) ForceRedrawByScroll(); } - if (!Settings.Get("DisableIconsOnPackageLists")) + if (!Settings.Get(Settings.K.DisableIconsOnPackageLists)) _ = LoadIconsForNewPackages(); } @@ -1021,11 +1021,11 @@ private void SidepanelWidth_SizeChanged(object sender, SizeChangedEventArgs e) if ((int)e.NewSize.Width < 100) { HideFilteringPane(); - Settings.SetDictionaryItem("SidepanelWidths", PAGE_NAME, 250); + Settings.SetDictionaryItem(Settings.K.SidepanelWidths, PAGE_NAME, 250); } else { - Settings.SetDictionaryItem("SidepanelWidths", PAGE_NAME, (int)e.NewSize.Width); + Settings.SetDictionaryItem(Settings.K.SidepanelWidths, PAGE_NAME, (int)e.NewSize.Width); } } @@ -1113,7 +1113,7 @@ private void ToggleFiltersButton_Click(object sender, RoutedEventArgs e) { if(FilteringPanel.DisplayMode is SplitViewDisplayMode.Inline) { - Settings.SetDictionaryItem("HideToggleFilters", PAGE_NAME, !ToggleFiltersButton.IsChecked ?? false); + Settings.SetDictionaryItem(Settings.K.HideToggleFilters, PAGE_NAME, !ToggleFiltersButton.IsChecked ?? false); } if (ToggleFiltersButton.IsChecked ?? false) @@ -1139,11 +1139,11 @@ private void ShowFilteringPane() int finalWidth = 250; try { - finalWidth = Settings.GetDictionaryItem("SidepanelWidths", PAGE_NAME); + finalWidth = Settings.GetDictionaryItem(Settings.K.SidepanelWidths, PAGE_NAME); } catch { - Settings.SetDictionaryItem("SidepanelWidths", PAGE_NAME, 250); + Settings.SetDictionaryItem(Settings.K.SidepanelWidths, PAGE_NAME, 250); } FilteringPanel.OpenPaneLength = finalWidth; PackagesListGrid.Margin = new Thickness(12, 0, 0, 0); @@ -1313,7 +1313,7 @@ private void SetFilterMode_Inline() filters.Margin = new Thickness(0); } - if (!Settings.GetDictionaryItem("HideToggleFilters", PAGE_NAME)) + if (!Settings.GetDictionaryItem(Settings.K.HideToggleFilters, PAGE_NAME)) { ShowFilteringPane(); } @@ -1346,7 +1346,7 @@ private void FilteringPanel_PaneClosing(SplitView sender, SplitViewPaneClosingEv } private void ViewModeSelector_SelectionChanged(object sender, SelectionChangedEventArgs e) { - Settings.SetDictionaryItem("PackageListViewMode", PAGE_NAME, ViewModeSelector.SelectedIndex); + Settings.SetDictionaryItem(Settings.K.PackageListViewMode, PAGE_NAME, ViewModeSelector.SelectedIndex); } FrameworkElement _lastContextMenuButtonTapped = null!; diff --git a/src/UniGetUI/Pages/SoftwarePages/InstalledPackagesPage.cs b/src/UniGetUI/Pages/SoftwarePages/InstalledPackagesPage.cs index b2a3b37dc4..a694c46479 100644 --- a/src/UniGetUI/Pages/SoftwarePages/InstalledPackagesPage.cs +++ b/src/UniGetUI/Pages/SoftwarePages/InstalledPackagesPage.cs @@ -285,13 +285,13 @@ protected override void WhenPackagesLoaded(ReloadReason reason) { if (!HasDoneBackup) { - if (Settings.Get("EnablePackageBackup")) + if (Settings.Get(Settings.K.EnablePackageBackup)) { _ = BackupPackages(); } } - if (WinGet.NO_PACKAGES_HAVE_BEEN_LOADED && !Settings.Get("DisableWinGetMalfunctionDetector")) + if (WinGet.NO_PACKAGES_HAVE_BEEN_LOADED && !Settings.Get(Settings.K.DisableWinGetMalfunctionDetector)) { var infoBar = MainApp.Instance.MainWindow.WinGetWarningBanner; infoBar.IsOpen = true; @@ -375,7 +375,7 @@ public static async Task BackupPackages() string BackupContents = await PackageBundlesPage.CreateBundle(packagesToExport.ToArray(), BundleFormatType.UBUNDLE); - string dirName = Settings.GetValue("ChangeBackupOutputDirectory"); + string dirName = Settings.GetValue(Settings.K.ChangeBackupOutputDirectory); if (dirName == "") { dirName = CoreData.UniGetUI_DefaultBackupDirectory; @@ -386,13 +386,13 @@ public static async Task BackupPackages() Directory.CreateDirectory(dirName); } - string fileName = Settings.GetValue("ChangeBackupFileName"); + string fileName = Settings.GetValue(Settings.K.ChangeBackupFileName); if (fileName == "") { fileName = CoreTools.Translate("{pcName} installed packages", new Dictionary { { "pcName", Environment.MachineName } }); } - if (Settings.Get("EnableBackupTimestamping")) + if (Settings.Get(Settings.K.EnableBackupTimestamping)) { fileName += " " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"); } diff --git a/src/UniGetUI/Pages/SoftwarePages/PackageBundlesPage.cs b/src/UniGetUI/Pages/SoftwarePages/PackageBundlesPage.cs index 92fdb9598c..712128aab4 100644 --- a/src/UniGetUI/Pages/SoftwarePages/PackageBundlesPage.cs +++ b/src/UniGetUI/Pages/SoftwarePages/PackageBundlesPage.cs @@ -662,8 +662,8 @@ public async Task AddFromBundle(string content, BundleFormatType format) bool showReport = false; var packageReport = new Dictionary>(); bool AllowCLIParameters = - SecureSettings.Get(SecureSettings.ALLOW_CLI_ARGUMENTS) && - SecureSettings.Get(SecureSettings.ALLOW_IMPORTING_CLI_ARGUMENTS); + SecureSettings.Get(SecureSettings.K.AllowCLIArguments) && + SecureSettings.Get(SecureSettings.K.AllowImportingCLIArguments); foreach (var pkg in DeserializedData.packages) diff --git a/src/UniGetUI/Pages/SoftwarePages/SoftwareUpdatesPage.cs b/src/UniGetUI/Pages/SoftwarePages/SoftwareUpdatesPage.cs index 5b9b232df4..eb3f502af3 100644 --- a/src/UniGetUI/Pages/SoftwarePages/SoftwareUpdatesPage.cs +++ b/src/UniGetUI/Pages/SoftwarePages/SoftwareUpdatesPage.cs @@ -339,18 +339,18 @@ protected override void WhenPackagesLoaded(ReloadReason reason) if (upgradablePackages.Count == 0) return; - bool EnableAutoUpdate = Settings.Get("AutomaticallyUpdatePackages"); + bool EnableAutoUpdate = Settings.Get(Settings.K.AutomaticallyUpdatePackages); if (EnableAutoUpdate) { var connectionCost = NetworkInformation.GetInternetConnectionProfile()?.GetConnectionCost().NetworkCostType; - if (connectionCost is NetworkCostType.Fixed or NetworkCostType.Variable && Settings.Get("DisableAUPOnMeteredConnections")) + if (connectionCost is NetworkCostType.Fixed or NetworkCostType.Variable && Settings.Get(Settings.K.DisableAUPOnMeteredConnections)) { Logger.Warn("Updates will not be installed automatically because the current internet connection is metered."); EnableAutoUpdate = false; } - if (PowerManager.EnergySaverStatus is EnergySaverStatus.On && Settings.Get("DisableAUPOnBatterySaver")) + if (PowerManager.EnergySaverStatus is EnergySaverStatus.On && Settings.Get(Settings.K.DisableAUPOnBatterySaver)) { Logger.Warn("Updates will not be installed automatically because battery saver is enabled."); EnableAutoUpdate = false; @@ -419,7 +419,7 @@ protected override void WhenPackagesLoaded(ReloadReason reason) string attribution = ""; foreach (IPackage package in upgradablePackages) { - if (!Settings.GetDictionaryItem("DisabledPackageManagerNotifications", package.Manager.Name)) + if (!Settings.GetDictionaryItem(Settings.K.DisabledPackageManagerNotifications, package.Manager.Name)) attribution += package.Name + ", "; } @@ -464,7 +464,7 @@ protected override void WhenPackagesLoaded(ReloadReason reason) bool SendNotification = false; foreach (var Package in upgradablePackages) { - if (!Settings.GetDictionaryItem("DisabledPackageManagerNotifications", Package.Manager.Name)) + if (!Settings.GetDictionaryItem(Settings.K.DisabledPackageManagerNotifications, Package.Manager.Name)) { SendNotification = true; break;