ConfigFile.cs 10 KB

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