Move LauncherConfig out of Core

pull/32/head
Miepee 4 years ago
parent e4e1d3303b
commit c2fa4c27a9

@ -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));
/// <summary>
/// Performs the entire AM2RLauncher update procedure.
/// Performs the entire AM2RLauncher update procedure.
/// </summary>
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");

@ -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);
}
/// <summary>Gets called when <see cref="autoUpdateAM2RCheck"/> gets clicked and writes its new value to the config.</summary>
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);
}
/// <summary>Gets called when <see cref="autoUpdateLauncherCheck"/> gets clicked and writes its new value to the config.</summary>
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);
}
/// <summary>Gets called when <see cref="hqMusicPCCheck"/> gets clicked and writes its new value to the config.</summary>
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);
}
/// <summary>Gets called when <see cref="hqMusicAndroidCheck"/> gets clicked and writes its new value to the config.</summary>
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);
}
/// <summary>
@ -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);
}
/// <summary>Gets called when user selects a different item from <see cref="mirrorDropDown"/>.
@ -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

@ -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 = "";
}
/// <summary>
/// Reads the Launcher config file on the current Platform and returns the value for <paramref name="property"/>.
/// </summary>
/// <param name="property">The property to get the value from.</param>
/// <returns>The value from <paramref name="property"/> as a string</returns>
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<XML.LauncherConfigXML>(launcherConfig));
}
// Deserialize the config xml into launcherConfig
launcherConfig = Serializer.Deserialize<XML.LauncherConfigXML>(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;
}
/// <summary>
/// Writes <paramref name="value"/> to <paramref name="property"/> in the Launcher Config file.
/// </summary>
/// <param name="property">The property whose value you want to change.</param>
/// <param name="value">The value that will be written.</param>
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<XML.LauncherConfigXML>(launcherConfig));
}
// Deserialize the config xml into launcherConfig
launcherConfig = Serializer.Deserialize<XML.LauncherConfigXML>(File.ReadAllText(launcherConfigFilePath));
// Uses indexer. Look at LauncherConfigXML for more info
launcherConfig[property] = value;
// Serialize back into the file
File.WriteAllText(launcherConfigFilePath, Serializer.Serialize<XML.LauncherConfigXML>(launcherConfig));
}
else
log.Error(OS.Name + " has no config to write to!");
}
/// <summary>
/// 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.
/// </summary>
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("<add name=\".*\" />");
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<XML.LauncherConfigXML>(File.ReadAllText(launcherConfigFilePath));
File.WriteAllText(launcherConfigFilePath, Serializer.Serialize<XML.LauncherConfigXML>(launcherConfig));
}
else
log.Error(OS.Name + " has no config to transfer over!");
}
}
}

@ -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
}
/// <summary>
/// Sets the global <see cref="updateState"/> and then changes the state of <see cref="playButton"/> accordingly.
/// Sets the global <see cref="updateState"/> and then changes the state of <see cref="playButton"/> accordingly.
/// </summary>
/// <param name="state">The state that should be set to.</param>
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
}
/// <summary>
/// Sets the global <see cref="apkButtonState"/> and then changes the state of <see cref="apkButton"/> accordingly.
/// Sets the global <see cref="apkButtonState"/> and then changes the state of <see cref="apkButton"/> accordingly.
/// </summary>
/// <param name="state">The state that should be set to.</param>
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)

@ -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);
/// <summary>The black background color.</summary>
// 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);
/// <summary>The lighter green color on hover.</summary>
private readonly Color colBGHover = Color.FromArgb(17, 28, 13);

@ -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;
/// <summary>
/// Class that handles how the Launcher settings are saved as XML. Only affects Linux

@ -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 <br/>
/// Mac: Will point to ~/Library/Preferences/AM2RLauncher
/// </summary>
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";
/// <summary>
/// Config file path for *nix based systems. Will be <see cref="NIXLAUNCHERCONFIGPATH"/> + "/config.xml".
/// </summary>
private static readonly string NIXLAUNCHERCONFIGFILEPATH = NIXLAUNCHERCONFIGPATH + "/config.xml";
public static readonly string NIXLAUNCHERCONFIGFILEPATH = NIXLAUNCHERCONFIGPATH + "/config.xml";
/// <summary>
/// Current Path where the Launcher is located. For more info, check <see cref="GenerateCurrentPath"/>.
@ -90,125 +89,7 @@ public static class CrossPlatformOperations
return new List<string>();
}
/// <summary>
/// Reads the Launcher config file on the current Platform and returns the value for <paramref name="property"/>.
/// </summary>
/// <param name="property">The property to get the value from.</param>
/// <returns>The value from <paramref name="property"/> as a string</returns>
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<XML.LauncherConfigXML>(launcherConfig));
}
// Deserialize the config xml into launcherConfig
launcherConfig = XML.Serializer.Deserialize<XML.LauncherConfigXML>(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;
}
/// <summary>
/// Writes <paramref name="value"/> to <paramref name="property"/> in the Launcher Config file.
/// </summary>
/// <param name="property">The property whose value you want to change.</param>
/// <param name="value">The value that will be written.</param>
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<XML.LauncherConfigXML>(launcherConfig));
}
// Deserialize the config xml into launcherConfig
launcherConfig = XML.Serializer.Deserialize<XML.LauncherConfigXML>(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<XML.LauncherConfigXML>(launcherConfig));
}
else
log.Error(OS.Name + " has no config to write to!");
}
/// <summary>
/// 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.
/// </summary>
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("<add name=\".*\" />");
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<XML.LauncherConfigXML>(File.ReadAllText(launcherConfigFilePath));
File.WriteAllText(launcherConfigFilePath, XML.Serializer.Serialize<XML.LauncherConfigXML>(launcherConfig));
}
else
log.Error(OS.Name + " has no config to transfer over!");
}
/// <summary>
/// This open a website cross-platform.

Loading…
Cancel
Save