Settings.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using System.Windows.Media;
  5. using Newtonsoft.Json;
  6. using WpfWindowPlacement;
  7. namespace DesktopClock.Properties
  8. {
  9. public sealed class Settings : INotifyPropertyChanged
  10. {
  11. public static readonly string Path = "DesktopClock.settings";
  12. private static readonly Lazy<Settings> _default = new Lazy<Settings>(() => LoadOrCreate());
  13. private static readonly JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings
  14. {
  15. Formatting = Formatting.Indented
  16. };
  17. private Settings()
  18. {
  19. }
  20. public event PropertyChangedEventHandler PropertyChanged;
  21. public static Settings Default => _default.Value;
  22. #region "Properties"
  23. public WindowPlacement Placement { get; set; }
  24. public bool Topmost { get; set; } = true;
  25. public bool ShowInTaskbar { get; set; } = true;
  26. public int Height { get; set; } = 40;
  27. public string TimeZone { get; set; } = string.Empty;
  28. public string Format { get; set; } = "F";
  29. public string Title { get; set; } = string.Empty;
  30. public Color TitleColor { get; set; } = Colors.Blue;
  31. public Color BackgroundColor { get; set; } = Colors.White;
  32. public double Opacity { get; set; } = 0.90;
  33. public Color TextColor { get; set; } = Colors.Black;
  34. public string FontFamily { get; set; } = "Arial";
  35. public int CornerRadius { get; set; } = 2;
  36. public DateTimeOffset DateToCountdownTo { get; set; } = DateTimeOffset.MinValue;
  37. #endregion "Properties"
  38. /// <summary>
  39. /// Saves to the default path in JSON format.
  40. /// </summary>
  41. public void Save()
  42. {
  43. using (var fileStream = new FileStream(Path, FileMode.Create))
  44. using (var streamWriter = new StreamWriter(fileStream))
  45. using (var jsonWriter = new JsonTextWriter(streamWriter))
  46. JsonSerializer.Create(_jsonSerializerSettings).Serialize(jsonWriter, this);
  47. }
  48. /// <summary>
  49. /// Loads from the default path in JSON format.
  50. /// </summary>
  51. private static Settings Load()
  52. {
  53. using (var fileStream = new FileStream(Path, FileMode.Open))
  54. using (var streamReader = new StreamReader(fileStream))
  55. using (var jsonReader = new JsonTextReader(streamReader))
  56. return JsonSerializer.Create(_jsonSerializerSettings).Deserialize<Settings>(jsonReader);
  57. }
  58. /// <summary>
  59. /// Loads from the default path or return a new instance if it fails.
  60. /// </summary>
  61. private static Settings LoadOrCreate()
  62. {
  63. try
  64. {
  65. return Load();
  66. }
  67. catch
  68. {
  69. return new Settings();
  70. }
  71. }
  72. }
  73. }