ConfigFile.cs 10 KB

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