ConfigFile.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. if (configDescription.AcceptableValues != null)
  165. {
  166. var genericArguments = configDescription.AcceptableValues.GetType().GetGenericArguments();
  167. if (genericArguments.Length > 0 && genericArguments[0] != typeof(T))
  168. throw new ArgumentException("AcceptableValues has a different type than the setting type", nameof(configDefinition));
  169. }
  170. entry.SetDescription(configDescription);
  171. }
  172. return new ConfigWrapper<T>(entry);
  173. }
  174. /// <summary>
  175. /// Create a new setting or access one of the existing ones. The setting is saved to drive and loaded automatically.
  176. /// If you are the creator of the setting, provide a ConfigDescription object to give user information about the setting.
  177. /// If you are using a setting created by another plugin/class, do not provide any ConfigDescription.
  178. /// </summary>
  179. [Obsolete("Use other Wrap overloads instead")]
  180. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  181. => Wrap(new ConfigDefinition(section, key), defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description));
  182. /// <summary>
  183. /// Create a new setting or access one of the existing ones. The setting is saved to drive and loaded automatically.
  184. /// If you are the creator of the setting, provide a ConfigDescription object to give user information about the setting.
  185. /// If you are using a setting created by another plugin/class, do not provide any ConfigDescription.
  186. /// </summary>
  187. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  188. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  189. /// <param name="key">Name of the setting.</param>
  190. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  191. /// <param name="configDescription">Description of the setting shown to the user.</param>
  192. /// <returns></returns>
  193. public ConfigWrapper<T> Wrap<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  194. => Wrap(new ConfigDefinition(section, key), defaultValue, configDescription);
  195. #endregion
  196. #region Events
  197. /// <summary>
  198. /// An event that is fired every time the config is reloaded.
  199. /// </summary>
  200. public event EventHandler ConfigReloaded;
  201. /// <summary>
  202. /// Fired when one of the settings is changed.
  203. /// </summary>
  204. public event EventHandler<SettingChangedEventArgs> SettingChanged;
  205. internal void OnSettingChanged(object sender, ConfigEntry changedEntry)
  206. {
  207. if (changedEntry == null) throw new ArgumentNullException(nameof(changedEntry));
  208. if (SettingChanged != null)
  209. {
  210. var args = new SettingChangedEventArgs(changedEntry);
  211. foreach (var callback in SettingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
  212. {
  213. try
  214. {
  215. callback(sender, args);
  216. }
  217. catch (Exception e)
  218. {
  219. Logger.Log(LogLevel.Error, e);
  220. }
  221. }
  222. }
  223. // Check sender to prevent infinite loops
  224. // todo batching / async?
  225. if (sender != this && SaveOnConfigSet)
  226. Save();
  227. }
  228. private void OnConfigReloaded()
  229. {
  230. if (ConfigReloaded != null)
  231. {
  232. foreach (var callback in ConfigReloaded.GetInvocationList().Cast<EventHandler>())
  233. {
  234. try
  235. {
  236. callback(this, EventArgs.Empty);
  237. }
  238. catch (Exception e)
  239. {
  240. Logger.Log(LogLevel.Error, e);
  241. }
  242. }
  243. }
  244. }
  245. #endregion
  246. #region File watcher
  247. private FileSystemWatcher _watcher;
  248. /// <summary>
  249. /// Start watching the config file on disk for changes.
  250. /// </summary>
  251. public void StartWatching()
  252. {
  253. lock (_ioLock)
  254. {
  255. if (_watcher != null) return;
  256. _watcher = new FileSystemWatcher
  257. {
  258. Path = Path.GetDirectoryName(ConfigFilePath) ?? throw new ArgumentException("Invalid config path"),
  259. Filter = Path.GetFileName(ConfigFilePath),
  260. IncludeSubdirectories = false,
  261. NotifyFilter = NotifyFilters.LastWrite,
  262. EnableRaisingEvents = true
  263. };
  264. _watcher.Changed += (sender, args) => Reload();
  265. }
  266. }
  267. /// <summary>
  268. /// Stop watching the config file on disk for changes.
  269. /// </summary>
  270. public void StopWatching()
  271. {
  272. lock (_ioLock)
  273. {
  274. if (_watcher != null)
  275. {
  276. _watcher.EnableRaisingEvents = false;
  277. _watcher.Dispose();
  278. _watcher = null;
  279. }
  280. }
  281. }
  282. /// <inheritdoc />
  283. ~ConfigFile()
  284. {
  285. StopWatching();
  286. }
  287. #endregion
  288. }
  289. }