ConfigFile.cs 10 KB

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