ConfigFile.cs 7.2 KB

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