ConfigFile.cs 11 KB

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