ConfigFile.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using BepInEx.Logging;
  9. namespace BepInEx.Configuration
  10. {
  11. /// <summary>
  12. /// A helper class to handle persistent data. All public methods are thread-safe.
  13. /// </summary>
  14. public class ConfigFile : IDictionary<ConfigDefinition, ConfigEntryBase>
  15. {
  16. private readonly BepInPlugin _ownerMetadata;
  17. internal static ConfigFile CoreConfig { get; } = new ConfigFile(Paths.BepInExConfigPath, true);
  18. /// <summary>
  19. /// All config entries inside
  20. /// </summary>
  21. protected Dictionary<ConfigDefinition, ConfigEntryBase> Entries { get; } = new Dictionary<ConfigDefinition, ConfigEntryBase>();
  22. private Dictionary<ConfigDefinition, string> OrphanedEntries { get; } = new Dictionary<ConfigDefinition, string>();
  23. /// <summary>
  24. /// Create a list with all config entries inside of this config file.
  25. /// </summary>
  26. [Obsolete("Use Keys instead")]
  27. public ReadOnlyCollection<ConfigDefinition> ConfigDefinitions
  28. {
  29. get
  30. {
  31. lock (_ioLock)
  32. {
  33. return Entries.Keys.ToList().AsReadOnly();
  34. }
  35. }
  36. }
  37. /// <summary>
  38. /// Full path to the config file. The file might not exist until a setting is added and changed, or <see cref="Save"/> is called.
  39. /// </summary>
  40. public string ConfigFilePath { get; }
  41. /// <summary>
  42. /// If enabled, writes the config to disk every time a value is set.
  43. /// If disabled, you have to manually use <see cref="Save"/> or the changes will be lost!
  44. /// </summary>
  45. public bool SaveOnConfigSet { get; set; } = true;
  46. /// <inheritdoc cref="ConfigFile(string, bool, BepInPlugin)"/>
  47. public ConfigFile(string configPath, bool saveOnInit) : this(configPath, saveOnInit, null) { }
  48. /// <summary>
  49. /// Create a new config file at the specified config path.
  50. /// </summary>
  51. /// <param name="configPath">Full path to a file that contains settings. The file will be created as needed.</param>
  52. /// <param name="saveOnInit">If the config file/directory doesn't exist, create it immediately.</param>
  53. /// <param name="ownerMetadata">Information about the plugin that owns this setting file.</param>
  54. public ConfigFile(string configPath, bool saveOnInit, BepInPlugin ownerMetadata)
  55. {
  56. _ownerMetadata = ownerMetadata;
  57. if (configPath == null) throw new ArgumentNullException(nameof(configPath));
  58. configPath = Path.GetFullPath(configPath);
  59. ConfigFilePath = configPath;
  60. if (File.Exists(ConfigFilePath))
  61. {
  62. Reload();
  63. }
  64. else if (saveOnInit)
  65. {
  66. Save();
  67. }
  68. }
  69. #region Save/Load
  70. private readonly object _ioLock = new object();
  71. /// <summary>
  72. /// Reloads the config from disk. Unsaved changes are lost.
  73. /// </summary>
  74. public void Reload()
  75. {
  76. lock (_ioLock)
  77. {
  78. OrphanedEntries.Clear();
  79. string currentSection = string.Empty;
  80. foreach (string rawLine in File.ReadAllLines(ConfigFilePath))
  81. {
  82. string line = rawLine.Trim();
  83. if (line.StartsWith("#")) //comment
  84. continue;
  85. if (line.StartsWith("[") && line.EndsWith("]")) //section
  86. {
  87. currentSection = line.Substring(1, line.Length - 2);
  88. continue;
  89. }
  90. string[] split = line.Split('='); //actual config line
  91. if (split.Length != 2)
  92. continue; //empty/invalid line
  93. string currentKey = split[0].Trim();
  94. string currentValue = split[1].Trim();
  95. var definition = new ConfigDefinition(currentSection, currentKey);
  96. Entries.TryGetValue(definition, out ConfigEntryBase entry);
  97. if (entry != null)
  98. entry.SetSerializedValue(currentValue);
  99. else
  100. OrphanedEntries[definition] = currentValue;
  101. }
  102. }
  103. OnConfigReloaded();
  104. }
  105. /// <summary>
  106. /// Writes the config to disk.
  107. /// </summary>
  108. public void Save()
  109. {
  110. lock (_ioLock)
  111. {
  112. string directoryName = Path.GetDirectoryName(ConfigFilePath);
  113. if (directoryName != null) Directory.CreateDirectory(directoryName);
  114. using (var writer = new StreamWriter(File.Create(ConfigFilePath), Encoding.UTF8))
  115. {
  116. if (_ownerMetadata != null)
  117. {
  118. writer.WriteLine($"## Settings file was created by plugin {_ownerMetadata.Name} v{_ownerMetadata.Version}");
  119. writer.WriteLine($"## Plugin GUID: {_ownerMetadata.GUID}");
  120. writer.WriteLine();
  121. }
  122. var allConfigEntries = Entries.Select(x => new { x.Key, entry = x.Value, value = x.Value.GetSerializedValue() })
  123. .Concat(OrphanedEntries.Select(x => new { x.Key, entry = (ConfigEntryBase)null, value = x.Value }));
  124. foreach (var sectionKv in allConfigEntries.GroupBy(x => x.Key.Section).OrderBy(x => x.Key))
  125. {
  126. // Section heading
  127. writer.WriteLine($"[{sectionKv.Key}]");
  128. foreach (var configEntry in sectionKv)
  129. {
  130. writer.WriteLine();
  131. configEntry.entry?.WriteDescription(writer);
  132. writer.WriteLine($"{configEntry.Key.Key} = {configEntry.value}");
  133. }
  134. writer.WriteLine();
  135. }
  136. }
  137. }
  138. }
  139. #endregion
  140. #region Wraps
  141. /// <summary>
  142. /// Access one of the existing settings. If the setting has not been added yet, false is returned. Otherwise, true.
  143. /// If the setting exists but has a different type than T, an exception is thrown.
  144. /// New settings should be added with <see cref="Bind{T}"/>.
  145. /// </summary>
  146. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  147. /// <param name="configDefinition">Section and Key of the setting.</param>
  148. /// <param name="entry">The ConfigEntry value to return.</param>
  149. public bool TryGetEntry<T>(ConfigDefinition configDefinition, out ConfigEntry<T> entry)
  150. {
  151. lock (_ioLock)
  152. {
  153. if (Entries.TryGetValue(configDefinition, out var rawEntry))
  154. {
  155. entry = (ConfigEntry<T>)rawEntry;
  156. return true;
  157. }
  158. entry = null;
  159. return false;
  160. }
  161. }
  162. /// <summary>
  163. /// Access one of the existing settings. If the setting has not been added yet, null is returned.
  164. /// If the setting exists but has a different type than T, an exception is thrown.
  165. /// New settings should be added with <see cref="Bind{T}"/>.
  166. /// </summary>
  167. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  168. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  169. /// <param name="key">Name of the setting.</param>
  170. /// <param name="entry">The ConfigEntry value to return.</param>
  171. public bool TryGetEntry<T>(string section, string key, out ConfigEntry<T> entry)
  172. {
  173. return TryGetEntry<T>(new ConfigDefinition(section, key), out entry);
  174. }
  175. /// <summary>
  176. /// Create a new setting. The setting is saved to drive and loaded automatically.
  177. /// Each definition can be used to add only one setting, trying to add a second setting will throw an exception.
  178. /// </summary>
  179. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  180. /// <param name="configDefinition">Section and Key of the setting.</param>
  181. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  182. /// <param name="configDescription">Description of the setting shown to the user and other metadata.</param>
  183. public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
  184. {
  185. if (!TomlTypeConverter.CanConvert(typeof(T)))
  186. throw new ArgumentException($"Type {typeof(T)} is not supported by the config system. Supported types: {string.Join(", ", TomlTypeConverter.GetSupportedTypes().Select(x => x.Name).ToArray())}");
  187. lock (_ioLock)
  188. {
  189. if (Entries.TryGetValue(configDefinition, out var rawEntry))
  190. return (ConfigEntry<T>)rawEntry;
  191. var entry = new ConfigEntry<T>(this, configDefinition, defaultValue, configDescription);
  192. Entries[configDefinition] = entry;
  193. if (OrphanedEntries.TryGetValue(configDefinition, out string homelessValue))
  194. {
  195. entry.SetSerializedValue(homelessValue);
  196. OrphanedEntries.Remove(configDefinition);
  197. }
  198. if (SaveOnConfigSet)
  199. Save();
  200. return entry;
  201. }
  202. }
  203. /// <summary>
  204. /// Create a new setting. The setting is saved to drive and loaded automatically.
  205. /// Each section and key pair can be used to add only one setting, trying to add a second setting will throw an exception.
  206. /// </summary>
  207. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  208. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  209. /// <param name="key">Name of the setting.</param>
  210. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  211. /// <param name="configDescription">Description of the setting shown to the user and other metadata.</param>
  212. public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  213. => Bind(new ConfigDefinition(section, key), defaultValue, configDescription);
  214. /// <summary>
  215. /// Create a new setting. The setting is saved to drive and loaded automatically.
  216. /// Each section and key pair can be used to add only one setting, trying to add a second setting will throw an exception.
  217. /// </summary>
  218. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  219. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  220. /// <param name="key">Name of the setting.</param>
  221. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  222. /// <param name="description">Simple description of the setting shown to the user.</param>
  223. public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description)
  224. => Bind(new ConfigDefinition(section, key), defaultValue, new ConfigDescription(description));
  225. /// <summary>
  226. /// Access a setting. Use Bind and GetSetting instead.
  227. /// </summary>
  228. [Obsolete("Use Bind instead")]
  229. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  230. {
  231. lock (_ioLock)
  232. {
  233. var definition = new ConfigDefinition(section, key, description);
  234. var setting = Bind(definition, defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description));
  235. return new ConfigWrapper<T>(setting);
  236. }
  237. }
  238. /// <summary>
  239. /// Access a setting. Use Bind and GetSetting instead.
  240. /// </summary>
  241. [Obsolete("Use Bind instead")]
  242. public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue = default(T))
  243. => Wrap(configDefinition.Section, configDefinition.Key, null, defaultValue);
  244. #endregion
  245. #region Events
  246. /// <summary>
  247. /// An event that is fired every time the config is reloaded.
  248. /// </summary>
  249. public event EventHandler ConfigReloaded;
  250. /// <summary>
  251. /// Fired when one of the settings is changed.
  252. /// </summary>
  253. public event EventHandler<SettingChangedEventArgs> SettingChanged;
  254. internal void OnSettingChanged(object sender, ConfigEntryBase changedEntryBase)
  255. {
  256. if (changedEntryBase == null) throw new ArgumentNullException(nameof(changedEntryBase));
  257. if (SaveOnConfigSet)
  258. Save();
  259. var settingChanged = SettingChanged;
  260. if (settingChanged == null) return;
  261. var args = new SettingChangedEventArgs(changedEntryBase);
  262. foreach (var callback in settingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
  263. {
  264. try { callback(sender, args); }
  265. catch (Exception e) { Logger.Log(LogLevel.Error, e); }
  266. }
  267. }
  268. private void OnConfigReloaded()
  269. {
  270. var configReloaded = ConfigReloaded;
  271. if (configReloaded == null) return;
  272. foreach (var callback in configReloaded.GetInvocationList().Cast<EventHandler>())
  273. {
  274. try { callback(this, EventArgs.Empty); }
  275. catch (Exception e) { Logger.Log(LogLevel.Error, e); }
  276. }
  277. }
  278. #endregion
  279. /// <inheritdoc />
  280. public IEnumerator<KeyValuePair<ConfigDefinition, ConfigEntryBase>> GetEnumerator()
  281. {
  282. // We can't really do a read lock for this
  283. return Entries.GetEnumerator();
  284. }
  285. IEnumerator IEnumerable.GetEnumerator()
  286. {
  287. return GetEnumerator();
  288. }
  289. void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Add(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
  290. {
  291. lock (_ioLock)
  292. Entries.Add(item.Key, item.Value);
  293. }
  294. /// <inheritdoc />
  295. public bool Contains(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
  296. {
  297. lock (_ioLock)
  298. return ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).Contains(item);
  299. }
  300. void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.CopyTo(KeyValuePair<ConfigDefinition, ConfigEntryBase>[] array, int arrayIndex)
  301. {
  302. lock (_ioLock)
  303. ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).CopyTo(array, arrayIndex);
  304. }
  305. bool ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Remove(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
  306. {
  307. lock (_ioLock)
  308. return Entries.Remove(item.Key);
  309. }
  310. /// <inheritdoc />
  311. public int Count
  312. {
  313. get
  314. {
  315. lock (_ioLock)
  316. return Entries.Count;
  317. }
  318. }
  319. /// <inheritdoc />
  320. public bool IsReadOnly => false;
  321. /// <inheritdoc />
  322. public bool ContainsKey(ConfigDefinition key)
  323. {
  324. lock (_ioLock)
  325. return Entries.ContainsKey(key);
  326. }
  327. /// <inheritdoc />
  328. public void Add(ConfigDefinition key, ConfigEntryBase value)
  329. {
  330. throw new InvalidOperationException("Directly adding a config entry is not supported");
  331. }
  332. /// <inheritdoc />
  333. public bool Remove(ConfigDefinition key)
  334. {
  335. lock (_ioLock)
  336. return Entries.Remove(key);
  337. }
  338. /// <inheritdoc />
  339. public void Clear()
  340. {
  341. lock (_ioLock)
  342. Entries.Clear();
  343. }
  344. bool IDictionary<ConfigDefinition, ConfigEntryBase>.TryGetValue(ConfigDefinition key, out ConfigEntryBase value)
  345. {
  346. lock (_ioLock)
  347. return Entries.TryGetValue(key, out value);
  348. }
  349. /// <inheritdoc />
  350. ConfigEntryBase IDictionary<ConfigDefinition, ConfigEntryBase>.this[ConfigDefinition key]
  351. {
  352. get
  353. {
  354. lock (_ioLock)
  355. return Entries[key];
  356. }
  357. set => throw new InvalidOperationException("Directly setting a config entry is not supported");
  358. }
  359. /// <inheritdoc />
  360. public ConfigEntryBase this[ConfigDefinition key]
  361. {
  362. get
  363. {
  364. lock (_ioLock)
  365. return Entries[key];
  366. }
  367. }
  368. /// <summary>
  369. ///
  370. /// </summary>
  371. /// <param name="section"></param>
  372. /// <param name="key"></param>
  373. public ConfigEntryBase this[string section, string key]
  374. => this[new ConfigDefinition(section, key)];
  375. /// <summary>
  376. /// Returns the ConfigDefinitions that the ConfigFile contains.
  377. /// <para>Creates a new array when the property is accessed. Thread-safe.</para>
  378. /// </summary>
  379. public ICollection<ConfigDefinition> Keys
  380. {
  381. get
  382. {
  383. lock (_ioLock)
  384. return Entries.Keys.ToArray();
  385. }
  386. }
  387. /// <summary>
  388. /// Returns the ConfigEntryBase values that the ConfigFile contains.
  389. /// <para>Creates a new array when the property is accessed. Thread-safe.</para>
  390. /// </summary>
  391. ICollection<ConfigEntryBase> IDictionary<ConfigDefinition, ConfigEntryBase>.Values
  392. {
  393. get
  394. {
  395. lock (_ioLock)
  396. return Entries.Values.ToArray();
  397. }
  398. }
  399. }
  400. }