code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#ifdef YUZU_USE_QT_WEB_ENGINE
#include <bit>

#include <QApplication>
#include <QKeyEvent>

#include <QWebEngineProfile>
#include <QWebEngineScript>
#include <QWebEngineScriptCollection>
#include <QWebEngineSettings>
#include <QWebEngineUrlScheme>

#include "hid_core/frontend/input_interpreter.h"
#include "yuzu/applets/qt_web_browser_scripts.h"
#endif

#include "common/fs/path_util.h"
#include "core/core.h"
#include "input_common/drivers/keyboard.h"
#include "yuzu/applets/qt_web_browser.h"
#include "yuzu/main.h"
#include "yuzu/util/url_request_interceptor.h"

#ifdef YUZU_USE_QT_WEB_ENGINE

namespace {

constexpr int HIDButtonToKey(Core::HID::NpadButton button) {
    switch (button) {
    case Core::HID::NpadButton::Left:
    case Core::HID::NpadButton::StickLLeft:
        return Qt::Key_Left;
    case Core::HID::NpadButton::Up:
    case Core::HID::NpadButton::StickLUp:
        return Qt::Key_Up;
    case Core::HID::NpadButton::Right:
    case Core::HID::NpadButton::StickLRight:
        return Qt::Key_Right;
    case Core::HID::NpadButton::Down:
    case Core::HID::NpadButton::StickLDown:
        return Qt::Key_Down;
    default:
        return 0;
    }
}

} // Anonymous namespace

QtNXWebEngineView::QtNXWebEngineView(QWidget* parent, Core::System& system,
                                     InputCommon::InputSubsystem* input_subsystem_)
    : QWebEngineView(parent), input_subsystem{input_subsystem_},
      url_interceptor(std::make_unique<UrlRequestInterceptor>()),
      input_interpreter(std::make_unique<InputInterpreter>(system)),
      default_profile{QWebEngineProfile::defaultProfile()}, global_settings{
                                                                default_profile->settings()} {
    default_profile->setPersistentStoragePath(QString::fromStdString(Common::FS::PathToUTF8String(
        Common::FS::GetYuzuPath(Common::FS::YuzuPath::YuzuDir) / "qtwebengine")));

    QWebEngineScript gamepad;
    QWebEngineScript window_nx;

    gamepad.setName(QStringLiteral("gamepad_script.js"));
    window_nx.setName(QStringLiteral("window_nx_script.js"));

    gamepad.setSourceCode(QString::fromStdString(GAMEPAD_SCRIPT));
    window_nx.setSourceCode(QString::fromStdString(WINDOW_NX_SCRIPT));

    gamepad.setInjectionPoint(QWebEngineScript::DocumentCreation);
    window_nx.setInjectionPoint(QWebEngineScript::DocumentCreation);

    gamepad.setWorldId(QWebEngineScript::MainWorld);
    window_nx.setWorldId(QWebEngineScript::MainWorld);

    gamepad.setRunsOnSubFrames(true);
    window_nx.setRunsOnSubFrames(true);

    default_profile->scripts()->insert(gamepad);
    default_profile->scripts()->insert(window_nx);

    default_profile->setUrlRequestInterceptor(url_interceptor.get());

    global_settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
    global_settings->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
    global_settings->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);
    global_settings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
    global_settings->setAttribute(QWebEngineSettings::AllowWindowActivationFromJavaScript, true);
    global_settings->setAttribute(QWebEngineSettings::ShowScrollBars, false);

    global_settings->setFontFamily(QWebEngineSettings::StandardFont, QStringLiteral("Roboto"));

    connect(
        page(), &QWebEnginePage::windowCloseRequested, page(),
        [this] {
            if (page()->url() == url_interceptor->GetRequestedURL()) {
                SetFinished(true);
                SetExitReason(Service::AM::Frontend::WebExitReason::WindowClosed);
            }
        },
        Qt::QueuedConnection);
}

QtNXWebEngineView::~QtNXWebEngineView() {
    SetFinished(true);
    StopInputThread();
}

void QtNXWebEngineView::LoadLocalWebPage(const std::string& main_url,
                                         const std::string& additional_args) {
    is_local = true;

    LoadExtractedFonts();
    FocusFirstLinkElement();
    SetUserAgent(UserAgent::WebApplet);
    SetFinished(false);
    SetExitReason(Service::AM::Frontend::WebExitReason::EndButtonPressed);
    SetLastURL("http://localhost/");
    StartInputThread();

    load(QUrl(QUrl::fromLocalFile(QString::fromStdString(main_url)).toString() +
              QString::fromStdString(additional_args)));
}

void QtNXWebEngineView::LoadExternalWebPage(const std::string& main_url,
                                            const std::string& additional_args) {
    is_local = false;

    FocusFirstLinkElement();
    SetUserAgent(UserAgent::WebApplet);
    SetFinished(false);
    SetExitReason(Service::AM::Frontend::WebExitReason::EndButtonPressed);
    SetLastURL("http://localhost/");
    StartInputThread();

    load(QUrl(QString::fromStdString(main_url) + QString::fromStdString(additional_args)));
}

void QtNXWebEngineView::SetUserAgent(UserAgent user_agent) {
    const QString user_agent_str = [user_agent] {
        switch (user_agent) {
        case UserAgent::WebApplet:
        default:
            return QStringLiteral("WebApplet");
        case UserAgent::ShopN:
            return QStringLiteral("ShopN");
        case UserAgent::LoginApplet:
            return QStringLiteral("LoginApplet");
        case UserAgent::ShareApplet:
            return QStringLiteral("ShareApplet");
        case UserAgent::LobbyApplet:
            return QStringLiteral("LobbyApplet");
        case UserAgent::WifiWebAuthApplet:
            return QStringLiteral("WifiWebAuthApplet");
        }
    }();

    QWebEngineProfile::defaultProfile()->setHttpUserAgent(
        QStringLiteral("Mozilla/5.0 (Nintendo Switch; %1) AppleWebKit/606.4 "
                       "(KHTML, like Gecko) NF/6.0.1.15.4 NintendoBrowser/5.1.0.20389")
            .arg(user_agent_str));
}

bool QtNXWebEngineView::IsFinished() const {
    return finished;
}

void QtNXWebEngineView::SetFinished(bool finished_) {
    finished = finished_;
}

Service::AM::Frontend::WebExitReason QtNXWebEngineView::GetExitReason() const {
    return exit_reason;
}

void QtNXWebEngineView::SetExitReason(Service::AM::Frontend::WebExitReason exit_reason_) {
    exit_reason = exit_reason_;
}

const std::string& QtNXWebEngineView::GetLastURL() const {
    return last_url;
}

void QtNXWebEngineView::SetLastURL(std::string last_url_) {
    last_url = std::move(last_url_);
}

QString QtNXWebEngineView::GetCurrentURL() const {
    return url_interceptor->GetRequestedURL().toString();
}

void QtNXWebEngineView::hide() {
    SetFinished(true);
    StopInputThread();

    QWidget::hide();
}

void QtNXWebEngineView::keyPressEvent(QKeyEvent* event) {
    if (is_local) {
        input_subsystem->GetKeyboard()->PressKey(event->key());
    }
}

void QtNXWebEngineView::keyReleaseEvent(QKeyEvent* event) {
    if (is_local) {
        input_subsystem->GetKeyboard()->ReleaseKey(event->key());
    }
}

template <Core::HID::NpadButton... T>
void QtNXWebEngineView::HandleWindowFooterButtonPressedOnce() {
    const auto f = [this](Core::HID::NpadButton button) {
        if (input_interpreter->IsButtonPressedOnce(button)) {
            const auto button_index = std::countr_zero(static_cast<u64>(button));

            page()->runJavaScript(
                QStringLiteral("yuzu_key_callbacks[%1] == null;").arg(button_index),
                [this, button](const QVariant& variant) {
                    if (variant.toBool()) {
                        switch (button) {
                        case Core::HID::NpadButton::A:
                            SendMultipleKeyPressEvents<Qt::Key_A, Qt::Key_Space, Qt::Key_Return>();
                            break;
                        case Core::HID::NpadButton::B:
                            SendKeyPressEvent(Qt::Key_B);
                            break;
                        case Core::HID::NpadButton::X:
                            SendKeyPressEvent(Qt::Key_X);
                            break;
                        case Core::HID::NpadButton::Y:
                            SendKeyPressEvent(Qt::Key_Y);
                            break;
                        default:
                            break;
                        }
                    }
                });

            page()->runJavaScript(
                QStringLiteral("if (yuzu_key_callbacks[%1] != null) { yuzu_key_callbacks[%1](); }")
                    .arg(button_index));
        }
    };

    (f(T), ...);
}

template <Core::HID::NpadButton... T>
void QtNXWebEngineView::HandleWindowKeyButtonPressedOnce() {
    const auto f = [this](Core::HID::NpadButton button) {
        if (input_interpreter->IsButtonPressedOnce(button)) {
            SendKeyPressEvent(HIDButtonToKey(button));
        }
    };

    (f(T), ...);
}

template <Core::HID::NpadButton... T>
void QtNXWebEngineView::HandleWindowKeyButtonHold() {
    const auto f = [this](Core::HID::NpadButton button) {
        if (input_interpreter->IsButtonHeld(button)) {
            SendKeyPressEvent(HIDButtonToKey(button));
        }
    };

    (f(T), ...);
}

void QtNXWebEngineView::SendKeyPressEvent(int key) {
    if (key == 0) {
        return;
    }

    QCoreApplication::postEvent(focusProxy(),
                                new QKeyEvent(QKeyEvent::KeyPress, key, Qt::NoModifier));
    QCoreApplication::postEvent(focusProxy(),
                                new QKeyEvent(QKeyEvent::KeyRelease, key, Qt::NoModifier));
}

void QtNXWebEngineView::StartInputThread() {
    if (input_thread_running) {
        return;
    }

    input_thread_running = true;
    input_thread = std::thread(&QtNXWebEngineView::InputThread, this);
}

void QtNXWebEngineView::StopInputThread() {
    if (is_local) {
        QWidget::releaseKeyboard();
    }

    input_thread_running = false;
    if (input_thread.joinable()) {
        input_thread.join();
    }
}

void QtNXWebEngineView::InputThread() {
    // Wait for 1 second before allowing any inputs to be processed.
    std::this_thread::sleep_for(std::chrono::seconds(1));

    if (is_local) {
        QWidget::grabKeyboard();
    }

    while (input_thread_running) {
        input_interpreter->PollInput();

        HandleWindowFooterButtonPressedOnce<Core::HID::NpadButton::A, Core::HID::NpadButton::B,
                                            Core::HID::NpadButton::X, Core::HID::NpadButton::Y,
                                            Core::HID::NpadButton::L, Core::HID::NpadButton::R>();

        HandleWindowKeyButtonPressedOnce<
            Core::HID::NpadButton::Left, Core::HID::NpadButton::Up, Core::HID::NpadButton::Right,
            Core::HID::NpadButton::Down, Core::HID::NpadButton::StickLLeft,
            Core::HID::NpadButton::StickLUp, Core::HID::NpadButton::StickLRight,
            Core::HID::NpadButton::StickLDown>();

        HandleWindowKeyButtonHold<
            Core::HID::NpadButton::Left, Core::HID::NpadButton::Up, Core::HID::NpadButton::Right,
            Core::HID::NpadButton::Down, Core::HID::NpadButton::StickLLeft,
            Core::HID::NpadButton::StickLUp, Core::HID::NpadButton::StickLRight,
            Core::HID::NpadButton::StickLDown>();

        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

void QtNXWebEngineView::LoadExtractedFonts() {
    QWebEngineScript nx_font_css;
    QWebEngineScript load_nx_font;

    auto fonts_dir_str = Common::FS::PathToUTF8String(
        Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "fonts/");

    std::replace(fonts_dir_str.begin(), fonts_dir_str.end(), '\\', '/');

    const auto fonts_dir = QString::fromStdString(fonts_dir_str);

    nx_font_css.setName(QStringLiteral("nx_font_css.js"));
    load_nx_font.setName(QStringLiteral("load_nx_font.js"));

    nx_font_css.setSourceCode(
        QString::fromStdString(NX_FONT_CSS)
            .arg(fonts_dir + QStringLiteral("FontStandard.ttf"))
            .arg(fonts_dir + QStringLiteral("FontChineseSimplified.ttf"))
            .arg(fonts_dir + QStringLiteral("FontExtendedChineseSimplified.ttf"))
            .arg(fonts_dir + QStringLiteral("FontChineseTraditional.ttf"))
            .arg(fonts_dir + QStringLiteral("FontKorean.ttf"))
            .arg(fonts_dir + QStringLiteral("FontNintendoExtended.ttf"))
            .arg(fonts_dir + QStringLiteral("FontNintendoExtended2.ttf")));
    load_nx_font.setSourceCode(QString::fromStdString(LOAD_NX_FONT));

    nx_font_css.setInjectionPoint(QWebEngineScript::DocumentReady);
    load_nx_font.setInjectionPoint(QWebEngineScript::Deferred);

    nx_font_css.setWorldId(QWebEngineScript::MainWorld);
    load_nx_font.setWorldId(QWebEngineScript::MainWorld);

    nx_font_css.setRunsOnSubFrames(true);
    load_nx_font.setRunsOnSubFrames(true);

    default_profile->scripts()->insert(nx_font_css);
    default_profile->scripts()->insert(load_nx_font);

    connect(
        url_interceptor.get(), &UrlRequestInterceptor::FrameChanged, url_interceptor.get(),
        [this] {
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            page()->runJavaScript(QString::fromStdString(LOAD_NX_FONT));
        },
        Qt::QueuedConnection);
}

void QtNXWebEngineView::FocusFirstLinkElement() {
    QWebEngineScript focus_link_element;

    focus_link_element.setName(QStringLiteral("focus_link_element.js"));
    focus_link_element.setSourceCode(QString::fromStdString(FOCUS_LINK_ELEMENT_SCRIPT));
    focus_link_element.setWorldId(QWebEngineScript::MainWorld);
    focus_link_element.setInjectionPoint(QWebEngineScript::Deferred);
    focus_link_element.setRunsOnSubFrames(true);
    default_profile->scripts()->insert(focus_link_element);
}

#endif

QtWebBrowser::QtWebBrowser(GMainWindow& main_window) {
    connect(this, &QtWebBrowser::MainWindowOpenWebPage, &main_window,
            &GMainWindow::WebBrowserOpenWebPage, Qt::QueuedConnection);
    connect(this, &QtWebBrowser::MainWindowRequestExit, &main_window,
            &GMainWindow::WebBrowserRequestExit, Qt::QueuedConnection);
    connect(&main_window, &GMainWindow::WebBrowserExtractOfflineRomFS, this,
            &QtWebBrowser::MainWindowExtractOfflineRomFS, Qt::QueuedConnection);
    connect(&main_window, &GMainWindow::WebBrowserClosed, this,
            &QtWebBrowser::MainWindowWebBrowserClosed, Qt::QueuedConnection);
}

QtWebBrowser::~QtWebBrowser() = default;

void QtWebBrowser::Close() const {
    callback = {};
    emit MainWindowRequestExit();
}

void QtWebBrowser::OpenLocalWebPage(const std::string& local_url,
                                    ExtractROMFSCallback extract_romfs_callback_,
                                    OpenWebPageCallback callback_) const {
    extract_romfs_callback = std::move(extract_romfs_callback_);
    callback = std::move(callback_);

    const auto index = local_url.find('?');

    if (index == std::string::npos) {
        emit MainWindowOpenWebPage(local_url, "", true);
    } else {
        emit MainWindowOpenWebPage(local_url.substr(0, index), local_url.substr(index), true);
    }
}

void QtWebBrowser::OpenExternalWebPage(const std::string& external_url,
                                       OpenWebPageCallback callback_) const {
    callback = std::move(callback_);

    const auto index = external_url.find('?');

    if (index == std::string::npos) {
        emit MainWindowOpenWebPage(external_url, "", false);
    } else {
        emit MainWindowOpenWebPage(external_url.substr(0, index), external_url.substr(index),
                                   false);
    }
}

void QtWebBrowser::MainWindowExtractOfflineRomFS() {
    extract_romfs_callback();
}

void QtWebBrowser::MainWindowWebBrowserClosed(Service::AM::Frontend::WebExitReason exit_reason,
                                              std::string last_url) {
    if (callback) {
        callback(exit_reason, last_url);
    }
}

repo_name: litucks/torzu

license: mit


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <atomic>
#include <thread>

#include <QObject>

#ifdef YUZU_USE_QT_WEB_ENGINE
#include <QWebEngineView>
#endif

#include "core/frontend/applets/web_browser.h"

class GMainWindow;
class InputInterpreter;
class UrlRequestInterceptor;

namespace Core {
class System;
}

namespace Core::HID {
enum class NpadButton : u64;
}

namespace InputCommon {
class InputSubsystem;
}

#ifdef YUZU_USE_QT_WEB_ENGINE

enum class UserAgent {
    WebApplet,
    ShopN,
    LoginApplet,
    ShareApplet,
    LobbyApplet,
    WifiWebAuthApplet,
};

class QWebEngineProfile;
class QWebEngineSettings;

class QtNXWebEngineView : public QWebEngineView {
    Q_OBJECT

public:
    explicit QtNXWebEngineView(QWidget* parent, Core::System& system,
                               InputCommon::InputSubsystem* input_subsystem_);
    ~QtNXWebEngineView() override;

    /**
     * Loads a HTML document that exists locally. Cannot be used to load external websites.
     *
     * @param main_url The url to the file.
     * @param additional_args Additional arguments appended to the main url.
     */
    void LoadLocalWebPage(const std::string& main_url, const std::string& additional_args);

    /**
     * Loads an external website. Cannot be used to load local urls.
     *
     * @param main_url The url to the website.
     * @param additional_args Additional arguments appended to the main url.
     */
    void LoadExternalWebPage(const std::string& main_url, const std::string& additional_args);

    /**
     * Sets the background color of the web page.
     *
     * @param color The color to set.
     */
    void SetBackgroundColor(QColor color);

    /**
     * Sets the user agent of the web browser.
     *
     * @param user_agent The user agent enum.
     */
    void SetUserAgent(UserAgent user_agent);

    [[nodiscard]] bool IsFinished() const;
    void SetFinished(bool finished_);

    [[nodiscard]] Service::AM::Frontend::WebExitReason GetExitReason() const;
    void SetExitReason(Service::AM::Frontend::WebExitReason exit_reason_);

    [[nodiscard]] const std::string& GetLastURL() const;
    void SetLastURL(std::string last_url_);

    /**
     * This gets the current URL that has been requested by the webpage.
     * This only applies to the main frame. Sub frames and other resources are ignored.
     *
     * @return Currently requested URL
     */
    [[nodiscard]] QString GetCurrentURL() const;

public slots:
    void hide();

protected:
    void keyPressEvent(QKeyEvent* event) override;
    void keyReleaseEvent(QKeyEvent* event) override;

private:
    /**
     * Handles button presses to execute functions assigned in yuzu_key_callbacks.
     * yuzu_key_callbacks contains specialized functions for the buttons in the window footer
     * that can be overridden by games to achieve desired functionality.
     *
     * @tparam HIDButton The list of buttons contained in yuzu_key_callbacks
     */
    template <Core::HID::NpadButton... T>
    void HandleWindowFooterButtonPressedOnce();

    /**
     * Handles button presses and converts them into keyboard input.
     * This should only be used to convert D-Pad or Analog Stick input into arrow keys.
     *
     * @tparam HIDButton The list of buttons that can be converted into keyboard input.
     */
    template <Core::HID::NpadButton... T>
    void HandleWindowKeyButtonPressedOnce();

    /**
     * Handles button holds and converts them into keyboard input.
     * This should only be used to convert D-Pad or Analog Stick input into arrow keys.
     *
     * @tparam HIDButton The list of buttons that can be converted into keyboard input.
     */
    template <Core::HID::NpadButton... T>
    void HandleWindowKeyButtonHold();

    /**
     * Sends a key press event to QWebEngineView.
     *
     * @param key Qt key code.
     */
    void SendKeyPressEvent(int key);

    /**
     * Sends multiple key press events to QWebEngineView.
     *
     * @tparam int Qt key code.
     */
    template <int... T>
    void SendMultipleKeyPressEvents() {
        (SendKeyPressEvent(T), ...);
    }

    void StartInputThread();
    void StopInputThread();

    /// The thread where input is being polled and processed.
    void InputThread();

    /// Loads the extracted fonts using JavaScript.
    void LoadExtractedFonts();

    /// Brings focus to the first available link element.
    void FocusFirstLinkElement();

    InputCommon::InputSubsystem* input_subsystem;

    std::unique_ptr<UrlRequestInterceptor> url_interceptor;

    std::unique_ptr<InputInterpreter> input_interpreter;

    std::thread input_thread;

    std::atomic<bool> input_thread_running{};

    std::atomic<bool> finished{};

    Service::AM::Frontend::WebExitReason exit_reason{
        Service::AM::Frontend::WebExitReason::EndButtonPressed};

    std::string last_url{"http://localhost/"};

    bool is_local{};

    QWebEngineProfile* default_profile;
    QWebEngineSettings* global_settings;
};

#endif

class QtWebBrowser final : public QObject, public Core::Frontend::WebBrowserApplet {
    Q_OBJECT

public:
    explicit QtWebBrowser(GMainWindow& parent);
    ~QtWebBrowser() override;

    void Close() const override;
    void OpenLocalWebPage(const std::string& local_url,
                          ExtractROMFSCallback extract_romfs_callback_,
                          OpenWebPageCallback callback_) const override;

    void OpenExternalWebPage(const std::string& external_url,
                             OpenWebPageCallback callback_) const override;

signals:
    void MainWindowOpenWebPage(const std::string& main_url, const std::string& additional_args,
                               bool is_local) const;
    void MainWindowRequestExit() const;

private:
    void MainWindowExtractOfflineRomFS();

    void MainWindowWebBrowserClosed(Service::AM::Frontend::WebExitReason exit_reason,
                                    std::string last_url);

    mutable ExtractROMFSCallback extract_romfs_callback;
    mutable OpenWebPageCallback callback;
};


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

constexpr char NX_FONT_CSS[] = R"(
(function() {
    css = document.createElement('style');
    css.type = 'text/css';
    css.id = 'nx_font';
    css.innerText = `
/* FontStandard */
@font-face {
    font-family: 'FontStandard';
    src: url('%1') format('truetype');
}

/* FontChineseSimplified */
@font-face {
    font-family: 'FontChineseSimplified';
    src: url('%2') format('truetype');
}

/* FontExtendedChineseSimplified */
@font-face {
    font-family: 'FontExtendedChineseSimplified';
    src: url('%3') format('truetype');
}

/* FontChineseTraditional */
@font-face {
    font-family: 'FontChineseTraditional';
    src: url('%4') format('truetype');
}

/* FontKorean */
@font-face {
    font-family: 'FontKorean';
    src: url('%5') format('truetype');
}

/* FontNintendoExtended */
@font-face {
    font-family: 'NintendoExt003';
    src: url('%6') format('truetype');
}

/* FontNintendoExtended2 */
@font-face {
    font-family: 'NintendoExt003';
    src: url('%7') format('truetype');
}
`;

    document.head.appendChild(css);
})();
)";

constexpr char LOAD_NX_FONT[] = R"(
(function() {
    var elements = document.querySelectorAll("*");

    for (var i = 0; i < elements.length; i++) {
        var style = window.getComputedStyle(elements[i], null);
        if (style.fontFamily.includes("Arial") || style.fontFamily.includes("Calibri") ||
            style.fontFamily.includes("Century") || style.fontFamily.includes("Times New Roman")) {
            elements[i].style.fontFamily = "FontStandard, FontChineseSimplified, FontExtendedChineseSimplified, FontChineseTraditional, FontKorean, NintendoExt003";
        } else {
            elements[i].style.fontFamily = style.fontFamily + ", FontStandard, FontChineseSimplified, FontExtendedChineseSimplified, FontChineseTraditional, FontKorean, NintendoExt003";
        }
    }
})();
)";

constexpr char FOCUS_LINK_ELEMENT_SCRIPT[] = R"(
if (document.getElementsByTagName("a").length > 0) {
    document.getElementsByTagName("a")[0].focus();
}
)";

constexpr char GAMEPAD_SCRIPT[] = R"(
window.addEventListener("gamepadconnected", function(e) {
    console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
        e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length);
});

window.addEventListener("gamepaddisconnected", function(e) {
    console.log("Gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id);
});
)";

constexpr char WINDOW_NX_SCRIPT[] = R"(
var end_applet = false;
var yuzu_key_callbacks = [];

(function() {
    class WindowNX {
        constructor() {
            yuzu_key_callbacks[1] = function() { window.history.back(); };
            yuzu_key_callbacks[2] = function() { window.nx.endApplet(); };
        }

        addEventListener(type, listener, options) {
            console.log("nx.addEventListener called, type=%s", type);

            window.addEventListener(type, listener, options);
        }

        endApplet() {
            console.log("nx.endApplet called");

            end_applet = true;
        }

        playSystemSe(system_se) {
            console.log("nx.playSystemSe is not implemented, system_se=%s", system_se);
        }

        sendMessage(message) {
            console.log("nx.sendMessage is not implemented, message=%s", message);
        }

        setCursorScrollSpeed(scroll_speed) {
            console.log("nx.setCursorScrollSpeed is not implemented, scroll_speed=%d", scroll_speed);
        }
    }

    class WindowNXFooter {
        setAssign(key, label, func, option) {
            console.log("nx.footer.setAssign called, key=%s", key);

            switch (key) {
                case "A":
                    yuzu_key_callbacks[0] = func;
                    break;
                case "B":
                    yuzu_key_callbacks[1] = func;
                    break;
                case "X":
                    yuzu_key_callbacks[2] = func;
                    break;
                case "Y":
                    yuzu_key_callbacks[3] = func;
                    break;
                case "L":
                    yuzu_key_callbacks[6] = func;
                    break;
                case "R":
                    yuzu_key_callbacks[7] = func;
                    break;
            }
        }

        setFixed(kind) {
            console.log("nx.footer.setFixed is not implemented, kind=%s", kind);
        }

        unsetAssign(key) {
            console.log("nx.footer.unsetAssign called, key=%s", key);

            switch (key) {
                case "A":
                    yuzu_key_callbacks[0] = function() {};
                    break;
                case "B":
                    yuzu_key_callbacks[1] = function() {};
                    break;
                case "X":
                    yuzu_key_callbacks[2] = function() {};
                    break;
                case "Y":
                    yuzu_key_callbacks[3] = function() {};
                    break;
                case "L":
                    yuzu_key_callbacks[6] = function() {};
                    break;
                case "R":
                    yuzu_key_callbacks[7] = function() {};
                    break;
            }
        }
    }

    class WindowNXPlayReport {
        incrementCounter(counter_id) {
            console.log("nx.playReport.incrementCounter is not implemented, counter_id=%d", counter_id);
        }

        setCounterSetIdentifier(counter_id) {
            console.log("nx.playReport.setCounterSetIdentifier is not implemented, counter_id=%d", counter_id);
        }
    }

    window.nx = new WindowNX();
    window.nx.footer = new WindowNXFooter();
    window.nx.playReport = new WindowNXPlayReport();
})();
)";


code:
// SPDX-FileCopyrightText: 2014 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <string>
#include <tuple>
#include <type_traits>
#include <glad/glad.h>

#include <QtCore/qglobal.h>
#include "common/settings_enums.h"
#include "uisettings.h"
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
#include <QCamera>
#include <QCameraImageCapture>
#include <QCameraInfo>
#endif
#include <QCursor>
#include <QEvent>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLayout>
#include <QList>
#include <QMessageBox>
#include <QScreen>
#include <QSize>
#include <QStringLiteral>
#include <QSurfaceFormat>
#include <QWindow>
#include <QtCore/qobjectdefs.h>

#ifdef HAS_OPENGL
#include <QOffscreenSurface>
#include <QOpenGLContext>
#endif

#include "common/microprofile.h"
#include "common/polyfill_thread.h"
#include "common/scm_rev.h"
#include "common/settings.h"
#include "common/settings_input.h"
#include "common/thread.h"
#include "core/core.h"
#include "core/cpu_manager.h"
#include "core/frontend/framebuffer_layout.h"
#include "core/frontend/graphics_context.h"
#include "input_common/drivers/camera.h"
#include "input_common/drivers/keyboard.h"
#include "input_common/drivers/mouse.h"
#include "input_common/drivers/tas_input.h"
#include "input_common/drivers/touch_screen.h"
#include "input_common/main.h"
#include "video_core/gpu.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/renderer_base.h"
#include "yuzu/bootmanager.h"
#include "yuzu/main.h"
#include "yuzu/qt_common.h"

class QObject;
class QPaintEngine;
class QSurface;

constexpr int default_mouse_constrain_timeout = 10;

EmuThread::EmuThread(Core::System& system) : m_system{system} {}

EmuThread::~EmuThread() = default;

void EmuThread::run() {
    const char* name = "EmuControlThread";
    MicroProfileOnThreadCreate(name);
    Common::SetCurrentThreadName(name);

    auto& gpu = m_system.GPU();
    auto stop_token = m_stop_source.get_token();

    m_system.RegisterHostThread();

    // Main process has been loaded. Make the context current to this thread and begin GPU and CPU
    // execution.
    gpu.ObtainContext();

    emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
    if (Settings::values.use_disk_shader_cache.GetValue()) {
        m_system.Renderer().ReadRasterizer()->LoadDiskResources(
            m_system.GetApplicationProcessProgramID(), stop_token,
            [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
                emit LoadProgress(stage, value, total);
            });
    }
    emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);

    gpu.ReleaseContext();
    gpu.Start();

    m_system.GetCpuManager().OnGpuReady();

    if (m_system.DebuggerEnabled()) {
        m_system.InitializeDebugger();
    }

    while (!stop_token.stop_requested()) {
        std::unique_lock lk{m_should_run_mutex};
        if (m_should_run) {
            m_system.Run();
            m_stopped.Reset();

            Common::CondvarWait(m_should_run_cv, lk, stop_token, [&] { return !m_should_run; });
        } else {
            m_system.Pause();
            m_stopped.Set();

            EmulationPaused(lk);
            Common::CondvarWait(m_should_run_cv, lk, stop_token, [&] { return m_should_run; });
            EmulationResumed(lk);
        }
    }

    // Shutdown the main emulated process
    m_system.DetachDebugger();
    m_system.ShutdownMainProcess();

#if MICROPROFILE_ENABLED
    MicroProfileOnThreadExit();
#endif
}

// Unlock while emitting signals so that the main thread can
// continue pumping events.

void EmuThread::EmulationPaused(std::unique_lock<std::mutex>& lk) {
    lk.unlock();
    emit DebugModeEntered();
    lk.lock();
}

void EmuThread::EmulationResumed(std::unique_lock<std::mutex>& lk) {
    lk.unlock();
    emit DebugModeLeft();
    lk.lock();
}

#ifdef HAS_OPENGL
class OpenGLSharedContext : public Core::Frontend::GraphicsContext {
public:
    /// Create the original context that should be shared from
    explicit OpenGLSharedContext(QSurface* surface_) : surface{surface_} {
        QSurfaceFormat format;
        format.setVersion(4, 6);
        format.setProfile(QSurfaceFormat::CompatibilityProfile);
        format.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions);
        if (Settings::values.renderer_debug) {
            format.setOption(QSurfaceFormat::FormatOption::DebugContext);
        }
        // TODO: expose a setting for buffer value (ie default/single/double/triple)
        format.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
        format.setSwapInterval(0);

        context = std::make_unique<QOpenGLContext>();
        context->setFormat(format);
        if (!context->create()) {
            LOG_ERROR(Frontend, "Unable to create main openGL context");
        }
    }

    /// Create the shared contexts for rendering and presentation
    explicit OpenGLSharedContext(QOpenGLContext* share_context, QSurface* main_surface = nullptr) {

        // disable vsync for any shared contexts
        auto format = share_context->format();
        const int swap_interval =
            Settings::values.vsync_mode.GetValue() == Settings::VSyncMode::Immediate ? 0 : 1;

        format.setSwapInterval(main_surface ? swap_interval : 0);

        context = std::make_unique<QOpenGLContext>();
        context->setShareContext(share_context);
        context->setFormat(format);
        if (!context->create()) {
            LOG_ERROR(Frontend, "Unable to create shared openGL context");
        }

        if (!main_surface) {
            offscreen_surface = std::make_unique<QOffscreenSurface>(nullptr);
            offscreen_surface->setFormat(format);
            offscreen_surface->create();
            surface = offscreen_surface.get();
        } else {
            surface = main_surface;
        }
    }

    ~OpenGLSharedContext() {
        DoneCurrent();
    }

    void SwapBuffers() override {
        context->swapBuffers(surface);
    }

    void MakeCurrent() override {
        // We can't track the current state of the underlying context in this wrapper class because
        // Qt may make the underlying context not current for one reason or another. In particular,
        // the WebBrowser uses GL, so it seems to conflict if we aren't careful.
        // Instead of always just making the context current (which does not have any caching to
        // check if the underlying context is already current) we can check for the current context
        // in the thread local data by calling `currentContext()` and checking if its ours.
        if (QOpenGLContext::currentContext() != context.get()) {
            context->makeCurrent(surface);
        }
    }

    void DoneCurrent() override {
        context->doneCurrent();
    }

    QOpenGLContext* GetShareContext() {
        return context.get();
    }

    const QOpenGLContext* GetShareContext() const {
        return context.get();
    }

private:
    // Avoid using Qt parent system here since we might move the QObjects to new threads
    // As a note, this means we should avoid using slots/signals with the objects too
    std::unique_ptr<QOpenGLContext> context;
    std::unique_ptr<QOffscreenSurface> offscreen_surface{};
    QSurface* surface;
};
#endif

class DummyContext : public Core::Frontend::GraphicsContext {};

class RenderWidget : public QWidget {
public:
    explicit RenderWidget(GRenderWindow* parent) : QWidget(parent), render_window(parent) {
        setAttribute(Qt::WA_NativeWindow);
        setAttribute(Qt::WA_PaintOnScreen);
        if (QtCommon::GetWindowSystemType() == Core::Frontend::WindowSystemType::Wayland) {
            setAttribute(Qt::WA_DontCreateNativeAncestors);
        }
    }

    virtual ~RenderWidget() = default;

    QPaintEngine* paintEngine() const override {
        return nullptr;
    }

private:
    GRenderWindow* render_window;
};

struct OpenGLRenderWidget : public RenderWidget {
    explicit OpenGLRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
        windowHandle()->setSurfaceType(QWindow::OpenGLSurface);
    }

    void SetContext(std::unique_ptr<Core::Frontend::GraphicsContext>&& context_) {
        context = std::move(context_);
    }

private:
    std::unique_ptr<Core::Frontend::GraphicsContext> context;
};

struct VulkanRenderWidget : public RenderWidget {
    explicit VulkanRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
        windowHandle()->setSurfaceType(QWindow::VulkanSurface);
    }
};

struct NullRenderWidget : public RenderWidget {
    explicit NullRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {}
};

GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_,
                             std::shared_ptr<InputCommon::InputSubsystem> input_subsystem_,
                             Core::System& system_)
    : QWidget(parent),
      emu_thread(emu_thread_), input_subsystem{std::move(input_subsystem_)}, system{system_} {
    setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
                       .arg(QString::fromUtf8(Common::g_build_name),
                            QString::fromUtf8(Common::g_scm_branch),
                            QString::fromUtf8(Common::g_scm_desc)));
    setAttribute(Qt::WA_AcceptTouchEvents);
    auto* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    setLayout(layout);
    input_subsystem->Initialize();
    this->setMouseTracking(true);

    strict_context_required = QGuiApplication::platformName() == QStringLiteral("wayland") ||
                              QGuiApplication::platformName() == QStringLiteral("wayland-egl");

    connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete);
    connect(this, &GRenderWindow::ExecuteProgramSignal, parent, &GMainWindow::OnExecuteProgram,
            Qt::QueuedConnection);
    connect(this, &GRenderWindow::ExitSignal, parent, &GMainWindow::OnExit, Qt::QueuedConnection);
    connect(this, &GRenderWindow::TasPlaybackStateChanged, parent, &GMainWindow::OnTasStateChanged);

    mouse_constrain_timer.setInterval(default_mouse_constrain_timeout);
    connect(&mouse_constrain_timer, &QTimer::timeout, this, &GRenderWindow::ConstrainMouse);
}

void GRenderWindow::ExecuteProgram(std::size_t program_index) {
    emit ExecuteProgramSignal(program_index);
}

void GRenderWindow::Exit() {
    emit ExitSignal();
}

GRenderWindow::~GRenderWindow() {
    input_subsystem->Shutdown();
}

void GRenderWindow::OnFrameDisplayed() {
    input_subsystem->GetTas()->UpdateThread();
    const InputCommon::TasInput::TasState new_tas_state =
        std::get<0>(input_subsystem->GetTas()->GetStatus());

    if (!first_frame) {
        last_tas_state = new_tas_state;
        first_frame = true;
        emit FirstFrameDisplayed();
    }

    if (new_tas_state != last_tas_state) {
        last_tas_state = new_tas_state;
        emit TasPlaybackStateChanged();
    }
}

bool GRenderWindow::IsShown() const {
    return !isMinimized();
}

// On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
//
// Older versions get the window size (density independent pixels),
// and hence, do not support DPI scaling ("retina" displays).
// The result will be a viewport that is smaller than the extent of the window.
void GRenderWindow::OnFramebufferSizeChanged() {
    // Screen changes potentially incur a change in screen DPI, hence we should update the
    // framebuffer size
    const qreal pixel_ratio = windowPixelRatio();
    const u32 width = this->width() * pixel_ratio;
    const u32 height = this->height() * pixel_ratio;
    UpdateCurrentFramebufferLayout(width, height);
}

void GRenderWindow::BackupGeometry() {
    geometry = QWidget::saveGeometry();
}

void GRenderWindow::RestoreGeometry() {
    // We don't want to back up the geometry here (obviously)
    QWidget::restoreGeometry(geometry);
}

void GRenderWindow::restoreGeometry(const QByteArray& geometry_) {
    // Make sure users of this class don't need to deal with backing up the geometry themselves
    QWidget::restoreGeometry(geometry_);
    BackupGeometry();
}

QByteArray GRenderWindow::saveGeometry() {
    // If we are a top-level widget, store the current geometry
    // otherwise, store the last backup
    if (parent() == nullptr) {
        return QWidget::saveGeometry();
    }

    return geometry;
}

qreal GRenderWindow::windowPixelRatio() const {
    return devicePixelRatioF();
}

std::pair<u32, u32> GRenderWindow::ScaleTouch(const QPointF& pos) const {
    const qreal pixel_ratio = windowPixelRatio();
    return {static_cast<u32>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
            static_cast<u32>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
}

void GRenderWindow::closeEvent(QCloseEvent* event) {
    emit Closed();
    QWidget::closeEvent(event);
}

void GRenderWindow::leaveEvent(QEvent* event) {
    if (Settings::values.mouse_panning) {
        const QRect& rect = QWidget::geometry();
        QPoint position = QCursor::pos();

        qint32 x = qBound(rect.left(), position.x(), rect.right());
        qint32 y = qBound(rect.top(), position.y(), rect.bottom());
        // Only start the timer if the mouse has left the window bound.
        // The leave event is also triggered when the window looses focus.
        if (x != position.x() || y != position.y()) {
            mouse_constrain_timer.start();
        }
        event->accept();
    }
}

int GRenderWindow::QtKeyToSwitchKey(Qt::Key qt_key) {
    static constexpr std::array<std::pair<Qt::Key, Settings::NativeKeyboard::Keys>, 106> key_map = {
        std::pair<Qt::Key, Settings::NativeKeyboard::Keys>{Qt::Key_A, Settings::NativeKeyboard::A},
        {Qt::Key_A, Settings::NativeKeyboard::A},
        {Qt::Key_B, Settings::NativeKeyboard::B},
        {Qt::Key_C, Settings::NativeKeyboard::C},
        {Qt::Key_D, Settings::NativeKeyboard::D},
        {Qt::Key_E, Settings::NativeKeyboard::E},
        {Qt::Key_F, Settings::NativeKeyboard::F},
        {Qt::Key_G, Settings::NativeKeyboard::G},
        {Qt::Key_H, Settings::NativeKeyboard::H},
        {Qt::Key_I, Settings::NativeKeyboard::I},
        {Qt::Key_J, Settings::NativeKeyboard::J},
        {Qt::Key_K, Settings::NativeKeyboard::K},
        {Qt::Key_L, Settings::NativeKeyboard::L},
        {Qt::Key_M, Settings::NativeKeyboard::M},
        {Qt::Key_N, Settings::NativeKeyboard::N},
        {Qt::Key_O, Settings::NativeKeyboard::O},
        {Qt::Key_P, Settings::NativeKeyboard::P},
        {Qt::Key_Q, Settings::NativeKeyboard::Q},
        {Qt::Key_R, Settings::NativeKeyboard::R},
        {Qt::Key_S, Settings::NativeKeyboard::S},
        {Qt::Key_T, Settings::NativeKeyboard::T},
        {Qt::Key_U, Settings::NativeKeyboard::U},
        {Qt::Key_V, Settings::NativeKeyboard::V},
        {Qt::Key_W, Settings::NativeKeyboard::W},
        {Qt::Key_X, Settings::NativeKeyboard::X},
        {Qt::Key_Y, Settings::NativeKeyboard::Y},
        {Qt::Key_Z, Settings::NativeKeyboard::Z},
        {Qt::Key_1, Settings::NativeKeyboard::N1},
        {Qt::Key_2, Settings::NativeKeyboard::N2},
        {Qt::Key_3, Settings::NativeKeyboard::N3},
        {Qt::Key_4, Settings::NativeKeyboard::N4},
        {Qt::Key_5, Settings::NativeKeyboard::N5},
        {Qt::Key_6, Settings::NativeKeyboard::N6},
        {Qt::Key_7, Settings::NativeKeyboard::N7},
        {Qt::Key_8, Settings::NativeKeyboard::N8},
        {Qt::Key_9, Settings::NativeKeyboard::N9},
        {Qt::Key_0, Settings::NativeKeyboard::N0},
        {Qt::Key_Return, Settings::NativeKeyboard::Return},
        {Qt::Key_Escape, Settings::NativeKeyboard::Escape},
        {Qt::Key_Backspace, Settings::NativeKeyboard::Backspace},
        {Qt::Key_Tab, Settings::NativeKeyboard::Tab},
        {Qt::Key_Space, Settings::NativeKeyboard::Space},
        {Qt::Key_Minus, Settings::NativeKeyboard::Minus},
        {Qt::Key_Plus, Settings::NativeKeyboard::Plus},
        {Qt::Key_questiondown, Settings::NativeKeyboard::Plus},
        {Qt::Key_BracketLeft, Settings::NativeKeyboard::OpenBracket},
        {Qt::Key_BraceLeft, Settings::NativeKeyboard::OpenBracket},
        {Qt::Key_BracketRight, Settings::NativeKeyboard::CloseBracket},
        {Qt::Key_BraceRight, Settings::NativeKeyboard::CloseBracket},
        {Qt::Key_Bar, Settings::NativeKeyboard::Pipe},
        {Qt::Key_Dead_Tilde, Settings::NativeKeyboard::Tilde},
        {Qt::Key_Ntilde, Settings::NativeKeyboard::Semicolon},
        {Qt::Key_Semicolon, Settings::NativeKeyboard::Semicolon},
        {Qt::Key_Apostrophe, Settings::NativeKeyboard::Quote},
        {Qt::Key_Dead_Grave, Settings::NativeKeyboard::Backquote},
        {Qt::Key_Comma, Settings::NativeKeyboard::Comma},
        {Qt::Key_Period, Settings::NativeKeyboard::Period},
        {Qt::Key_Slash, Settings::NativeKeyboard::Slash},
        {Qt::Key_CapsLock, Settings::NativeKeyboard::CapsLockKey},
        {Qt::Key_F1, Settings::NativeKeyboard::F1},
        {Qt::Key_F2, Settings::NativeKeyboard::F2},
        {Qt::Key_F3, Settings::NativeKeyboard::F3},
        {Qt::Key_F4, Settings::NativeKeyboard::F4},
        {Qt::Key_F5, Settings::NativeKeyboard::F5},
        {Qt::Key_F6, Settings::NativeKeyboard::F6},
        {Qt::Key_F7, Settings::NativeKeyboard::F7},
        {Qt::Key_F8, Settings::NativeKeyboard::F8},
        {Qt::Key_F9, Settings::NativeKeyboard::F9},
        {Qt::Key_F10, Settings::NativeKeyboard::F10},
        {Qt::Key_F11, Settings::NativeKeyboard::F11},
        {Qt::Key_F12, Settings::NativeKeyboard::F12},
        {Qt::Key_Print, Settings::NativeKeyboard::PrintScreen},
        {Qt::Key_ScrollLock, Settings::NativeKeyboard::ScrollLockKey},
        {Qt::Key_Pause, Settings::NativeKeyboard::Pause},
        {Qt::Key_Insert, Settings::NativeKeyboard::Insert},
        {Qt::Key_Home, Settings::NativeKeyboard::Home},
        {Qt::Key_PageUp, Settings::NativeKeyboard::PageUp},
        {Qt::Key_Delete, Settings::NativeKeyboard::Delete},
        {Qt::Key_End, Settings::NativeKeyboard::End},
        {Qt::Key_PageDown, Settings::NativeKeyboard::PageDown},
        {Qt::Key_Right, Settings::NativeKeyboard::Right},
        {Qt::Key_Left, Settings::NativeKeyboard::Left},
        {Qt::Key_Down, Settings::NativeKeyboard::Down},
        {Qt::Key_Up, Settings::NativeKeyboard::Up},
        {Qt::Key_NumLock, Settings::NativeKeyboard::NumLockKey},
        // Numpad keys are missing here
        {Qt::Key_F13, Settings::NativeKeyboard::F13},
        {Qt::Key_F14, Settings::NativeKeyboard::F14},
        {Qt::Key_F15, Settings::NativeKeyboard::F15},
        {Qt::Key_F16, Settings::NativeKeyboard::F16},
        {Qt::Key_F17, Settings::NativeKeyboard::F17},
        {Qt::Key_F18, Settings::NativeKeyboard::F18},
        {Qt::Key_F19, Settings::NativeKeyboard::F19},
        {Qt::Key_F20, Settings::NativeKeyboard::F20},
        {Qt::Key_F21, Settings::NativeKeyboard::F21},
        {Qt::Key_F22, Settings::NativeKeyboard::F22},
        {Qt::Key_F23, Settings::NativeKeyboard::F23},
        {Qt::Key_F24, Settings::NativeKeyboard::F24},
        // {Qt::..., Settings::NativeKeyboard::KPComma},
        // {Qt::..., Settings::NativeKeyboard::Ro},
        {Qt::Key_Hiragana_Katakana, Settings::NativeKeyboard::KatakanaHiragana},
        {Qt::Key_yen, Settings::NativeKeyboard::Yen},
        {Qt::Key_Henkan, Settings::NativeKeyboard::Henkan},
        {Qt::Key_Muhenkan, Settings::NativeKeyboard::Muhenkan},
        // {Qt::..., Settings::NativeKeyboard::NumPadCommaPc98},
        {Qt::Key_Hangul, Settings::NativeKeyboard::HangulEnglish},
        {Qt::Key_Hangul_Hanja, Settings::NativeKeyboard::Hanja},
        {Qt::Key_Katakana, Settings::NativeKeyboard::KatakanaKey},
        {Qt::Key_Hiragana, Settings::NativeKeyboard::HiraganaKey},
        {Qt::Key_Zenkaku_Hankaku, Settings::NativeKeyboard::ZenkakuHankaku},
        // Modifier keys are handled by the modifier property
    };

    for (const auto& [qkey, nkey] : key_map) {
        if (qt_key == qkey) {
            return nkey;
        }
    }

    return Settings::NativeKeyboard::None;
}

int GRenderWindow::QtModifierToSwitchModifier(Qt::KeyboardModifiers qt_modifiers) {
    int modifier = 0;

    if ((qt_modifiers & Qt::KeyboardModifier::ShiftModifier) != 0) {
        modifier |= 1 << Settings::NativeKeyboard::LeftShift;
    }
    if ((qt_modifiers & Qt::KeyboardModifier::ControlModifier) != 0) {
        modifier |= 1 << Settings::NativeKeyboard::LeftControl;
    }
    if ((qt_modifiers & Qt::KeyboardModifier::AltModifier) != 0) {
        modifier |= 1 << Settings::NativeKeyboard::LeftAlt;
    }
    if ((qt_modifiers & Qt::KeyboardModifier::MetaModifier) != 0) {
        modifier |= 1 << Settings::NativeKeyboard::LeftMeta;
    }

    // TODO: These keys can't be obtained with Qt::KeyboardModifier

    // if ((qt_modifiers & 0x10) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::RightShift;
    // }
    // if ((qt_modifiers & 0x20) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::RightControl;
    // }
    // if ((qt_modifiers & 0x40) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::RightAlt;
    // }
    // if ((qt_modifiers & 0x80) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::RightMeta;
    // }
    // if ((qt_modifiers & 0x100) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::CapsLock;
    // }
    // if ((qt_modifiers & 0x200) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::NumLock;
    // }
    // if ((qt_modifiers & ???) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::ScrollLock;
    // }
    // if ((qt_modifiers & ???) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::Katakana;
    // }
    // if ((qt_modifiers & ???) != 0) {
    //    modifier |= 1 << Settings::NativeKeyboard::Hiragana;
    // }
    return modifier;
}

void GRenderWindow::keyPressEvent(QKeyEvent* event) {
    /**
     * This feature can be enhanced with the following functions, but they do not provide
     * cross-platform behavior.
     *
     * event->nativeVirtualKey() can distinguish between keys on the numpad.
     * event->nativeModifiers() can distinguish between left and right keys and numlock,
     * capslock, scroll lock.
     */
    if (!event->isAutoRepeat()) {
        const auto modifier = QtModifierToSwitchModifier(event->modifiers());
        const auto key = QtKeyToSwitchKey(Qt::Key(event->key()));
        input_subsystem->GetKeyboard()->SetKeyboardModifiers(modifier);
        input_subsystem->GetKeyboard()->PressKeyboardKey(key);
        // This is used for gamepads that can have any key mapped
        input_subsystem->GetKeyboard()->PressKey(event->key());
    }
}

void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
    /**
     * This feature can be enhanced with the following functions, but they do not provide
     * cross-platform behavior.
     *
     * event->nativeVirtualKey() can distinguish between keys on the numpad.
     * event->nativeModifiers() can distinguish between left and right buttons and numlock,
     * capslock, scroll lock.
     */
    if (!event->isAutoRepeat()) {
        const auto modifier = QtModifierToSwitchModifier(event->modifiers());
        const auto key = QtKeyToSwitchKey(Qt::Key(event->key()));
        input_subsystem->GetKeyboard()->SetKeyboardModifiers(modifier);
        input_subsystem->GetKeyboard()->ReleaseKeyboardKey(key);
        // This is used for gamepads that can have any key mapped
        input_subsystem->GetKeyboard()->ReleaseKey(event->key());
    }
}

InputCommon::MouseButton GRenderWindow::QtButtonToMouseButton(Qt::MouseButton button) {
    switch (button) {
    case Qt::LeftButton:
        return InputCommon::MouseButton::Left;
    case Qt::RightButton:
        return InputCommon::MouseButton::Right;
    case Qt::MiddleButton:
        return InputCommon::MouseButton::Wheel;
    case Qt::BackButton:
        return InputCommon::MouseButton::Backward;
    case Qt::ForwardButton:
        return InputCommon::MouseButton::Forward;
    case Qt::TaskButton:
        return InputCommon::MouseButton::Task;
    default:
        return InputCommon::MouseButton::Extra;
    }
}

void GRenderWindow::mousePressEvent(QMouseEvent* event) {
    // Touch input is handled in TouchBeginEvent
    if (event->source() == Qt::MouseEventSynthesizedBySystem) {
        return;
    }
    // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
    // coordinates and map them to the current render area
    const auto pos = mapFromGlobal(QCursor::pos());
    const auto [x, y] = ScaleTouch(pos);
    const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
    const auto button = QtButtonToMouseButton(event->button());

    input_subsystem->GetMouse()->PressMouseButton(button);
    input_subsystem->GetMouse()->PressButton(pos.x(), pos.y(), button);
    input_subsystem->GetMouse()->PressTouchButton(touch_x, touch_y, button);

    emit MouseActivity();
}

void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
    // Touch input is handled in TouchUpdateEvent
    if (event->source() == Qt::MouseEventSynthesizedBySystem) {
        return;
    }
    // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
    // coordinates and map them to the current render area
    const auto pos = mapFromGlobal(QCursor::pos());
    const auto [x, y] = ScaleTouch(pos);
    const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
    const int center_x = width() / 2;
    const int center_y = height() / 2;

    input_subsystem->GetMouse()->MouseMove(touch_x, touch_y);
    input_subsystem->GetMouse()->TouchMove(touch_x, touch_y);
    input_subsystem->GetMouse()->Move(pos.x(), pos.y(), center_x, center_y);

    // Center mouse for mouse panning
    if (Settings::values.mouse_panning && !Settings::values.mouse_enabled) {
        QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
    }

    // Constrain mouse for mouse emulation with mouse panning
    if (Settings::values.mouse_panning && Settings::values.mouse_enabled) {
        const auto [clamped_mouse_x, clamped_mouse_y] = ClipToTouchScreen(x, y);
        QCursor::setPos(mapToGlobal(
            QPoint{static_cast<int>(clamped_mouse_x), static_cast<int>(clamped_mouse_y)}));
    }

    mouse_constrain_timer.stop();
    emit MouseActivity();
}

void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
    // Touch input is handled in TouchEndEvent
    if (event->source() == Qt::MouseEventSynthesizedBySystem) {
        return;
    }

    const auto button = QtButtonToMouseButton(event->button());
    input_subsystem->GetMouse()->ReleaseButton(button);
}

void GRenderWindow::ConstrainMouse() {
    if (emu_thread == nullptr || !Settings::values.mouse_panning) {
        mouse_constrain_timer.stop();
        return;
    }
    if (!this->isActiveWindow()) {
        mouse_constrain_timer.stop();
        return;
    }

    if (Settings::values.mouse_enabled) {
        const auto pos = mapFromGlobal(QCursor::pos());
        const int new_pos_x = std::clamp(pos.x(), 0, width());
        const int new_pos_y = std::clamp(pos.y(), 0, height());

        QCursor::setPos(mapToGlobal(QPoint{new_pos_x, new_pos_y}));
        return;
    }

    const int center_x = width() / 2;
    const int center_y = height() / 2;

    QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
}

void GRenderWindow::wheelEvent(QWheelEvent* event) {
    const int x = event->angleDelta().x();
    const int y = event->angleDelta().y();
    input_subsystem->GetMouse()->MouseWheelChange(x, y);
}

void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
    QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
    for (const auto& touch_point : touch_points) {
        const auto [x, y] = ScaleTouch(touch_point.pos());
        const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
        input_subsystem->GetTouchScreen()->TouchPressed(touch_x, touch_y, touch_point.id());
    }
}

void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
    QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
    input_subsystem->GetTouchScreen()->ClearActiveFlag();
    for (const auto& touch_point : touch_points) {
        const auto [x, y] = ScaleTouch(touch_point.pos());
        const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
        input_subsystem->GetTouchScreen()->TouchMoved(touch_x, touch_y, touch_point.id());
    }
    input_subsystem->GetTouchScreen()->ReleaseInactiveTouch();
}

void GRenderWindow::TouchEndEvent() {
    input_subsystem->GetTouchScreen()->ReleaseAllTouch();
}

void GRenderWindow::InitializeCamera() {
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
    constexpr auto camera_update_ms = std::chrono::milliseconds{50}; // (50ms, 20Hz)
    if (!Settings::values.enable_ir_sensor) {
        return;
    }

    bool camera_found = false;
    const QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    for (const QCameraInfo& cameraInfo : cameras) {
        if (Settings::values.ir_sensor_device.GetValue() == cameraInfo.deviceName().toStdString() ||
            Settings::values.ir_sensor_device.GetValue() == "Auto") {
            camera = std::make_unique<QCamera>(cameraInfo);
            if (!camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder) &&
                !camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) {
                LOG_ERROR(Frontend,
                          "Camera doesn't support CaptureViewfinder or CaptureStillImage");
                continue;
            }
            camera_found = true;
            break;
        }
    }

    if (!camera_found) {
        return;
    }

    camera_capture = std::make_unique<QCameraImageCapture>(camera.get());

    if (!camera_capture->isCaptureDestinationSupported(
            QCameraImageCapture::CaptureDestination::CaptureToBuffer)) {
        LOG_ERROR(Frontend, "Camera doesn't support saving to buffer");
        return;
    }

    const auto camera_width = input_subsystem->GetCamera()->getImageWidth();
    const auto camera_height = input_subsystem->GetCamera()->getImageHeight();
    camera_data.resize(camera_width * camera_height);
    camera_capture->setCaptureDestination(QCameraImageCapture::CaptureDestination::CaptureToBuffer);
    connect(camera_capture.get(), &QCameraImageCapture::imageCaptured, this,
            &GRenderWindow::OnCameraCapture);
    camera->unload();
    if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder)) {
        camera->setCaptureMode(QCamera::CaptureViewfinder);
    } else if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) {
        camera->setCaptureMode(QCamera::CaptureStillImage);
    }
    camera->load();
    camera->start();

    pending_camera_snapshots = 0;
    is_virtual_camera = false;

    camera_timer = std::make_unique<QTimer>();
    connect(camera_timer.get(), &QTimer::timeout, [this] { RequestCameraCapture(); });
    // This timer should be dependent of camera resolution 5ms for every 100 pixels
    camera_timer->start(camera_update_ms);
#endif
}

void GRenderWindow::FinalizeCamera() {
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
    if (camera_timer) {
        camera_timer->stop();
    }
    if (camera) {
        camera->unload();
    }
#endif
}

void GRenderWindow::RequestCameraCapture() {
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
    if (!Settings::values.enable_ir_sensor) {
        return;
    }

    // If the camera doesn't capture, test for virtual cameras
    if (pending_camera_snapshots > 5) {
        is_virtual_camera = true;
    }
    // Virtual cameras like obs need to reset the camera every capture
    if (is_virtual_camera) {
        camera->stop();
        camera->start();
    }

    pending_camera_snapshots++;
    camera_capture->capture();
#endif
}

void GRenderWindow::OnCameraCapture(int requestId, const QImage& img) {
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
    // TODO: Capture directly in the format and resolution needed
    const auto camera_width = input_subsystem->GetCamera()->getImageWidth();
    const auto camera_height = input_subsystem->GetCamera()->getImageHeight();
    const auto converted =
        img.scaled(static_cast<int>(camera_width), static_cast<int>(camera_height),
                   Qt::AspectRatioMode::IgnoreAspectRatio,
                   Qt::TransformationMode::SmoothTransformation)
            .mirrored(false, true);
    if (camera_data.size() != camera_width * camera_height) {
        camera_data.resize(camera_width * camera_height);
    }
    std::memcpy(camera_data.data(), converted.bits(), camera_width * camera_height * sizeof(u32));
    input_subsystem->GetCamera()->SetCameraData(camera_width, camera_height, camera_data);
    pending_camera_snapshots = 0;
#endif
}

bool GRenderWindow::event(QEvent* event) {
    if (event->type() == QEvent::TouchBegin) {
        TouchBeginEvent(static_cast<QTouchEvent*>(event));
        return true;
    } else if (event->type() == QEvent::TouchUpdate) {
        TouchUpdateEvent(static_cast<QTouchEvent*>(event));
        return true;
    } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
        TouchEndEvent();
        return true;
    }

    return QWidget::event(event);
}

void GRenderWindow::focusOutEvent(QFocusEvent* event) {
    QWidget::focusOutEvent(event);
    input_subsystem->GetKeyboard()->ReleaseAllKeys();
    input_subsystem->GetMouse()->ReleaseAllButtons();
    input_subsystem->GetTouchScreen()->ReleaseAllTouch();
}

void GRenderWindow::resizeEvent(QResizeEvent* event) {
    QWidget::resizeEvent(event);
    OnFramebufferSizeChanged();
}

std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
#ifdef HAS_OPENGL
    if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
        auto c = static_cast<OpenGLSharedContext*>(main_context.get());
        // Bind the shared contexts to the main surface in case the backend wants to take over
        // presentation
        return std::make_unique<OpenGLSharedContext>(c->GetShareContext(),
                                                     child_widget->windowHandle());
    }
#endif
    return std::make_unique<DummyContext>();
}

bool GRenderWindow::InitRenderTarget() {
    ReleaseRenderTarget();

    {
        // Create a dummy render widget so that Qt
        // places the render window at the correct position.
        const RenderWidget dummy_widget{this};
    }

    first_frame = false;

    switch (Settings::values.renderer_backend.GetValue()) {
    case Settings::RendererBackend::OpenGL:
        if (!InitializeOpenGL()) {
            return false;
        }
        break;
    case Settings::RendererBackend::Vulkan:
        if (!InitializeVulkan()) {
            return false;
        }
        break;
    case Settings::RendererBackend::Null:
        InitializeNull();
        break;
    }

    // Update the Window System information with the new render target
    window_info = QtCommon::GetWindowSystemInfo(child_widget->windowHandle());

    child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
    layout()->addWidget(child_widget);
    // Reset minimum required size to avoid resizing issues on the main window after restarting.
    setMinimumSize(1, 1);

    resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);

    OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
    OnFramebufferSizeChanged();
    BackupGeometry();

    if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
        if (!LoadOpenGL()) {
            return false;
        }
    }

    return true;
}

void GRenderWindow::ReleaseRenderTarget() {
    if (child_widget) {
        layout()->removeWidget(child_widget);
        child_widget->deleteLater();
        child_widget = nullptr;
    }
    main_context.reset();
}

void GRenderWindow::CaptureScreenshot(const QString& screenshot_path) {
    auto& renderer = system.Renderer();

    if (renderer.IsScreenshotPending()) {
        LOG_WARNING(Render,
                    "A screenshot is already requested or in progress, ignoring the request");
        return;
    }

    const Layout::FramebufferLayout layout{[]() {
        u32 height = UISettings::values.screenshot_height.GetValue();
        if (height == 0) {
            height = Settings::IsDockedMode() ? Layout::ScreenDocked::Height
                                              : Layout::ScreenUndocked::Height;
            height *= Settings::values.resolution_info.up_factor;
        }
        const u32 width =
            UISettings::CalculateWidth(height, Settings::values.aspect_ratio.GetValue());
        return Layout::DefaultFrameLayout(width, height);
    }()};

    screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
    renderer.RequestScreenshot(
        screenshot_image.bits(),
        [=, this](bool invert_y) {
            const std::string std_screenshot_path = screenshot_path.toStdString();
            if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) {
                LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
            } else {
                LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
            }
        },
        layout);
}

bool GRenderWindow::IsLoadingComplete() const {
    return first_frame;
}

void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
    setMinimumSize(minimal_size.first, minimal_size.second);
}

bool GRenderWindow::InitializeOpenGL() {
#ifdef HAS_OPENGL
    if (!QOpenGLContext::supportsThreadedOpenGL()) {
        QMessageBox::warning(this, tr("OpenGL not available!"),
                             tr("OpenGL shared contexts are not supported."));
        return false;
    }

    // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
    // WA_DontShowOnScreen, WA_DeleteOnClose
    auto child = new OpenGLRenderWidget(this);
    child_widget = child;
    child_widget->windowHandle()->create();
    auto context = std::make_shared<OpenGLSharedContext>(child->windowHandle());
    main_context = context;
    child->SetContext(
        std::make_unique<OpenGLSharedContext>(context->GetShareContext(), child->windowHandle()));

    return true;
#else
    QMessageBox::warning(this, tr("OpenGL not available!"),
                         tr("yuzu has not been compiled with OpenGL support."));
    return false;
#endif
}

bool GRenderWindow::InitializeVulkan() {
    auto child = new VulkanRenderWidget(this);
    child_widget = child;
    child_widget->windowHandle()->create();
    main_context = std::make_unique<DummyContext>();

    return true;
}

void GRenderWindow::InitializeNull() {
    child_widget = new NullRenderWidget(this);
    main_context = std::make_unique<DummyContext>();
}

bool GRenderWindow::LoadOpenGL() {
    auto context = CreateSharedContext();
    auto scope = context->Acquire();
    if (!gladLoadGL()) {
        QMessageBox::warning(
            this, tr("Error while initializing OpenGL!"),
            tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver."));
        return false;
    }

    const QString renderer =
        QString::fromUtf8(reinterpret_cast<const char*>(glGetString(GL_RENDERER)));

    if (!GLAD_GL_VERSION_4_6) {
        LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString());
        QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"),
                             tr("Your GPU may not support OpenGL 4.6, or you do not have the "
                                "latest graphics driver.<br><br>GL Renderer:<br>%1")
                                 .arg(renderer));
        return false;
    }

    QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
    if (!unsupported_gl_extensions.empty()) {
        QMessageBox::warning(
            this, tr("Error while initializing OpenGL!"),
            tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you "
               "have the latest graphics driver.<br><br>GL Renderer:<br>%1<br><br>Unsupported "
               "extensions:<br>%2")
                .arg(renderer)
                .arg(unsupported_gl_extensions.join(QStringLiteral("<br>"))));
        return false;
    }
    return true;
}

QStringList GRenderWindow::GetUnsupportedGLExtensions() const {
    QStringList unsupported_ext;

    // Extensions required to support some texture formats.
    if (!GLAD_GL_EXT_texture_compression_s3tc) {
        unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc"));
    }
    if (!GLAD_GL_ARB_texture_compression_rgtc) {
        unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc"));
    }

    if (!unsupported_ext.empty()) {
        const std::string gl_renderer{reinterpret_cast<const char*>(glGetString(GL_RENDERER))};
        LOG_ERROR(Frontend, "GPU does not support all required extensions: {}", gl_renderer);
    }
    for (const QString& ext : unsupported_ext) {
        LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString());
    }

    return unsupported_ext;
}

void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread_) {
    emu_thread = emu_thread_;
}

void GRenderWindow::OnEmulationStopping() {
    emu_thread = nullptr;
}

void GRenderWindow::showEvent(QShowEvent* event) {
    QWidget::showEvent(event);

    // windowHandle() is not initialized until the Window is shown, so we connect it here.
    connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
            Qt::UniqueConnection);
}

bool GRenderWindow::eventFilter(QObject* object, QEvent* event) {
    if (event->type() == QEvent::HoverMove) {
        if (Settings::values.mouse_panning || Settings::values.mouse_enabled) {
            auto* hover_event = static_cast<QMouseEvent*>(event);
            mouseMoveEvent(hover_event);
            return false;
        }
        emit MouseActivity();
    }
    return false;
}


code:
// SPDX-FileCopyrightText: 2014 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <condition_variable>
#include <cstddef>
#include <memory>
#include <mutex>
#include <utility>
#include <vector>

#include <QByteArray>
#include <QImage>
#include <QObject>
#include <QPoint>
#include <QString>
#include <QStringList>
#include <QThread>
#include <QTimer>
#include <QWidget>
#include <qglobal.h>
#include <qnamespace.h>
#include <qobjectdefs.h>

#include "common/common_types.h"
#include "common/logging/log.h"
#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "core/frontend/emu_window.h"

class GMainWindow;
class QCamera;
class QCameraImageCapture;
class QCloseEvent;
class QFocusEvent;
class QKeyEvent;
class QMouseEvent;
class QObject;
class QResizeEvent;
class QShowEvent;
class QTouchEvent;
class QWheelEvent;

namespace Core {
class System;
} // namespace Core

namespace InputCommon {
class InputSubsystem;
enum class MouseButton;
} // namespace InputCommon

namespace InputCommon::TasInput {
enum class TasState;
} // namespace InputCommon::TasInput

namespace VideoCore {
enum class LoadCallbackStage;
} // namespace VideoCore

class EmuThread final : public QThread {
    Q_OBJECT

public:
    explicit EmuThread(Core::System& system);
    ~EmuThread() override;

    /**
     * Start emulation (on new thread)
     * @warning Only call when not running!
     */
    void run() override;

    /**
     * Sets whether the emulation thread should run or not
     * @param should_run Boolean value, set the emulation thread to running if true
     */
    void SetRunning(bool should_run) {
        // TODO: Prevent other threads from modifying the state until we finish.
        {
            // Notify the running thread to change state.
            std::unique_lock run_lk{m_should_run_mutex};
            m_should_run = should_run;
            m_should_run_cv.notify_one();
        }

        // Wait until paused, if pausing.
        if (!should_run) {
            m_stopped.Wait();
        }
    }

    /**
     * Check if the emulation thread is running or not
     * @return True if the emulation thread is running, otherwise false
     */
    bool IsRunning() const {
        return m_should_run;
    }

    /**
     * Requests for the emulation thread to immediately stop running
     */
    void ForceStop() {
        LOG_WARNING(Frontend, "Force stopping EmuThread");
        m_stop_source.request_stop();
    }

private:
    void EmulationPaused(std::unique_lock<std::mutex>& lk);
    void EmulationResumed(std::unique_lock<std::mutex>& lk);

private:
    Core::System& m_system;

    std::stop_source m_stop_source;
    std::mutex m_should_run_mutex;
    std::condition_variable_any m_should_run_cv;
    Common::Event m_stopped;
    bool m_should_run{true};

signals:
    /**
     * Emitted when the CPU has halted execution
     *
     * @warning When connecting to this signal from other threads, make sure to specify either
     * Qt::QueuedConnection (invoke slot within the destination object's message thread) or even
     * Qt::BlockingQueuedConnection (additionally block source thread until slot returns)
     */
    void DebugModeEntered();

    /**
     * Emitted right before the CPU continues execution
     *
     * @warning When connecting to this signal from other threads, make sure to specify either
     * Qt::QueuedConnection (invoke slot within the destination object's message thread) or even
     * Qt::BlockingQueuedConnection (additionally block source thread until slot returns)
     */
    void DebugModeLeft();

    void LoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total);
};

class GRenderWindow : public QWidget, public Core::Frontend::EmuWindow {
    Q_OBJECT

public:
    explicit GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_,
                           std::shared_ptr<InputCommon::InputSubsystem> input_subsystem_,
                           Core::System& system_);
    ~GRenderWindow() override;

    // EmuWindow implementation.
    void OnFrameDisplayed() override;
    bool IsShown() const override;
    std::unique_ptr<Core::Frontend::GraphicsContext> CreateSharedContext() const override;

    void BackupGeometry();
    void RestoreGeometry();
    void restoreGeometry(const QByteArray& geometry_); // overridden
    QByteArray saveGeometry();                         // overridden

    qreal windowPixelRatio() const;

    std::pair<u32, u32> ScaleTouch(const QPointF& pos) const;

    void closeEvent(QCloseEvent* event) override;
    void leaveEvent(QEvent* event) override;

    void resizeEvent(QResizeEvent* event) override;

    /// Converts a Qt keyboard key into NativeKeyboard key
    static int QtKeyToSwitchKey(Qt::Key qt_keys);

    /// Converts a Qt modifier keys into NativeKeyboard modifier keys
    static int QtModifierToSwitchModifier(Qt::KeyboardModifiers qt_modifiers);

    void keyPressEvent(QKeyEvent* event) override;
    void keyReleaseEvent(QKeyEvent* event) override;

    /// Converts a Qt mouse button into MouseInput mouse button
    static InputCommon::MouseButton QtButtonToMouseButton(Qt::MouseButton button);

    void mousePressEvent(QMouseEvent* event) override;
    void mouseMoveEvent(QMouseEvent* event) override;
    void mouseReleaseEvent(QMouseEvent* event) override;
    void wheelEvent(QWheelEvent* event) override;

    void InitializeCamera();
    void FinalizeCamera();

    bool event(QEvent* event) override;

    void focusOutEvent(QFocusEvent* event) override;

    bool InitRenderTarget();

    /// Destroy the previous run's child_widget which should also destroy the child_window
    void ReleaseRenderTarget();

    bool IsLoadingComplete() const;

    void CaptureScreenshot(const QString& screenshot_path);

    /**
     * Instructs the window to re-launch the application using the specified program_index.
     * @param program_index Specifies the index within the application of the program to launch.
     */
    void ExecuteProgram(std::size_t program_index);

    /// Instructs the window to exit the application.
    void Exit();

public slots:
    void OnEmulationStarting(EmuThread* emu_thread_);
    void OnEmulationStopping();
    void OnFramebufferSizeChanged();

signals:
    /// Emitted when the window is closed
    void Closed();
    void FirstFrameDisplayed();
    void ExecuteProgramSignal(std::size_t program_index);
    void ExitSignal();
    void MouseActivity();
    void TasPlaybackStateChanged();

private:
    void TouchBeginEvent(const QTouchEvent* event);
    void TouchUpdateEvent(const QTouchEvent* event);
    void TouchEndEvent();
    void ConstrainMouse();

    void RequestCameraCapture();
    void OnCameraCapture(int requestId, const QImage& img);

    void OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) override;

    bool InitializeOpenGL();
    bool InitializeVulkan();
    void InitializeNull();
    bool LoadOpenGL();
    QStringList GetUnsupportedGLExtensions() const;

    EmuThread* emu_thread;
    std::shared_ptr<InputCommon::InputSubsystem> input_subsystem;

    // Main context that will be shared with all other contexts that are requested.
    // If this is used in a shared context setting, then this should not be used directly, but
    // should instead be shared from
    std::shared_ptr<Core::Frontend::GraphicsContext> main_context;

    /// Temporary storage of the screenshot taken
    QImage screenshot_image;

    QByteArray geometry;

    QWidget* child_widget = nullptr;

    bool first_frame = false;
    InputCommon::TasInput::TasState last_tas_state;

#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
    bool is_virtual_camera;
    int pending_camera_snapshots;
    std::vector<u32> camera_data;
    std::unique_ptr<QCamera> camera;
    std::unique_ptr<QCameraImageCapture> camera_capture;
    std::unique_ptr<QTimer> camera_timer;
#endif

    QTimer mouse_constrain_timer;

    Core::System& system;

protected:
    void showEvent(QShowEvent* event) override;
    bool eventFilter(QObject* object, QEvent* event) override;
};


code:
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <algorithm>
#include <ranges>

#if defined(_WIN32)
#include <client/windows/handler/exception_handler.h>
#elif defined(__linux__)
#include <client/linux/handler/exception_handler.h>
#else
#error Minidump creation not supported on this platform
#endif

#include "common/fs/fs_paths.h"
#include "common/fs/path_util.h"
#include "yuzu/breakpad.h"

namespace Breakpad {

static void PruneDumpDirectory(const std::filesystem::path& dump_path) {
    // Code in this function should be exception-safe.
    struct Entry {
        std::filesystem::path path;
        std::filesystem::file_time_type last_write_time;
    };
    std::vector<Entry> existing_dumps;

    // Get existing entries.
    std::error_code ec;
    std::filesystem::directory_iterator dir(dump_path, ec);
    for (auto& entry : dir) {
        if (entry.is_regular_file()) {
            existing_dumps.push_back(Entry{
                .path = entry.path(),
                .last_write_time = entry.last_write_time(ec),
            });
        }
    }

    // Sort descending by creation date.
    std::ranges::stable_sort(existing_dumps, [](const auto& a, const auto& b) {
        return a.last_write_time > b.last_write_time;
    });

    // Delete older dumps.
    for (size_t i = 5; i < existing_dumps.size(); i++) {
        std::filesystem::remove(existing_dumps[i].path, ec);
    }
}

#if defined(__linux__)
[[noreturn]] bool DumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context,
                               bool succeeded) {
    // Prevent time- and space-consuming core dumps from being generated, as we have
    // already generated a minidump and a core file will not be useful anyway.
    _exit(1);
}
#endif

void InstallCrashHandler() {
    // Write crash dumps to profile directory.
    const auto dump_path = GetYuzuPath(Common::FS::YuzuPath::CrashDumpsDir);
    PruneDumpDirectory(dump_path);

#if defined(_WIN32)
    // TODO: If we switch to MinGW builds for Windows, this needs to be wrapped in a C API.
    static google_breakpad::ExceptionHandler eh{dump_path, nullptr, nullptr, nullptr,
                                                google_breakpad::ExceptionHandler::HANDLER_ALL};
#elif defined(__linux__)
    static google_breakpad::MinidumpDescriptor descriptor{dump_path};
    static google_breakpad::ExceptionHandler eh{descriptor, nullptr, DumpCallback,
                                                nullptr,    true,    -1};
#endif
}

} // namespace Breakpad


code:
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

namespace Breakpad {

void InstallCrashHandler();

}


code:
// SPDX-FileCopyrightText: 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <QButtonGroup>
#include <QMessageBox>
#include <QPushButton>
#include <QtConcurrent/qtconcurrentrun.h>
#include "common/logging/log.h"
#include "common/telemetry.h"
#include "core/telemetry_session.h"
#include "ui_compatdb.h"
#include "yuzu/compatdb.h"

CompatDB::CompatDB(Core::TelemetrySession& telemetry_session_, QWidget* parent)
    : QWizard(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint),
      ui{std::make_unique<Ui::CompatDB>()}, telemetry_session{telemetry_session_} {
    ui->setupUi(this);

    connect(ui->radioButton_GameBoot_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_GameBoot_No, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Gameplay_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Gameplay_No, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_NoFreeze_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_NoFreeze_No, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Complete_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Complete_No, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Graphical_Major, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Graphical_Minor, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Graphical_No, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Audio_Major, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Audio_Minor, &QRadioButton::clicked, this, &CompatDB::EnableNext);
    connect(ui->radioButton_Audio_No, &QRadioButton::clicked, this, &CompatDB::EnableNext);

    connect(button(NextButton), &QPushButton::clicked, this, &CompatDB::Submit);
    connect(&testcase_watcher, &QFutureWatcher<bool>::finished, this,
            &CompatDB::OnTestcaseSubmitted);
}

CompatDB::~CompatDB() = default;

enum class CompatDBPage {
    Intro = 0,
    GameBoot = 1,
    GamePlay = 2,
    Freeze = 3,
    Completion = 4,
    Graphical = 5,
    Audio = 6,
    Final = 7,
};

void CompatDB::Submit() {
    QButtonGroup* compatibility_GameBoot = new QButtonGroup(this);
    compatibility_GameBoot->addButton(ui->radioButton_GameBoot_Yes, 0);
    compatibility_GameBoot->addButton(ui->radioButton_GameBoot_No, 1);

    QButtonGroup* compatibility_Gameplay = new QButtonGroup(this);
    compatibility_Gameplay->addButton(ui->radioButton_Gameplay_Yes, 0);
    compatibility_Gameplay->addButton(ui->radioButton_Gameplay_No, 1);

    QButtonGroup* compatibility_NoFreeze = new QButtonGroup(this);
    compatibility_NoFreeze->addButton(ui->radioButton_NoFreeze_Yes, 0);
    compatibility_NoFreeze->addButton(ui->radioButton_NoFreeze_No, 1);

    QButtonGroup* compatibility_Complete = new QButtonGroup(this);
    compatibility_Complete->addButton(ui->radioButton_Complete_Yes, 0);
    compatibility_Complete->addButton(ui->radioButton_Complete_No, 1);

    QButtonGroup* compatibility_Graphical = new QButtonGroup(this);
    compatibility_Graphical->addButton(ui->radioButton_Graphical_Major, 0);
    compatibility_Graphical->addButton(ui->radioButton_Graphical_Minor, 1);
    compatibility_Graphical->addButton(ui->radioButton_Graphical_No, 2);

    QButtonGroup* compatibility_Audio = new QButtonGroup(this);
    compatibility_Audio->addButton(ui->radioButton_Audio_Major, 0);
    compatibility_Graphical->addButton(ui->radioButton_Audio_Minor, 1);
    compatibility_Audio->addButton(ui->radioButton_Audio_No, 2);

    const int compatibility = static_cast<int>(CalculateCompatibility());

    switch ((static_cast<CompatDBPage>(currentId()))) {
    case CompatDBPage::Intro:
        break;
    case CompatDBPage::GameBoot:
        if (compatibility_GameBoot->checkedId() == -1) {
            button(NextButton)->setEnabled(false);
        }
        break;
    case CompatDBPage::GamePlay:
        if (compatibility_Gameplay->checkedId() == -1) {
            button(NextButton)->setEnabled(false);
        }
        break;
    case CompatDBPage::Freeze:
        if (compatibility_NoFreeze->checkedId() == -1) {
            button(NextButton)->setEnabled(false);
        }
        break;
    case CompatDBPage::Completion:
        if (compatibility_Complete->checkedId() == -1) {
            button(NextButton)->setEnabled(false);
        }
        break;
    case CompatDBPage::Graphical:
        if (compatibility_Graphical->checkedId() == -1) {
            button(NextButton)->setEnabled(false);
        }
        break;
    case CompatDBPage::Audio:
        if (compatibility_Audio->checkedId() == -1) {
            button(NextButton)->setEnabled(false);
        }
        break;
    case CompatDBPage::Final:
        back();
        LOG_INFO(Frontend, "Compatibility Rating: {}", compatibility);
        telemetry_session.AddField(Common::Telemetry::FieldType::UserFeedback, "Compatibility",
                                   compatibility);

        button(NextButton)->setEnabled(false);
        button(NextButton)->setText(tr("Submitting"));
        button(CancelButton)->setVisible(false);

        testcase_watcher.setFuture(
            QtConcurrent::run([this] { return telemetry_session.SubmitTestcase(); }));
        break;
    default:
        LOG_ERROR(Frontend, "Unexpected page: {}", currentId());
        break;
    }
}

int CompatDB::nextId() const {
    switch ((static_cast<CompatDBPage>(currentId()))) {
    case CompatDBPage::Intro:
        return static_cast<int>(CompatDBPage::GameBoot);
    case CompatDBPage::GameBoot:
        if (ui->radioButton_GameBoot_No->isChecked()) {
            return static_cast<int>(CompatDBPage::Final);
        }
        return static_cast<int>(CompatDBPage::GamePlay);
    case CompatDBPage::GamePlay:
        if (ui->radioButton_Gameplay_No->isChecked()) {
            return static_cast<int>(CompatDBPage::Final);
        }
        return static_cast<int>(CompatDBPage::Freeze);
    case CompatDBPage::Freeze:
        if (ui->radioButton_NoFreeze_No->isChecked()) {
            return static_cast<int>(CompatDBPage::Final);
        }
        return static_cast<int>(CompatDBPage::Completion);
    case CompatDBPage::Completion:
        if (ui->radioButton_Complete_No->isChecked()) {
            return static_cast<int>(CompatDBPage::Final);
        }
        return static_cast<int>(CompatDBPage::Graphical);
    case CompatDBPage::Graphical:
        return static_cast<int>(CompatDBPage::Audio);
    case CompatDBPage::Audio:
        return static_cast<int>(CompatDBPage::Final);
    case CompatDBPage::Final:
        return -1;
    default:
        LOG_ERROR(Frontend, "Unexpected page: {}", currentId());
        return static_cast<int>(CompatDBPage::Intro);
    }
}

CompatibilityStatus CompatDB::CalculateCompatibility() const {
    if (ui->radioButton_GameBoot_No->isChecked()) {
        return CompatibilityStatus::WontBoot;
    }

    if (ui->radioButton_Gameplay_No->isChecked()) {
        return CompatibilityStatus::IntroMenu;
    }

    if (ui->radioButton_NoFreeze_No->isChecked() || ui->radioButton_Complete_No->isChecked()) {
        return CompatibilityStatus::Ingame;
    }

    if (ui->radioButton_Graphical_Major->isChecked() || ui->radioButton_Audio_Major->isChecked()) {
        return CompatibilityStatus::Ingame;
    }

    if (ui->radioButton_Graphical_Minor->isChecked() || ui->radioButton_Audio_Minor->isChecked()) {
        return CompatibilityStatus::Playable;
    }

    return CompatibilityStatus::Perfect;
}

void CompatDB::OnTestcaseSubmitted() {
    if (!testcase_watcher.result()) {
        QMessageBox::critical(this, tr("Communication error"),
                              tr("An error occurred while sending the Testcase"));
        button(NextButton)->setEnabled(true);
        button(NextButton)->setText(tr("Next"));
        button(CancelButton)->setVisible(true);
    } else {
        next();
        // older versions of QT don't support the "NoCancelButtonOnLastPage" option, this is a
        // workaround
        button(CancelButton)->setVisible(false);
    }
}

void CompatDB::EnableNext() {
    button(NextButton)->setEnabled(true);
}


code:
// SPDX-FileCopyrightText: 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <memory>
#include <QFutureWatcher>
#include <QWizard>
#include "core/telemetry_session.h"

namespace Ui {
class CompatDB;
}

enum class CompatibilityStatus {
    Perfect = 0,
    Playable = 1,
    // Unused: Okay = 2,
    Ingame = 3,
    IntroMenu = 4,
    WontBoot = 5,
};

class CompatDB : public QWizard {
    Q_OBJECT

public:
    explicit CompatDB(Core::TelemetrySession& telemetry_session_, QWidget* parent = nullptr);
    ~CompatDB();
    int nextId() const override;

private:
    QFutureWatcher<bool> testcase_watcher;

    std::unique_ptr<Ui::CompatDB> ui;

    void Submit();
    CompatibilityStatus CalculateCompatibility() const;
    void OnTestcaseSubmitted();
    void EnableNext();

    Core::TelemetrySession& telemetry_session;
};


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <algorithm>

#include <fmt/format.h>

#include "yuzu/compatibility_list.h"

CompatibilityList::const_iterator FindMatchingCompatibilityEntry(
    const CompatibilityList& compatibility_list, u64 program_id) {
    return std::find_if(compatibility_list.begin(), compatibility_list.end(),
                        [program_id](const auto& element) {
                            std::string pid = fmt::format("{:016X}", program_id);
                            return element.first == pid;
                        });
}


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <string>
#include <unordered_map>

#include <QString>

#include "common/common_types.h"

using CompatibilityList = std::unordered_map<std::string, std::pair<QString, QString>>;

CompatibilityList::const_iterator FindMatchingCompatibilityEntry(
    const CompatibilityList& compatibility_list, u64 program_id);


code:
// SPDX-FileCopyrightText: 2016 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <memory>
#include <type_traits>
#include <vector>
#include "yuzu/configuration/configuration_shared.h"

namespace ConfigurationShared {

Tab::Tab(std::shared_ptr<std::vector<Tab*>> group, QWidget* parent) : QWidget(parent) {
    if (group != nullptr) {
        group->push_back(this);
    }
}

Tab::~Tab() = default;

} // namespace ConfigurationShared


code:
// SPDX-FileCopyrightText: 2016 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <memory>
#include <vector>
#include <QString>
#include <QWidget>
#include <qobjectdefs.h>

class QObject;

namespace ConfigurationShared {

class Tab : public QWidget {
    Q_OBJECT

public:
    explicit Tab(std::shared_ptr<std::vector<Tab*>> group, QWidget* parent = nullptr);
    ~Tab();

    virtual void ApplyConfiguration() = 0;
    virtual void SetConfiguration() = 0;
};

} // namespace ConfigurationShared


code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>ConfigureDialog</class>
 <widget class="QDialog" name="ConfigureDialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>650</width>
    <height>650</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>0</width>
    <height>650</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>yuzu Configuration</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <widget class="QListWidget" name="selectorList">
       <property name="minimumSize">
        <size>
         <width>120</width>
         <height>0</height>
        </size>
       </property>
       <property name="maximumSize">
        <size>
         <width>120</width>
         <height>16777215</height>
        </size>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QTabWidget" name="tabWidget">
       <property name="currentIndex">
        <number>-1</number>
       </property>
      </widget>
     </item>
    </layout>
   </item>
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout_2">
     <property name="leftMargin">
      <number>0</number>
     </property>
     <property name="topMargin">
      <number>0</number>
     </property>
     <property name="rightMargin">
      <number>0</number>
     </property>
     <property name="bottomMargin">
      <number>0</number>
     </property>
     <item>
      <widget class="QLabel" name="label">
       <property name="text">
        <string>Some settings are only available when a game is not running.</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QDialogButtonBox" name="buttonBox">
       <property name="standardButtons">
        <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>ConfigureDialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>20</x>
     <y>20</y>
    </hint>
    <hint type="destinationlabel">
     <x>20</x>
     <y>20</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>ConfigureDialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>20</x>
     <y>20</y>
    </hint>
    <hint type="destinationlabel">
     <x>20</x>
     <y>20</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>


code:
// SPDX-FileCopyrightText: 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/settings.h"
#include "core/core.h"
#include "ui_configure_applets.h"
#include "yuzu/configuration/configuration_shared.h"
#include "yuzu/configuration/configure_applets.h"
#include "yuzu/configuration/shared_widget.h"

ConfigureApplets::ConfigureApplets(Core::System& system_,
                                   std::shared_ptr<std::vector<ConfigurationShared::Tab*>> group_,
                                   const ConfigurationShared::Builder& builder, QWidget* parent)
    : Tab(group_, parent), ui{std::make_unique<Ui::ConfigureApplets>()}, system{system_} {
    ui->setupUi(this);

    Setup(builder);

    SetConfiguration();
}

ConfigureApplets::~ConfigureApplets() = default;

void ConfigureApplets::changeEvent(QEvent* event) {
    if (event->type() == QEvent::LanguageChange) {
        RetranslateUI();
    }

    QWidget::changeEvent(event);
}

void ConfigureApplets::RetranslateUI() {
    ui->retranslateUi(this);
}

void ConfigureApplets::Setup(const ConfigurationShared::Builder& builder) {
    auto& library_applets_layout = *ui->group_library_applet_modes->layout();
    std::map<u32, QWidget*> applets_hold{};

    std::vector<Settings::BasicSetting*> settings;
    auto push = [&settings](auto& list) {
        for (auto setting : list) {
            settings.push_back(setting);
        }
    };

    push(Settings::values.linkage.by_category[Settings::Category::LibraryApplet]);

    for (auto setting : settings) {
        ConfigurationShared::Widget* widget = builder.BuildWidget(setting, apply_funcs);

        if (widget == nullptr) {
            continue;
        }
        if (!widget->Valid()) {
            widget->deleteLater();
            continue;
        }

        // Untested applets
        if (setting->Id() == Settings::values.data_erase_applet_mode.Id() ||
            setting->Id() == Settings::values.net_connect_applet_mode.Id() ||
            setting->Id() == Settings::values.shop_applet_mode.Id() ||
            setting->Id() == Settings::values.login_share_applet_mode.Id() ||
            setting->Id() == Settings::values.wifi_web_auth_applet_mode.Id() ||
            setting->Id() == Settings::values.my_page_applet_mode.Id()) {
            widget->setHidden(true);
        }

        applets_hold.emplace(setting->Id(), widget);
    }
    for (const auto& [label, widget] : applets_hold) {
        library_applets_layout.addWidget(widget);
    }
}

void ConfigureApplets::SetConfiguration() {}

void ConfigureApplets::ApplyConfiguration() {
    const bool powered_on = system.IsPoweredOn();
    for (const auto& func : apply_funcs) {
        func(powered_on);
    }
}


code:
// SPDX-FileCopyrightText: 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <QWidget>
#include "yuzu/configuration/configuration_shared.h"

class QCheckBox;
class QLineEdit;
class QComboBox;
class QDateTimeEdit;
namespace Core {
class System;
}

namespace Ui {
class ConfigureApplets;
}

namespace ConfigurationShared {
class Builder;
}

class ConfigureApplets : public ConfigurationShared::Tab {
public:
    explicit ConfigureApplets(Core::System& system_,
                              std::shared_ptr<std::vector<ConfigurationShared::Tab*>> group,
                              const ConfigurationShared::Builder& builder,
                              QWidget* parent = nullptr);
    ~ConfigureApplets() override;

    void ApplyConfiguration() override;
    void SetConfiguration() override;

private:
    void changeEvent(QEvent* event) override;
    void RetranslateUI();

    void Setup(const ConfigurationShared::Builder& builder);

    std::vector<std::function<void(bool)>> apply_funcs{};

    std::unique_ptr<Ui::ConfigureApplets> ui;
    bool enabled = false;

    Core::System& system;
};