Skip to content

Commit

Permalink
Refactor SettingsIo, move all File IO to SettingsIo
Browse files Browse the repository at this point in the history
Use SettingsIo from now on to load and save settings, as this will handle locating and saving in the settings directory for us. Added some more methods and XML documentation to help describe the code, as well as other refactoring to make it more suitable to bring to other apps.

Now the overhaul of the Settings handling is complete!
  • Loading branch information
JaykeBird committed Apr 18, 2023
1 parent 4764bae commit 66e7058
Show file tree
Hide file tree
Showing 5 changed files with 348 additions and 188 deletions.
68 changes: 11 additions & 57 deletions PathfinderJson/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,40 +101,17 @@ public static BitmapImage GetResourcesImage(string name, ColorScheme cs)

private void Application_Startup(object sender, StartupEventArgs e)
{
SettingsIo.SetupBaseDirectories(); // this does not create the actual settings directory, that is done a few lines later

(string? settingsDir, bool canUpdate) = SettingsIo.FindLatestSettings();
if (settingsDir == null || (SettingsIo.IsPortable && Directory.Exists(SettingsIo.SettingsDirectory)))
{
// settingsDir is null if no old settings directories could be found, so we'll just default to the standard directory
// otherwise, if this is a Portable app and the portable settings app already exists, just use the standard directory
settingsDir = SettingsIo.SettingsDirectory;
}

// now the actual settings directory is created (could not be created prior to FindLatestSettings to prevent a false positive)
Directory.CreateDirectory(SettingsIo.SettingsDirectory);

if (canUpdate)
// let's put this right at the top before any JSON deserialization occurs
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings
{
// settings stored in old directory, ask user to update
string pStr = SettingsIo.IsPortable ? "(or non-portable) " : "";
var result = MessageBox.Show($"Settings for a previous {pStr}version of PathfinderJson was located. Do you want to transfer these settings to this version?",
"Old Settings Found", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);

if (result == MessageBoxResult.Yes)
{
// transfer from old to new
foreach (string sff in Directory.GetFiles(settingsDir))
{
// TODO: add try-catch statements
File.Copy(sff, Path.Combine(SettingsIo.SettingsDirectory, Path.GetFileName(sff)), true);
}
}
} // otherwise, settings is in the standard location

string settingsFileName = Path.Combine(SettingsIo.SettingsDirectory, "settings.json");
DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
};

Settings = SettingsIo.LoadSettingsJson<Settings>(settingsFileName);
string settingsFileName = "settings.json";
string settingsFilePath = Path.Combine(SettingsIo.SettingsDirectory, settingsFileName);
// this one method does a lot of work behind the scenes to set up everything lol
Settings = SettingsIo.PrepareSettingsJson<Settings>();

if (Settings.UseStartupOptimization)
{
Expand All @@ -143,12 +120,6 @@ private void Application_Startup(object sender, StartupEventArgs e)
ProfileOptimization.StartProfile(VersionInt + "_Startup.profile");
}

Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings
{
DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
};

string file = "";

if (e.Args.Length > 0)
Expand All @@ -161,6 +132,7 @@ private void Application_Startup(object sender, StartupEventArgs e)

if (SystemParameters.HighContrast)
{
// if the system is in High Contrast, let's ask the user if they want PathfinderJson in High Contrast mode
if (Settings.HighContrastTheme == NO_HIGH_CONTRAST)
{
ColorScheme ncs;
Expand Down Expand Up @@ -212,25 +184,7 @@ private void Application_Startup(object sender, StartupEventArgs e)
}
}

try
{
Settings.Save(Path.Combine(SettingsIo.SettingsDirectory, "settings.json"));
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (System.Security.SecurityException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (IOException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
SettingsIo.SaveSettingsJson(Settings);
}
}

Expand Down
20 changes: 1 addition & 19 deletions PathfinderJson/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,25 +316,7 @@ void SaveSettings(bool updateFonts = false)
SaveEditorFontSettings();
}

try
{
App.Settings.Save(Path.Combine(SettingsIo.SettingsDirectory, "settings.json"));
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (System.Security.SecurityException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (IOException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
SettingsIo.SaveSettingsJson(App.Settings);
}

void ReloadSettings()
Expand Down
38 changes: 18 additions & 20 deletions PathfinderJson/Options.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace PathfinderJson
{
/// <summary>
/// Interaction logic for Options.xaml
/// A modal dialog that allows the end user to select and change options for PathfinderJson.
/// </summary>
public partial class Options : FlatWindow
{
Expand Down Expand Up @@ -185,6 +185,22 @@ void LoadSettings()
chkLineNumbers.IsChecked = s.EditorLineNumbers;
chkWordWrap.IsChecked = s.EditorWordWrap;

if (chkLineNumbers.IsChecked)
{
// <ColumnDefinition x:Name="colNum" Width="Auto" MinWidth="10" />
// <ColumnDefinition x: Name = "colBuff" Width = "2" />

colNum.Width = new GridLength(0, GridUnitType.Auto);
colNum.MinWidth = 10;
colBuff.Width = new GridLength(2);
}
else
{
colNum.Width = new GridLength(0, GridUnitType.Pixel);
colNum.MinWidth = 0;
colBuff.Width = new GridLength(0);
}

// Advanced options
chkUseOptimization.IsChecked = s.UseStartupOptimization;
}
Expand Down Expand Up @@ -277,25 +293,7 @@ void SaveSettings()

// ----------------------------------------
// finally, save the settings to a file
try
{
App.Settings.Save(Path.Combine(SettingsIo.SettingsDirectory, "settings.json"));
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (System.Security.SecurityException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (IOException)
{
MessageBox.Show("The settings file for PathfinderJson could not be saved. Please check the permissions for your AppData folder.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
SettingsIo.SaveSettingsJson(App.Settings);
}

void LoadEditorFontSettings(Settings s)
Expand Down
80 changes: 40 additions & 40 deletions PathfinderJson/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,46 +11,46 @@ namespace PathfinderJson
public class Settings
{

public static Settings LoadSettings(string filename)
{
try
{
using StreamReader file = File.OpenText(filename);
JsonSerializer serializer = new JsonSerializer();

Settings? ss = (Settings?)serializer.Deserialize(file, typeof(Settings));
if (ss == null) ss = new Settings();
return ss;
}
catch (JsonReaderException)
{
MessageBox.Show("The settings file for PathfinderJson was corrupted. PathfinderJson will continue with default settings.",
"Settings Error", MessageBoxButton.OK, MessageBoxImage.Warning);
Settings sn = new Settings();
sn.Save(filename); // exception handling not needed for these as calling function handles exceptions
return sn;
}
catch (FileNotFoundException)
{
Settings sn = new Settings();
sn.Save(filename); // exception handling not needed for these as calling function handles exceptions
return sn;
}
}

public void Save(string filename)
{
DirectoryInfo? di = Directory.GetParent(filename);

if (di != null && !di.Exists)
{
di.Create();
}

using StreamWriter file = new StreamWriter(filename, false, new UTF8Encoding(false));
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, this);
}
//public static Settings LoadSettings(string filename)
//{
// try
// {
// using StreamReader file = File.OpenText(filename);
// JsonSerializer serializer = new JsonSerializer();

// Settings? ss = (Settings?)serializer.Deserialize(file, typeof(Settings));
// if (ss == null) ss = new Settings();
// return ss;
// }
// catch (JsonReaderException)
// {
// MessageBox.Show("The settings file for PathfinderJson was corrupted. PathfinderJson will continue with default settings.",
// "Settings Error", MessageBoxButton.OK, MessageBoxImage.Warning);
// Settings sn = new Settings();
// sn.Save(filename); // exception handling not needed for these as calling function handles exceptions
// return sn;
// }
// catch (FileNotFoundException)
// {
// Settings sn = new Settings();
// sn.Save(filename); // exception handling not needed for these as calling function handles exceptions
// return sn;
// }
//}

//public void Save(string filename)
//{
// DirectoryInfo? di = Directory.GetParent(filename);

// if (di != null && !di.Exists)
// {
// di.Create();
// }

// using StreamWriter file = new StreamWriter(filename, false, new UTF8Encoding(false));
// JsonSerializer serializer = new JsonSerializer();
// serializer.Serialize(file, this);
//}

[JsonProperty("themeColor")]
public string ThemeColor { get; set; } = "CD853F";
Expand Down

0 comments on commit 66e7058

Please sign in to comment.