ConfigFile.cs 12 KB

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