ConfigFile.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using BepInEx.Logging;
  8. namespace BepInEx.Configuration
  9. {
  10. /// <summary>
  11. /// A helper class to handle persistent data.
  12. /// </summary>
  13. public class ConfigFile
  14. {
  15. internal static ConfigFile CoreConfig { get; } = new ConfigFile(Paths.BepInExConfigPath, true);
  16. protected Dictionary<ConfigDefinition, ConfigEntry> Entries { get; } = new Dictionary<ConfigDefinition, ConfigEntry>();
  17. [Obsolete("Use ConfigEntries instead")]
  18. public ReadOnlyCollection<ConfigDefinition> ConfigDefinitions => Entries.Keys.ToList().AsReadOnly();
  19. public ReadOnlyCollection<ConfigEntry> ConfigEntries => Entries.Values.ToList().AsReadOnly();
  20. public string ConfigFilePath { get; }
  21. /// <summary>
  22. /// If enabled, writes the config to disk every time a value is set. If disabled, you have to manually save or the changes will be lost!
  23. /// </summary>
  24. public bool SaveOnConfigSet { get; set; } = true;
  25. public ConfigFile(string configPath, bool saveOnInit)
  26. {
  27. if (configPath == null) throw new ArgumentNullException(nameof(configPath));
  28. configPath = Path.GetFullPath(configPath);
  29. ConfigFilePath = configPath;
  30. if (File.Exists(ConfigFilePath))
  31. {
  32. Reload();
  33. }
  34. else if (saveOnInit)
  35. {
  36. Save();
  37. }
  38. StartWatching();
  39. }
  40. #region Save/Load
  41. private readonly object _ioLock = new object();
  42. /// <summary>
  43. /// Reloads the config from disk. Unsaved changes are lost.
  44. /// </summary>
  45. public void Reload()
  46. {
  47. lock (_ioLock)
  48. {
  49. string currentSection = string.Empty;
  50. foreach (string rawLine in File.ReadAllLines(ConfigFilePath))
  51. {
  52. string line = rawLine.Trim();
  53. if (line.StartsWith("#")) //comment
  54. continue;
  55. if (line.StartsWith("[") && line.EndsWith("]")) //section
  56. {
  57. currentSection = line.Substring(1, line.Length - 2);
  58. continue;
  59. }
  60. string[] split = line.Split('='); //actual config line
  61. if (split.Length != 2)
  62. continue; //empty/invalid line
  63. string currentKey = split[0].Trim();
  64. string currentValue = split[1].Trim();
  65. var definition = new ConfigDefinition(currentSection, currentKey);
  66. Entries.TryGetValue(definition, out ConfigEntry entry);
  67. if (entry == null)
  68. {
  69. entry = new ConfigEntry(this, definition);
  70. Entries[definition] = entry;
  71. }
  72. entry.SetSerializedValue(currentValue, true, this);
  73. }
  74. }
  75. OnConfigReloaded();
  76. }
  77. /// <summary>
  78. /// Writes the config to disk.
  79. /// </summary>
  80. public void Save()
  81. {
  82. lock (_ioLock)
  83. {
  84. StopWatching();
  85. string directoryName = Path.GetDirectoryName(ConfigFilePath);
  86. if (directoryName != null) Directory.CreateDirectory(directoryName);
  87. using (var writer = new StreamWriter(File.Create(ConfigFilePath), Encoding.UTF8))
  88. {
  89. foreach (var sectionKv in Entries.GroupBy(x => x.Key.Section).OrderBy(x => x.Key))
  90. {
  91. // Section heading
  92. writer.WriteLine($"[{sectionKv.Key}]");
  93. foreach (var configEntry in sectionKv.Select(x => x.Value))
  94. {
  95. writer.WriteLine();
  96. configEntry.WriteDescription(writer);
  97. writer.WriteLine($"{configEntry.Definition.Key} = {configEntry.GetSerializedValue()}");
  98. }
  99. writer.WriteLine();
  100. }
  101. }
  102. StartWatching();
  103. }
  104. }
  105. #endregion
  106. #region Wraps
  107. public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
  108. {
  109. if (!TomlTypeConverter.CanConvert(typeof(T)))
  110. throw new ArgumentException($"Type {typeof(T)} is not supported by the config system. Supported types: {string.Join(", ", TomlTypeConverter.GetSupportedTypes().Select(x => x.Name).ToArray())}");
  111. Entries.TryGetValue(configDefinition, out var entry);
  112. if (entry == null)
  113. {
  114. entry = new ConfigEntry(this, configDefinition, typeof(T), defaultValue);
  115. Entries[configDefinition] = entry;
  116. }
  117. else
  118. {
  119. entry.SetTypeAndDefaultValue(typeof(T), defaultValue, !Equals(defaultValue, default(T)));
  120. }
  121. if (configDescription != null)
  122. {
  123. if (entry.Description != null)
  124. Logger.Log(LogLevel.Warning, $"Tried to add configDescription to setting {configDefinition} when it already had one defined. Only add configDescription once or a random one will be used.");
  125. entry.Description = configDescription;
  126. }
  127. return new ConfigWrapper<T>(entry);
  128. }
  129. [Obsolete("Use other Wrap overloads instead")]
  130. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  131. => Wrap(new ConfigDefinition(section, key), defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description));
  132. public ConfigWrapper<T> Wrap<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  133. => Wrap(new ConfigDefinition(section, key), defaultValue, configDescription);
  134. #endregion
  135. #region Events
  136. /// <summary>
  137. /// An event that is fired every time the config is reloaded.
  138. /// </summary>
  139. public event EventHandler ConfigReloaded;
  140. /// <summary>
  141. /// Fired when one of the settings is changed.
  142. /// </summary>
  143. public event EventHandler<SettingChangedEventArgs> SettingChanged;
  144. protected internal void OnSettingChanged(object sender, ConfigEntry changedEntry)
  145. {
  146. if (changedEntry == null) throw new ArgumentNullException(nameof(changedEntry));
  147. if (SettingChanged != null)
  148. {
  149. var args = new SettingChangedEventArgs(changedEntry);
  150. foreach (var callback in SettingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
  151. {
  152. try
  153. {
  154. callback(sender, args);
  155. }
  156. catch (Exception e)
  157. {
  158. Logger.Log(LogLevel.Error, e);
  159. }
  160. }
  161. }
  162. // todo better way to prevent write loop? maybe do some caching?
  163. if (sender != this && SaveOnConfigSet)
  164. Save();
  165. }
  166. protected void OnConfigReloaded()
  167. {
  168. if (ConfigReloaded != null)
  169. {
  170. foreach (var callback in ConfigReloaded.GetInvocationList().Cast<EventHandler>())
  171. {
  172. try
  173. {
  174. callback(this, EventArgs.Empty);
  175. }
  176. catch (Exception e)
  177. {
  178. Logger.Log(LogLevel.Error, e);
  179. }
  180. }
  181. }
  182. }
  183. #endregion
  184. #region File watcher
  185. private FileSystemWatcher _watcher;
  186. /// <summary>
  187. /// Start watching the config file on disk for changes.
  188. /// </summary>
  189. public void StartWatching()
  190. {
  191. lock (_ioLock)
  192. {
  193. if (_watcher != null) return;
  194. _watcher = new FileSystemWatcher
  195. {
  196. Path = Path.GetDirectoryName(ConfigFilePath) ?? throw new ArgumentException("Invalid config path"),
  197. Filter = Path.GetFileName(ConfigFilePath),
  198. IncludeSubdirectories = false,
  199. NotifyFilter = NotifyFilters.LastWrite,
  200. EnableRaisingEvents = true
  201. };
  202. _watcher.Changed += (sender, args) => Reload();
  203. }
  204. }
  205. /// <summary>
  206. /// Stop watching the config file on disk for changes.
  207. /// </summary>
  208. public void StopWatching()
  209. {
  210. lock (_ioLock)
  211. {
  212. _watcher?.Dispose();
  213. _watcher = null;
  214. }
  215. }
  216. ~ConfigFile()
  217. {
  218. StopWatching();
  219. }
  220. #endregion
  221. }
  222. }