ConfigFile.cs 20 KB

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