SongBrowserSettings.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Xml.Serialization;
  5. namespace SongBrowserPlugin
  6. {
  7. [Serializable]
  8. public enum SongSortMode
  9. {
  10. Default,
  11. Favorites,
  12. Original,
  13. }
  14. [Serializable]
  15. public class SongBrowserSettings
  16. {
  17. public SongSortMode sortMode = default(SongSortMode);
  18. public List<String> favorites;
  19. [NonSerialized]
  20. private static Logger Log = new Logger("SongBrowserPlugin-Settings");
  21. /// <summary>
  22. /// Constructor.
  23. /// </summary>
  24. public SongBrowserSettings()
  25. {
  26. favorites = new List<String>();
  27. }
  28. /// <summary>
  29. /// Helper to acquire settings path at runtime.
  30. /// </summary>
  31. /// <returns></returns>
  32. public static String SettingsPath()
  33. {
  34. return Path.Combine(Environment.CurrentDirectory, "song_browser_settings.xml");
  35. }
  36. /// <summary>
  37. /// Load the settings file for this plugin.
  38. /// If we fail to load return Default settings.
  39. /// </summary>
  40. /// <returns>SongBrowserSettings</returns>
  41. public static SongBrowserSettings Load()
  42. {
  43. Log.Debug("Load Song Browser Settings");
  44. SongBrowserSettings retVal = null;
  45. String settingsFilePath = SongBrowserSettings.SettingsPath();
  46. if (!File.Exists(settingsFilePath))
  47. {
  48. Log.Debug("Settings file does not exist, returning defaults: " + settingsFilePath);
  49. return new SongBrowserSettings();
  50. }
  51. // Deserialization from JSON
  52. FileStream fs = null;
  53. try
  54. {
  55. fs = File.OpenRead(settingsFilePath);
  56. XmlSerializer serializer = new XmlSerializer(typeof(SongBrowserSettings));
  57. retVal = (SongBrowserSettings)serializer.Deserialize(fs);
  58. Log.Debug("sortMode: " + retVal.sortMode);
  59. }
  60. catch (Exception e)
  61. {
  62. Log.Exception("Unable to deserialize song browser settings file: " + e.Message);
  63. // Return default settings
  64. retVal = new SongBrowserSettings();
  65. }
  66. finally
  67. {
  68. if (fs != null) { fs.Close(); }
  69. }
  70. return retVal;
  71. }
  72. /// <summary>
  73. /// Save this Settings insance to file.
  74. /// </summary>
  75. public void Save()
  76. {
  77. String settingsFilePath = SongBrowserSettings.SettingsPath();
  78. FileStream fs = new FileStream(settingsFilePath, FileMode.Create, FileAccess.Write);
  79. XmlSerializer serializer = new XmlSerializer(typeof(SongBrowserSettings));
  80. serializer.Serialize(fs, this);
  81. fs.Close();
  82. }
  83. }
  84. }