// Made by MarC0 / ManlyMarco // Copyright 2018 GNU General Public License v3.0 using System; using System.Collections.Generic; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using ConfigurationManager.Utilities; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using UnityEngine; #if IL2CPP using BepInEx.Unity.IL2CPP; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using BaseUnityPlugin = BepInEx.Unity.IL2CPP.BasePlugin; #endif namespace ConfigurationManager { /// /// An easy way to let user configure how a plugin behaves without the need to make your own GUI. The user can change any of the settings you expose, even keyboard shortcuts. /// https://github.com/ManlyMarco/BepInEx.ConfigurationManager /// [BepInPlugin(GUID, "Configuration Manager", Constants.Version)] [Browsable(false)] public class ConfigurationManager : BaseUnityPlugin { /// /// GUID of this plugin /// public const string GUID = "com.bepis.bepinex.configurationmanager"; /// /// Version constant /// public const string Version = Constants.Version; internal static ManualLogSource Logger; private static SettingFieldDrawer _fieldDrawer; private static readonly Color _advancedSettingColor = new Color(1f, 0.95f, 0.67f, 1f); private const int WindowId = -68; private const string SearchBoxName = "searchBox"; private bool _focusSearchBox; private string _searchString = string.Empty; /// /// Skin to draw the settings window with, for example to match the look of the game. Null (the default) keeps the default look. /// The window, its controls and tooltips are drawn with this skin, and its window style draws the window background. /// The dimmed backdrop behind a window that has not been moved yet keeps the default skin. /// Plugin and category headers use the custom styles named and /// if the skin has them. /// public GUISkin WindowSkin { get; set; } /// /// Name of the custom style in used for plugin headers, if present. /// public const string PluginHeaderStyleName = "ConfigurationManager.PluginHeader"; /// /// Name of the custom style in used for category headers, if present. /// public const string CategoryHeaderStyleName = "ConfigurationManager.CategoryHeader"; /// /// Event fired every time the manager window is shown or hidden. /// public event EventHandler> DisplayingWindowChanged; /// /// Disable the hotkey check used by config manager. If enabled you have to set to show the manager. /// public bool OverrideHotkey; private bool _displayingWindow; private bool _obsoleteCursor; private string _modsWithoutSettings; private List _allSettings; private List _filteredSetings = new List(); internal Rect SettingWindowRect { get; private set; } private bool _windowWasMoved; /// /// Window is visible and is blocking the whole screen. This is true until the user moves the window, which lets it run while user interacts with the game. /// public bool IsWindowFullscreen => DisplayingWindow && !_windowWasMoved; private bool _tipsPluginHeaderWasClicked, _tipsWindowWasMoved; private Rect _screenRect; private Vector2 _settingWindowScrollPos; private int _tipsHeight; private PropertyInfo _curLockState; private PropertyInfo _curVisible; private int _previousCursorLockState; private bool _previousCursorVisible; internal int LeftColumnWidth { get; private set; } internal int RightColumnWidth => _rightColumnBaseWidth - _resetButtonExtraWidth; private int _rightColumnBaseWidth; private int _resetButtonExtraWidth; private static readonly GUIContent _resetUntranslated = new GUIContent("Reset"); private readonly ConfigEntry _showAdvanced; private readonly ConfigEntry _showKeybinds; private readonly ConfigEntry _showSettings; private readonly ConfigEntry _keybind; private readonly ConfigEntry _hideSingleSection; private readonly ConfigEntry _pluginConfigCollapsedDefault; private bool _showDebug; /// public ConfigurationManager() { #if IL2CPP Logger = Log; #else Logger = base.Logger; #endif _fieldDrawer = new SettingFieldDrawer(this); _showAdvanced = Config.Bind("Filtering", "Show advanced", false); _showKeybinds = Config.Bind("Filtering", "Show keybinds", true); _showSettings = Config.Bind("Filtering", "Show settings", true); _keybind = Config.Bind("General", "Show config manager", new KeyboardShortcut(KeyCode.F1), new ConfigDescription("The shortcut used to toggle the config manager window on and off.\n" + "The key can be overridden by a game-specific plugin if necessary, in that case this setting is ignored.")); _hideSingleSection = Config.Bind("General", "Hide single sections", false, new ConfigDescription("Show section title for plugins with only one section")); _pluginConfigCollapsedDefault = Config.Bind("General", "Plugin collapsed default", true, new ConfigDescription("If set to true plugins will be collapsed when opening the configuration manager window")); } #if IL2CPP /// public override void Load() { ConfigurationManagerBehaviour.Plugin = this; AddComponent(); } private class ConfigurationManagerBehaviour : MonoBehaviour { internal static ConfigurationManager Plugin; private void Start() => Plugin.Start(); private void Update() => Plugin.Update(); private void LateUpdate() => Plugin.LateUpdate(); private void OnGUI() => Plugin.OnGUI(); } #endif /// /// Is the config manager main window displayed on screen /// public bool DisplayingWindow { get => _displayingWindow; set { if (_displayingWindow == value) return; _displayingWindow = value; SettingFieldDrawer.ClearCache(); if (_displayingWindow) { CalculateWindowRect(); BuildSettingList(); _focusSearchBox = true; // Do through reflection for unity 4 compat if (_curLockState != null) { _previousCursorLockState = _obsoleteCursor ? Convert.ToInt32((bool)_curLockState.GetValue(null, null)) : (int)_curLockState.GetValue(null, null); _previousCursorVisible = (bool)_curVisible.GetValue(null, null); } } else { if (!_previousCursorVisible || _previousCursorLockState != 0) // 0 = CursorLockMode.None SetUnlockCursor(_previousCursorLockState, _previousCursorVisible); } DisplayingWindowChanged?.Invoke(this, new ValueChangedEventArgs(value)); } } /// /// Register a custom setting drawer for a given type. The action is ran in OnGui in a single setting slot. /// Do not use any Begin / End layout methods, and avoid raising height from standard. /// public static void RegisterCustomSettingDrawer(Type settingType, Action onGuiDrawer) { if (settingType == null) throw new ArgumentNullException(nameof(settingType)); if (onGuiDrawer == null) throw new ArgumentNullException(nameof(onGuiDrawer)); if (SettingFieldDrawer.SettingDrawHandlers.ContainsKey(settingType)) Logger.LogWarning("Tried to add a setting drawer for type " + settingType.FullName + " while one already exists."); else SettingFieldDrawer.SettingDrawHandlers[settingType] = onGuiDrawer; } /// /// Rebuild the setting list. Use to update the config manager window if config settings were removed or added while it was open. /// public void BuildSettingList() { SettingSearcher.CollectSettings(out var results, out var modsWithoutSettings, _showDebug); _modsWithoutSettings = string.Join(", ", modsWithoutSettings.Select(x => x.TrimStart('!')).OrderBy(x => x).ToArray()); _allSettings = results.ToList(); BuildFilteredSettingList(); } private void BuildFilteredSettingList() { IEnumerable results = _allSettings; var searchStrings = SearchString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (searchStrings.Length > 0) { results = results.Where(x => ContainsSearchString(x, searchStrings)); } else { if (!_showAdvanced.Value) results = results.Where(x => x.IsAdvanced != true); if (!_showKeybinds.Value) results = results.Where(x => !IsKeyboardShortcut(x)); if (!_showSettings.Value) results = results.Where(x => x.IsAdvanced == true || IsKeyboardShortcut(x)); } const string shortcutsCatName = "Keyboard shortcuts"; var settingsAreCollapsed = _pluginConfigCollapsedDefault.Value; var nonDefaultCollpasingStateByPluginName = new HashSet(); foreach (var pluginSetting in _filteredSetings) { if (pluginSetting.Collapsed != settingsAreCollapsed) { nonDefaultCollpasingStateByPluginName.Add(pluginSetting.Info.Name); } } _filteredSetings = results .GroupBy(x => x.PluginInfo) .Select(pluginSettings => { var originalCategoryOrder = pluginSettings.Select(x => x.Category).Distinct().ToList(); var categories = pluginSettings .GroupBy(x => x.Category) .OrderBy(x => originalCategoryOrder.IndexOf(x.Key)) .ThenBy(x => x.Key) .Select(x => new PluginSettingsData.PluginSettingsGroupData { Name = x.Key, Settings = x.OrderByDescending(set => set.Order).ThenBy(set => set.DispName).ToList() }); var website = Utils.GetWebsite(pluginSettings.First().PluginInstance); return new PluginSettingsData { Info = pluginSettings.Key, Categories = categories.ToList(), Collapsed = nonDefaultCollpasingStateByPluginName.Contains(pluginSettings.Key.Name) ? !settingsAreCollapsed : settingsAreCollapsed, Website = website }; }) .OrderBy(x => x.Info.Name) .ToList(); } private static bool IsKeyboardShortcut(SettingEntryBase x) { return x.SettingType == typeof(KeyboardShortcut) || x.SettingType == typeof(KeyCode); } private static bool ContainsSearchString(SettingEntryBase setting, string[] searchStrings) { var combinedSearchTarget = setting.PluginInfo.Name + "\n" + setting.PluginInfo.GUID + "\n" + setting.DispName + "\n" + setting.Category + "\n" + setting.Description + "\n" + setting.DefaultValue + "\n" + setting.Get(); return searchStrings.All(s => combinedSearchTarget.IndexOf(s, StringComparison.InvariantCultureIgnoreCase) >= 0); } private void CalculateWindowRect() { var width = Mathf.Min(Screen.width, 650); var height = Screen.height < 560 ? Screen.height : Screen.height - 100; var offsetX = Mathf.RoundToInt((Screen.width - width) / 2f); var offsetY = Mathf.RoundToInt((Screen.height - height) / 2f); SettingWindowRect = new Rect(offsetX, offsetY, width, height); _screenRect = new Rect(0, 0, Screen.width, Screen.height); LeftColumnWidth = Mathf.RoundToInt(SettingWindowRect.width / 2.5f); _rightColumnBaseWidth = (int)SettingWindowRect.width - LeftColumnWidth - 115; _windowWasMoved = false; } private void OnGUI() { if (DisplayingWindow) { SetUnlockCursor(0, true); Vector2 mousePosition = UnityInput.Current.mousePosition; mousePosition.y = Screen.height - mousePosition.y; // If the window hasn't been moved by the user yet, block the whole screen and use a solid background to make the window easier to see if (!_windowWasMoved) { if (GUI.Button(_screenRect, string.Empty, GUI.skin.box) && !SettingWindowRect.Contains(mousePosition)) DisplayingWindow = false; // A custom skin draws the window background with its own window style if (WindowSkin == null) ImguiUtils.DrawWindowBackground(SettingWindowRect); } var defaultSkin = GUI.skin; if (WindowSkin != null) GUI.skin = WindowSkin; var newRect = GUILayout.Window(WindowId, SettingWindowRect, (GUI.WindowFunction)SettingsWindow, "Plugin / mod settings"); GUI.skin = defaultSkin; if (newRect != SettingWindowRect) { _windowWasMoved = true; SettingWindowRect = newRect; _tipsWindowWasMoved = true; } if (!SettingFieldDrawer.SettingKeyboardShortcut && (!_windowWasMoved || SettingWindowRect.Contains(mousePosition))) UnityInput.Current.ResetInputAxes(); } } private static void DrawTooltip(Rect area) { string tooltip = GUI.tooltip; if (!string.IsNullOrEmpty(tooltip)) { var style = GUI.skin.box.CreateCopy(); style.wordWrap = true; style.alignment = TextAnchor.MiddleCenter; GUIContent content = ImguiUtils.Content(tooltip); const int width = 400; var height = style.CalcHeight(content, 400) + 10; var mousePosition = Event.current.mousePosition; var x = mousePosition.x + width > area.width ? area.width - width : mousePosition.x; var y = mousePosition.y + 25 + height > area.height ? mousePosition.y - height : mousePosition.y + 25; Rect position = new Rect(x, y, width, height); ImguiUtils.DrawContolBackground(position, Color.black); GUI.Label(position, content, style); } } private void SettingsWindow(int id) { // The right column leaves room for an untranslated "Reset" button. A translated label is usually longer, and the // fixed-width fields then push the button past the right edge of the window, so grow the room by the difference. var buttonStyle = GUI.skin.button; _resetButtonExtraWidth = Mathf.Max(0, Mathf.CeilToInt(buttonStyle.CalcSize(ImguiUtils.Content("Reset")).x - buttonStyle.CalcSize(_resetUntranslated).x)); DrawWindowHeader(); _settingWindowScrollPos = GUILayout.BeginScrollView(_settingWindowScrollPos, false, true); var scrollPosition = _settingWindowScrollPos.y; var scrollHeight = SettingWindowRect.height; GUILayout.BeginVertical(); { if (string.IsNullOrEmpty(SearchString)) { DrawTips(); if (_tipsHeight == 0 && Event.current.type == EventType.Repaint) _tipsHeight = (int)GUILayoutUtility.GetLastRect().height; } var currentHeight = _tipsHeight; foreach (var plugin in _filteredSetings) { var visible = plugin.Height == 0 || currentHeight + plugin.Height >= scrollPosition && currentHeight <= scrollPosition + scrollHeight; if (visible) { try { DrawSinglePlugin(plugin); } #if IL2CPP catch (Il2CppException) #else catch (ArgumentException) #endif { // Needed to avoid GUILayout: Mismatched LayoutGroup.Repaint crashes on large lists } if (plugin.Height == 0 && Event.current.type == EventType.Repaint) plugin.Height = (int)GUILayoutUtility.GetLastRect().height; } else { try { GUILayout.Space(plugin.Height); } #if IL2CPP catch (Il2CppException) #else catch (ArgumentException) #endif { // Needed to avoid GUILayout: Mismatched LayoutGroup.Repaint crashes on large lists } } currentHeight += plugin.Height; } if (_showDebug) { GUILayout.Space(10); GUILayout.Label("Plugins with no options available: " + _modsWithoutSettings); } else { // Always leave some space in case there's a dropdown box at the very bottom of the list GUILayout.Space(70); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); if (!SettingFieldDrawer.DrawCurrentDropdown()) DrawTooltip(SettingWindowRect); GUI.DragWindow(); } private void DrawTips() { var tip = !_tipsPluginHeaderWasClicked ? ImguiUtils.Content("Tip: Click plugin names to expand. Click setting and group names to see their descriptions.") : !_tipsWindowWasMoved ? ImguiUtils.Content("Tip: You can drag this window to move it. It will stay open while you interact with the game.") : null; if (tip != null) { GUILayout.BeginHorizontal(); { GUILayout.Label(tip); } GUILayout.EndHorizontal(); } } private void DrawWindowHeader() { GUILayout.BeginHorizontal(GUI.skin.box); { GUI.enabled = SearchString == string.Empty; var newVal = GUILayout.Toggle(_showSettings.Value, ImguiUtils.Content("Normal settings")); if (_showSettings.Value != newVal) { _showSettings.Value = newVal; BuildFilteredSettingList(); } newVal = GUILayout.Toggle(_showKeybinds.Value, ImguiUtils.Content("Keyboard shortcuts")); if (_showKeybinds.Value != newVal) { _showKeybinds.Value = newVal; BuildFilteredSettingList(); } var origColor = GUI.color; GUI.color = _advancedSettingColor; newVal = GUILayout.Toggle(_showAdvanced.Value, ImguiUtils.Content("Advanced settings")); if (_showAdvanced.Value != newVal) { _showAdvanced.Value = newVal; BuildFilteredSettingList(); } GUI.color = origColor; GUI.enabled = true; GUILayout.Space(8); newVal = GUILayout.Toggle(_showDebug, ImguiUtils.Content("Debug info")); if (_showDebug != newVal) { _showDebug = newVal; BuildSettingList(); } if (GUILayout.Button(ImguiUtils.Content("Open Log"))) { try { Utils.OpenLog(); } catch (SystemException ex) { Logger.Log(LogLevel.Message | LogLevel.Error, ex.Message); } } GUILayout.Space(8); if (GUILayout.Button(ImguiUtils.Content("Close"))) { DisplayingWindow = false; } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(GUI.skin.box); { GUILayout.Label(ImguiUtils.Content("Search: "), GUILayout.ExpandWidth(false)); GUI.SetNextControlName(SearchBoxName); SearchString = GUILayout.TextField(SearchString, GUILayout.ExpandWidth(true)); if (_focusSearchBox) { GUI.FocusWindow(WindowId); GUI.FocusControl(SearchBoxName); _focusSearchBox = false; } if (GUILayout.Button(ImguiUtils.Content("Clear"), GUILayout.ExpandWidth(false))) SearchString = string.Empty; GUILayout.Space(8); if (GUILayout.Button(ImguiUtils.Content(_pluginConfigCollapsedDefault.Value ? "Expand All" : "Collapse All"), GUILayout.ExpandWidth(false))) { var newValue = !_pluginConfigCollapsedDefault.Value; _pluginConfigCollapsedDefault.Value = newValue; foreach (var plugin in _filteredSetings) plugin.Collapsed = newValue; _tipsPluginHeaderWasClicked = true; } } GUILayout.EndHorizontal(); } /// /// String currently entered into the search box /// public string SearchString { get => _searchString; private set { if (value == null) value = string.Empty; if (_searchString == value) return; _searchString = value; BuildFilteredSettingList(); } } private void DrawSinglePlugin(PluginSettingsData plugin) { GUILayout.BeginVertical(GUI.skin.box); var categoryHeader = _showDebug ? new GUIContent($"{plugin.Info.Name.TrimStart('!')} {plugin.Info.Version}", null, "GUID: " + plugin.Info.GUID) : new GUIContent($"{plugin.Info.Name.TrimStart('!')} {plugin.Info.Version}"); var isSearching = !string.IsNullOrEmpty(SearchString); { var hasWebsite = plugin.Website != null; if (hasWebsite) { GUILayout.BeginHorizontal(); GUILayout.Space(29); // Same as the URL button to keep the plugin name centered } if (SettingFieldDrawer.DrawPluginHeader(categoryHeader, plugin.Collapsed && !isSearching) && !isSearching) { _tipsPluginHeaderWasClicked = true; plugin.Collapsed = !plugin.Collapsed; } if (hasWebsite) { var origColor = GUI.color; GUI.color = Color.gray; if (GUILayout.Button(new GUIContent("URL", null, plugin.Website), GUI.skin.label, GUILayout.ExpandWidth(false))) Utils.OpenWebsite(plugin.Website); GUI.color = origColor; GUILayout.EndHorizontal(); } } if (isSearching || !plugin.Collapsed) { foreach (var category in plugin.Categories) { if (!string.IsNullOrEmpty(category.Name)) { if (plugin.Categories.Count > 1 || !_hideSingleSection.Value) SettingFieldDrawer.DrawCategoryHeader(category.Name); } foreach (var setting in category.Settings) { DrawSingleSetting(setting); GUILayout.Space(2); } } } GUILayout.EndVertical(); } private void DrawSingleSetting(SettingEntryBase setting) { GUILayout.BeginHorizontal(); { try { DrawSettingName(setting); _fieldDrawer.DrawSettingValue(setting); DrawDefaultButton(setting); } catch (Exception ex) { Logger.Log(LogLevel.Error, $"Failed to draw setting {setting.DispName} - {ex}"); GUILayout.Label("Failed to draw this field, check log for details."); } } GUILayout.EndHorizontal(); } private void DrawSettingName(SettingEntryBase setting) { if (setting.HideSettingName) return; var origColor = GUI.color; if (setting.IsAdvanced == true) GUI.color = _advancedSettingColor; GUILayout.Label(new GUIContent(setting.DispName.TrimStart('!'), null, setting.Description), GUILayout.Width(LeftColumnWidth), GUILayout.MaxWidth(LeftColumnWidth)); GUI.color = origColor; } private static void DrawDefaultButton(SettingEntryBase setting) { if (setting.HideDefaultButton) return; object defaultValue = setting.DefaultValue; if (defaultValue != null || setting.SettingType.IsClass) { GUILayout.Space(5); if (GUILayout.Button(ImguiUtils.Content("Reset"), GUILayout.ExpandWidth(false))) setting.Set(defaultValue); } } private void Start() { // Use reflection to keep compatibility with unity 4.x since it doesn't have Cursor var tCursor = typeof(Cursor); _curLockState = tCursor.GetProperty("lockState", BindingFlags.Static | BindingFlags.Public); _curVisible = tCursor.GetProperty("visible", BindingFlags.Static | BindingFlags.Public); if (_curLockState == null && _curVisible == null) { _obsoleteCursor = true; _curLockState = typeof(Screen).GetProperty("lockCursor", BindingFlags.Static | BindingFlags.Public); _curVisible = typeof(Screen).GetProperty("showCursor", BindingFlags.Static | BindingFlags.Public); } // Check if user has permissions to write config files to disk try { Config.Save(); } catch (IOException ex) { Logger.Log(LogLevel.Message | LogLevel.Warning, "WARNING: Failed to write to config directory, expect issues!\nError message:" + ex.Message); } catch (UnauthorizedAccessException ex) { Logger.Log(LogLevel.Message | LogLevel.Warning, "WARNING: Permission denied to write to config directory, expect issues!\nError message:" + ex.Message); } } private void Update() { if (DisplayingWindow) SetUnlockCursor(0, true); if (OverrideHotkey) return; if (_keybind.Value.IsDown()) DisplayingWindow = !DisplayingWindow; } private void LateUpdate() { if (DisplayingWindow) SetUnlockCursor(0, true); } private void SetUnlockCursor(int lockState, bool cursorVisible) { if (_curLockState != null) { // Do through reflection for unity 4 compat //Cursor.lockState = CursorLockMode.None; //Cursor.visible = true; if (_obsoleteCursor) _curLockState.SetValue(null, Convert.ToBoolean(lockState), null); else _curLockState.SetValue(null, lockState, null); _curVisible.SetValue(null, cursorVisible, null); } } private sealed class PluginSettingsData { public BepInPlugin Info; public List Categories; public int Height; public string Website; private bool _collapsed; public bool Collapsed { get => _collapsed; set { _collapsed = value; Height = 0; } } public sealed class PluginSettingsGroupData { public string Name; public List Settings; } } } }