ConfigFile.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. /// <summary>
  17. /// All config entries inside
  18. /// </summary>
  19. protected Dictionary<ConfigDefinition, ConfigEntry> Entries { get; } = new Dictionary<ConfigDefinition, ConfigEntry>();
  20. /// <summary>
  21. /// Create a list with all config entries inside of this config file.
  22. /// </summary>
  23. [Obsolete("Use GetConfigEntries instead")]
  24. public ReadOnlyCollection<ConfigDefinition> ConfigDefinitions => Entries.Keys.ToList().AsReadOnly();
  25. /// <summary>
  26. /// Create an array with all config entries inside of this config file. Should be only used for metadata purposes.
  27. /// If you want to access and modify an existing setting then use <see cref="Wrap{T}(ConfigDefinition,T,ConfigDescription)"/>
  28. /// instead with no description.
  29. /// </summary>
  30. public ConfigEntry[] GetConfigEntries() => Entries.Values.ToArray();
  31. /// <summary>
  32. /// Full path to the config file. The file might not exist until a setting is added and changed, or <see cref="Save"/> is called.
  33. /// </summary>
  34. public string ConfigFilePath { get; }
  35. /// <summary>
  36. /// If enabled, writes the config to disk every time a value is set.
  37. /// If disabled, you have to manually use <see cref="Save"/> or the changes will be lost!
  38. /// </summary>
  39. public bool SaveOnConfigSet { get; set; } = true;
  40. /// <summary>
  41. /// Create a new config file at the specified config path.
  42. /// </summary>
  43. /// <param name="configPath">Full path to a file that contains settings. The file will be created as needed.</param>
  44. /// <param name="saveOnInit">If the config file/directory doesn't exist, create it immediately.</param>
  45. public ConfigFile(string configPath, bool saveOnInit)
  46. {
  47. if (configPath == null) throw new ArgumentNullException(nameof(configPath));
  48. configPath = Path.GetFullPath(configPath);
  49. ConfigFilePath = configPath;
  50. if (File.Exists(ConfigFilePath))
  51. {
  52. Reload();
  53. }
  54. else if (saveOnInit)
  55. {
  56. Save();
  57. }
  58. StartWatching();
  59. }
  60. #region Save/Load
  61. private readonly object _ioLock = new object();
  62. /// <summary>
  63. /// Reloads the config from disk. Unsaved changes are lost.
  64. /// </summary>
  65. public void Reload()
  66. {
  67. lock (_ioLock)
  68. {
  69. string currentSection = string.Empty;
  70. foreach (string rawLine in File.ReadAllLines(ConfigFilePath))
  71. {
  72. string line = rawLine.Trim();
  73. if (line.StartsWith("#")) //comment
  74. continue;
  75. if (line.StartsWith("[") && line.EndsWith("]")) //section
  76. {
  77. currentSection = line.Substring(1, line.Length - 2);
  78. continue;
  79. }
  80. string[] split = line.Split('='); //actual config line
  81. if (split.Length != 2)
  82. continue; //empty/invalid line
  83. string currentKey = split[0].Trim();
  84. string currentValue = split[1].Trim();
  85. var definition = new ConfigDefinition(currentSection, currentKey);
  86. Entries.TryGetValue(definition, out ConfigEntry entry);
  87. if (entry == null)
  88. {
  89. entry = new ConfigEntry(this, definition);
  90. Entries[definition] = entry;
  91. }
  92. entry.SetSerializedValue(currentValue, true, this);
  93. }
  94. }
  95. OnConfigReloaded();
  96. }
  97. /// <summary>
  98. /// Writes the config to disk.
  99. /// </summary>
  100. public void Save()
  101. {
  102. lock (_ioLock)
  103. {
  104. StopWatching();
  105. string directoryName = Path.GetDirectoryName(ConfigFilePath);
  106. if (directoryName != null) Directory.CreateDirectory(directoryName);
  107. using (var writer = new StreamWriter(File.Create(ConfigFilePath), Encoding.UTF8))
  108. {
  109. foreach (var sectionKv in Entries.GroupBy(x => x.Key.Section).OrderBy(x => x.Key))
  110. {
  111. // Section heading
  112. writer.WriteLine($"[{sectionKv.Key}]");
  113. foreach (var configEntry in sectionKv.Select(x => x.Value))
  114. {
  115. writer.WriteLine();
  116. configEntry.WriteDescription(writer);
  117. writer.WriteLine($"{configEntry.Definition.Key} = {configEntry.GetSerializedValue()}");
  118. }
  119. writer.WriteLine();
  120. }
  121. }
  122. StartWatching();
  123. }
  124. }
  125. #endregion
  126. #region Wraps
  127. /// <summary>
  128. /// Create a new setting or access one of the existing ones. The setting is saved to drive and loaded automatically.
  129. /// If you are the creator of the setting, provide a ConfigDescription object to give user information about the setting.
  130. /// If you are using a setting created by another plugin/class, do not provide any ConfigDescription.
  131. /// </summary>
  132. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  133. /// <param name="configDefinition">Section and Key of the setting.</param>
  134. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  135. /// <param name="configDescription">Description of the setting shown to the user.</param>
  136. /// <returns></returns>
  137. public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
  138. {
  139. if (!TomlTypeConverter.CanConvert(typeof(T)))
  140. throw new ArgumentException($"Type {typeof(T)} is not supported by the config system. Supported types: {string.Join(", ", TomlTypeConverter.GetSupportedTypes().Select(x => x.Name).ToArray())}");
  141. Entries.TryGetValue(configDefinition, out var entry);
  142. if (entry == null)
  143. {
  144. entry = new ConfigEntry(this, configDefinition, typeof(T), defaultValue);
  145. Entries[configDefinition] = entry;
  146. }
  147. else
  148. {
  149. entry.SetTypeAndDefaultValue(typeof(T), defaultValue, !Equals(defaultValue, default(T)));
  150. }
  151. if (configDescription != null)
  152. {
  153. if (entry.Description != null)
  154. 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.");
  155. entry.Description = configDescription;
  156. }
  157. return new ConfigWrapper<T>(entry);
  158. }
  159. /// <summary>
  160. /// Create a new setting or access one of the existing ones. The setting is saved to drive and loaded automatically.
  161. /// If you are the creator of the setting, provide a ConfigDescription object to give user information about the setting.
  162. /// If you are using a setting created by another plugin/class, do not provide any ConfigDescription.
  163. /// </summary>
  164. [Obsolete("Use other Wrap overloads instead")]
  165. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  166. => Wrap(new ConfigDefinition(section, key), defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description));
  167. /// <summary>
  168. /// Create a new setting or access one of the existing ones. The setting is saved to drive and loaded automatically.
  169. /// If you are the creator of the setting, provide a ConfigDescription object to give user information about the setting.
  170. /// If you are using a setting created by another plugin/class, do not provide any ConfigDescription.
  171. /// </summary>
  172. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  173. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  174. /// <param name="key">Name of the setting.</param>
  175. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  176. /// <param name="configDescription">Description of the setting shown to the user.</param>
  177. /// <returns></returns>
  178. public ConfigWrapper<T> Wrap<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  179. => Wrap(new ConfigDefinition(section, key), defaultValue, configDescription);
  180. #endregion
  181. #region Events
  182. /// <summary>
  183. /// An event that is fired every time the config is reloaded.
  184. /// </summary>
  185. public event EventHandler ConfigReloaded;
  186. /// <summary>
  187. /// Fired when one of the settings is changed.
  188. /// </summary>
  189. public event EventHandler<SettingChangedEventArgs> SettingChanged;
  190. internal void OnSettingChanged(object sender, ConfigEntry changedEntry)
  191. {
  192. if (changedEntry == null) throw new ArgumentNullException(nameof(changedEntry));
  193. if (SettingChanged != null)
  194. {
  195. var args = new SettingChangedEventArgs(changedEntry);
  196. foreach (var callback in SettingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
  197. {
  198. try
  199. {
  200. callback(sender, args);
  201. }
  202. catch (Exception e)
  203. {
  204. Logger.Log(LogLevel.Error, e);
  205. }
  206. }
  207. }
  208. // Check sender to prevent infinite loops
  209. // todo batching / async?
  210. if (sender != this && SaveOnConfigSet)
  211. Save();
  212. }
  213. private void OnConfigReloaded()
  214. {
  215. if (ConfigReloaded != null)
  216. {
  217. foreach (var callback in ConfigReloaded.GetInvocationList().Cast<EventHandler>())
  218. {
  219. try
  220. {
  221. callback(this, EventArgs.Empty);
  222. }
  223. catch (Exception e)
  224. {
  225. Logger.Log(LogLevel.Error, e);
  226. }
  227. }
  228. }
  229. }
  230. #endregion
  231. #region File watcher
  232. private FileSystemWatcher _watcher;
  233. /// <summary>
  234. /// Start watching the config file on disk for changes.
  235. /// </summary>
  236. public void StartWatching()
  237. {
  238. lock (_ioLock)
  239. {
  240. if (_watcher != null) return;
  241. _watcher = new FileSystemWatcher
  242. {
  243. Path = Path.GetDirectoryName(ConfigFilePath) ?? throw new ArgumentException("Invalid config path"),
  244. Filter = Path.GetFileName(ConfigFilePath),
  245. IncludeSubdirectories = false,
  246. NotifyFilter = NotifyFilters.LastWrite,
  247. EnableRaisingEvents = true
  248. };
  249. _watcher.Changed += (sender, args) => Reload();
  250. }
  251. }
  252. /// <summary>
  253. /// Stop watching the config file on disk for changes.
  254. /// </summary>
  255. public void StopWatching()
  256. {
  257. lock (_ioLock)
  258. {
  259. if (_watcher != null)
  260. {
  261. _watcher.EnableRaisingEvents = false;
  262. _watcher.Dispose();
  263. _watcher = null;
  264. }
  265. }
  266. }
  267. /// <inheritdoc />
  268. ~ConfigFile()
  269. {
  270. StopWatching();
  271. }
  272. #endregion
  273. }
  274. }