diff --git a/AM2RLauncher/AM2RLauncher/LauncherUpdater.cs b/AM2RLauncher/AM2RLauncher/LauncherUpdater.cs index a42ff54..98b13a5 100644 --- a/AM2RLauncher/AM2RLauncher/LauncherUpdater.cs +++ b/AM2RLauncher/AM2RLauncher/LauncherUpdater.cs @@ -1,4 +1,5 @@ using AM2RLauncher.Core; +using AM2RLauncher; using Eto.Forms; using log4net; using System; @@ -33,7 +34,7 @@ namespace AM2RLauncher private static readonly ILog log = LogManager.GetLogger(typeof(MainForm)); /// - /// Performs the entire AM2RLauncher update procedure. + /// Performs the entire AM2RLauncher update procedure. /// public static void Main() { @@ -79,7 +80,7 @@ namespace AM2RLauncher } // Check settings if autoUpdateLauncher is set to true - bool autoUpdate = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher")); + bool autoUpdate = Boolean.Parse(MainForm.ReadFromConfig("AutoUpdateLauncher")); if (autoUpdate) { @@ -118,7 +119,7 @@ namespace AM2RLauncher int onlineNum = Int32.Parse(onlineVersionArray[i]); int localNum = Int32.Parse(localVersionArray[i]); if (onlineNum > localNum) - { + { isCurrentVersionOutdated = true; break; } @@ -140,7 +141,7 @@ namespace AM2RLauncher "Please recompile AM2RLauncher again or disable auto-updating"); return; } - + log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + "."); string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/"; @@ -211,7 +212,7 @@ namespace AM2RLauncher Directory.Delete(tmpUpdatePath, true); - CrossPlatformOperations.CopyOldConfigToNewConfig(); + MainForm.CopyOldConfigToNewConfig(); log.Info("Files extracted. Preparing to restart executable..."); if (OS.IsLinux) System.Diagnostics.Process.Start("chmod", "+x " + updatePath + "./AM2RLauncher.Gtk"); diff --git a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Events.cs b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Events.cs index 0df1747..1ea0ed9 100644 --- a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Events.cs +++ b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Events.cs @@ -82,10 +82,10 @@ namespace AM2RLauncher { log.Info("Attempting to close MainForm!"); - CrossPlatformOperations.WriteToConfig("Width", ClientSize.Width); - CrossPlatformOperations.WriteToConfig("Height", ClientSize.Height); - CrossPlatformOperations.WriteToConfig("IsMaximized", this.WindowState == WindowState.Maximized); - CrossPlatformOperations.WriteToConfig("ProfileIndex", profileIndex.ToString()); + WriteToConfig("Width", ClientSize.Width); + WriteToConfig("Height", ClientSize.Height); + WriteToConfig("IsMaximized", this.WindowState == WindowState.Maximized); + WriteToConfig("ProfileIndex", profileIndex.ToString()); switch (updateState) { @@ -112,7 +112,7 @@ namespace AM2RLauncher } // This needs to be made invisible, otherwise a tray indicator will be visible (on linux?) that clicking crashes the application - //TODO: this sounds like an eto bug. check if this can get reproduced. + //TODO: this sounds like an eto issue. check if this can get reproduced. trayIndicator.Visible = false; if (e.Cancel) @@ -451,7 +451,7 @@ namespace AM2RLauncher #endregion - default: throw new NotImplementedException("Encountered invalid update state: " + updateState + "!"); + default: log.Error("Encountered invalid update state: " + updateState + "!"); break; } } @@ -550,35 +550,35 @@ namespace AM2RLauncher private void LanguageDropDownSelectedIndexChanged(object sender, EventArgs e) { log.Info("languageDropDown.SelectedIndex has been changed to " + languageDropDown.SelectedIndex + "."); - CrossPlatformOperations.WriteToConfig("Language", languageDropDown.SelectedIndex == 0 ? "Default" : languageDropDown.Items[languageDropDown.SelectedIndex].Text); + WriteToConfig("Language", languageDropDown.SelectedIndex == 0 ? "Default" : languageDropDown.Items[languageDropDown.SelectedIndex].Text); } /// Gets called when gets clicked and writes its new value to the config. private void AutoUpdateAM2RCheckChanged(object sender, EventArgs e) { log.Info("Auto Update AM2R has been set to " + autoUpdateAM2RCheck.Checked + "."); - CrossPlatformOperations.WriteToConfig("AutoUpdateAM2R", (bool)autoUpdateAM2RCheck.Checked); + WriteToConfig("AutoUpdateAM2R", (bool)autoUpdateAM2RCheck.Checked); } /// Gets called when gets clicked and writes its new value to the config. private void AutoUpdateLauncherCheckChanged(object sender, EventArgs e) { log.Info("Auto Update Launcher has been set to " + autoUpdateAM2RCheck.Checked + "."); - CrossPlatformOperations.WriteToConfig("AutoUpdateLauncher", (bool)autoUpdateAM2RCheck.Checked); + WriteToConfig("AutoUpdateLauncher", (bool)autoUpdateAM2RCheck.Checked); } /// Gets called when gets clicked and writes its new value to the config. private void HqMusicPCCheckChanged(object sender, EventArgs e) { log.Info("PC HQ Music option has been changed to " + hqMusicPCCheck.Checked); - CrossPlatformOperations.WriteToConfig("MusicHQPC", hqMusicPCCheck.Checked); + WriteToConfig("MusicHQPC", hqMusicPCCheck.Checked); } /// Gets called when gets clicked and writes its new value to the config. private void HqMusicAndroidCheckChanged(object sender, EventArgs e) { log.Info("Android HQ Music option has been changed to " + hqMusicAndroidCheck.Checked); - CrossPlatformOperations.WriteToConfig("MusicHQAndroid", hqMusicAndroidCheck.Checked); + WriteToConfig("MusicHQAndroid", hqMusicAndroidCheck.Checked); } /// @@ -587,7 +587,7 @@ namespace AM2RLauncher private void ProfileDebugLogCheckedChanged(object sender, EventArgs e) { log.Info("Create Game Debug Logs option has been set to " + profileDebugLogCheck.Checked + "."); - CrossPlatformOperations.WriteToConfig("ProfileDebugLog", profileDebugLogCheck.Checked); + WriteToConfig("ProfileDebugLog", profileDebugLogCheck.Checked); } /// Gets called when user selects a different item from . @@ -599,7 +599,7 @@ namespace AM2RLauncher log.Info("Current mirror has been set to " + currentMirror + "."); - CrossPlatformOperations.WriteToConfig("MirrorIndex", mirrorDropDown.SelectedIndex); + WriteToConfig("MirrorIndex", mirrorDropDown.SelectedIndex); // Don't overwrite the git config while we download!!! if (updateState == PlayButtonState.Downloading) return; @@ -622,7 +622,7 @@ namespace AM2RLauncher private void CustomMirrorCheckChanged(object sender, EventArgs e) { log.Info("Use Custom Mirror option has been set to " + customMirrorCheck.Checked + "."); - CrossPlatformOperations.WriteToConfig("CustomMirrorEnabled", (bool)customMirrorCheck.Checked); + WriteToConfig("CustomMirrorEnabled", (bool)customMirrorCheck.Checked); EnableMirrorControlsAccordingly(); @@ -655,7 +655,7 @@ namespace AM2RLauncher } currentMirror = mirrorText; - CrossPlatformOperations.WriteToConfig("CustomMirrorText", currentMirror); + WriteToConfig("CustomMirrorText", currentMirror); log.Info("Overwriting mirror in gitconfig."); @@ -676,7 +676,7 @@ namespace AM2RLauncher private void CustomEnvVarTextBoxLostFocus(object sender, EventArgs e) { log.Info("Custom Environment variables have been set to \"" + customEnvVarTextBox.Text + "\"."); - CrossPlatformOperations.WriteToConfig("CustomEnvVar", customEnvVarTextBox.Text); + WriteToConfig("CustomEnvVar", customEnvVarTextBox.Text); } #endregion diff --git a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Methods.cs b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Methods.cs index cbd4f3d..9fee901 100644 --- a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Methods.cs +++ b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.Methods.cs @@ -1,8 +1,13 @@ using AM2RLauncher.Core; +using AM2RLauncher.Core.XML; using AM2RLauncher.Language; using Eto.Forms; using LibGit2Sharp; using System; +using System.Configuration; +using System.IO; +using System.Text.RegularExpressions; +using Configuration = System.Configuration.Configuration; namespace AM2RLauncher { @@ -110,5 +115,125 @@ namespace AM2RLauncher progressLabel.Visible = true; progressLabel.Text = ""; } + + /// + /// Reads the Launcher config file on the current Platform and returns the value for . + /// + /// The property to get the value from. + /// The value from as a string + public static string ReadFromConfig(string property) + { + log.Info($"Reading {property} from config."); + if (OS.IsWindows) + { + // We use the configuration manager in order to read `property` from the app.config and then return it + ConnectionStringSettings appConfig = ConfigurationManager.ConnectionStrings[property]; + if (appConfig == null) throw new ArgumentException("The property " + property + " could not be found."); + return appConfig.ConnectionString; + } + if (OS.IsUnix) + { + string launcherConfigPath = CrossPlatformOperations.NIXLAUNCHERCONFIGPATH; + string launcherConfigFilePath = launcherConfigPath + "/config.xml"; + XML.LauncherConfigXML launcherConfig = new XML.LauncherConfigXML(); + + // If folder doesn't exist, create it and the config file + if (!Directory.Exists(launcherConfigPath) || !File.Exists(launcherConfigFilePath)) + { + Directory.CreateDirectory(launcherConfigPath); + File.WriteAllText(launcherConfigFilePath, Serializer.Serialize(launcherConfig)); + } + + // Deserialize the config xml into launcherConfig + launcherConfig = Serializer.Deserialize(File.ReadAllText(launcherConfigFilePath)); + + // This uses the indexer, which means, we can use the variable in order to get the property. Look at LauncherConfigXML for more info + return launcherConfig[property]?.ToString(); + } + + log.Error(OS.Name + " has no config to read from!"); + return null; + } + + /// + /// Writes to in the Launcher Config file. + /// + /// The property whose value you want to change. + /// The value that will be written. + public static void WriteToConfig(string property, object value) + { + log.Info($"Writing {value} of type {value.GetType()} to {property} to config."); + if (OS.IsWindows) + { + // We use the configuration manager in order to read from the app.config, change the value and save it + Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + if (appConfig == null) + throw new NullReferenceException("Could not find the Config file! Please make sure it exists!"); + ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)appConfig.GetSection("connectionStrings"); + if (connectionStringsSection?.ConnectionStrings[property]?.ConnectionString == null) + throw new ArgumentException("The property " + property + " could not be found."); + connectionStringsSection.ConnectionStrings[property].ConnectionString = value.ToString(); + appConfig.Save(); + ConfigurationManager.RefreshSection("connectionStrings"); + } + else if (OS.IsUnix) + { + string launcherConfigPath = CrossPlatformOperations.NIXLAUNCHERCONFIGPATH; + string launcherConfigFilePath = CrossPlatformOperations.NIXLAUNCHERCONFIGFILEPATH; + XML.LauncherConfigXML launcherConfig = new XML.LauncherConfigXML(); + + // If folder doesn't exist, create it and the config file + if (!Directory.Exists(launcherConfigPath) || !File.Exists(launcherConfigFilePath)) + { + Directory.CreateDirectory(launcherConfigPath); + File.WriteAllText(launcherConfigFilePath, Serializer.Serialize(launcherConfig)); + } + // Deserialize the config xml into launcherConfig + launcherConfig = Serializer.Deserialize(File.ReadAllText(launcherConfigFilePath)); + + // Uses indexer. Look at LauncherConfigXML for more info + launcherConfig[property] = value; + + // Serialize back into the file + File.WriteAllText(launcherConfigFilePath, Serializer.Serialize(launcherConfig)); + } + else + log.Error(OS.Name + " has no config to write to!"); + } + + /// + /// When a Launcher update occurs that introduces new config properties, this method ensures that the old user config is copied over as much as possible. + /// + public static void CopyOldConfigToNewConfig() + { + if (OS.IsWindows) + { + string oldConfigPath = CrossPlatformOperations.LAUNCHERNAME + ".oldCfg"; + string newConfigPath = CrossPlatformOperations.LAUNCHERNAME + ".config"; + string oldConfigText = File.ReadAllText(oldConfigPath); + string newConfigText = File.ReadAllText(newConfigPath); + + Regex settingRegex = new Regex(""); + + MatchCollection oldMatch = settingRegex.Matches(oldConfigText); + MatchCollection newMatch = settingRegex.Matches(newConfigText); + + for (int i = 0; i < oldMatch.Count; i++) + newConfigText = newConfigText.Replace(newMatch[i].Value, oldMatch[i].Value); + + File.WriteAllText(newConfigPath, newConfigText); + + } + else if (OS.IsUnix) + { + string launcherConfigFilePath = CrossPlatformOperations.NIXLAUNCHERCONFIGFILEPATH; + + // For some reason deserializing and saving back again works, not exactly sure why, but I'll take it + XML.LauncherConfigXML launcherConfig = Serializer.Deserialize(File.ReadAllText(launcherConfigFilePath)); + File.WriteAllText(launcherConfigFilePath, Serializer.Serialize(launcherConfig)); + } + else + log.Error(OS.Name + " has no config to transfer over!"); + } } } \ No newline at end of file diff --git a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.StateMachine.cs b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.StateMachine.cs index f675163..4d25f78 100644 --- a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.StateMachine.cs +++ b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.StateMachine.cs @@ -37,7 +37,7 @@ namespace AM2RLauncher playButton.Enabled = false; return; } - + playButton.Enabled = true; // If PatchData isn't cloned, we still need to download if (!Profile.IsPatchDataCloned()) @@ -52,7 +52,7 @@ namespace AM2RLauncher SetPlayButtonState(PlayButtonState.Select11); return; } - + var isProfileValid = IsProfileIndexValid(); // If current profile is installed, we're ready to play! if (isProfileValid && Profile.IsProfileInstalled(profileList[profileIndex.Value])) @@ -124,7 +124,7 @@ namespace AM2RLauncher case PlayButtonState.Install: case PlayButtonState.Play: profileDropDown.Enabled = true; break; - + } if (apkButtonState == ApkButtonState.Creating) profileDropDown.Enabled = false; @@ -144,7 +144,7 @@ namespace AM2RLauncher { // Safety check if (modSettingsProfileDropDown == null || modSettingsProfileDropDown.Items.Count <= 0) return; - + bool enabled = false; switch (updateState) { @@ -192,7 +192,7 @@ namespace AM2RLauncher } /// - /// Sets the global and then changes the state of accordingly. + /// Sets the global and then changes the state of accordingly. /// /// The state that should be set to. private void SetPlayButtonState(PlayButtonState state) @@ -200,13 +200,13 @@ namespace AM2RLauncher updateState = state; switch (updateState) { - case PlayButtonState.Download: - case PlayButtonState.Downloading: - case PlayButtonState.Select11: - case PlayButtonState.Install: + case PlayButtonState.Download: + case PlayButtonState.Downloading: + case PlayButtonState.Select11: + case PlayButtonState.Install: case PlayButtonState.Play: playButton.Enabled = true; break; - case PlayButtonState.Installing: + case PlayButtonState.Installing: case PlayButtonState.Playing: playButton.Enabled = false; break; } playButton.Text = GetPlayButtonText(); @@ -218,7 +218,7 @@ namespace AM2RLauncher } /// - /// Sets the global and then changes the state of accordingly. + /// Sets the global and then changes the state of accordingly. /// /// The state that should be set to. private void SetApkButtonState(ApkButtonState state) @@ -314,7 +314,7 @@ namespace AM2RLauncher } // Read the value from the config - string profIndexString = CrossPlatformOperations.ReadFromConfig("ProfileIndex"); + string profIndexString = ReadFromConfig("ProfileIndex"); // Check if either no profile was found or the setting says that the last current profile didn't exist if (profileDropDown.Items.Count == 0) diff --git a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.UI.cs b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.UI.cs index 54a8e7d..c5a867c 100644 --- a/AM2RLauncher/AM2RLauncher/MainForm/MainForm.UI.cs +++ b/AM2RLauncher/AM2RLauncher/MainForm/MainForm.UI.cs @@ -118,7 +118,7 @@ namespace AM2RLauncher log.Info("Actual Launcher location: " + Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)); // Set the language to what User wanted or choose local language - string userLanguage = CrossPlatformOperations.ReadFromConfig("Language").ToLower(); + string userLanguage = ReadFromConfig("Language").ToLower(); if (!userLanguage.Equals("default")) Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.AllCultures).First(c => c.NativeName.ToLower().Contains(userLanguage)); @@ -179,14 +179,14 @@ namespace AM2RLauncher Icon = new Icon(1f, am2rIcon); Title = "AM2RLauncher " + VERSION + ": " + splash; MinimumSize = new Size(500, 400); - // TODO: for some reason, this sometimes doesn't work on Linux. Was reported at eto, stays here until its fixed - ClientSize = new Size(Int32.Parse(CrossPlatformOperations.ReadFromConfig("Width")), Int32.Parse(CrossPlatformOperations.ReadFromConfig("Height"))); + // TODO: for some reason, this doesn't work on Linux. Was reported at eto, stays here until its fixed + ClientSize = new Size(Int32.Parse(ReadFromConfig("Width")), Int32.Parse(ReadFromConfig("Height"))); if (ClientSize.Width < 500) ClientSize = new Size(500, ClientSize.Height); if (ClientSize.Height < 400) ClientSize = new Size(ClientSize.Width, 400); log.Info("Start the launcher with Size: " + ClientSize.Width + ", " + ClientSize.Height); - if (Boolean.Parse(CrossPlatformOperations.ReadFromConfig("IsMaximized"))) Maximize(); + if (Boolean.Parse(ReadFromConfig("IsMaximized"))) Maximize(); Drawable drawable = new Drawable { BackgroundColor = colBGNoAlpha }; @@ -398,7 +398,7 @@ namespace AM2RLauncher if (OS.IsUnix && !isInternetThere) changelogWebView = new WebView(); - //TODO: these clip on gtk, test on other platforms. maybe eto bug. + //TODO: these clip on gtk, Eto issue Label changelogNoConnectionLabel = new Label { Text = Text.NoInternetConnection, @@ -516,7 +516,7 @@ namespace AM2RLauncher languageDropDown.Items.AddRange(languageList); - var tmpLanguage = CrossPlatformOperations.ReadFromConfig("Language"); + var tmpLanguage = ReadFromConfig("Language"); languageDropDown.SelectedIndex = tmpLanguage == "Default" ? 0 : languageDropDown.Items.IndexOf(languageDropDown.Items.FirstOrDefault(x => x.Text.Equals(tmpLanguage))); if (languageDropDown.SelectedIndex == -1) @@ -528,7 +528,7 @@ namespace AM2RLauncher // autoUpdateAM2R checkbox autoUpdateAM2RCheck = new CheckBox { - Checked = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateAM2R")), + Checked = Boolean.Parse(ReadFromConfig("AutoUpdateAM2R")), Text = Text.AutoUpdateAM2R, TextColor = colGreen }; @@ -537,7 +537,7 @@ namespace AM2RLauncher // autoUpdateLauncher checkbox autoUpdateLauncherCheck = new CheckBox { - Checked = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher")), + Checked = Boolean.Parse(ReadFromConfig("AutoUpdateLauncher")), Text = Text.AutoUpdateLauncher, TextColor = colGreen }; @@ -545,7 +545,7 @@ namespace AM2RLauncher // HQ music, PC hqMusicPCCheck = new CheckBox { - Checked = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("MusicHQPC")), + Checked = Boolean.Parse(ReadFromConfig("MusicHQPC")), Text = Text.HighQualityPC, TextColor = colGreen }; @@ -553,7 +553,7 @@ namespace AM2RLauncher // HQ music, Android hqMusicAndroidCheck = new CheckBox { - Checked = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("MusicHQAndroid")), + Checked = Boolean.Parse(ReadFromConfig("MusicHQAndroid")), Text = Text.HighQualityAndroid, TextColor = colGreen }; @@ -561,7 +561,7 @@ namespace AM2RLauncher // Create game debug logs profileDebugLogCheck = new CheckBox { - Checked = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("ProfileDebugLog")), + Checked = Boolean.Parse(ReadFromConfig("ProfileDebugLog")), Text = Text.ProfileDebugCheckBox, TextColor = colGreen }; @@ -583,7 +583,7 @@ namespace AM2RLauncher { customEnvVarTextBox = new TextBox { - Text = CrossPlatformOperations.ReadFromConfig("CustomEnvVar"), + Text = ReadFromConfig("CustomEnvVar"), BackgroundColor = colBGNoAlpha, TextColor = colGreen }; @@ -605,7 +605,7 @@ namespace AM2RLauncher mirrorDropDown = new DropDown(); mirrorDropDown.Items.AddRange(mirrorDescriptionList); // As above, find a way to get this inside the dropDown definition - mirrorIndex = (Int32.Parse(CrossPlatformOperations.ReadFromConfig("MirrorIndex")) < mirrorDropDown.Items.Count) ? Int32.Parse(CrossPlatformOperations.ReadFromConfig("MirrorIndex")) + mirrorIndex = (Int32.Parse(ReadFromConfig("MirrorIndex")) < mirrorDropDown.Items.Count) ? Int32.Parse(ReadFromConfig("MirrorIndex")) : 0; mirrorDropDown.SelectedIndex = mirrorIndex; @@ -614,14 +614,14 @@ namespace AM2RLauncher // Custom mirror customMirrorCheck = new CheckBox { - Checked = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("CustomMirrorEnabled")), + Checked = Boolean.Parse(ReadFromConfig("CustomMirrorEnabled")), Text = Text.CustomMirrorCheck, TextColor = colGreen }; customMirrorTextBox = new TextBox { - Text = CrossPlatformOperations.ReadFromConfig("CustomMirrorText"), + Text = ReadFromConfig("CustomMirrorText"), BackgroundColor = colBGNoAlpha, TextColor = colGreen }; @@ -847,7 +847,7 @@ namespace AM2RLauncher private readonly Color colBGNoAlpha = Color.FromArgb(10, 10, 10); /// The black background color. // XORG can't display alpha anyway, and Wayland breaks with it. - // TODO: that sounds like an Eto bug. investigate, try to open eto issue. + // TODO: that sounds like an Eto issue. investigate, try to open eto issue. private readonly Color colBG = OS.IsLinux ? Color.FromArgb(10, 10, 10) : Color.FromArgb(10, 10, 10, 80); /// The lighter green color on hover. private readonly Color colBGHover = Color.FromArgb(17, 28, 13); diff --git a/AM2RLauncher/AM2RLauncherCore/XML/LauncherConfigXML.cs b/AM2RLauncher/AM2RLauncher/XML/LauncherConfigXML.cs similarity index 98% rename from AM2RLauncher/AM2RLauncherCore/XML/LauncherConfigXML.cs rename to AM2RLauncher/AM2RLauncher/XML/LauncherConfigXML.cs index a643562..c89d5be 100644 --- a/AM2RLauncher/AM2RLauncherCore/XML/LauncherConfigXML.cs +++ b/AM2RLauncher/AM2RLauncher/XML/LauncherConfigXML.cs @@ -2,9 +2,7 @@ using System.Linq; using System.Xml.Serialization; -namespace AM2RLauncher.Core.XML; - -//TODO: AM2RLauncher specific, should probably get moved. +namespace AM2RLauncher.XML; /// /// Class that handles how the Launcher settings are saved as XML. Only affects Linux diff --git a/AM2RLauncher/AM2RLauncherCore/CrossPlatformOperations.cs b/AM2RLauncher/AM2RLauncherCore/CrossPlatformOperations.cs index c45837e..b503fb1 100644 --- a/AM2RLauncher/AM2RLauncherCore/CrossPlatformOperations.cs +++ b/AM2RLauncher/AM2RLauncherCore/CrossPlatformOperations.cs @@ -5,7 +5,6 @@ using System.Configuration; using System.Diagnostics; using System.IO; using System.Reflection; -using System.Text.RegularExpressions; namespace AM2RLauncher.Core; @@ -39,14 +38,14 @@ public static class CrossPlatformOperations /// Linux: Will point to XDG_CONFIG_HOME/AM2RLauncher
/// Mac: Will point to ~/Library/Preferences/AM2RLauncher ///
- private static readonly string NIXLAUNCHERCONFIGPATH = OS.IsLinux ? (String.IsNullOrWhiteSpace(LINUXXDGCONFIG) ? NIXHOME + "/.config" + public static readonly string NIXLAUNCHERCONFIGPATH = OS.IsLinux ? (String.IsNullOrWhiteSpace(LINUXXDGCONFIG) ? NIXHOME + "/.config" : LINUXXDGCONFIG) + "/AM2RLauncher" : NIXHOME + "/Library/Preferences/AM2RLauncher"; /// /// Config file path for *nix based systems. Will be + "/config.xml". /// - private static readonly string NIXLAUNCHERCONFIGFILEPATH = NIXLAUNCHERCONFIGPATH + "/config.xml"; + public static readonly string NIXLAUNCHERCONFIGFILEPATH = NIXLAUNCHERCONFIGPATH + "/config.xml"; /// /// Current Path where the Launcher is located. For more info, check . @@ -90,125 +89,7 @@ public static class CrossPlatformOperations return new List(); } - /// - /// Reads the Launcher config file on the current Platform and returns the value for . - /// - /// The property to get the value from. - /// The value from as a string - public static string ReadFromConfig(string property) - { - log.Info($"Reading {property} from config."); - if (OS.IsWindows) - { - // We use the configuration manager in order to read `property` from the app.config and then return it - ConnectionStringSettings appConfig = ConfigurationManager.ConnectionStrings[property]; - if (appConfig == null) throw new ArgumentException("The property " + property + " could not be found."); - return appConfig.ConnectionString; - } - if (OS.IsUnix) - { - string launcherConfigPath = NIXLAUNCHERCONFIGPATH; - string launcherConfigFilePath = launcherConfigPath + "/config.xml"; - XML.LauncherConfigXML launcherConfig = new XML.LauncherConfigXML(); - - // If folder doesn't exist, create it and the config file - if (!Directory.Exists(launcherConfigPath) || !File.Exists(launcherConfigFilePath)) - { - Directory.CreateDirectory(launcherConfigPath); - File.WriteAllText(launcherConfigFilePath, XML.Serializer.Serialize(launcherConfig)); - } - - // Deserialize the config xml into launcherConfig - launcherConfig = XML.Serializer.Deserialize(File.ReadAllText(launcherConfigFilePath)); - - // This uses the indexer, which means, we can use the variable in order to get the property. Look at LauncherConfigXML for more info - return launcherConfig[property]?.ToString(); - } - log.Error(OS.Name + " has no config to read from!"); - return null; - } - - /// - /// Writes to in the Launcher Config file. - /// - /// The property whose value you want to change. - /// The value that will be written. - public static void WriteToConfig(string property, object value) - { - log.Info($"Writing {value} of type {value.GetType()} to {property} to config."); - if (OS.IsWindows) - { - // We use the configuration manager in order to read from the app.config, change the value and save it - Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); - if (appConfig == null) - throw new NullReferenceException("Could not find the Config file! Please make sure it exists!"); - ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)appConfig.GetSection("connectionStrings"); - if (connectionStringsSection?.ConnectionStrings[property]?.ConnectionString == null) - throw new ArgumentException("The property " + property + " could not be found."); - connectionStringsSection.ConnectionStrings[property].ConnectionString = value.ToString(); - appConfig.Save(); - ConfigurationManager.RefreshSection("connectionStrings"); - } - else if (OS.IsUnix) - { - string launcherConfigPath = NIXLAUNCHERCONFIGPATH; - string launcherConfigFilePath = NIXLAUNCHERCONFIGFILEPATH; - XML.LauncherConfigXML launcherConfig = new XML.LauncherConfigXML(); - - // If folder doesn't exist, create it and the config file - if (!Directory.Exists(launcherConfigPath) || !File.Exists(launcherConfigFilePath)) - { - Directory.CreateDirectory(launcherConfigPath); - File.WriteAllText(launcherConfigFilePath, XML.Serializer.Serialize(launcherConfig)); - } - // Deserialize the config xml into launcherConfig - launcherConfig = XML.Serializer.Deserialize(File.ReadAllText(launcherConfigFilePath)); - - // Uses indexer. Look at LauncherConfigXML for more info - launcherConfig[property] = value; - - // Serialize back into the file - File.WriteAllText(launcherConfigFilePath, XML.Serializer.Serialize(launcherConfig)); - } - else - log.Error(OS.Name + " has no config to write to!"); - } - - /// - /// When a Launcher update occurs that introduces new config properties, this method ensures that the old user config is copied over as much as possible. - /// - public static void CopyOldConfigToNewConfig() - { - if (OS.IsWindows) - { - string oldConfigPath = LAUNCHERNAME + ".oldCfg"; - string newConfigPath = LAUNCHERNAME + ".config"; - string oldConfigText = File.ReadAllText(oldConfigPath); - string newConfigText = File.ReadAllText(newConfigPath); - - Regex settingRegex = new Regex(""); - - MatchCollection oldMatch = settingRegex.Matches(oldConfigText); - MatchCollection newMatch = settingRegex.Matches(newConfigText); - - for (int i = 0; i < oldMatch.Count; i++) - newConfigText = newConfigText.Replace(newMatch[i].Value, oldMatch[i].Value); - - File.WriteAllText(newConfigPath, newConfigText); - - } - else if (OS.IsUnix) - { - string launcherConfigFilePath = NIXLAUNCHERCONFIGFILEPATH; - - // For some reason deserializing and saving back again works, not exactly sure why, but I'll take it - XML.LauncherConfigXML launcherConfig = XML.Serializer.Deserialize(File.ReadAllText(launcherConfigFilePath)); - File.WriteAllText(launcherConfigFilePath, XML.Serializer.Serialize(launcherConfig)); - } - else - log.Error(OS.Name + " has no config to transfer over!"); - } /// /// This open a website cross-platform.