ConfigFile.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. All public methods are thread-safe.
  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="AddSetting{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. /// Access one of the existing settings. If the setting has not been added yet, null is returned.
  158. /// If the setting exists but has a different type than T, an exception is thrown.
  159. /// New settings should be added with <see cref="AddSetting{T}(ConfigDefinition,T,ConfigDescription)"/>.
  160. /// </summary>
  161. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  162. /// <param name="section">Section/category/group of the setting. Settings are grouped by this.</param>
  163. /// <param name="key">Name of the setting.</param>
  164. public ConfigEntry<T> GetSetting<T>(string section, string key)
  165. {
  166. lock (_ioLock)
  167. {
  168. Entries.TryGetValue(new ConfigDefinition(section, key), out var entry);
  169. return (ConfigEntry<T>)entry;
  170. }
  171. }
  172. /// <summary>
  173. /// Create a new setting. The setting is saved to drive and loaded automatically.
  174. /// Each definition can be used to add only one setting, trying to add a second setting will throw an exception.
  175. /// </summary>
  176. /// <typeparam name="T">Type of the value contained in this setting.</typeparam>
  177. /// <param name="configDefinition">Section and Key of the setting.</param>
  178. /// <param name="defaultValue">Value of the setting if the setting was not created yet.</param>
  179. /// <param name="configDescription">Description of the setting shown to the user.</param>
  180. public ConfigEntry<T> AddSetting<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
  181. {
  182. if (!TomlTypeConverter.CanConvert(typeof(T)))
  183. throw new ArgumentException($"Type {typeof(T)} is not supported by the config system. Supported types: {string.Join(", ", TomlTypeConverter.GetSupportedTypes().Select(x => x.Name).ToArray())}");
  184. lock (_ioLock)
  185. {
  186. if (Entries.ContainsKey(configDefinition))
  187. throw new ArgumentException("The setting " + configDefinition + " has already been created. Use GetSetting to get it.");
  188. try
  189. {
  190. _disableSaving = true;
  191. var entry = new ConfigEntry<T>(this, configDefinition, defaultValue, configDescription);
  192. Entries[configDefinition] = entry;
  193. if (HomelessEntries.TryGetValue(configDefinition, out string homelessValue))
  194. {
  195. entry.SetSerializedValue(homelessValue);
  196. HomelessEntries.Remove(configDefinition);
  197. }
  198. _disableSaving = false;
  199. if (SaveOnConfigSet)
  200. Save();
  201. return entry;
  202. }
  203. finally
  204. {
  205. _disableSaving = false;
  206. }
  207. }
  208. }
  209. /// <summary>
  210. /// Create a new setting. The setting is saved to drive and loaded automatically.
  211. /// Each section and key pair can be used to add only one setting, trying to add a second setting will throw an exception.
  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 ConfigEntry<T> AddSetting<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
  219. => AddSetting(new ConfigDefinition(section, key), defaultValue, configDescription);
  220. /// <summary>
  221. /// Access a setting. Use AddSetting and GetSetting instead.
  222. /// </summary>
  223. [Obsolete("Use AddSetting and GetSetting instead")]
  224. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  225. {
  226. lock (_ioLock)
  227. {
  228. var setting = GetSetting<T>(section, key) ?? AddSetting(section, key, defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description));
  229. return new ConfigWrapper<T>(setting);
  230. }
  231. }
  232. /// <summary>
  233. /// Access a setting. Use AddSetting and GetSetting instead.
  234. /// </summary>
  235. [Obsolete("Use AddSetting and GetSetting instead")]
  236. public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue = default(T))
  237. => Wrap(configDefinition.Section, configDefinition.Key, null, defaultValue);
  238. #endregion
  239. #region Events
  240. /// <summary>
  241. /// An event that is fired every time the config is reloaded.
  242. /// </summary>
  243. public event EventHandler ConfigReloaded;
  244. /// <summary>
  245. /// Fired when one of the settings is changed.
  246. /// </summary>
  247. public event EventHandler<SettingChangedEventArgs> SettingChanged;
  248. internal void OnSettingChanged(object sender, ConfigEntryBase changedEntryBase)
  249. {
  250. if (changedEntryBase == null) throw new ArgumentNullException(nameof(changedEntryBase));
  251. if (SaveOnConfigSet)
  252. Save();
  253. var settingChanged = SettingChanged;
  254. if (settingChanged == null) return;
  255. var args = new SettingChangedEventArgs(changedEntryBase);
  256. foreach (var callback in settingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
  257. {
  258. try { callback(sender, args); }
  259. catch (Exception e) { Logger.Log(LogLevel.Error, e); }
  260. }
  261. }
  262. private void OnConfigReloaded()
  263. {
  264. var configReloaded = ConfigReloaded;
  265. if (configReloaded == null) return;
  266. foreach (var callback in configReloaded.GetInvocationList().Cast<EventHandler>())
  267. {
  268. try { callback(this, EventArgs.Empty); }
  269. catch (Exception e) { Logger.Log(LogLevel.Error, e); }
  270. }
  271. }
  272. #endregion
  273. }
  274. }