ConfigFile.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 PluginMetadata _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. /// 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, PluginMetadata)"/>
  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, PluginMetadata 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('='); //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(File.Create(ConfigFilePath), 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, false is returned. Otherwise, true.
  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="Bind{T}"/>.
  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. /// <param name="entry">The ConfigEntry value to return.</param>
  160. public bool TryGetEntry<T>(ConfigDefinition configDefinition, out ConfigEntry<T> entry)
  161. {
  162. lock (_ioLock)
  163. {
  164. if (Entries.TryGetValue(configDefinition, out var rawEntry))
  165. {
  166. entry = (ConfigEntry<T>)rawEntry;
  167. return true;
  168. }
  169. entry = null;
  170. return false;
  171. }
  172. }
  173. /// <summary>
  174. /// Access one of the existing settings. If the setting has not been added yet, null is returned.
  175. /// If the setting exists but has a different type than T, an exception is thrown.
  176. /// New settings should be added with <see cref="Bind{T}"/>.
  177. /// </summary>
  178. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  179. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  180. /// <param name="key">Name of the setting.</param>
  181. /// <param name="entry">The ConfigEntry value to return.</param>
  182. public bool TryGetEntry<T>(string section, string key, out ConfigEntry<T> entry)
  183. {
  184. return TryGetEntry<T>(new ConfigDefinition(section, key), out entry);
  185. }
  186. /// <summary>
  187. /// Create a new setting. The setting is saved to drive and loaded automatically.
  188. /// Each definition can be used to add only one setting, trying to add a second setting will throw an exception.
  189. /// </summary>
  190. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  191. /// <param name="configDefinition">Section and Key of the setting.</param>
  192. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  193. /// <param name="configDescription">Description of the setting shown to the user and other metadata.</param>
  194. public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
  195. {
  196. if (!TomlTypeConverter.CanConvert(typeof(T)))
  197. throw new ArgumentException($"Type {typeof(T)} is not supported by the config system. Supported types: {string.Join(", ", TomlTypeConverter.GetSupportedTypes().Select(x => x.Name).ToArray())}");
  198. lock (_ioLock)
  199. {
  200. if (Entries.TryGetValue(configDefinition, out var rawEntry))
  201. return (ConfigEntry<T>)rawEntry;
  202. var entry = new ConfigEntry<T>(this, configDefinition, defaultValue, configDescription);
  203. Entries[configDefinition] = entry;
  204. if (OrphanedEntries.TryGetValue(configDefinition, out string homelessValue))
  205. {
  206. entry.SetSerializedValue(homelessValue);
  207. OrphanedEntries.Remove(configDefinition);
  208. }
  209. if (SaveOnConfigSet)
  210. Save();
  211. return entry;
  212. }
  213. }
  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="configDescription">Description of the setting shown to the user and other metadata.</param>
  223. public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  224. => Bind(new ConfigDefinition(section, key), defaultValue, configDescription);
  225. /// <summary>
  226. /// Create a new setting. The setting is saved to drive and loaded automatically.
  227. /// Each section and key pair can be used to add only one setting, trying to add a second setting will throw an exception.
  228. /// </summary>
  229. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  230. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  231. /// <param name="key">Name of the setting.</param>
  232. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  233. /// <param name="description">Simple description of the setting shown to the user.</param>
  234. public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description)
  235. => Bind(new ConfigDefinition(section, key), defaultValue, new ConfigDescription(description));
  236. /// <summary>
  237. /// Create a new setting. The setting is saved to drive and loaded automatically.
  238. /// Each definition can be used to add only one setting, trying to add a second setting will throw an exception.
  239. /// </summary>
  240. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  241. /// <param name="configDefinition">Section and Key of the setting.</param>
  242. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  243. /// <param name="configDescription">Description of the setting shown to the user and other metadata.</param>
  244. [Obsolete("Use bind instead")]
  245. public ConfigEntry<T> AddSetting<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
  246. => Bind(configDefinition, defaultValue, configDescription);
  247. /// <summary>
  248. /// Create a new setting. The setting is saved to drive and loaded automatically.
  249. /// Each section and key pair can be used to add only one setting, trying to add a second setting will throw an exception.
  250. /// </summary>
  251. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  252. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  253. /// <param name="key">Name of the setting.</param>
  254. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  255. /// <param name="configDescription">Description of the setting shown to the user and other metadata.</param>
  256. [Obsolete("Use bind instead")]
  257. public ConfigEntry<T> AddSetting<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  258. => Bind(new ConfigDefinition(section, key), defaultValue, configDescription);
  259. /// <summary>
  260. /// Create a new setting. The setting is saved to drive and loaded automatically.
  261. /// Each section and key pair can be used to add only one setting, trying to add a second setting will throw an exception.
  262. /// </summary>
  263. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  264. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  265. /// <param name="key">Name of the setting.</param>
  266. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  267. /// <param name="description">Simple description of the setting shown to the user.</param>
  268. [Obsolete("Use bind instead")]
  269. public ConfigEntry<T> AddSetting<T>(string section, string key, T defaultValue, string description)
  270. => Bind(new ConfigDefinition(section, key), defaultValue, new ConfigDescription(description));
  271. /// <summary>
  272. /// Access a setting. Use Bind instead.
  273. /// </summary>
  274. [Obsolete("Use Bind instead")]
  275. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  276. {
  277. lock (_ioLock)
  278. {
  279. var definition = new ConfigDefinition(section, key, description);
  280. var setting = Bind(definition, defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description));
  281. return new ConfigWrapper<T>(setting);
  282. }
  283. }
  284. /// <summary>
  285. /// Access a setting. Use Bind instead.
  286. /// </summary>
  287. [Obsolete("Use Bind instead")]
  288. public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue = default(T))
  289. => Wrap(configDefinition.Section, configDefinition.Key, null, defaultValue);
  290. #endregion
  291. #region Events
  292. /// <summary>
  293. /// An event that is fired every time the config is reloaded.
  294. /// </summary>
  295. public event EventHandler ConfigReloaded;
  296. /// <summary>
  297. /// Fired when one of the settings is changed.
  298. /// </summary>
  299. public event EventHandler<SettingChangedEventArgs> SettingChanged;
  300. internal void OnSettingChanged(object sender, ConfigEntryBase changedEntryBase)
  301. {
  302. if (changedEntryBase == null) throw new ArgumentNullException(nameof(changedEntryBase));
  303. if (SaveOnConfigSet)
  304. Save();
  305. var settingChanged = SettingChanged;
  306. if (settingChanged == null) return;
  307. var args = new SettingChangedEventArgs(changedEntryBase);
  308. foreach (var callback in settingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
  309. {
  310. try { callback(sender, args); }
  311. catch (Exception e) { Logger.Log(LogLevel.Error, e); }
  312. }
  313. }
  314. private void OnConfigReloaded()
  315. {
  316. var configReloaded = ConfigReloaded;
  317. if (configReloaded == null) return;
  318. foreach (var callback in configReloaded.GetInvocationList().Cast<EventHandler>())
  319. {
  320. try { callback(this, EventArgs.Empty); }
  321. catch (Exception e) { Logger.Log(LogLevel.Error, e); }
  322. }
  323. }
  324. #endregion
  325. /// <inheritdoc />
  326. public IEnumerator<KeyValuePair<ConfigDefinition, ConfigEntryBase>> GetEnumerator()
  327. {
  328. // We can't really do a read lock for this
  329. return Entries.GetEnumerator();
  330. }
  331. IEnumerator IEnumerable.GetEnumerator()
  332. {
  333. return GetEnumerator();
  334. }
  335. void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Add(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
  336. {
  337. lock (_ioLock)
  338. Entries.Add(item.Key, item.Value);
  339. }
  340. /// <inheritdoc />
  341. public bool Contains(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
  342. {
  343. lock (_ioLock)
  344. return ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).Contains(item);
  345. }
  346. void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.CopyTo(KeyValuePair<ConfigDefinition, ConfigEntryBase>[] array, int arrayIndex)
  347. {
  348. lock (_ioLock)
  349. ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).CopyTo(array, arrayIndex);
  350. }
  351. bool ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Remove(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
  352. {
  353. lock (_ioLock)
  354. return Entries.Remove(item.Key);
  355. }
  356. /// <inheritdoc />
  357. public int Count
  358. {
  359. get
  360. {
  361. lock (_ioLock)
  362. return Entries.Count;
  363. }
  364. }
  365. /// <inheritdoc />
  366. public bool IsReadOnly => false;
  367. /// <inheritdoc />
  368. public bool ContainsKey(ConfigDefinition key)
  369. {
  370. lock (_ioLock)
  371. return Entries.ContainsKey(key);
  372. }
  373. /// <inheritdoc />
  374. public void Add(ConfigDefinition key, ConfigEntryBase value)
  375. {
  376. throw new InvalidOperationException("Directly adding a config entry is not supported");
  377. }
  378. /// <inheritdoc />
  379. public bool Remove(ConfigDefinition key)
  380. {
  381. lock (_ioLock)
  382. return Entries.Remove(key);
  383. }
  384. /// <inheritdoc />
  385. public void Clear()
  386. {
  387. lock (_ioLock)
  388. Entries.Clear();
  389. }
  390. bool IDictionary<ConfigDefinition, ConfigEntryBase>.TryGetValue(ConfigDefinition key, out ConfigEntryBase value)
  391. {
  392. lock (_ioLock)
  393. return Entries.TryGetValue(key, out value);
  394. }
  395. /// <inheritdoc />
  396. ConfigEntryBase IDictionary<ConfigDefinition, ConfigEntryBase>.this[ConfigDefinition key]
  397. {
  398. get
  399. {
  400. lock (_ioLock)
  401. return Entries[key];
  402. }
  403. set => throw new InvalidOperationException("Directly setting a config entry is not supported");
  404. }
  405. /// <inheritdoc />
  406. public ConfigEntryBase this[ConfigDefinition key]
  407. {
  408. get
  409. {
  410. lock (_ioLock)
  411. return Entries[key];
  412. }
  413. }
  414. /// <summary>
  415. ///
  416. /// </summary>
  417. /// <param name="section"></param>
  418. /// <param name="key"></param>
  419. public ConfigEntryBase this[string section, string key]
  420. => this[new ConfigDefinition(section, key)];
  421. /// <summary>
  422. /// Returns the ConfigDefinitions that the ConfigFile contains.
  423. /// <para>Creates a new array when the property is accessed. Thread-safe.</para>
  424. /// </summary>
  425. public ICollection<ConfigDefinition> Keys
  426. {
  427. get
  428. {
  429. lock (_ioLock)
  430. return Entries.Keys.ToArray();
  431. }
  432. }
  433. /// <summary>
  434. /// Returns the ConfigEntryBase values that the ConfigFile contains.
  435. /// <para>Creates a new array when the property is accessed. Thread-safe.</para>
  436. /// </summary>
  437. ICollection<ConfigEntryBase> IDictionary<ConfigDefinition, ConfigEntryBase>.Values
  438. {
  439. get
  440. {
  441. lock (_ioLock)
  442. return Entries.Values.ToArray();
  443. }
  444. }
  445. }
  446. }