try not to crash when size of arrays in config file changes

This commit is contained in:
zeromus 2012-03-24 17:47:52 +00:00
parent 96fc783107
commit 0bb9f65038
3 changed files with 26 additions and 5 deletions

View File

@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Newtonsoft.Json;
@ -7,7 +8,7 @@ namespace BizHawk.MultiClient
{
public static class ConfigService
{
public static T Load<T>(string filepath) where T : new()
public static T Load<T>(string filepath, T currentConfig) where T : new()
{
T config = new T();
@ -22,9 +23,29 @@ namespace BizHawk.MultiClient
config = (T)s.Deserialize(r, typeof(T));
}
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
catch (Exception e) { MessageBox.Show(e.ToString()); }
if (config == null) return new T();
else return config;
//patch up arrays in the config with the minimum number of things
foreach(var fi in typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public))
if (fi.FieldType.IsArray)
{
Array aold = fi.GetValue(currentConfig) as Array;
Array anew = fi.GetValue(config) as Array;
if (aold.Length == anew.Length) continue;
//create an array of the right size
Array acreate = Array.CreateInstance(fi.FieldType.GetElementType(), Math.Max(aold.Length,anew.Length));
//copy the old values in, (presumably the defaults), and then copy the new ones on top
Array.Copy(aold, acreate, Math.Min(aold.Length,acreate.Length));
Array.Copy(anew, acreate, Math.Min(anew.Length, acreate.Length));
//stash it into the config struct
fi.SetValue(config, acreate);
}
return config;
}
public static void Save(string filepath, object config)

View File

@ -1126,7 +1126,7 @@ namespace BizHawk.MultiClient
private void loadConfigToolStripMenuItem_Click(object sender, EventArgs e)
{
Global.Config = ConfigService.Load<Config>(PathManager.DefaultIniPath);
Global.Config = ConfigService.Load<Config>(PathManager.DefaultIniPath, Global.Config);
Global.RenderPanel.AddMessage("Saved loaded");
}

View File

@ -16,7 +16,7 @@ namespace BizHawk.MultiClient
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Global.Config = ConfigService.Load<Config>(PathManager.DefaultIniPath);
Global.Config = ConfigService.Load<Config>(PathManager.DefaultIniPath, new Config());
#if WINDOWS
try { Global.DSound = new DirectSound(); }