Skip to content

An OpenMW mod that lets you play the whole Elder Scrolls III: Morrowind as a top-down isometric game — with full online co-op or MMO modes.

C++
64.3 KB
Raw Blame
#include "settingswindow.hpp"

#include <algorithm>
#include <array>

#include <unicode/locid.h>

#include <MyGUI_Button.h>
#include <MyGUI_ComboBox.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_Gui.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_ListBox.h>
#include <MyGUI_ScrollBar.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TabControl.h>
#include <MyGUI_TabItem.h>
#include <MyGUI_UString.h>
#include <MyGUI_Window.h>

#include <SDL_video.h>

#include <components/debug/debuglog.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/l10n/manager.hpp>
#include <components/lua_ui/scriptsettings.hpp>
#include <components/lua_ui/widget.hpp>
#include <components/misc/constants.hpp>
#include <components/misc/display.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/lightmanager.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/recursivedirectoryiterator.hpp>
#include <components/widgets/sharedstatebutton.hpp>

#include "../mwbase/environment.hpp"
#include "../mwbase/inputmanager.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"

#include "../mwlua/luamanagerimp.hpp"
#include "../mwmp/Main.hpp"

#include "confirmationdialog.hpp"
#include "weightedsearch.hpp"

namespace
{
    std::string_view textureFilteringToStr(const std::string& mipFilter, const std::string& magFilter)
    {
        if (mipFilter == "none")
            return "#{OMWEngine:TextureFilteringDisabled}";

        if (magFilter == "linear")
        {
            if (mipFilter == "linear")
                return "#{OMWEngine:TextureFilteringTrilinear}";
            if (mipFilter == "nearest")
                return "#{OMWEngine:TextureFilteringBilinear}";
        }
        else if (magFilter == "nearest")
            return "#{OMWEngine:TextureFilteringNearest}";

        Log(Debug::Warning) << "Warning: Invalid texture filtering options: " << mipFilter << ", " << magFilter;
        return "#{OMWEngine:TextureFilteringOther}";
    }

    MyGUI::UString lightingMethodToStr(SceneUtil::LightingMethod method)
    {
        std::string_view result;
        switch (method)
        {
            case SceneUtil::LightingMethod::PerObjectUniform:
                result = "#{OMWEngine:LightingMethodShadersCompatibility}";
                break;
            case SceneUtil::LightingMethod::SingleUBO:
            default:
                result = "#{OMWEngine:LightingMethodShaders}";
                break;
        }

        return MyGUI::LanguageManager::getInstance().replaceTags(MyGUI::UString(result));
    }

    bool sortResolutions(std::pair<int, int> left, std::pair<int, int> right)
    {
        if (left.first == right.first)
            return left.second > right.second;
        return left.first > right.first;
    }

    const std::string_view checkButtonType = "CheckButton";
    const std::string_view sliderType = "Slider";

    std::string_view getSettingType(MyGUI::Widget* widget)
    {
        return widget->getUserString("SettingType");
    }

    std::string_view getSettingName(MyGUI::Widget* widget)
    {
        return widget->getUserString("SettingName");
    }

    std::string_view getSettingCategory(MyGUI::Widget* widget)
    {
        return widget->getUserString("SettingCategory");
    }

    std::string_view getSettingValueType(MyGUI::Widget* widget)
    {
        return widget->getUserString("SettingValueType");
    }

    void getSettingMinMax(MyGUI::Widget* widget, float& min, float& max)
    {
        const char* settingMin = "SettingMin";
        const char* settingMax = "SettingMax";
        min = 0.f;
        max = 1.f;
        if (!widget->getUserString(settingMin).empty())
            min = MyGUI::utility::parseFloat(widget->getUserString(settingMin));
        if (!widget->getUserString(settingMax).empty())
            max = MyGUI::utility::parseFloat(widget->getUserString(settingMax));
    }

    void updateMaxLightsComboBox(MyGUI::ComboBox* box)
    {
        constexpr int min = 8;
        constexpr int max = 64;
        constexpr int increment = 8;
        const int maxLights = Settings::shaders().mMaxLights;
        // show increments of 8 in dropdown
        if (maxLights >= min && maxLights <= max && !(maxLights % increment))
            box->setIndexSelected((maxLights / increment) - 1);
        else
            box->setIndexSelected(MyGUI::ITEM_NONE);
    }

    void updateSliderLabel(MyGUI::ScrollBar* scroller, MyGUI::TextBox* textBox,
        const std::vector<icu::UnicodeString>& argNames, const std::vector<icu::Formattable>& args)
    {
        if (textBox != nullptr)
        {
            auto l10n = MWBase::Environment::get().getL10nManager()->getContext("OMWEngine");
            std::string labelCaption
                = l10n->formatMessage(scroller->getUserString("SettingLabelCaption"), argNames, args);
            textBox->setCaption(labelCaption);
        }
    }

    // Isowind: the tab bar inside a page of Options (the Video page's), if it has one
    MyGUI::TabControl* findTabControl(MyGUI::Widget* parent)
    {
        MyGUI::EnumeratorWidgetPtr children = parent->getEnumerator();
        while (children.next())
        {
            MyGUI::Widget* widget = children.current();
            if (!widget->getVisible())
                continue;
            if (MyGUI::TabControl* tabs = widget->castType<MyGUI::TabControl>(false))
                return tabs;
            if (MyGUI::TabControl* tabs = findTabControl(widget))
                return tabs;
        }
        return nullptr;
    }

    // A tab's caption without the spaces it is padded with
    std::string tabName(const MyGUI::UString& caption)
    {
        const std::string name = caption.asUTF8();
        const size_t first = name.find_first_not_of(' ');
        if (first == std::string::npos)
            return {};
        return name.substr(first, name.find_last_not_of(' ') - first + 1);
    }
}

namespace MWGui
{
    void SettingsWindow::configureWidgets(MyGUI::Widget* widget, bool init)
    {
        MyGUI::EnumeratorWidgetPtr widgets = widget->getEnumerator();
        while (widgets.next())
        {
            MyGUI::Widget* current = widgets.current();

            std::string_view type = getSettingType(current);
            if (type == checkButtonType)
            {
                std::string_view initialValue
                    = Settings::get<bool>(getSettingCategory(current), getSettingName(current)) ? "#{Interface:On}"
                                                                                                : "#{Interface:Off}";
                current->castType<MyGUI::Button>()->setCaptionWithReplacing(initialValue);
                if (init)
                    current->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onButtonToggled);
            }
            if (type == sliderType)
            {
                MyGUI::ScrollBar* scroll = current->castType<MyGUI::ScrollBar>();
                std::string_view valueType = getSettingValueType(current);
                std::vector<icu::UnicodeString> argNames;
                std::vector<icu::Formattable> args;
                if (valueType == "Float" || valueType == "Integer" || valueType == "Cell")
                {
                    // TODO: ScrollBar isn't meant for this. should probably use a dedicated FloatSlider widget
                    float min, max;
                    getSettingMinMax(scroll, min, max);
                    float value;

                    if (valueType == "Cell")
                    {
                        value = Settings::get<float>(getSettingCategory(current), getSettingName(current));
                        argNames.emplace_back("cells");
                        args.emplace_back(value / Constants::CellSizeInUnits);
                    }
                    else if (valueType == "Float")
                    {
                        value = Settings::get<float>(getSettingCategory(current), getSettingName(current));
                        argNames.emplace_back("value");
                        args.emplace_back(value);
                    }
                    else
                    {
                        const int intValue = Settings::get<int>(getSettingCategory(current), getSettingName(current));
                        argNames.emplace_back("value");
                        args.emplace_back(intValue);
                        value = static_cast<float>(intValue);
                    }

                    value = std::clamp(value, min, max);
                    value = (value - min) / (max - min);

                    scroll->setScrollPosition(static_cast<size_t>(value * (scroll->getScrollRange() - 1)));
                }
                else
                {
                    const int value = Settings::get<int>(getSettingCategory(current), getSettingName(current));
                    argNames.emplace_back("value");
                    args.emplace_back(value);
                    scroll->setScrollPosition(value);
                }
                if (init)
                    scroll->eventScrollChangePosition
                        += MyGUI::newDelegate(this, &SettingsWindow::onSliderChangePosition);
                if (scroll->getVisible())
                    updateSliderLabel(scroll, getSliderLabel(scroll), argNames, args);
            }

            configureWidgets(current, init);
        }
    }

    void SettingsWindow::onFrame(float duration)
    {
        // Isowind: with a controller the control the pointer is on is framed, however the pointer got there
        if (Settings::gui().mControllerMenus && MWBase::Environment::get().getInputManager()->joystickLastUsed())
            frameControl(controlUnderPointer(collectControls()));
        else if (mControllerFrame)
            frameControl(nullptr);

        if (mScriptView->getVisible())
        {
            const auto scriptsSize = mScriptAdapter->getSize();
            if (mScriptView->getCanvasSize() != scriptsSize)
                mScriptView->setCanvasSize(scriptsSize);
        }
    }

    MyGUI::TextBox* SettingsWindow::getSliderLabel(MyGUI::ScrollBar* scroller) const
    {
        auto labelWidgetName = scroller->getUserString("SettingLabelWidget");
        if (!labelWidgetName.empty())
        {
            MyGUI::TextBox* textBox;
            getWidget(textBox, labelWidgetName);
            return textBox;
        }
        return nullptr;
    }

    SettingsWindow::SettingsWindow(Files::ConfigurationManager& cfgMgr)
        : WindowBase("openmw_settings_window.layout")
        , mKeyboardMode(true)
        , mCurrentPage(static_cast<size_t>(-1))
        , mCfgMgr(cfgMgr)
    {
        const bool terrain = Settings::terrain().mDistantTerrain;
        const std::string_view widgetName = terrain ? "RenderingDistanceSlider" : "LargeRenderingDistanceSlider";
        MyGUI::Widget* unusedSlider;
        getWidget(unusedSlider, widgetName);
        unusedSlider->setVisible(false);

        configureWidgets(mMainWidget, true);

        setTitle("#{OMWEngine:SettingsWindow}");

        getWidget(mSettingsTab, "SettingsTab");
        getWidget(mOkButton, "OkButton");
        getWidget(mResolutionList, "ResolutionList");
        getWidget(mWindowModeList, "WindowModeList");
        getWidget(mVSyncModeList, "VSyncModeList");
        getWidget(mWindowBorderButton, "WindowBorderButton");
        getWidget(mTextureFilteringButton, "TextureFilteringButton");
        getWidget(mControlsBox, "ControlsBox");
        getWidget(mResetControlsButton, "ResetControlsButton");
        getWidget(mKeyboardSwitch, "KeyboardButton");
        getWidget(mControllerSwitch, "ControllerButton");
        getWidget(mWaterRefractionButton, "WaterRefractionButton");
        getWidget(mSunlightScatteringButton, "SunlightScatteringButton");
        getWidget(mWobblyShoresButton, "WobblyShoresButton");
        getWidget(mWaterTextureSize, "WaterTextureSize");
        getWidget(mWaterReflectionDetail, "WaterReflectionDetail");
        getWidget(mWaterRainRippleDetail, "WaterRainRippleDetail");
        getWidget(mPrimaryLanguage, "PrimaryLanguage");
        getWidget(mSecondaryLanguage, "SecondaryLanguage");
        getWidget(mGmstOverridesL10n, "GmstOverridesL10nButton");
        getWidget(mWindowModeHint, "WindowModeHint");
        getWidget(mLightingMethodButton, "LightingMethodButton");
        getWidget(mLightsResetButton, "LightsResetButton");
        getWidget(mMaxLights, "MaxLights");
        getWidget(mScriptFilter, "ScriptFilter");
        getWidget(mScriptList, "ScriptList");
        getWidget(mScriptBox, "ScriptBox");
        getWidget(mScriptView, "ScriptView");
        getWidget(mScriptAdapter, "ScriptAdapter");
        getWidget(mScriptDisabled, "ScriptDisabled");

#ifndef WIN32
        // hide gamma controls since it currently does not work under Linux
        MyGUI::ScrollBar* gammaSlider;
        getWidget(gammaSlider, "GammaSlider");
        gammaSlider->setVisible(false);
        MyGUI::TextBox* textBox;
        getWidget(textBox, "GammaText");
        textBox->setVisible(false);
        getWidget(textBox, "GammaTextDark");
        textBox->setVisible(false);
        getWidget(textBox, "GammaTextLight");
        textBox->setVisible(false);
#endif

        mMainWidget->castType<MyGUI::Window>()->eventWindowChangeCoord
            += MyGUI::newDelegate(this, &SettingsWindow::onWindowResize);

        mSettingsTab->eventTabChangeSelect += MyGUI::newDelegate(this, &SettingsWindow::onTabChanged);
        for (size_t i = 0; i < mSettingsTab->getItemCount(); ++i)
        {
            if (MyGUI::TabControl* subTabs = findTabControl(mSettingsTab->getItemAt(i)))
                subTabs->eventTabChangeSelect += MyGUI::newDelegate(this, &SettingsWindow::onSubTabChanged);
        }
        mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onOkButtonClicked);
        mTextureFilteringButton->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onTextureFilteringChanged);
        mResolutionList->eventListChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onResolutionSelected);

        mWaterRefractionButton->eventMouseButtonClick
            += MyGUI::newDelegate(this, &SettingsWindow::onRefractionButtonClicked);
        mWaterTextureSize->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onWaterTextureSizeChanged);
        mWaterReflectionDetail->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onWaterReflectionDetailChanged);
        mWaterRainRippleDetail->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onWaterRainRippleDetailChanged);

        mLightingMethodButton->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onLightingMethodButtonChanged);
        mLightsResetButton->eventMouseButtonClick
            += MyGUI::newDelegate(this, &SettingsWindow::onLightsResetButtonClicked);
        mMaxLights->eventComboChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onMaxLightsChanged);

        mWindowModeList->eventComboChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onWindowModeChanged);
        mVSyncModeList->eventComboChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onVSyncModeChanged);

        mKeyboardSwitch->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onKeyboardSwitchClicked);
        mControllerSwitch->eventMouseButtonClick
            += MyGUI::newDelegate(this, &SettingsWindow::onControllerSwitchClicked);

        mPrimaryLanguage->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onPrimaryLanguageChanged);
        mSecondaryLanguage->eventComboChangePosition
            += MyGUI::newDelegate(this, &SettingsWindow::onSecondaryLanguageChanged);
        mGmstOverridesL10n->eventMouseButtonClick
            += MyGUI::newDelegate(this, &SettingsWindow::onGmstOverridesL10nChanged);

        computeMinimumWindowSize();

        center();

        mResetControlsButton->eventMouseButtonClick
            += MyGUI::newDelegate(this, &SettingsWindow::onResetDefaultBindings);

        // fill resolution list
        const int screen = Settings::video().mScreen;
        int numDisplayModes = SDL_GetNumDisplayModes(screen);
        std::vector<std::pair<int, int>> resolutions;
        for (int i = 0; i < numDisplayModes; i++)
        {
            SDL_DisplayMode mode;
            SDL_GetDisplayMode(screen, i, &mode);
            resolutions.emplace_back(mode.w, mode.h);
        }
        std::sort(resolutions.begin(), resolutions.end(), sortResolutions);
        for (std::pair<int, int>& resolution : resolutions)
        {
            std::string str = Misc::getResolutionText(resolution.first, resolution.second);

            if (mResolutionList->findItemIndexWith(str) == MyGUI::ITEM_NONE)
                mResolutionList->addItem(str, resolution);
        }
        highlightCurrentResolution();

        mTextureFilteringButton->setCaptionWithReplacing(
            textureFilteringToStr(Settings::general().mTextureMipmap, Settings::general().mTextureMinFilter));

        int waterTextureSize = Settings::water().mRttSize;
        if (waterTextureSize >= 512)
            mWaterTextureSize->setIndexSelected(0);
        if (waterTextureSize >= 1024)
            mWaterTextureSize->setIndexSelected(1);
        if (waterTextureSize >= 2048)
            mWaterTextureSize->setIndexSelected(2);

        const int waterReflectionDetail = Settings::water().mReflectionDetail;
        mWaterReflectionDetail->setIndexSelected(waterReflectionDetail);

        const int waterRainRippleDetail = Settings::water().mRainRippleDetail;
        mWaterRainRippleDetail->setIndexSelected(waterRainRippleDetail);

        const bool waterRefraction = Settings::water().mRefraction;
        mSunlightScatteringButton->setEnabled(waterRefraction);
        mWobblyShoresButton->setEnabled(waterRefraction);

        updateMaxLightsComboBox(mMaxLights);

        const Settings::WindowMode windowMode = Settings::video().mWindowMode;
        mWindowBorderButton->setEnabled(
            windowMode != Settings::WindowMode::Fullscreen && windowMode != Settings::WindowMode::WindowedFullscreen);

        mWindowModeHint->setVisible(windowMode == Settings::WindowMode::WindowedFullscreen);

        mKeyboardSwitch->setStateSelected(true);
        mControllerSwitch->setStateSelected(false);

        mScriptFilter->eventEditTextChange += MyGUI::newDelegate(this, &SettingsWindow::onScriptFilterChange);
        mScriptList->eventListMouseItemActivate += MyGUI::newDelegate(this, &SettingsWindow::onScriptListSelection);
        // Isowind: the D-pad's left / right (or the arrow keys) on the list opens the page too
        mScriptList->eventListChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onScriptListSelection);

        std::vector<std::string> availableLanguages;
        const VFS::Manager* vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
        constexpr VFS::Path::NormalizedView l10n("l10n/");
        for (const auto& path : vfs->getRecursiveDirectoryIterator(l10n))
        {
            if (path.extension() == "yaml")
            {
                std::string_view localeName(path.stem());
                if (localeName == "gmst")
                    continue; // fake locale to get gmst strings from content files
                if (std::find(availableLanguages.begin(), availableLanguages.end(), localeName)
                    == availableLanguages.end())
                    availableLanguages.emplace_back(localeName);
            }
        }

        std::sort(availableLanguages.begin(), availableLanguages.end());

        std::vector<std::string> currentLocales = Settings::general().mPreferredLocales;
        if (currentLocales.empty())
            currentLocales.push_back("en");

        icu::Locale primaryLocale(currentLocales[0].c_str());

        mPrimaryLanguage->removeAllItems();
        mPrimaryLanguage->setIndexSelected(MyGUI::ITEM_NONE);

        mSecondaryLanguage->removeAllItems();
        mSecondaryLanguage->addItem(
            MyGUI::LanguageManager::getInstance().replaceTags("#{Interface:None}"), std::string());
        mSecondaryLanguage->setIndexSelected(0);

        size_t i = 0;
        for (const auto& language : availableLanguages)
        {
            icu::Locale locale(language.c_str());

            icu::UnicodeString str(language.c_str());
            locale.getDisplayName(primaryLocale, str);
            std::string localeString;
            str.toUTF8String(localeString);

            mPrimaryLanguage->addItem(localeString, language);
            mSecondaryLanguage->addItem(localeString, language);

            if (language == currentLocales[0])
                mPrimaryLanguage->setIndexSelected(i);
            if (currentLocales.size() > 1 && language == currentLocales[1])
                mSecondaryLanguage->setIndexSelected(i + 1);

            i++;
        }

        mControllerButtons.mA = "#{Interface:Select}";
        mControllerButtons.mB = "#{Interface:OK}";
        mControllerButtons.mLStick = "#{Interface:Mouse}";
        mControllerButtons.mDpad = "#{Interface:Move}";
        mControllerButtons.mL1 = "#{Interface:Prev}";
        mControllerButtons.mR1 = "#{Interface:Next}";
    }

    void SettingsWindow::onTabChanged(MyGUI::TabControl* /*sender*/, size_t /*index*/)
    {
        resetScrollbars();
        MWBase::Environment::get().getWindowManager()->updateControllerButtonsOverlay();
    }

    void SettingsWindow::onSubTabChanged(MyGUI::TabControl* /*sender*/, size_t /*index*/)
    {
        // The legend names the tabs the triggers go to
        MWBase::Environment::get().getWindowManager()->updateControllerButtonsOverlay();
    }

    void SettingsWindow::onOkButtonClicked(MyGUI::Widget* /*sender*/)
    {
        MWBase::Environment::get().getWindowManager()->toggleSettingsWindow();
    }

    void SettingsWindow::onResolutionSelected(MyGUI::ListBox* /*sender*/, size_t index)
    {
        if (index == MyGUI::ITEM_NONE)
            return;

        ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
        dialog->askForConfirmation("#{OMWEngine:ConfirmResolution}");
        dialog->eventOkClicked.clear();
        dialog->eventOkClicked += MyGUI::newDelegate(this, &SettingsWindow::onResolutionAccept);
        dialog->eventCancelClicked.clear();
        dialog->eventCancelClicked += MyGUI::newDelegate(this, &SettingsWindow::onResolutionCancel);
    }

    void SettingsWindow::onResolutionAccept()
    {
        auto resolution = mResolutionList->getItemDataAt<std::pair<int, int>>(mResolutionList->getIndexSelected());
        if (resolution)
        {
            Settings::video().mResolutionX.set(resolution->first);
            Settings::video().mResolutionY.set(resolution->second);

            apply();
        }
    }

    void SettingsWindow::onResolutionCancel()
    {
        highlightCurrentResolution();
    }

    void SettingsWindow::highlightCurrentResolution()
    {
        mResolutionList->setIndexSelected(MyGUI::ITEM_NONE);

        const int currentX = Settings::video().mResolutionX;
        const int currentY = Settings::video().mResolutionY;

        for (size_t i = 0; i < mResolutionList->getItemCount(); ++i)
        {
            auto resolution = mResolutionList->getItemDataAt<std::pair<int, int>>(i);
            if (resolution && resolution->first == currentX && resolution->second == currentY)
            {
                mResolutionList->setIndexSelected(i);
                break;
            }
        }
    }

    void SettingsWindow::onRefractionButtonClicked(MyGUI::Widget* /*sender*/)
    {
        const bool refractionEnabled = Settings::water().mRefraction;

        mSunlightScatteringButton->setEnabled(refractionEnabled);
        mWobblyShoresButton->setEnabled(refractionEnabled);
    }

    void SettingsWindow::onWaterTextureSizeChanged(MyGUI::ComboBox* /*sender*/, size_t pos)
    {
        int size = 0;
        if (pos == 0)
            size = 512;
        else if (pos == 1)
            size = 1024;
        else if (pos == 2)
            size = 2048;
        Settings::water().mRttSize.set(size);
        apply();
    }

    void SettingsWindow::onWaterReflectionDetailChanged(MyGUI::ComboBox* /*sender*/, size_t pos)
    {
        Settings::water().mReflectionDetail.set(static_cast<int>(pos));
        apply();
    }

    void SettingsWindow::onWaterRainRippleDetailChanged(MyGUI::ComboBox* /*sender*/, size_t pos)
    {
        Settings::water().mRainRippleDetail.set(static_cast<int>(pos));
        apply();
    }

    void SettingsWindow::onLightingMethodButtonChanged(MyGUI::ComboBox* sender, size_t pos)
    {
        if (pos == MyGUI::ITEM_NONE)
            return;

        sender->setCaptionWithReplacing(sender->getItemNameAt(sender->getIndexSelected()));

        MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
            "#{OMWEngine:ChangeRequiresRestart}", { "#{Interface:OK}" }, true);

        Settings::shaders().mLightingMethod.set(
            Settings::parseLightingMethod(*sender->getItemDataAt<std::string>(pos)));
        apply();
    }

    void SettingsWindow::onLanguageChanged(size_t langPriority, MyGUI::ComboBox* sender, size_t pos)
    {
        if (pos == MyGUI::ITEM_NONE)
            return;

        sender->setCaptionWithReplacing(sender->getItemNameAt(sender->getIndexSelected()));

        MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
            "#{OMWEngine:ChangeRequiresRestart}", { "#{Interface:OK}" }, true);

        std::vector<std::string> currentLocales = Settings::general().mPreferredLocales;
        if (currentLocales.size() <= langPriority)
            currentLocales.resize(langPriority + 1, "en");

        const auto& languageCode = *sender->getItemDataAt<std::string>(pos);
        if (!languageCode.empty())
            currentLocales[langPriority] = languageCode;
        else
            currentLocales.resize(1);

        Settings::general().mPreferredLocales.set(currentLocales);
    }

    void SettingsWindow::onGmstOverridesL10nChanged(MyGUI::Widget*)
    {
        MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
            "#{OMWEngine:ChangeRequiresRestart}", { "#{Interface:OK}" }, true);
    }

    void SettingsWindow::onVSyncModeChanged(MyGUI::ComboBox* sender, size_t pos)
    {
        if (pos == MyGUI::ITEM_NONE)
            return;

        Settings::video().mVsyncMode.set(static_cast<SDLUtil::VSyncMode>(sender->getIndexSelected()));
        apply();
    }

    void SettingsWindow::onWindowModeChanged(MyGUI::ComboBox* sender, size_t pos)
    {
        if (pos == MyGUI::ITEM_NONE)
            return;

        const Settings::WindowMode windowMode = static_cast<Settings::WindowMode>(sender->getIndexSelected());
        if (windowMode == Settings::WindowMode::WindowedFullscreen)
        {
            mResolutionList->setEnabled(false);
            mWindowModeHint->setVisible(true);
        }
        else
        {
            mResolutionList->setEnabled(true);
            mWindowModeHint->setVisible(false);
        }

        if (windowMode == Settings::WindowMode::Windowed)
            mWindowBorderButton->setEnabled(true);
        else
            mWindowBorderButton->setEnabled(false);

        Settings::video().mWindowMode.set(windowMode);
        apply();
    }

    void SettingsWindow::onMaxLightsChanged(MyGUI::ComboBox* /*sender*/, size_t pos)
    {
        Settings::shaders().mMaxLights.set(8 * static_cast<int>(pos + 1));
        apply();
        configureWidgets(mMainWidget, false);
    }

    void SettingsWindow::onLightsResetButtonClicked(MyGUI::Widget* /*sender*/)
    {
        std::vector<std::string> buttons = { "#{Interface:Yes}", "#{Interface:No}" };
        MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
            "#{OMWEngine:LightingResetToDefaults}", buttons, true);
        int selectedButton = MWBase::Environment::get().getWindowManager()->readPressedButton();
        if (selectedButton == 1 || selectedButton == -1)
            return;

        Settings::shaders().mForcePerPixelLighting.reset();
        Settings::shaders().mClassicFalloff.reset();
        Settings::shaders().mClampLighting.reset();
        Settings::shaders().mMatchSunlightToSun.reset();
        Settings::shaders().mLightBoundsMultiplier.reset();
        Settings::shaders().mMaximumLightDistance.reset();
        Settings::shaders().mLightFadeStart.reset();
        Settings::shaders().mMinimumInteriorBrightness.reset();
        Settings::shaders().mMaxLights.reset();
        Settings::shaders().mLightingMethod.reset();

        const SceneUtil::LightingMethod lightingMethod = Settings::shaders().mLightingMethod;
        const std::size_t lightIndex = mLightingMethodButton->findItemIndexWith(lightingMethodToStr(lightingMethod));
        mLightingMethodButton->setIndexSelected(lightIndex);
        updateMaxLightsComboBox(mMaxLights);

        apply();
        configureWidgets(mMainWidget, false);
    }

    void SettingsWindow::onButtonToggled(MyGUI::Widget* sender)
    {
        const std::string on = MWBase::Environment::get().getL10nManager()->getMessage("Interface", "On");
        const std::string off = MWBase::Environment::get().getL10nManager()->getMessage("Interface", "Off");
        bool newState;
        if (sender->castType<MyGUI::Button>()->getCaption() == on)
        {
            sender->castType<MyGUI::Button>()->setCaption(MyGUI::UString(off));
            newState = false;
        }
        else
        {
            sender->castType<MyGUI::Button>()->setCaption(MyGUI::UString(on));
            newState = true;
        }

        if (getSettingType(sender) == checkButtonType)
        {
            Settings::get<bool>(getSettingCategory(sender), getSettingName(sender)).set(newState);
            apply();
            return;
        }
    }

    void SettingsWindow::onTextureFilteringChanged(MyGUI::ComboBox* /*sender*/, size_t pos)
    {
        auto& generalSettings = Settings::general();
        switch (pos)
        {
            case 0: // Bilinear with mips
                generalSettings.mTextureMipmap.set("nearest");
                generalSettings.mTextureMagFilter.set("linear");
                generalSettings.mTextureMinFilter.set("linear");
                break;
            case 1: // Trilinear with mips
                generalSettings.mTextureMipmap.set("linear");
                generalSettings.mTextureMagFilter.set("linear");
                generalSettings.mTextureMinFilter.set("linear");
                break;
            default:
                Log(Debug::Warning) << "Unexpected texture filtering option pos " << pos;
                break;
        }

        apply();
    }

    void SettingsWindow::onResChange(int /*width*/, int /*height*/)
    {
        center();
        highlightCurrentResolution();
    }

    void SettingsWindow::onSliderChangePosition(MyGUI::ScrollBar* scroller, size_t pos)
    {
        if (getSettingType(scroller) == "Slider")
        {
            std::vector<icu::UnicodeString> argNames;
            std::vector<icu::Formattable> args;
            std::string_view valueType = getSettingValueType(scroller);
            if (valueType == "Float" || valueType == "Integer" || valueType == "Cell")
            {
                float value = pos / float(scroller->getScrollRange() - 1);

                float min, max;
                getSettingMinMax(scroller, min, max);
                value = min + (max - min) * value;

                if (valueType == "Cell")
                {
                    Settings::get<float>(getSettingCategory(scroller), getSettingName(scroller)).set(value);
                    argNames.emplace_back("cells");
                    args.emplace_back(value / Constants::CellSizeInUnits);
                }
                else if (valueType == "Float")
                {
                    Settings::get<float>(getSettingCategory(scroller), getSettingName(scroller)).set(value);
                    argNames.emplace_back("value");
                    args.emplace_back(value);
                }
                else
                {
                    int intValue = static_cast<int>(value);
                    Settings::get<int>(getSettingCategory(scroller), getSettingName(scroller)).set(intValue);
                    argNames.emplace_back("value");
                    args.emplace_back(intValue);
                }
            }
            else
            {
                int intValue = static_cast<int>(pos);
                Settings::get<int>(getSettingCategory(scroller), getSettingName(scroller)).set(intValue);
                argNames.emplace_back("value");
                args.emplace_back(intValue);
            }
            updateSliderLabel(scroller, getSliderLabel(scroller), argNames, args);

            apply();
        }
    }

    void SettingsWindow::apply()
    {
        const Settings::CategorySettingVector changed = Settings::Manager::getPendingChanges();
        MWBase::Environment::get().getWorld()->processChangedSettings(changed);
        MWBase::Environment::get().getSoundManager()->processChangedSettings(changed);
        MWBase::Environment::get().getWindowManager()->processChangedSettings(changed);
        MWBase::Environment::get().getInputManager()->processChangedSettings(changed);
        MWBase::Environment::get().getMechanicsManager()->processChangedSettings(changed);
        Settings::Manager::resetPendingChanges();
    }

    void SettingsWindow::onKeyboardSwitchClicked(MyGUI::Widget* /*sender*/)
    {
        if (mKeyboardMode)
            return;
        mKeyboardMode = true;
        mKeyboardSwitch->setStateSelected(true);
        mControllerSwitch->setStateSelected(false);
        updateControlsBox();
        resetScrollbars();
        MWBase::Environment::get().getWindowManager()->updateControllerButtonsOverlay();
    }

    void SettingsWindow::onControllerSwitchClicked(MyGUI::Widget* /*sender*/)
    {
        if (!mKeyboardMode)
            return;
        mKeyboardMode = false;
        mKeyboardSwitch->setStateSelected(false);
        mControllerSwitch->setStateSelected(true);
        updateControlsBox();
        resetScrollbars();
        MWBase::Environment::get().getWindowManager()->updateControllerButtonsOverlay();
    }

    void SettingsWindow::updateControlsBox()
    {
        frameControl(nullptr); // (it may be among the rows about to go)
        while (mControlsBox->getChildCount())
            MyGUI::Gui::getInstance().destroyWidget(mControlsBox->getChildAt(0));

        MWBase::Environment::get().getWindowManager()->removeStaticMessageBox();
        const auto inputManager = MWBase::Environment::get().getInputManager();
        const auto& actions
            = mKeyboardMode ? inputManager->getActionKeySorting() : inputManager->getActionControllerSorting();

        for (const int& action : actions)
        {
            std::string desc{ inputManager->getActionDescription(action) };
            if (desc.empty())
                continue;

            std::string binding;
            if (mKeyboardMode)
                binding = inputManager->getActionKeyBindingName(action);
            else
                binding = inputManager->getActionControllerBindingName(action);

            Gui::SharedStateButton* leftText = mControlsBox->createWidget<Gui::SharedStateButton>(
                "SandTextButton", MyGUI::IntCoord(), MyGUI::Align::Default);
            leftText->setCaptionWithReplacing(desc);

            Gui::SharedStateButton* rightText = mControlsBox->createWidget<Gui::SharedStateButton>(
                "SandTextButton", MyGUI::IntCoord(), MyGUI::Align::Default);
            rightText->setCaptionWithReplacing(binding);
            rightText->setTextAlign(MyGUI::Align::Right);
            rightText->setUserData(action); // save the action id for callbacks
            rightText->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onRebindAction);
            rightText->eventMouseWheel += MyGUI::newDelegate(this, &SettingsWindow::onInputTabMouseWheel);

            Gui::ButtonGroup group;
            group.push_back(leftText);
            group.push_back(rightText);
            Gui::SharedStateButton::createButtonGroup(group);
        }

        layoutControlsBox();
    }

    void SettingsWindow::updateLightSettings()
    {
        auto lightingMethod = MWBase::Environment::get().getResourceSystem()->getSceneManager()->getLightingMethod();
        MyGUI::UString lightingMethodStr = lightingMethodToStr(lightingMethod);

        mLightingMethodButton->removeAllItems();

        std::array<SceneUtil::LightingMethod, 2> methods = {
            SceneUtil::LightingMethod::PerObjectUniform,
            SceneUtil::LightingMethod::SingleUBO,
        };

        for (const auto& method : methods)
        {
            if (!MWBase::Environment::get().getResourceSystem()->getSceneManager()->isSupportedLightingMethod(method))
                continue;

            mLightingMethodButton->addItem(
                lightingMethodToStr(method), SceneUtil::LightManager::getLightingMethodString(method));
        }
        mLightingMethodButton->setIndexSelected(mLightingMethodButton->findItemIndexWith(lightingMethodStr));
    }

    void SettingsWindow::updateWindowModeSettings()
    {
        const Settings::WindowMode windowMode = Settings::video().mWindowMode;
        const std::size_t windowModeIndex = static_cast<std::size_t>(windowMode);

        mWindowModeList->setIndexSelected(windowModeIndex);

        if (windowMode != Settings::WindowMode::Windowed && windowModeIndex != MyGUI::ITEM_NONE)
        {
            // check if this resolution is supported in fullscreen
            if (mResolutionList->getIndexSelected() != MyGUI::ITEM_NONE)
            {
                auto resolution
                    = mResolutionList->getItemDataAt<std::pair<int, int>>(mResolutionList->getIndexSelected());
                if (resolution)
                {
                    Settings::video().mResolutionX.set(resolution->first);
                    Settings::video().mResolutionY.set(resolution->second);
                }
            }

            bool supported = false;
            int fallbackX = 0, fallbackY = 0;
            for (size_t i = 0; i < mResolutionList->getItemCount(); ++i)
            {
                auto resolution = mResolutionList->getItemDataAt<std::pair<int, int>>(i);
                if (!resolution)
                    continue;

                if (i == 0)
                {
                    fallbackX = resolution->first;
                    fallbackY = resolution->second;
                }

                if (resolution->first == Settings::video().mResolutionX
                    && resolution->second == Settings::video().mResolutionY)
                    supported = true;
            }

            if (!supported && mResolutionList->getItemCount())
            {
                if (fallbackX != 0 && fallbackY != 0)
                {
                    Settings::video().mResolutionX.set(fallbackX);
                    Settings::video().mResolutionY.set(fallbackY);
                }
            }

            mWindowBorderButton->setEnabled(false);
        }

        if (windowMode == Settings::WindowMode::WindowedFullscreen)
            mResolutionList->setEnabled(false);
    }

    void SettingsWindow::updateVSyncModeSettings()
    {
        mVSyncModeList->setIndexSelected(static_cast<size_t>(Settings::video().mVsyncMode));
    }

    void SettingsWindow::layoutControlsBox()
    {
        const int h = Settings::gui().mFontSize + 2;
        const int w = mControlsBox->getWidth() - 28;
        const int noWidgetsInRow = 2;
        const int totalH = static_cast<int>(mControlsBox->getChildCount() / noWidgetsInRow) * h;

        for (size_t i = 0; i < mControlsBox->getChildCount(); i++)
        {
            MyGUI::Widget* widget = mControlsBox->getChildAt(i);
            widget->setCoord(0, static_cast<int>(i / noWidgetsInRow * h), w, h);
        }

        // Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
        // scrollbar is hidden
        mControlsBox->setVisibleVScroll(false);
        mControlsBox->setCanvasSize(mControlsBox->getWidth(), std::max(totalH, mControlsBox->getHeight()));
        mControlsBox->setVisibleVScroll(true);
    }

    void SettingsWindow::renderScriptSettings()
    {
        mScriptAdapter->detach();

        mScriptList->removeAllItems();
        mScriptView->setCanvasSize({ 0, 0 });

        struct WeightedPage
        {
            size_t mIndex;
            std::string mName;
            size_t mNameWeight;
            size_t mHintWeight;

            constexpr bool operator<(const WeightedPage& rhs) const
            {
                if (mNameWeight != rhs.mNameWeight)
                    return mNameWeight > rhs.mNameWeight;
                if (mHintWeight != rhs.mHintWeight)
                    return mHintWeight > rhs.mHintWeight;
                return mName < rhs.mName;
            }
        };

        const std::vector<std::string> patternArray = generatePatternArray(mScriptFilter->getCaption());
        std::vector<WeightedPage> weightedPages;
        weightedPages.reserve(LuaUi::scriptSettingsPageCount());
        for (size_t i = 0; i < LuaUi::scriptSettingsPageCount(); ++i)
        {
            LuaUi::ScriptSettingsPage page = LuaUi::scriptSettingsPageAt(i);
            size_t nameWeight = weightedSearch(page.mName, patternArray);
            size_t hintWeight = weightedSearch(page.mSearchHints, patternArray);
            if ((nameWeight + hintWeight) > 0)
                weightedPages.push_back({ i, page.mName, nameWeight, hintWeight });
        }
        std::sort(weightedPages.begin(), weightedPages.end());
        for (const WeightedPage& weightedPage : weightedPages)
            mScriptList->addItem(weightedPage.mName, weightedPage.mIndex);

        // Hide script settings when the game world isn't loaded
        bool disabled = LuaUi::scriptSettingsPageCount() == 0;
        mScriptFilter->setVisible(!disabled);
        mScriptList->setVisible(!disabled);
        mScriptBox->setVisible(!disabled);
        mScriptDisabled->setVisible(disabled);

        LuaUi::attachPageAt(mCurrentPage, mScriptAdapter);
    }

    void SettingsWindow::onScriptFilterChange(MyGUI::EditBox*)
    {
        renderScriptSettings();
    }

    void SettingsWindow::onScriptListSelection(MyGUI::ListBox*, size_t index)
    {
        mScriptAdapter->detach();
        mCurrentPage = static_cast<size_t>(-1);
        if (index < mScriptList->getItemCount())
        {
            mCurrentPage = *mScriptList->getItemDataAt<size_t>(index);
            LuaUi::attachPageAt(mCurrentPage, mScriptAdapter);
        }
    }

    void SettingsWindow::onRebindAction(MyGUI::Widget* sender)
    {
        int actionId = *sender->getUserData<int>();

        sender->castType<MyGUI::Button>()->setCaptionWithReplacing("#{Interface:None}");

        MWBase::Environment::get().getWindowManager()->staticMessageBox("#{OMWEngine:RebindAction}");
        MWBase::Environment::get().getWindowManager()->disallowMouse();

        MWBase::Environment::get().getInputManager()->enableDetectingBindingMode(actionId, mKeyboardMode);
    }

    void SettingsWindow::onInputTabMouseWheel(MyGUI::Widget* /*sender*/, int rel)
    {
        if (mControlsBox->getViewOffset().top + rel * 0.3f > 0)
            mControlsBox->setViewOffset(MyGUI::IntPoint(0, 0));
        else
            mControlsBox->setViewOffset(
                MyGUI::IntPoint(0, static_cast<int>(mControlsBox->getViewOffset().top + rel * 0.3f)));
    }

    void SettingsWindow::onResetDefaultBindings(MyGUI::Widget* /*sender*/)
    {
        ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
        dialog->askForConfirmation("#{OMWEngine:ConfirmResetBindings}");
        dialog->eventOkClicked.clear();
        dialog->eventOkClicked += MyGUI::newDelegate(this, &SettingsWindow::onResetDefaultBindingsAccept);
        dialog->eventCancelClicked.clear();
    }

    void SettingsWindow::onResetDefaultBindingsAccept()
    {
        if (mKeyboardMode)
            MWBase::Environment::get().getInputManager()->resetToDefaultKeyBindings();
        else
            MWBase::Environment::get().getInputManager()->resetToDefaultControllerBindings();
        updateControlsBox();
    }

    void SettingsWindow::onOpen()
    {
        highlightCurrentResolution();
        updateControlsBox();
        updateLightSettings();
        updateWindowModeSettings();
        updateVSyncModeSettings();
        resetScrollbars();
        renderScriptSettings();

        // Isowind multiplayer: the server sets the difficulty, so its slider is hidden
        MyGUI::Widget* difficultyText = nullptr;
        getWidget(difficultyText, "DifficultyText");
        difficultyText->getParent()->setVisible(!mwmp::Main::isInitialized());

        MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mOkButton);

        // Isowind: with a controller the pointer starts on the page's first control
        if (Settings::gui().mControllerMenus && MWBase::Environment::get().getInputManager()->joystickLastUsed())
            pointAtFirstControl();
    }

    void SettingsWindow::onClose()
    {
        frameControl(nullptr);
        // Save user settings
        Settings::Manager::saveUser(mCfgMgr.getUserConfigPath() / "settings.cfg");
        MWBase::Environment::get().getLuaManager()->savePermanentStorage(mCfgMgr.getUserConfigPath());
        MWBase::Environment::get().getInputManager()->saveBindings();
    }

    void SettingsWindow::onWindowResize(MyGUI::Window* /*sender*/)
    {
        layoutControlsBox();
    }

    void SettingsWindow::computeMinimumWindowSize()
    {
        auto* window = mMainWidget->castType<MyGUI::Window>();
        auto minSize = window->getMinSize();

        // Window should be at minimum wide enough to show all tabs.
        int tabBarWidth = 0;
        for (uint32_t i = 0; i < mSettingsTab->getItemCount(); i++)
        {
            tabBarWidth += mSettingsTab->getButtonWidthAt(i);
        }

        // Need to include window margins
        int margins = mMainWidget->getWidth() - mSettingsTab->getWidth();
        int minimumWindowWidth = tabBarWidth + margins;

        if (minimumWindowWidth > minSize.width)
        {
            minSize.width = minimumWindowWidth;
            window->setMinSize(minSize);

            // Make a dummy call to setSize so MyGUI can apply any resize resulting from the change in MinSize
            mMainWidget->setSize(mMainWidget->getSize());
        }
    }

    void SettingsWindow::resetScrollbars()
    {
        mResolutionList->setScrollPosition(0);
        mControlsBox->setViewOffset(MyGUI::IntPoint(0, 0));
    }

    bool SettingsWindow::stepTab(int delta)
    {
        mSettingsTab->setIndexSelected(wrap(mSettingsTab->getIndexSelected(), mSettingsTab->getItemCount(), delta));
        MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
        winMgr->playSound(ESM::RefId::stringRefId("Menu Click"));
        winMgr->updateControllerButtonsOverlay();
        return true;
    }

    bool SettingsWindow::onControllerButtonEvent(const SDL_ControllerButtonEvent& arg)
    {
        if (arg.button == SDL_CONTROLLER_BUTTON_B)
        {
            onOkButtonClicked(mOkButton);
            return true;
        }
        else if (arg.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER || arg.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)
        {
            stepTab(arg.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ? 1 : -1);
            pointAtFirstControl();
            return true;
        }
        // Isowind: the D-pad steps the pointer through the page's controls, A works the one it is on
        else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
        {
            stepControl(-1);
            return true;
        }
        else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
        {
            stepControl(1);
            return true;
        }
        else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT)
        {
            adjustControl(-1);
            return true;
        }
        else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT)
        {
            adjustControl(1);
            return true;
        }
        else if (arg.button == SDL_CONTROLLER_BUTTON_A)
        {
            selectControl();
            return true;
        }

        return false;
    }

    namespace
    {
        bool isInside(const MyGUI::Widget* widget, const MyGUI::Widget* parent)
        {
            for (; widget != nullptr; widget = widget->getParent())
            {
                if (widget == parent)
                    return true;
            }
            return false;
        }

        // A widget of a script's settings page that a click works (a binding, a "Yes" / "No", the arrows, Reset)
        bool isScriptClickable(MyGUI::Widget* widget)
        {
            const LuaUi::WidgetExtension* lua = dynamic_cast<LuaUi::WidgetExtension*>(widget);
            return lua != nullptr && lua->hasCallback("mouseClick");
        }

        void clickAtPointer()
        {
            MyGUI::InputManager& input = MyGUI::InputManager::getInstance();
            const MyGUI::IntPoint mouse = input.getMousePosition();
            input.injectMousePress(mouse.left, mouse.top, MyGUI::MouseButton::Left);
            input.injectMouseRelease(mouse.left, mouse.top, MyGUI::MouseButton::Left);
        }
    }

    // The controls of the page: buttons (checkboxes among them), sliders, drop-down lists, lists, text boxes, inner
    // tab bars (the outer tabs are the bumpers') and what a script's page has to click, top to bottom
    void SettingsWindow::collectControls(MyGUI::Widget* parent, std::vector<MyGUI::Widget*>& controls) const
    {
        MyGUI::EnumeratorWidgetPtr children = parent->getEnumerator();
        while (children.next())
        {
            MyGUI::Widget* widget = children.current();
            if (!widget->getVisible() || !widget->getEnabled())
                continue;
            // Before the text boxes: a script's text is one
            if (isScriptClickable(widget))
                controls.push_back(widget);
            else if (MyGUI::TabControl* tabs = widget->castType<MyGUI::TabControl>(false))
            {
                if (tabs != mSettingsTab)
                    controls.push_back(tabs);
                if (tabs->getIndexSelected() != MyGUI::ITEM_NONE)
                    collectControls(tabs->getItemAt(tabs->getIndexSelected()), controls);
            }
            else if (widget->castType<MyGUI::ComboBox>(false) || widget->castType<MyGUI::ListBox>(false)
                || widget->castType<MyGUI::ScrollBar>(false))
                controls.push_back(widget);
            else if (MyGUI::EditBox* edit = widget->castType<MyGUI::EditBox>(false))
            {
                if (!edit->getEditStatic() && !edit->getEditReadOnly())
                    controls.push_back(widget);
            }
            else if (widget->castType<MyGUI::Button>(false))
            {
                // The names in the controls list are buttons too; only the bindings beside them do anything
                if (!isInside(widget, mControlsBox) || widget->getUserData<int>(false) != nullptr)
                    controls.push_back(widget);
            }
            else
                collectControls(widget, controls);
        }
    }

    std::vector<MyGUI::Widget*> SettingsWindow::collectControls() const
    {
        std::vector<MyGUI::Widget*> controls;
        collectControls(mMainWidget, controls);
        std::stable_sort(controls.begin(), controls.end(), [](const MyGUI::Widget* a, const MyGUI::Widget* b) {
            const MyGUI::IntCoord coordA = a->getAbsoluteCoord();
            const MyGUI::IntCoord coordB = b->getAbsoluteCoord();
            return coordA.top != coordB.top ? coordA.top < coordB.top : coordA.left < coordB.left;
        });
        return controls;
    }

    MyGUI::Widget* SettingsWindow::controlUnderPointer(const std::vector<MyGUI::Widget*>& controls) const
    {
        for (MyGUI::Widget* widget = MyGUI::InputManager::getInstance().getMouseFocusWidget(); widget != nullptr;
            widget = widget->getParent())
        {
            if (std::find(controls.begin(), controls.end(), widget) != controls.end())
                return widget;
        }
        return nullptr;
    }

    void SettingsWindow::pointAt(MyGUI::Widget* control)
    {
        if (!control)
            return;
        // A row of the controls list, or a script's setting, scrolls into view first
        for (MyGUI::ScrollView* view : { mControlsBox, mScriptView })
        {
            if (!isInside(control, view) || control == view)
                continue;
            MyGUI::IntPoint offset = view->getViewOffset();
            const MyGUI::IntCoord viewCoord = view->getViewCoord();
            const int top = control->getAbsoluteTop() - view->getAbsoluteTop() - viewCoord.top;
            if (top < 0)
                offset.top -= top;
            else if (top + control->getHeight() > viewCoord.height)
                offset.top -= top + control->getHeight() - viewCoord.height;
            view->setViewOffset(offset);
        }
        // The middle of the control; an inner tab bar on the tabs themselves along its top, and a list on the row
        // it has chosen, if that is in view
        MyGUI::Widget* target = control;
        float yFraction = 0.5f;
        if (control->castType<MyGUI::TabControl>(false))
            yFraction = std::min(0.5f, 12.f / static_cast<float>(std::max(1, control->getHeight())));
        else if (MyGUI::ListBox* list = control->castType<MyGUI::ListBox>(false))
        {
            MyGUI::Widget* row = list->getIndexSelected() != MyGUI::ITEM_NONE
                ? list->getWidgetByIndex(list->getIndexSelected())
                : nullptr;
            if (row && row->getVisible())
                target = row;
            else
                yFraction = std::min(0.5f, 12.f / static_cast<float>(std::max(1, control->getHeight())));
        }
        MWBase::InputManager* input = MWBase::Environment::get().getInputManager();
        input->setGamepadGuiCursorEnabled(true);
        input->warpMouseToWidget(target, yFraction);
        // The warp may not come back as a mouse move (Wayland): tell the GUI where the pointer is ourselves
        const MyGUI::IntCoord coord = target->getAbsoluteCoord();
        MyGUI::InputManager::getInstance().injectMouseMove(
            coord.left + coord.width / 2, coord.top + static_cast<int>(coord.height * yFraction), 0);
        // The pointer shows and is live on the control, besides the frame (frameControl): stepping finds the control
        // it is on by the GUI's mouse focus, which a hidden pointer doesn't keep (the D-pad would stay on one control)
        MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
        winMgr->setCursorVisible(true);
        winMgr->setCursorActive(true);
        frameControl(control);
    }

    // Morrowind's gold box frame around the control, drawn beside it in its own parent so it scrolls along. On a
    // script's page that is the page's adapter: the script rebuilds its own widgets, which would take the frame along.
    void SettingsWindow::frameControl(MyGUI::Widget* control)
    {
        constexpr int margin = 3;
        const bool onScriptPage = control && isInside(control, mScriptAdapter);
        if (control != mFramedControl || !control)
        {
            if (mControllerFrame)
            {
                MyGUI::Gui::getInstance().destroyWidget(mControllerFrame);
                mControllerFrame = nullptr;
            }
            mFramedControl = control;
            if (!control || !control->getParent())
                return;
            MyGUI::Widget* parent = onScriptPage ? mScriptAdapter : control->getParent();
            mControllerFrame
                = parent->createWidget<MyGUI::Widget>("MW_Box_Overlay", MyGUI::IntCoord(), MyGUI::Align::Default);
            mControllerFrame->setNeedMouseFocus(false);
        }
        if (mControllerFrame)
        {
            MyGUI::IntCoord coord = control->getCoord();
            if (onScriptPage)
                coord = control->getAbsoluteCoord() - mScriptAdapter->getAbsolutePosition();
            mControllerFrame->setCoord(
                coord.left - margin, coord.top - margin, coord.width + 2 * margin, coord.height + 2 * margin);
        }
    }

    void SettingsWindow::pointAtFirstControl()
    {
        const std::vector<MyGUI::Widget*> controls = collectControls();
        if (!controls.empty())
            pointAt(controls.front());
    }

    void SettingsWindow::stepControl(int delta)
    {
        const std::vector<MyGUI::Widget*> controls = collectControls();
        if (controls.empty())
            return;
        // From the control the pointer is on, or else from the pointer itself
        MyGUI::IntPoint from = MyGUI::InputManager::getInstance().getMousePosition();
        if (const MyGUI::Widget* current = controlUnderPointer(controls))
        {
            const MyGUI::IntCoord coord = current->getAbsoluteCoord();
            from = MyGUI::IntPoint(coord.left + coord.width / 2, coord.top + coord.height / 2);
        }
        // The nearest control below (or above): the next row down wins over a nearer one off to the side, so a
        // column is walked before the next one. None: round to the far end.
        MyGUI::Widget* best = nullptr;
        MyGUI::Widget* farthest = nullptr;
        int bestScore = 0;
        int farthestY = 0;
        for (MyGUI::Widget* control : controls)
        {
            const MyGUI::IntCoord coord = control->getAbsoluteCoord();
            const int x = coord.left + coord.width / 2;
            const int y = coord.top + coord.height / 2;
            const int dy = (y - from.top) * delta;
            if (dy > 2)
            {
                const int score = dy + std::abs(x - from.left) / 2;
                if (!best || score < bestScore)
                {
                    best = control;
                    bestScore = score;
                }
            }
            const int toward = -y * delta;
            if (!farthest || toward > farthestY)
            {
                farthest = control;
                farthestY = toward;
            }
        }
        pointAt(best ? best : farthest);
    }

    void SettingsWindow::adjustControl(int delta)
    {
        MyGUI::Widget* control = controlUnderPointer(collectControls());
        if (!control)
            return;
        if (MyGUI::ScrollBar* slider = control->castType<MyGUI::ScrollBar>(false))
        {
            const int range = static_cast<int>(slider->getScrollRange());
            if (range <= 0)
                return;
            const int step = std::max(1, static_cast<int>(slider->getScrollPage()));
            const int position = std::clamp(static_cast<int>(slider->getScrollPosition()) + delta * step, 0, range - 1);
            slider->setScrollPosition(position);
            onSliderChangePosition(slider, position);
        }
        else if (MyGUI::ComboBox* combo = control->castType<MyGUI::ComboBox>(false))
        {
            if (combo->getItemCount() == 0)
                return;
            const size_t index = wrap(combo->getIndexSelected(), combo->getItemCount(), delta);
            combo->setIndexSelected(index);
            combo->eventComboChangePosition(combo, index);
        }
        else if (MyGUI::ListBox* list = control->castType<MyGUI::ListBox>(false))
        {
            const size_t count = list->getItemCount();
            if (count == 0)
                return;
            size_t index = list->getIndexSelected();
            if (index == MyGUI::ITEM_NONE)
                index = 0;
            else if (delta < 0)
                index = index == 0 ? 0 : index - 1;
            else
                index = std::min(index + 1, count - 1);
            list->setIndexSelected(index);
            list->beginToItemAt(index);
            list->eventListChangePosition(list, index);
            // The pointer goes along to the row, so that A there doesn't click the one it was on
            pointAt(list);
        }
        else if (MyGUI::TabControl* tabs = control->castType<MyGUI::TabControl>(false))
        {
            if (tabs->getItemCount() == 0)
                return;
            tabs->setIndexSelected(wrap(tabs->getIndexSelected(), tabs->getItemCount(), delta));
            onSubTabChanged(tabs, tabs->getIndexSelected());
            pointAt(tabs);
        }
        else
            return;
        MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
        winMgr->playSound(ESM::RefId::stringRefId("Menu Click"));
        winMgr->setCursorActive(true);
    }

    void SettingsWindow::selectControl()
    {
        MyGUI::Widget* control = controlUnderPointer(collectControls());
        MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
        if (control
            && (control->castType<MyGUI::ComboBox>(false) || control->castType<MyGUI::ScrollBar>(false)
                || control->castType<MyGUI::TabControl>(false)))
        {
            // Stepped through rather than dropped down
            adjustControl(1);
            return;
        }
        if (!control || isScriptClickable(control) || control->castType<MyGUI::ListBox>(false))
        {
            // A row of a list, a script's setting, or something the page doesn't know: a click there
            clickAtPointer();
        }
        else if (MyGUI::EditBox* edit = control->castType<MyGUI::EditBox>(false))
        {
            // The keyboard on the screen comes up for it
            winMgr->setKeyFocusWidget(edit);
        }
        else if (MyGUI::Button* button = control->castType<MyGUI::Button>(false))
            button->eventMouseButtonClick(button);
        winMgr->playSound(ESM::RefId::stringRefId("Menu Click"));
        winMgr->setCursorActive(true);
    }

    MyGUI::Widget* SettingsWindow::getShownPage() const
    {
        const size_t index = mSettingsTab->getIndexSelected();
        return index != MyGUI::ITEM_NONE ? mSettingsTab->getItemAt(index) : nullptr;
    }

    MyGUI::TabControl* SettingsWindow::getSubTabs() const
    {
        MyGUI::Widget* page = getShownPage();
        return page ? findTabControl(page) : nullptr;
    }

    bool SettingsWindow::stepSubTab(int delta)
    {
        if (isInside(mKeyboardSwitch, getShownPage()))
        {
            // Two of them: either way goes to the other
            if (mKeyboardMode)
                onControllerSwitchClicked(mControllerSwitch);
            else
                onKeyboardSwitchClicked(mKeyboardSwitch);
        }
        else if (MyGUI::TabControl* tabs = getSubTabs(); tabs && tabs->getItemCount() > 1)
        {
            tabs->setIndexSelected(wrap(tabs->getIndexSelected(), tabs->getItemCount(), delta));
            onSubTabChanged(tabs, tabs->getIndexSelected());
        }
        else
            return false;
        MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Menu Click"));
        return true;
    }

    bool SettingsWindow::onControllerTrigger(int delta)
    {
        // The pointer starts on the tab as it does on a page the bumpers turn to. On a page without tabs inside the
        // triggers do nothing, rather than go to the windows under Options.
        if (stepSubTab(delta))
            pointAtFirstControl();
        return true;
    }

    ControllerButtons* SettingsWindow::getControllerButtons()
    {
        // The triggers, by the names of the tabs inside the page they go to: the one either side, or of two the
        // other on its side
        std::vector<std::string> names;
        size_t shown = 0;
        if (isInside(mKeyboardSwitch, getShownPage()))
        {
            names = { tabName(mKeyboardSwitch->getCaption()), tabName(mControllerSwitch->getCaption()) };
            shown = mKeyboardMode ? 0 : 1;
        }
        else if (MyGUI::TabControl* tabs = getSubTabs(); tabs && tabs->getIndexSelected() != MyGUI::ITEM_NONE)
        {
            for (size_t i = 0; i < tabs->getItemCount(); ++i)
                names.push_back(tabName(tabs->getItemNameAt(i)));
            shown = tabs->getIndexSelected();
        }
        mControllerButtons.mL2.clear();
        mControllerButtons.mR2.clear();
        if (names.size() > 2 || (names.size() == 2 && shown == 1))
            mControllerButtons.mL2 = names[wrap(shown, names.size(), -1)];
        if (names.size() > 2 || (names.size() == 2 && shown == 0))
            mControllerButtons.mR2 = names[wrap(shown, names.size(), 1)];
        return &mControllerButtons;
    }

}