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

#pragma once

#include <memory>
#include <optional>

#include <filesystem>
#include <QMainWindow>
#include <QMessageBox>
#include <QPushButton>
#include <QTimer>
#include <QTranslator>

#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "configuration/qt_config.h"
#include "frontend_common/content_manager.h"
#include "input_common/drivers/tas_input.h"
#include "yuzu/compatibility_list.h"
#include "yuzu/hotkeys.h"
#include "yuzu/util/controller_navigation.h"

#ifdef __unix__
#include <QVariant>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QtDBus>
#endif

class QtConfig;
class ClickableLabel;
class EmuThread;
class GameList;
class GImageInfo;
class GRenderWindow;
class LoadingScreen;
class MicroProfileDialog;
class OverlayDialog;
class ProfilerWidget;
class ControllerDialog;
class QLabel;
class MultiplayerState;
class QPushButton;
class QProgressDialog;
class QSlider;
class QHBoxLayout;
class WaitTreeWidget;
enum class GameListOpenTarget;
enum class GameListRemoveTarget;
enum class GameListShortcutTarget;
enum class DumpRomFSTarget;
enum class InstalledEntryType;
class GameListPlaceholder;

class QtAmiiboSettingsDialog;
class QtControllerSelectorDialog;
class QtProfileSelectionDialog;
class QtSoftwareKeyboardDialog;
class QtNXWebEngineView;

enum class StartGameType {
    Normal, // Can use custom configuration
    Global, // Only uses global configuration
};

namespace Core {
enum class SystemResultStatus : u32;
class System;
} // namespace Core

namespace Core::Frontend {
struct CabinetParameters;
struct ControllerParameters;
struct InlineAppearParameters;
struct InlineTextParameters;
struct KeyboardInitializeParameters;
struct ProfileSelectParameters;
} // namespace Core::Frontend

namespace DiscordRPC {
class DiscordInterface;
}

namespace PlayTime {
class PlayTimeManager;
}

namespace FileSys {
class ContentProvider;
class ManualContentProvider;
class VfsFilesystem;
} // namespace FileSys

namespace InputCommon {
class InputSubsystem;
}

namespace Service::AM {
struct FrontendAppletParameters;
enum class AppletId : u32;
} // namespace Service::AM

namespace Service::AM::Frontend {
enum class SwkbdResult : u32;
enum class SwkbdTextCheckResult : u32;
enum class SwkbdReplyType : u32;
enum class WebExitReason : u32;
} // namespace Service::AM::Frontend

namespace Service::NFC {
class NfcDevice;
} // namespace Service::NFC

namespace Service::NFP {
enum class CabinetMode : u8;
} // namespace Service::NFP

namespace Ui {
class MainWindow;
}

enum class EmulatedDirectoryTarget {
    NAND,
    SDMC,
};

namespace VkDeviceInfo {
class Record;
}

class VolumeButton : public QPushButton {
    Q_OBJECT
public:
    explicit VolumeButton(QWidget* parent = nullptr) : QPushButton(parent), scroll_multiplier(1) {
        connect(&scroll_timer, &QTimer::timeout, this, &VolumeButton::ResetMultiplier);
    }

signals:
    void VolumeChanged();

protected:
    void wheelEvent(QWheelEvent* event) override;

private slots:
    void ResetMultiplier();

private:
    int scroll_multiplier;
    QTimer scroll_timer;
    constexpr static int MaxMultiplier = 8;
};

class GMainWindow : public QMainWindow {
    Q_OBJECT

    /// Max number of recently loaded items to keep track of
    static const int max_recent_files_item = 10;

    enum {
        CREATE_SHORTCUT_MSGBOX_FULLSCREEN_YES,
        CREATE_SHORTCUT_MSGBOX_SUCCESS,
        CREATE_SHORTCUT_MSGBOX_ERROR,
        CREATE_SHORTCUT_MSGBOX_APPVOLATILE_WARNING,
    };

public:
    void filterBarSetChecked(bool state);
    void UpdateUITheme();
    explicit GMainWindow(std::unique_ptr<QtConfig> config_, bool has_broken_vulkan);
    ~GMainWindow() override;

    bool DropAction(QDropEvent* event);
    void AcceptDropEvent(QDropEvent* event);

signals:

    /**
     * Signal that is emitted when a new EmuThread has been created and an emulation session is
     * about to start. At this time, the core system emulation has been initialized, and all
     * emulation handles and memory should be valid.
     *
     * @param emu_thread Pointer to the newly created EmuThread (to be used by widgets that need to
     *      access/change emulation state).
     */
    void EmulationStarting(EmuThread* emu_thread);

    /**
     * Signal that is emitted when emulation is about to stop. At this time, the EmuThread and core
     * system emulation handles and memory are still valid, but are about become invalid.
     */
    void EmulationStopping();

    // Signal that tells widgets to update icons to use the current theme
    void UpdateThemedIcons();

    void UpdateInstallProgress();

    void AmiiboSettingsFinished(bool is_success, const std::string& name);

    void ControllerSelectorReconfigureFinished(bool is_success);

    void ErrorDisplayFinished();

    void ProfileSelectorFinishedSelection(std::optional<Common::UUID> uuid);

    void SoftwareKeyboardSubmitNormalText(Service::AM::Frontend::SwkbdResult result,
                                          std::u16string submitted_text, bool confirmed);
    void SoftwareKeyboardSubmitInlineText(Service::AM::Frontend::SwkbdReplyType reply_type,
                                          std::u16string submitted_text, s32 cursor_position);

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

    void SigInterrupt();

public slots:
    void OnLoadComplete();
    void OnExecuteProgram(std::size_t program_index);
    void OnExit();
    void OnSaveConfig();
    void AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters,
                                  std::shared_ptr<Service::NFC::NfcDevice> nfp_device);
    void AmiiboSettingsRequestExit();
    void ControllerSelectorReconfigureControllers(
        const Core::Frontend::ControllerParameters& parameters);
    void ControllerSelectorRequestExit();
    void SoftwareKeyboardInitialize(
        bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters);
    void SoftwareKeyboardShowNormal();
    void SoftwareKeyboardShowTextCheck(
        Service::AM::Frontend::SwkbdTextCheckResult text_check_result,
        std::u16string text_check_message);
    void SoftwareKeyboardShowInline(Core::Frontend::InlineAppearParameters appear_parameters);
    void SoftwareKeyboardHideInline();
    void SoftwareKeyboardInlineTextChanged(Core::Frontend::InlineTextParameters text_parameters);
    void SoftwareKeyboardExit();
    void ErrorDisplayDisplayError(QString error_code, QString error_text);
    void ErrorDisplayRequestExit();
    void ProfileSelectorSelectProfile(const Core::Frontend::ProfileSelectParameters& parameters);
    void ProfileSelectorRequestExit();
    void WebBrowserOpenWebPage(const std::string& main_url, const std::string& additional_args,
                               bool is_local);
    void WebBrowserRequestExit();
    void OnAppFocusStateChanged(Qt::ApplicationState state);
    void OnTasStateChanged();

private:
    /// Updates an action's shortcut and text to reflect an updated hotkey from the hotkey registry.
    void LinkActionShortcut(QAction* action, const QString& action_name,
                            const bool tas_allowed = false);

    void RegisterMetaTypes();

    void InitializeWidgets();
    void InitializeDebugWidgets();
    void InitializeRecentFileMenuActions();

    void SetDefaultUIGeometry();
    void RestoreUIState();

    void ConnectWidgetEvents();
    void ConnectMenuEvents();
    void UpdateMenuState();

    void SetupPrepareForSleep();

    void PreventOSSleep();
    void AllowOSSleep();

    bool LoadROM(const QString& filename, Service::AM::FrontendAppletParameters params);
    void BootGame(const QString& filename, Service::AM::FrontendAppletParameters params,
                  StartGameType with_config = StartGameType::Normal);
    void BootGameFromList(const QString& filename, StartGameType with_config);
    void ShutdownGame();

    void ShowTelemetryCallout();
    void SetDiscordEnabled(bool state);
    void LoadAmiibo(const QString& filename);

    bool SelectAndSetCurrentUser(const Core::Frontend::ProfileSelectParameters& parameters);

    /**
     * Stores the filename in the recently loaded files list.
     * The new filename is stored at the beginning of the recently loaded files list.
     * After inserting the new entry, duplicates are removed meaning that if
     * this was inserted from \a OnMenuRecentFile(), the entry will be put on top
     * and remove from its previous position.
     *
     * Finally, this function calls \a UpdateRecentFiles() to update the UI.
     *
     * @param filename the filename to store
     */
    void StoreRecentFile(const QString& filename);

    /**
     * Updates the recent files menu.
     * Menu entries are rebuilt from the configuration file.
     * If there is no entry in the menu, the menu is greyed out.
     */
    void UpdateRecentFiles();

    /**
     * If the emulation is running,
     * asks the user if he really want to close the emulator
     *
     * @return true if the user confirmed
     */
    bool ConfirmClose();
    bool ConfirmChangeGame();
    bool ConfirmForceLockedExit();
    void RequestGameExit();
    void RequestGameResume();
    void changeEvent(QEvent* event) override;
    void closeEvent(QCloseEvent* event) override;

    std::string CreateTASFramesString(
        std::array<size_t, InputCommon::TasInput::PLAYER_NUMBER> frames) const;

#ifdef __unix__
    void SetupSigInterrupts();
    static void HandleSigInterrupt(int);
    void OnSigInterruptNotifierActivated();
    void SetGamemodeEnabled(bool state);
#endif

    Service::AM::FrontendAppletParameters ApplicationAppletParameters();
    Service::AM::FrontendAppletParameters LibraryAppletParameters(u64 program_id,
                                                                  Service::AM::AppletId applet_id);

private slots:
    void OnStartGame();
    void OnRestartGame();
    void OnPauseGame();
    void OnPauseContinueGame();
    void OnStopGame();
    void OnPrepareForSleep(bool prepare_sleep);
    void OnMenuReportCompatibility();
    void OnOpenModsPage();
    void OnOpenQuickstartGuide();
    void OnOpenFAQ();
    /// Called whenever a user selects a game in the game list widget.
    void OnGameListLoadFile(QString game_path, u64 program_id);
    void OnGameListOpenFolder(u64 program_id, GameListOpenTarget target,
                              const std::string& game_path);
    void OnTransferableShaderCacheOpenFile(u64 program_id);
    void OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type);
    void OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target,
                              const std::string& game_path);
    void OnGameListRemovePlayTimeData(u64 program_id);
    void OnGameListDumpRomFS(u64 program_id, const std::string& game_path, DumpRomFSTarget target);
    void OnGameListVerifyIntegrity(const std::string& game_path);
    void OnGameListCopyTID(u64 program_id);
    void OnGameListNavigateToGamedbEntry(u64 program_id,
                                         const CompatibilityList& compatibility_list);
    void OnGameListCreateShortcut(u64 program_id, const std::string& game_path,
                                  GameListShortcutTarget target);
    void OnGameListOpenDirectory(const QString& directory);
    void OnGameListAddDirectory();
    void OnGameListShowList(bool show);
    void OnGameListOpenPerGameProperties(const std::string& file);
    void OnMenuLoadFile();
    void OnMenuLoadFolder();
    void IncrementInstallProgress();
    void OnMenuInstallToNAND();
    void OnMenuRecentFile();
    void OnConfigure();
    void OnConfigureTas();
    void OnDecreaseVolume();
    void OnIncreaseVolume();
    void OnMute();
    void OnTasStartStop();
    void OnTasRecord();
    void OnTasReset();
    void OnToggleGraphicsAPI();
    void OnToggleDockedMode();
    void OnToggleGpuAccuracy();
    void OnToggleAdaptingFilter();
    void OnConfigurePerGame();
    void OnLoadAmiibo();
    void OnOpenYuzuFolder();
    void OnVerifyInstalledContents();
    void OnInstallFirmware();
    void OnInstallDecryptionKeys();
    void OnAbout();
    void OnToggleFilterBar();
    void OnToggleStatusBar();
    void OnDisplayTitleBars(bool);
    void InitializeHotkeys();
    void ToggleFullscreen();
    bool UsingExclusiveFullscreen();
    void ShowFullscreen();
    void HideFullscreen();
    void ToggleWindowMode();
    void ResetWindowSize(u32 width, u32 height);
    void ResetWindowSize720();
    void ResetWindowSize900();
    void ResetWindowSize1080();
    void OnAlbum();
    void OnCabinet(Service::NFP::CabinetMode mode);
    void OnMiiEdit();
    void OnOpenControllerMenu();
    void OnCaptureScreenshot();
    void OnCheckFirmwareDecryption();
    void OnLanguageChanged(const QString& locale);
    void OnMouseActivity();
    bool OnShutdownBegin();
    void OnShutdownBeginDialog();
    void OnEmulationStopped();
    void OnEmulationStopTimeExpired();

private:
    QString GetGameListErrorRemoving(InstalledEntryType type) const;
    void RemoveBaseContent(u64 program_id, InstalledEntryType type);
    void RemoveUpdateContent(u64 program_id, InstalledEntryType type);
    void RemoveAddOnContent(u64 program_id, InstalledEntryType type);
    void RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target);
    void RemoveVulkanDriverPipelineCache(u64 program_id);
    void RemoveAllTransferableShaderCaches(u64 program_id);
    void RemoveCustomConfiguration(u64 program_id, const std::string& game_path);
    void RemovePlayTimeData(u64 program_id);
    void RemoveCacheStorage(u64 program_id);
    bool SelectRomFSDumpTarget(const FileSys::ContentProvider&, u64 program_id,
                               u64* selected_title_id, u8* selected_content_record_type);
    ContentManager::InstallResult InstallNCA(const QString& filename);
    void MigrateConfigFiles();
    void UpdateWindowTitle(std::string_view title_name = {}, std::string_view title_version = {},
                           std::string_view gpu_vendor = {});
    void UpdateDockedButton();
    void UpdateAPIText();
    void UpdateFilterText();
    void UpdateAAText();
    void UpdateVolumeUI();
    void UpdateStatusBar();
    void UpdateGPUAccuracyButton();
    void UpdateStatusButtons();
    void UpdateUISettings();
    void UpdateInputDrivers();
    void HideMouseCursor();
    void ShowMouseCursor();
    void OpenURL(const QUrl& url);
    void LoadTranslation();
    void OpenPerGameConfiguration(u64 title_id, const std::string& file_name);
    bool CheckDarkMode();
    bool CheckFirmwarePresence();
    void SetFirmwareVersion();
    void ConfigureFilesystemProvider(const std::string& filepath);
    /**
     * Open (or not) the right confirm dialog based on current setting and game exit lock
     * @returns true if the player confirmed or the settings do no require it
     */
    bool ConfirmShutdownGame();

    QString GetTasStateDescription() const;
    bool CreateShortcutMessagesGUI(QWidget* parent, int imsg, const QString& game_title);
    bool MakeShortcutIcoPath(const u64 program_id, const std::string_view game_file_name,
                             std::filesystem::path& out_icon_path);
    bool CreateShortcutLink(const std::filesystem::path& shortcut_path, const std::string& comment,
                            const std::filesystem::path& icon_path,
                            const std::filesystem::path& command, const std::string& arguments,
                            const std::string& categories, const std::string& keywords,
                            const std::string& name);
    /**
     * Mimic the behavior of QMessageBox::question but link controller navigation to the dialog
     * The only difference is that it returns a boolean.
     *
     * @returns true if buttons contains QMessageBox::Yes and the user clicks on the "Yes" button.
     */
    bool question(QWidget* parent, const QString& title, const QString& text,
                  QMessageBox::StandardButtons buttons =
                      QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No),
                  QMessageBox::StandardButton defaultButton = QMessageBox::NoButton);

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

    std::unique_ptr<Core::System> system;
    std::unique_ptr<DiscordRPC::DiscordInterface> discord_rpc;
    std::unique_ptr<PlayTime::PlayTimeManager> play_time_manager;
    std::shared_ptr<InputCommon::InputSubsystem> input_subsystem;

    MultiplayerState* multiplayer_state = nullptr;

    GRenderWindow* render_window;
    GameList* game_list;
    LoadingScreen* loading_screen;
    QTimer shutdown_timer;
    OverlayDialog* shutdown_dialog{};

    GameListPlaceholder* game_list_placeholder;

    std::vector<VkDeviceInfo::Record> vk_device_records;

    // Status bar elements
    QLabel* message_label = nullptr;
    QLabel* shader_building_label = nullptr;
    QLabel* res_scale_label = nullptr;
    QLabel* emu_speed_label = nullptr;
    QLabel* game_fps_label = nullptr;
    QLabel* emu_frametime_label = nullptr;
    QLabel* tas_label = nullptr;
    QLabel* firmware_label = nullptr;
    QPushButton* gpu_accuracy_button = nullptr;
    QPushButton* renderer_status_button = nullptr;
    QPushButton* dock_status_button = nullptr;
    QPushButton* filter_status_button = nullptr;
    QPushButton* aa_status_button = nullptr;
    VolumeButton* volume_button = nullptr;
    QWidget* volume_popup = nullptr;
    QSlider* volume_slider = nullptr;
    QTimer status_bar_update_timer;

    std::unique_ptr<QtConfig> config;

    // Whether emulation is currently running in yuzu.
    bool emulation_running = false;
    std::unique_ptr<EmuThread> emu_thread;
    // The path to the game currently running
    QString current_game_path;
    // Whether a user was set on the command line (skips UserSelector if it's forced to show up)
    bool user_flag_cmd_line = false;

    bool auto_paused = false;
    bool auto_muted = false;
    QTimer mouse_hide_timer;
    QTimer update_input_timer;

    QString startup_icon_theme;
    bool os_dark_mode = false;

    // FS
    std::shared_ptr<FileSys::VfsFilesystem> vfs;
    std::unique_ptr<FileSys::ManualContentProvider> provider;

    // Debugger panes
    ProfilerWidget* profilerWidget;
    MicroProfileDialog* microProfileDialog;
    WaitTreeWidget* waitTreeWidget;
    ControllerDialog* controller_dialog;

    QAction* actions_recent_files[max_recent_files_item];

    // stores default icon theme search paths for the platform
    QStringList default_theme_paths;

    HotkeyRegistry hotkey_registry;

    QTranslator translator;

    // Install progress dialog
    QProgressDialog* install_progress;

    // Last game booted, used for multi-process apps
    QString last_filename_booted;

    // Applets
    QtAmiiboSettingsDialog* cabinet_applet = nullptr;
    QtControllerSelectorDialog* controller_applet = nullptr;
    QtProfileSelectionDialog* profile_select_applet = nullptr;
    QDialog* error_applet = nullptr;
    QtSoftwareKeyboardDialog* software_keyboard = nullptr;
    QtNXWebEngineView* web_applet = nullptr;

    // True if amiibo file select is visible
    bool is_amiibo_file_select_active{};

    // True if load file select is visible
    bool is_load_file_select_active{};

    // True if TAS recording dialog is visible
    bool is_tas_recording_dialog_active{};

#ifdef __unix__
    QSocketNotifier* sig_interrupt_notifier;
    static std::array<int, 3> sig_interrupt_fds;
#endif

protected:
    void dropEvent(QDropEvent* event) override;
    void dragEnterEvent(QDragEnterEvent* event) override;
    void dragMoveEvent(QDragMoveEvent* event) override;
};

repo_name: litucks/torzu

license: mit


code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1280</width>
    <height>720</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>yuzu</string>
  </property>
  <property name="windowIcon">
   <iconset resource="yuzu.qrc">
    <normaloff>:/img/yuzu.ico</normaloff>:/img/yuzu.ico</iconset>
  </property>
  <property name="tabShape">
   <enum>QTabWidget::Rounded</enum>
  </property>
  <property name="dockNestingEnabled">
   <bool>true</bool>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QHBoxLayout" name="horizontalLayout">
    <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>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1280</width>
     <height>21</height>
    </rect>
   </property>
   <widget class="QMenu" name="menu_File">
    <property name="title">
     <string>&File</string>
    </property>
    <widget class="QMenu" name="menu_recent_files">
     <property name="title">
      <string>&Recent Files</string>
     </property>
    </widget>
    <addaction name="action_Install_File_NAND"/>
    <addaction name="separator"/>
    <addaction name="action_Load_File"/>
    <addaction name="action_Load_Folder"/>
    <addaction name="separator"/>
    <addaction name="menu_recent_files"/>
    <addaction name="separator"/>
    <addaction name="action_Load_Amiibo"/>
    <addaction name="separator"/>
    <addaction name="action_Open_yuzu_Folder"/>
    <addaction name="separator"/>
    <addaction name="action_Exit"/>
   </widget>
   <widget class="QMenu" name="menu_Emulation">
    <property name="title">
     <string>&Emulation</string>
    </property>
    <addaction name="action_Pause"/>
    <addaction name="action_Stop"/>
    <addaction name="action_Restart"/>
    <addaction name="separator"/>
    <addaction name="action_Configure"/>
    <addaction name="action_Configure_Current_Game"/>
   </widget>
   <widget class="QMenu" name="menu_View">
    <property name="title">
     <string>&View</string>
    </property>
    <widget class="QMenu" name="menu_Reset_Window_Size">
     <property name="title">
      <string>&Reset Window Size</string>
     </property>
    </widget>
    <widget class="QMenu" name="menu_View_Debugging">
     <property name="title">
      <string>&Debugging</string>
     </property>
    </widget>
    <action name="action_Reset_Window_Size_720">
     <property name="text">
      <string>Reset Window Size to &720p</string>
     </property>
     <property name="iconText">
      <string>Reset Window Size to 720p</string>
     </property>
    </action>
    <action name="action_Reset_Window_Size_900">
     <property name="text">
      <string>Reset Window Size to &900p</string>
     </property>
     <property name="iconText">
      <string>Reset Window Size to 900p</string>
     </property>
    </action>
    <action name="action_Reset_Window_Size_1080">
     <property name="text">
      <string>Reset Window Size to &1080p</string>
     </property>
     <property name="iconText">
      <string>Reset Window Size to 1080p</string>
     </property>
    </action>
    <addaction name="action_Fullscreen"/>
    <addaction name="action_Single_Window_Mode"/>
    <addaction name="action_Display_Dock_Widget_Headers"/>
    <addaction name="action_Show_Filter_Bar"/>
    <addaction name="action_Show_Status_Bar"/>
    <addaction name="separator"/>
    <addaction name="menu_Reset_Window_Size"/>
    <addaction name="menu_View_Debugging"/>
   </widget>
   <widget class="QMenu" name="menu_Multiplayer">
    <property name="enabled">
     <bool>true</bool>
    </property>
    <property name="title">
     <string>&Multiplayer</string>
    </property>
    <addaction name="action_View_Lobby"/>
    <addaction name="action_Start_Room"/>
    <addaction name="action_Connect_To_Room"/>
    <addaction name="separator"/>
    <addaction name="action_Show_Room"/>
    <addaction name="action_Leave_Room"/>
   </widget>
   <widget class="QMenu" name="menu_Tools">
    <property name="title">
     <string>&Tools</string>
    </property>
    <widget class="QMenu" name="menu_cabinet_applet">
     <property name="title">
      <string>&Amiibo</string>
     </property>
     <addaction name="action_Load_Cabinet_Nickname_Owner"/>
     <addaction name="action_Load_Cabinet_Eraser"/>
     <addaction name="action_Load_Cabinet_Restorer"/>
     <addaction name="action_Load_Cabinet_Formatter"/>
    </widget>
    <widget class="QMenu" name="menuTAS">
     <property name="title">
      <string>&TAS</string>
     </property>
     <addaction name="action_TAS_Start"/>
     <addaction name="action_TAS_Record"/>
     <addaction name="action_TAS_Reset"/>
     <addaction name="separator"/>
     <addaction name="action_Configure_Tas"/>
    </widget>
    <addaction name="action_Install_Keys"/>
    <addaction name="action_Install_Firmware"/>
    <addaction name="action_Verify_installed_contents"/>
    <addaction name="separator"/>
    <addaction name="menu_cabinet_applet"/>
    <addaction name="action_Load_Album"/>
    <addaction name="action_Load_Mii_Edit"/>
    <addaction name="action_Open_Controller_Menu"/>
    <addaction name="separator"/>
    <addaction name="action_Capture_Screenshot"/>
    <addaction name="menuTAS"/>
   </widget>
   <widget class="QMenu" name="menu_Help">
    <property name="title">
     <string>&Help</string>
    </property>
    <addaction name="action_Report_Compatibility"/>
    <addaction name="action_Open_Mods_Page"/>
    <addaction name="action_Open_Quickstart_Guide"/>
    <addaction name="action_Open_FAQ"/>
    <addaction name="separator"/>
    <addaction name="action_About"/>
   </widget>
   <addaction name="menu_File"/>
   <addaction name="menu_Emulation"/>
   <addaction name="menu_View"/>
   <addaction name="menu_Tools"/>
   <addaction name="menu_Multiplayer"/>
   <addaction name="menu_Help"/>
  </widget>
  <action name="action_Install_File_NAND">
   <property name="enabled">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>&Install Files to NAND...</string>
   </property>
  </action>
  <action name="action_Load_File">
   <property name="text">
    <string>L&oad File...</string>
   </property>
  </action>
  <action name="action_Load_Folder">
   <property name="text">
    <string>Load &Folder...</string>
   </property>
  </action>
  <action name="action_Exit">
   <property name="text">
    <string>E&xit</string>
   </property>
  </action>
  <action name="action_Pause">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Pause</string>
   </property>
  </action>
  <action name="action_Stop">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Stop</string>
   </property>
  </action>
  <action name="action_Verify_installed_contents">
   <property name="text">
    <string>&Verify Installed Contents</string>
   </property>
  </action>
  <action name="action_About">
   <property name="text">
    <string>&About yuzu</string>
   </property>
  </action>
  <action name="action_Single_Window_Mode">
   <property name="checkable">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>Single &Window Mode</string>
   </property>
  </action>
  <action name="action_Configure">
   <property name="text">
    <string>Con&figure...</string>
   </property>
   <property name="menuRole">
    <enum>QAction::PreferencesRole</enum>
   </property>
  </action>
  <action name="action_Display_Dock_Widget_Headers">
   <property name="checkable">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>Display D&ock Widget Headers</string>
   </property>
  </action>
  <action name="action_Show_Filter_Bar">
   <property name="checkable">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>Show &Filter Bar</string>
   </property>
  </action>
  <action name="action_Show_Status_Bar">
   <property name="checkable">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>Show &Status Bar</string>
   </property>
   <property name="iconText">
    <string>Show Status Bar</string>
   </property>
  </action>
  <action name="action_View_Lobby">
   <property name="enabled">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>&Browse Public Game Lobby</string>
   </property>
  </action>
  <action name="action_Start_Room">
   <property name="enabled">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>&Create Room</string>
   </property>
  </action>
  <action name="action_Leave_Room">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Leave Room</string>
   </property>
  </action>
  <action name="action_Connect_To_Room">
   <property name="text">
    <string>&Direct Connect to Room</string>
   </property>
  </action>
  <action name="action_Show_Room">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Show Current Room</string>
   </property>
  </action>
  <action name="action_Fullscreen">
   <property name="checkable">
    <bool>true</bool>
   </property>
   <property name="text">
    <string>F&ullscreen</string>
   </property>
  </action>
  <action name="action_Restart">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Restart</string>
   </property>
  </action>
  <action name="action_Load_Amiibo">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>Load/Remove &Amiibo...</string>
   </property>
  </action>
  <action name="action_Report_Compatibility">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Report Compatibility</string>
   </property>
   <property name="visible">
    <bool>false</bool>
   </property>
  </action>
  <action name="action_Open_Mods_Page">
   <property name="text">
    <string>Open &Mods Page</string>
   </property>
  </action>
  <action name="action_Open_Quickstart_Guide">
   <property name="text">
    <string>Open &Quickstart Guide</string>
   </property>
  </action>
  <action name="action_Open_FAQ">
   <property name="text">
    <string>&FAQ</string>
   </property>
  </action>
  <action name="action_Open_yuzu_Folder">
   <property name="text">
    <string>Open &yuzu Folder</string>
   </property>
  </action>
  <action name="action_Capture_Screenshot">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Capture Screenshot</string>
   </property>
  </action>
  <action name="action_Load_Album">
   <property name="text">
    <string>Open &Album</string>
   </property>
  </action>
  <action name="action_Load_Cabinet_Nickname_Owner">
   <property name="text">
    <string>&Set Nickname and Owner</string>
   </property>
  </action>
  <action name="action_Load_Cabinet_Eraser">
   <property name="text">
    <string>&Delete Game Data</string>
   </property>
  </action>
  <action name="action_Load_Cabinet_Restorer">
   <property name="text">
    <string>&Restore Amiibo</string>
   </property>
  </action>
  <action name="action_Load_Cabinet_Formatter">
   <property name="text">
    <string>&Format Amiibo</string>
   </property>
  </action>
  <action name="action_Load_Mii_Edit">
   <property name="text">
    <string>Open &Mii Editor</string>
   </property>
  </action>
  <action name="action_Configure_Tas">
   <property name="text">
    <string>&Configure TAS...</string>
   </property>
   <property name="menuRole">
    <enum>QAction::NoRole</enum>
   </property>
  </action>
  <action name="action_Configure_Current_Game">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>Configure C&urrent Game...</string>
   </property>
   <property name="menuRole">
    <enum>QAction::NoRole</enum>
   </property>
  </action>
  <action name="action_TAS_Start">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Start</string>
   </property>
  </action>
  <action name="action_TAS_Reset">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>&Reset</string>
   </property>
  </action>
  <action name="action_TAS_Record">
   <property name="enabled">
    <bool>false</bool>
   </property>
   <property name="text">
    <string>R&ecord</string>
   </property>
  </action>
  <action name="action_Open_Controller_Menu">
   <property name="text">
    <string>Open &Controller Menu</string>
   </property>
  </action>
  <action name="action_Install_Firmware">
   <property name="text">
    <string>Install Firmware</string>
   </property>
  </action>
  <action name="action_Install_Keys">
   <property name="text">
    <string>Install Decryption Keys</string>
   </property>
  </action>
 </widget>
 <resources>
  <include location="yuzu.qrc"/>
 </resources>
 <connections/>
</ui>


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

#include <array>
#include <future>
#include <QColor>
#include <QDesktopServices>
#include <QFutureWatcher>
#include <QImage>
#include <QList>
#include <QLocale>
#include <QMenu>
#include <QMessageBox>
#include <QMetaType>
#include <QTime>
#include <QUrl>
#include <QtConcurrent/QtConcurrentRun>
#include "common/logging/log.h"
#include "network/announce_multiplayer_session.h"
#include "ui_chat_room.h"
#include "yuzu/game_list_p.h"
#include "yuzu/multiplayer/chat_room.h"
#include "yuzu/multiplayer/message.h"
#ifdef ENABLE_WEB_SERVICE
#include "web_service/web_backend.h"
#endif

class ChatMessage {
public:
    explicit ChatMessage(const Network::ChatEntry& chat, Network::RoomNetwork& room_network,
                         QTime ts = {}) {
        /// Convert the time to their default locale defined format
        QLocale locale;
        timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat);
        nickname = QString::fromStdString(chat.nickname);
        username = QString::fromStdString(chat.username);
        message = QString::fromStdString(chat.message);

        // Check for user pings
        QString cur_nickname, cur_username;
        if (auto room = room_network.GetRoomMember().lock()) {
            cur_nickname = QString::fromStdString(room->GetNickname());
            cur_username = QString::fromStdString(room->GetUsername());
        }

        // Handle pings at the beginning and end of message
        QString fixed_message = QStringLiteral(" %1 ").arg(message);
        if (fixed_message.contains(QStringLiteral(" @%1 ").arg(cur_nickname)) ||
            (!cur_username.isEmpty() &&
             fixed_message.contains(QStringLiteral(" @%1 ").arg(cur_username)))) {

            contains_ping = true;
        } else {
            contains_ping = false;
        }
    }

    bool ContainsPing() const {
        return contains_ping;
    }

    /// Format the message using the players color
    QString GetPlayerChatMessage(u16 player) const {
        const bool is_dark_theme = QIcon::themeName().contains(QStringLiteral("dark")) ||
                                   QIcon::themeName().contains(QStringLiteral("midnight"));
        auto color =
            is_dark_theme ? player_color_dark[player % 16] : player_color_default[player % 16];
        QString name;
        if (username.isEmpty() || username == nickname) {
            name = nickname;
        } else {
            name = QStringLiteral("%1 (%2)").arg(nickname, username);
        }

        QString style, text_color;
        if (ContainsPing()) {
            // Add a background color to these messages
            style = QStringLiteral("background-color: %1").arg(QString::fromStdString(ping_color));
            // Add a font color
            text_color = QStringLiteral("color='#000000'");
        }

        return QStringLiteral("[%1] <%3> %6")
            .arg(timestamp, QString::fromStdString(color), name.toHtmlEscaped(), style, text_color,
                 message.toHtmlEscaped());
    }

private:
    static constexpr std::array<const char*, 16> player_color_default = {
        {"#0000FF", "#FF0000", "#8A2BE2", "#FF69B4", "#1E90FF", "#008000", "#00FF7F", "#B22222",
         "#DAA520", "#FF4500", "#2E8B57", "#5F9EA0", "#D2691E", "#9ACD32", "#FF7F50", "#FFFF00"}};
    static constexpr std::array<const char*, 16> player_color_dark = {
        {"#559AD1", "#4EC9A8", "#D69D85", "#C6C923", "#B975B5", "#D81F1F", "#7EAE39", "#4F8733",
         "#F7CD8A", "#6FCACF", "#CE4897", "#8A2BE2", "#D2691E", "#9ACD32", "#FF7F50", "#152ccd"}};
    static constexpr char ping_color[] = "#FFFF00";

    QString timestamp;
    QString nickname;
    QString username;
    QString message;
    bool contains_ping;
};

class StatusMessage {
public:
    explicit StatusMessage(const QString& msg, QTime ts = {}) {
        /// Convert the time to their default locale defined format
        QLocale locale;
        timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat);
        message = msg;
    }

    QString GetSystemChatMessage() const {
        return QStringLiteral("[%1] * %3")
            .arg(timestamp, QString::fromStdString(system_color), message);
    }

private:
    static constexpr const char system_color[] = "#FF8C00";
    QString timestamp;
    QString message;
};

class PlayerListItem : public QStandardItem {
public:
    static const int NicknameRole = Qt::UserRole + 1;
    static const int UsernameRole = Qt::UserRole + 2;
    static const int AvatarUrlRole = Qt::UserRole + 3;
    static const int GameNameRole = Qt::UserRole + 4;
    static const int GameVersionRole = Qt::UserRole + 5;

    PlayerListItem() = default;
    explicit PlayerListItem(const std::string& nickname, const std::string& username,
                            const std::string& avatar_url,
                            const AnnounceMultiplayerRoom::GameInfo& game_info) {
        setEditable(false);
        setData(QString::fromStdString(nickname), NicknameRole);
        setData(QString::fromStdString(username), UsernameRole);
        setData(QString::fromStdString(avatar_url), AvatarUrlRole);
        if (game_info.name.empty()) {
            setData(QObject::tr("Not playing a game"), GameNameRole);
        } else {
            setData(QString::fromStdString(game_info.name), GameNameRole);
        }
        setData(QString::fromStdString(game_info.version), GameVersionRole);
    }

    QVariant data(int role) const override {
        if (role != Qt::DisplayRole) {
            return QStandardItem::data(role);
        }
        QString name;
        const QString nickname = data(NicknameRole).toString();
        const QString username = data(UsernameRole).toString();
        if (username.isEmpty() || username == nickname) {
            name = nickname;
        } else {
            name = QStringLiteral("%1 (%2)").arg(nickname, username);
        }
        const QString version = data(GameVersionRole).toString();
        QString version_string;
        if (!version.isEmpty()) {
            version_string = QStringLiteral("(%1)").arg(version);
        }
        return QStringLiteral("%1\n      %2 %3")
            .arg(name, data(GameNameRole).toString(), version_string);
    }
};

ChatRoom::ChatRoom(QWidget* parent) : QWidget(parent), ui(std::make_unique<Ui::ChatRoom>()) {
    ui->setupUi(this);

    // set the item_model for player_view

    player_list = new QStandardItemModel(ui->player_view);
    ui->player_view->setModel(player_list);
    ui->player_view->setContextMenuPolicy(Qt::CustomContextMenu);
    // set a header to make it look better though there is only one column
    player_list->insertColumns(0, 1);
    player_list->setHeaderData(0, Qt::Horizontal, tr("Members"));

    ui->chat_history->document()->setMaximumBlockCount(max_chat_lines);

    auto font = ui->chat_history->font();
    font.setPointSizeF(10);
    ui->chat_history->setFont(font);

    // register the network structs to use in slots and signals
    qRegisterMetaType<Network::ChatEntry>();
    qRegisterMetaType<Network::StatusMessageEntry>();
    qRegisterMetaType<Network::RoomInformation>();
    qRegisterMetaType<Network::RoomMember::State>();

    // Connect all the widgets to the appropriate events
    connect(ui->player_view, &QTreeView::customContextMenuRequested, this,
            &ChatRoom::PopupContextMenu);
    connect(ui->chat_message, &QLineEdit::returnPressed, this, &ChatRoom::OnSendChat);
    connect(ui->chat_message, &QLineEdit::textChanged, this, &ChatRoom::OnChatTextChanged);
    connect(ui->send_message, &QPushButton::clicked, this, &ChatRoom::OnSendChat);
}

ChatRoom::~ChatRoom() = default;

void ChatRoom::Initialize(Network::RoomNetwork* room_network_) {
    room_network = room_network_;
    // setup the callbacks for network updates
    if (auto member = room_network->GetRoomMember().lock()) {
        member->BindOnChatMessageReceived(
            [this](const Network::ChatEntry& chat) { emit ChatReceived(chat); });
        member->BindOnStatusMessageReceived(
            [this](const Network::StatusMessageEntry& status_message) {
                emit StatusMessageReceived(status_message);
            });
        connect(this, &ChatRoom::ChatReceived, this, &ChatRoom::OnChatReceive);
        connect(this, &ChatRoom::StatusMessageReceived, this, &ChatRoom::OnStatusMessageReceive);
    }
}

void ChatRoom::SetModPerms(bool is_mod) {
    has_mod_perms = is_mod;
}

void ChatRoom::RetranslateUi() {
    ui->retranslateUi(this);
}

void ChatRoom::Clear() {
    ui->chat_history->clear();
    block_list.clear();
}

void ChatRoom::AppendStatusMessage(const QString& msg) {
    ui->chat_history->append(StatusMessage(msg).GetSystemChatMessage());
}

void ChatRoom::AppendChatMessage(const QString& msg) {
    ui->chat_history->append(msg);
}

void ChatRoom::SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname) {
    if (auto room = room_network->GetRoomMember().lock()) {
        auto members = room->GetMemberInformation();
        auto it = std::find_if(members.begin(), members.end(),
                               [&nickname](const Network::RoomMember::MemberInformation& member) {
                                   return member.nickname == nickname;
                               });
        if (it == members.end()) {
            NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::NO_SUCH_USER);
            return;
        }
        room->SendModerationRequest(type, nickname);
    }
}

bool ChatRoom::ValidateMessage(const std::string& msg) {
    return !msg.empty();
}

void ChatRoom::OnRoomUpdate(const Network::RoomInformation& info) {
    // TODO(B3N30): change title
    if (auto room_member = room_network->GetRoomMember().lock()) {
        SetPlayerList(room_member->GetMemberInformation());
    }
}

void ChatRoom::Disable() {
    ui->send_message->setDisabled(true);
    ui->chat_message->setDisabled(true);
}

void ChatRoom::Enable() {
    ui->send_message->setEnabled(true);
    ui->chat_message->setEnabled(true);
}

void ChatRoom::OnChatReceive(const Network::ChatEntry& chat) {
    if (!ValidateMessage(chat.message)) {
        return;
    }
    if (auto room = room_network->GetRoomMember().lock()) {
        // get the id of the player
        auto members = room->GetMemberInformation();
        auto it = std::find_if(members.begin(), members.end(),
                               [&chat](const Network::RoomMember::MemberInformation& member) {
                                   return member.nickname == chat.nickname &&
                                          member.username == chat.username;
                               });
        if (it == members.end()) {
            LOG_INFO(Network, "Chat message received from unknown player. Ignoring it.");
            return;
        }
        if (block_list.count(chat.nickname)) {
            LOG_INFO(Network, "Chat message received from blocked player {}. Ignoring it.",
                     chat.nickname);
            return;
        }
        auto player = std::distance(members.begin(), it);
        ChatMessage m(chat, *room_network);
        if (m.ContainsPing()) {
            emit UserPinged();
        }
        AppendChatMessage(m.GetPlayerChatMessage(player));
    }
}

void ChatRoom::OnStatusMessageReceive(const Network::StatusMessageEntry& status_message) {
    QString name;
    if (status_message.username.empty() || status_message.username == status_message.nickname) {
        name = QString::fromStdString(status_message.nickname);
    } else {
        name = QStringLiteral("%1 (%2)").arg(QString::fromStdString(status_message.nickname),
                                             QString::fromStdString(status_message.username));
    }
    QString message;
    switch (status_message.type) {
    case Network::IdMemberJoin:
        message = tr("%1 has joined").arg(name);
        break;
    case Network::IdMemberLeave:
        message = tr("%1 has left").arg(name);
        break;
    case Network::IdMemberKicked:
        message = tr("%1 has been kicked").arg(name);
        break;
    case Network::IdMemberBanned:
        message = tr("%1 has been banned").arg(name);
        break;
    case Network::IdAddressUnbanned:
        message = tr("%1 has been unbanned").arg(name);
        break;
    }
    if (!message.isEmpty())
        AppendStatusMessage(message);
}

void ChatRoom::OnSendChat() {
    if (auto room_member = room_network->GetRoomMember().lock()) {
        if (!room_member->IsConnected()) {
            return;
        }
        auto message = ui->chat_message->text().toStdString();
        if (!ValidateMessage(message)) {
            return;
        }
        auto nick = room_member->GetNickname();
        auto username = room_member->GetUsername();
        Network::ChatEntry chat{nick, username, message};

        auto members = room_member->GetMemberInformation();
        auto it = std::find_if(members.begin(), members.end(),
                               [&chat](const Network::RoomMember::MemberInformation& member) {
                                   return member.nickname == chat.nickname &&
                                          member.username == chat.username;
                               });
        if (it == members.end()) {
            LOG_INFO(Network, "Cannot find self in the player list when sending a message.");
        }
        auto player = std::distance(members.begin(), it);
        ChatMessage m(chat, *room_network);
        room_member->SendChatMessage(message);
        AppendChatMessage(m.GetPlayerChatMessage(player));
        ui->chat_message->clear();
    }
}

void ChatRoom::UpdateIconDisplay() {
    for (int row = 0; row < player_list->invisibleRootItem()->rowCount(); ++row) {
        QStandardItem* item = player_list->invisibleRootItem()->child(row);
        const std::string avatar_url =
            item->data(PlayerListItem::AvatarUrlRole).toString().toStdString();
        if (icon_cache.count(avatar_url)) {
            item->setData(icon_cache.at(avatar_url), Qt::DecorationRole);
        } else {
            item->setData(QIcon::fromTheme(QStringLiteral("no_avatar")).pixmap(48),
                          Qt::DecorationRole);
        }
    }
}

void ChatRoom::SetPlayerList(const Network::RoomMember::MemberList& member_list) {
    // TODO(B3N30): Remember which row is selected
    player_list->removeRows(0, player_list->rowCount());
    for (const auto& member : member_list) {
        if (member.nickname.empty())
            continue;
        QStandardItem* name_item = new PlayerListItem(member.nickname, member.username,
                                                      member.avatar_url, member.game_info);

#ifdef ENABLE_WEB_SERVICE
        if (!icon_cache.count(member.avatar_url) && !member.avatar_url.empty()) {
            // Start a request to get the member's avatar
            const QUrl url(QString::fromStdString(member.avatar_url));
            QFuture<std::string> future = QtConcurrent::run([url] {
                WebService::Client client(
                    QStringLiteral("%1://%2").arg(url.scheme(), url.host()).toStdString(), "", "");
                auto result = client.GetImage(url.path().toStdString(), true);
                if (result.returned_data.empty()) {
                    LOG_ERROR(WebService, "Failed to get avatar");
                }
                return result.returned_data;
            });
            auto* future_watcher = new QFutureWatcher<std::string>(this);
            connect(future_watcher, &QFutureWatcher<std::string>::finished, this,
                    [this, future_watcher, avatar_url = member.avatar_url] {
                        const std::string result = future_watcher->result();
                        if (result.empty())
                            return;
                        QPixmap pixmap;
                        if (!pixmap.loadFromData(reinterpret_cast<const u8*>(result.data()),
                                                 static_cast<uint>(result.size())))
                            return;
                        icon_cache[avatar_url] =
                            pixmap.scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                        // Update all the displayed icons with the new icon_cache
                        UpdateIconDisplay();
                    });
            future_watcher->setFuture(future);
        }
#endif

        player_list->invisibleRootItem()->appendRow(name_item);
    }
    UpdateIconDisplay();
    // TODO(B3N30): Restore row selection
}

void ChatRoom::OnChatTextChanged() {
    if (ui->chat_message->text().length() > static_cast<int>(Network::MaxMessageSize))
        ui->chat_message->setText(
            ui->chat_message->text().left(static_cast<int>(Network::MaxMessageSize)));
}

void ChatRoom::PopupContextMenu(const QPoint& menu_location) {
    QModelIndex item = ui->player_view->indexAt(menu_location);
    if (!item.isValid())
        return;

    std::string nickname =
        player_list->item(item.row())->data(PlayerListItem::NicknameRole).toString().toStdString();

    QMenu context_menu;

    QString username = player_list->item(item.row())->data(PlayerListItem::UsernameRole).toString();
    if (!username.isEmpty()) {
        QAction* view_profile_action = context_menu.addAction(tr("View Profile"));
        connect(view_profile_action, &QAction::triggered, [username] {
            QDesktopServices::openUrl(
                QUrl(QStringLiteral("https://community.citra-emu.org/u/%1").arg(username)));
        });
    }

    std::string cur_nickname;
    if (auto room = room_network->GetRoomMember().lock()) {
        cur_nickname = room->GetNickname();
    }

    if (nickname != cur_nickname) { // You can't block yourself
        QAction* block_action = context_menu.addAction(tr("Block Player"));

        block_action->setCheckable(true);
        block_action->setChecked(block_list.count(nickname) > 0);

        connect(block_action, &QAction::triggered, [this, nickname] {
            if (block_list.count(nickname)) {
                block_list.erase(nickname);
            } else {
                QMessageBox::StandardButton result = QMessageBox::question(
                    this, tr("Block Player"),
                    tr("When you block a player, you will no longer receive chat messages from "
                       "them.

Are you sure you would like to block %1?")
                        .arg(QString::fromStdString(nickname)),
                    QMessageBox::Yes | QMessageBox::No);
                if (result == QMessageBox::Yes)
                    block_list.emplace(nickname);
            }
        });
    }

    if (has_mod_perms && nickname != cur_nickname) { // You can't kick or ban yourself
        context_menu.addSeparator();

        QAction* kick_action = context_menu.addAction(tr("Kick"));
        QAction* ban_action = context_menu.addAction(tr("Ban"));

        connect(kick_action, &QAction::triggered, [this, nickname] {
            QMessageBox::StandardButton result =
                QMessageBox::question(this, tr("Kick Player"),
                                      tr("Are you sure you would like to kick %1?")
                                          .arg(QString::fromStdString(nickname)),
                                      QMessageBox::Yes | QMessageBox::No);
            if (result == QMessageBox::Yes)
                SendModerationRequest(Network::IdModKick, nickname);
        });
        connect(ban_action, &QAction::triggered, [this, nickname] {
            QMessageBox::StandardButton result = QMessageBox::question(
                this, tr("Ban Player"),
                tr("Are you sure you would like to kick and ban %1?\n\nThis would "
                   "ban both their forum username and their IP address.")
                    .arg(QString::fromStdString(nickname)),
                QMessageBox::Yes | QMessageBox::No);
            if (result == QMessageBox::Yes)
                SendModerationRequest(Network::IdModBan, nickname);
        });
    }

    context_menu.exec(ui->player_view->viewport()->mapToGlobal(menu_location));
}


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

#pragma once

#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <QDialog>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
#include <QVariant>
#include "network/network.h"

namespace Ui {
class ChatRoom;
}

namespace Core {
class AnnounceMultiplayerSession;
}

class ConnectionError;
class ComboBoxProxyModel;

class ChatMessage;

class ChatRoom : public QWidget {
    Q_OBJECT

public:
    explicit ChatRoom(QWidget* parent);
    void Initialize(Network::RoomNetwork* room_network);
    void RetranslateUi();
    void SetPlayerList(const Network::RoomMember::MemberList& member_list);
    void Clear();
    void AppendStatusMessage(const QString& msg);
    ~ChatRoom();

    void SetModPerms(bool is_mod);
    void UpdateIconDisplay();

public slots:
    void OnRoomUpdate(const Network::RoomInformation& info);
    void OnChatReceive(const Network::ChatEntry&);
    void OnStatusMessageReceive(const Network::StatusMessageEntry&);
    void OnSendChat();
    void OnChatTextChanged();
    void PopupContextMenu(const QPoint& menu_location);
    void Disable();
    void Enable();

signals:
    void ChatReceived(const Network::ChatEntry&);
    void StatusMessageReceived(const Network::StatusMessageEntry&);
    void UserPinged();

private:
    static constexpr u32 max_chat_lines = 1000;
    void AppendChatMessage(const QString&);
    bool ValidateMessage(const std::string&);
    void SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname);

    bool has_mod_perms = false;
    QStandardItemModel* player_list;
    std::unique_ptr<Ui::ChatRoom> ui;
    std::unordered_set<std::string> block_list;
    std::unordered_map<std::string, QPixmap> icon_cache;
    Network::RoomNetwork* room_network;
};

Q_DECLARE_METATYPE(Network::ChatEntry);
Q_DECLARE_METATYPE(Network::StatusMessageEntry);
Q_DECLARE_METATYPE(Network::RoomInformation);
Q_DECLARE_METATYPE(Network::RoomMember::State);
Q_DECLARE_METATYPE(Network::RoomMember::Error);


code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>ChatRoom</class>
 <widget class="QWidget" name="ChatRoom">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>807</width>
    <height>432</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Room Window</string>
  </property>
  <layout class="QHBoxLayout" name="horizontalLayout">
   <item>
    <widget class="QTreeView" name="player_view"/>
   </item>
   <item>
    <layout class="QVBoxLayout" name="verticalLayout_4">
     <item>
      <widget class="QTextEdit" name="chat_history">
       <property name="undoRedoEnabled">
        <bool>false</bool>
       </property>
       <property name="readOnly">
        <bool>true</bool>
       </property>
       <property name="textInteractionFlags">
        <set>Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
       </property>
      </widget>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout_3">
       <item>
        <widget class="QLineEdit" name="chat_message">
         <property name="placeholderText">
          <string>Send Chat Message</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="send_message">
         <property name="text">
          <string>Send Message</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>


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

#include <future>
#include <QColor>
#include <QImage>
#include <QList>
#include <QLocale>
#include <QMetaType>
#include <QTime>
#include <QtConcurrent/QtConcurrentRun>
#include "common/logging/log.h"
#include "network/announce_multiplayer_session.h"
#include "ui_client_room.h"
#include "yuzu/game_list_p.h"
#include "yuzu/multiplayer/client_room.h"
#include "yuzu/multiplayer/message.h"
#include "yuzu/multiplayer/moderation_dialog.h"
#include "yuzu/multiplayer/state.h"

ClientRoomWindow::ClientRoomWindow(QWidget* parent, Network::RoomNetwork& room_network_)
    : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint),
      ui(std::make_unique<Ui::ClientRoom>()), room_network{room_network_} {
    ui->setupUi(this);
    ui->chat->Initialize(&room_network);

    // setup the callbacks for network updates
    if (auto member = room_network.GetRoomMember().lock()) {
        member->BindOnRoomInformationChanged(
            [this](const Network::RoomInformation& info) { emit RoomInformationChanged(info); });
        member->BindOnStateChanged(
            [this](const Network::RoomMember::State& state) { emit StateChanged(state); });

        connect(this, &ClientRoomWindow::RoomInformationChanged, this,
                &ClientRoomWindow::OnRoomUpdate);
        connect(this, &ClientRoomWindow::StateChanged, this, &::ClientRoomWindow::OnStateChange);
        // Update the state
        OnStateChange(member->GetState());
    } else {
        // TODO (jroweboy) network was not initialized?
    }

    connect(ui->disconnect, &QPushButton::clicked, this, &ClientRoomWindow::Disconnect);
    ui->disconnect->setDefault(false);
    ui->disconnect->setAutoDefault(false);
    connect(ui->moderation, &QPushButton::clicked, [this] {
        ModerationDialog dialog(room_network, this);
        dialog.exec();
    });
    ui->moderation->setDefault(false);
    ui->moderation->setAutoDefault(false);
    connect(ui->chat, &ChatRoom::UserPinged, this, &ClientRoomWindow::ShowNotification);
    UpdateView();
}

ClientRoomWindow::~ClientRoomWindow() = default;

void ClientRoomWindow::SetModPerms(bool is_mod) {
    ui->chat->SetModPerms(is_mod);
    ui->moderation->setVisible(is_mod);
    ui->moderation->setDefault(false);
    ui->moderation->setAutoDefault(false);
}

void ClientRoomWindow::RetranslateUi() {
    ui->retranslateUi(this);
    ui->chat->RetranslateUi();
}

void ClientRoomWindow::OnRoomUpdate(const Network::RoomInformation& info) {
    UpdateView();
}

void ClientRoomWindow::OnStateChange(const Network::RoomMember::State& state) {
    if (state == Network::RoomMember::State::Joined ||
        state == Network::RoomMember::State::Moderator) {
        ui->chat->Clear();
        ui->chat->AppendStatusMessage(tr("Connected"));
        SetModPerms(state == Network::RoomMember::State::Moderator);
    }
    UpdateView();
}

void ClientRoomWindow::Disconnect() {
    auto parent = static_cast<MultiplayerState*>(parentWidget());
    if (parent->OnCloseRoom()) {
        ui->chat->AppendStatusMessage(tr("Disconnected"));
        close();
    }
}

void ClientRoomWindow::UpdateView() {
    if (auto member = room_network.GetRoomMember().lock()) {
        if (member->IsConnected()) {
            ui->chat->Enable();
            ui->disconnect->setEnabled(true);
            auto memberlist = member->GetMemberInformation();
            ui->chat->SetPlayerList(memberlist);
            const auto information = member->GetRoomInformation();
            setWindowTitle(QString(tr("%1 - %2 (%3/%4 members) - connected"))
                               .arg(QString::fromStdString(information.name))
                               .arg(QString::fromStdString(information.preferred_game.name))
                               .arg(memberlist.size())
                               .arg(information.member_slots));
            ui->description->setText(QString::fromStdString(information.description));
            return;
        }
    }
    // TODO(B3N30): can't get RoomMember*, show error and close window
    close();
}

void ClientRoomWindow::UpdateIconDisplay() {
    ui->chat->UpdateIconDisplay();
}


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

#pragma once

#include "yuzu/multiplayer/chat_room.h"

namespace Ui {
class ClientRoom;
}

class ClientRoomWindow : public QDialog {
    Q_OBJECT

public:
    explicit ClientRoomWindow(QWidget* parent, Network::RoomNetwork& room_network_);
    ~ClientRoomWindow();

    void RetranslateUi();
    void UpdateIconDisplay();

public slots:
    void OnRoomUpdate(const Network::RoomInformation&);
    void OnStateChange(const Network::RoomMember::State&);

signals:
    void RoomInformationChanged(const Network::RoomInformation&);
    void StateChanged(const Network::RoomMember::State&);
    void ShowNotification();

private:
    void Disconnect();
    void UpdateView();
    void SetModPerms(bool is_mod);

    QStandardItemModel* player_list;
    std::unique_ptr<Ui::ClientRoom> ui;
    Network::RoomNetwork& room_network;
};


code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>ClientRoom</class>
 <widget class="QWidget" name="ClientRoom">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>807</width>
    <height>432</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Room Window</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QVBoxLayout" name="verticalLayout_3">
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <property name="rightMargin">
        <number>0</number>
       </property>
       <item>
        <widget class="QLabel" name="description">
         <property name="text">
          <string>Room Description</string>
         </property>
        </widget>
       </item>
       <item>
        <spacer name="horizontalSpacer">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="moderation">
         <property name="text">
          <string>Moderation...</string>
         </property>
         <property name="visible">
          <bool>false</bool>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="disconnect">
         <property name="text">
          <string>Leave Room</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
     <item>
      <widget class="ChatRoom" name="chat" native="true"/>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <customwidgets>
  <customwidget>
   <class>ChatRoom</class>
   <extends>QWidget</extends>
   <header>multiplayer/chat_room.h</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>


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

#include <QComboBox>
#include <QFuture>
#include <QIntValidator>
#include <QRegularExpressionValidator>
#include <QString>
#include <QtConcurrent/QtConcurrentRun>
#include "common/settings.h"
#include "core/core.h"
#include "core/internal_network/network_interface.h"
#include "network/network.h"
#include "ui_direct_connect.h"
#include "yuzu/main.h"
#include "yuzu/multiplayer/client_room.h"
#include "yuzu/multiplayer/direct_connect.h"
#include "yuzu/multiplayer/message.h"
#include "yuzu/multiplayer/state.h"
#include "yuzu/multiplayer/validation.h"
#include "yuzu/uisettings.h"

enum class ConnectionType : u8 { TraversalServer, IP };

DirectConnectWindow::DirectConnectWindow(Core::System& system_, QWidget* parent)
    : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint),
      ui(std::make_unique<Ui::DirectConnect>()), system{system_}, room_network{
                                                                      system.GetRoomNetwork()} {

    ui->setupUi(this);

    // setup the watcher for background connections
    watcher = new QFutureWatcher<void>;
    connect(watcher, &QFutureWatcher<void>::finished, this, &DirectConnectWindow::OnConnection);

    ui->nickname->setValidator(validation.GetNickname());
    ui->nickname->setText(
        QString::fromStdString(UISettings::values.multiplayer_nickname.GetValue()));
    if (ui->nickname->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) {
        // Use yuzu Web Service user name as nickname by default
        ui->nickname->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue()));
    }
    ui->ip->setValidator(validation.GetIP());
    ui->ip->setText(QString::fromStdString(UISettings::values.multiplayer_ip.GetValue()));
    ui->port->setValidator(validation.GetPort());
    ui->port->setText(QString::number(UISettings::values.multiplayer_port.GetValue()));

    // TODO(jroweboy): Show or hide the connection options based on the current value of the combo
    // box. Add this back in when the traversal server support is added.
    connect(ui->connect, &QPushButton::clicked, this, &DirectConnectWindow::Connect);
}

DirectConnectWindow::~DirectConnectWindow() = default;

void DirectConnectWindow::RetranslateUi() {
    ui->retranslateUi(this);
}

void DirectConnectWindow::Connect() {
    if (!Network::GetSelectedNetworkInterface()) {
        NetworkMessage::ErrorManager::ShowError(
            NetworkMessage::ErrorManager::NO_INTERFACE_SELECTED);
        return;
    }
    if (!ui->nickname->hasAcceptableInput()) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID);
        return;
    }
    if (system.IsPoweredOn()) {
        if (!NetworkMessage::WarnGameRunning()) {
            return;
        }
    }
    if (const auto member = room_network.GetRoomMember().lock()) {
        // Prevent the user from trying to join a room while they are already joining.
        if (member->GetState() == Network::RoomMember::State::Joining) {
            return;
        } else if (member->IsConnected()) {
            // And ask if they want to leave the room if they are already in one.
            if (!NetworkMessage::WarnDisconnect()) {
                return;
            }
        }
    }
    if (!ui->ip->hasAcceptableInput()) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::IP_ADDRESS_NOT_VALID);
        return;
    }
    if (!ui->port->hasAcceptableInput()) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PORT_NOT_VALID);
        return;
    }

    // Store settings
    UISettings::values.multiplayer_nickname = ui->nickname->text().toStdString();
    UISettings::values.multiplayer_ip = ui->ip->text().toStdString();
    if (!ui->port->text().isEmpty()) {
        UISettings::values.multiplayer_port = ui->port->text().toInt();
    } else {
        UISettings::values.multiplayer_port = UISettings::values.multiplayer_port.GetDefault();
    }

    emit SaveConfig();

    // attempt to connect in a different thread
    QFuture<void> f = QtConcurrent::run([&] {
        if (auto room_member = room_network.GetRoomMember().lock()) {
            auto port = UISettings::values.multiplayer_port.GetValue();
            room_member->Join(ui->nickname->text().toStdString(),
                              ui->ip->text().toStdString().c_str(), port, 0, Network::NoPreferredIP,
                              ui->password->text().toStdString().c_str());
        }
    });
    watcher->setFuture(f);
    // and disable widgets and display a connecting while we wait
    BeginConnecting();
}

void DirectConnectWindow::BeginConnecting() {
    ui->connect->setEnabled(false);
    ui->connect->setText(tr("Connecting"));
}

void DirectConnectWindow::EndConnecting() {
    ui->connect->setEnabled(true);
    ui->connect->setText(tr("Connect"));
}

void DirectConnectWindow::OnConnection() {
    EndConnecting();

    if (auto room_member = room_network.GetRoomMember().lock()) {
        if (room_member->IsConnected()) {
            close();
        }
    }
}


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

#pragma once

#include <memory>
#include <QDialog>
#include <QFutureWatcher>
#include "yuzu/multiplayer/validation.h"

namespace Ui {
class DirectConnect;
}

namespace Core {
class System;
}

class DirectConnectWindow : public QDialog {
    Q_OBJECT

public:
    explicit DirectConnectWindow(Core::System& system_, QWidget* parent = nullptr);
    ~DirectConnectWindow();

    void RetranslateUi();

signals:
    /**
     * Signalled by this widget when it is closing itself and destroying any state such as
     * connections that it might have.
     */
    void Closed();
    void SaveConfig();

private slots:
    void OnConnection();

private:
    void Connect();
    void BeginConnecting();
    void EndConnecting();

    QFutureWatcher<void>* watcher;
    std::unique_ptr<Ui::DirectConnect> ui;
    Validation validation;
    Core::System& system;
    Network::RoomNetwork& room_network;
};


code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>DirectConnect</class>
 <widget class="QWidget" name="DirectConnect">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>455</width>
    <height>161</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Direct Connect</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QVBoxLayout" name="verticalLayout_3">
     <item>
      <layout class="QVBoxLayout" name="verticalLayout_2">
       <item>
        <layout class="QHBoxLayout" name="horizontalLayout">
         <property name="spacing">
          <number>0</number>
         </property>
         <property name="leftMargin">
          <number>0</number>
         </property>
         <item>
          <widget class="QWidget" name="ip_container" native="true">
           <layout class="QHBoxLayout" name="ip_layout">
            <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_2">
              <property name="text">
               <string>Server Address</string>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QLineEdit" name="ip">
              <property name="toolTip">
               <string>
Server address of the host
</string>
              </property>
              <property name="maxLength">
               <number>253</number>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QLabel" name="label_3">
              <property name="text">
               <string>Port</string>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QLineEdit" name="port">
              <property name="toolTip">
               <string>
Port number the host is listening on
</string>
              </property>
              <property name="maxLength">
               <number>5</number>
              </property>
              <property name="placeholderText">
               <string notr="true" extracomment="placeholder string that tells user default port">24872</string>
              </property>
              <property name="maximumSize">
               <size>
                <width>65</width>
                <height>50</height>
               </size>
              </property>
             </widget>
            </item>
           </layout>
          </widget>
         </item>
        </layout>
       </item>
       <item>
        <layout class="QHBoxLayout" name="horizontalLayout_2">
         <item>
          <widget class="QLabel" name="label_5">
           <property name="text">
            <string>Nickname</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QLineEdit" name="nickname">
           <property name="maxLength">
            <number>20</number>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QLabel" name="label">
           <property name="text">
            <string>Password</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QLineEdit" name="password"/>
         </item>
        </layout>
       </item>
      </layout>
     </item>
     <item>
      <spacer name="verticalSpacer">
       <property name="orientation">
        <enum>Qt::Vertical</enum>
       </property>
       <property name="sizeHint" stdset="0">
        <size>
         <width>20</width>
         <height>20</height>
        </size>
       </property>
      </spacer>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout_3">
       <item>
        <spacer name="horizontalSpacer">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="connect">
         <property name="text">
          <string>Connect</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>


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

#include <future>
#include <QColor>
#include <QImage>
#include <QList>
#include <QLocale>
#include <QMessageBox>
#include <QMetaType>
#include <QTime>
#include <QtConcurrent/QtConcurrentRun>
#include "common/logging/log.h"
#include "common/settings.h"
#include "core/core.h"
#include "core/internal_network/network_interface.h"
#include "network/announce_multiplayer_session.h"
#include "ui_host_room.h"
#include "yuzu/game_list_p.h"
#include "yuzu/main.h"
#include "yuzu/multiplayer/host_room.h"
#include "yuzu/multiplayer/message.h"
#include "yuzu/multiplayer/state.h"
#include "yuzu/multiplayer/validation.h"
#include "yuzu/uisettings.h"
#ifdef ENABLE_WEB_SERVICE
#include "web_service/verify_user_jwt.h"
#endif

HostRoomWindow::HostRoomWindow(QWidget* parent, QStandardItemModel* list,
                               std::shared_ptr<Core::AnnounceMultiplayerSession> session,
                               Core::System& system_)
    : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint),
      ui(std::make_unique<Ui::HostRoom>()),
      announce_multiplayer_session(session), system{system_}, room_network{
                                                                  system.GetRoomNetwork()} {
    ui->setupUi(this);

    // set up validation for all of the fields
    ui->room_name->setValidator(validation.GetRoomName());
    ui->username->setValidator(validation.GetNickname());
    ui->port->setValidator(validation.GetPort());
    ui->port->setPlaceholderText(QString::number(Network::DefaultRoomPort));

    // Create a proxy to the game list to display the list of preferred games
    game_list = new QStandardItemModel;
    UpdateGameList(list);

    proxy = new ComboBoxProxyModel;
    proxy->setSourceModel(game_list);
    proxy->sort(0, Qt::AscendingOrder);
    ui->game_list->setModel(proxy);

    // Connect all the widgets to the appropriate events
    connect(ui->host, &QPushButton::clicked, this, &HostRoomWindow::Host);

    // Restore the settings:
    ui->username->setText(
        QString::fromStdString(UISettings::values.multiplayer_room_nickname.GetValue()));
    if (ui->username->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) {
        // Use yuzu Web Service user name as nickname by default
        ui->username->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue()));
    }
    ui->room_name->setText(
        QString::fromStdString(UISettings::values.multiplayer_room_name.GetValue()));
    ui->port->setText(QString::number(UISettings::values.multiplayer_room_port.GetValue()));
    ui->max_player->setValue(UISettings::values.multiplayer_max_player.GetValue());
    int index = UISettings::values.multiplayer_host_type.GetValue();
    if (index < ui->host_type->count()) {
        ui->host_type->setCurrentIndex(index);
    }
    index = ui->game_list->findData(UISettings::values.multiplayer_game_id.GetValue(),
                                    GameListItemPath::ProgramIdRole);
    if (index != -1) {
        ui->game_list->setCurrentIndex(index);
    }
    ui->room_description->setText(
        QString::fromStdString(UISettings::values.multiplayer_room_description.GetValue()));
}

HostRoomWindow::~HostRoomWindow() = default;

void HostRoomWindow::UpdateGameList(QStandardItemModel* list) {
    game_list->clear();
    for (int i = 0; i < list->rowCount(); i++) {
        auto parent = list->item(i, 0);
        for (int j = 0; j < parent->rowCount(); j++) {
            game_list->appendRow(parent->child(j)->clone());
        }
    }
}

void HostRoomWindow::RetranslateUi() {
    ui->retranslateUi(this);
}

std::unique_ptr<Network::VerifyUser::Backend> HostRoomWindow::CreateVerifyBackend(
    bool use_validation) const {
    std::unique_ptr<Network::VerifyUser::Backend> verify_backend;
    if (use_validation) {
#ifdef ENABLE_WEB_SERVICE
        verify_backend =
            std::make_unique<WebService::VerifyUserJWT>(Settings::values.web_api_url.GetValue());
#else
        verify_backend = std::make_unique<Network::VerifyUser::NullBackend>();
#endif
    } else {
        verify_backend = std::make_unique<Network::VerifyUser::NullBackend>();
    }
    return verify_backend;
}

void HostRoomWindow::Host() {
    if (!Network::GetSelectedNetworkInterface()) {
        NetworkMessage::ErrorManager::ShowError(
            NetworkMessage::ErrorManager::NO_INTERFACE_SELECTED);
        return;
    }
    if (!ui->username->hasAcceptableInput()) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID);
        return;
    }
    if (!ui->room_name->hasAcceptableInput()) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::ROOMNAME_NOT_VALID);
        return;
    }
    if (!ui->port->hasAcceptableInput()) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PORT_NOT_VALID);
        return;
    }
    if (ui->game_list->currentIndex() == -1) {
        NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::GAME_NOT_SELECTED);
        return;
    }
    if (system.IsPoweredOn()) {
        if (!NetworkMessage::WarnGameRunning()) {
            return;
        }
    }
    if (auto member = room_network.GetRoomMember().lock()) {
        if (member->GetState() == Network::RoomMember::State::Joining) {
            return;
        } else if (member->IsConnected()) {
            auto parent = static_cast<MultiplayerState*>(parentWidget());
            if (!parent->OnCloseRoom()) {
                close();
                return;
            }
        }
        ui->host->setDisabled(true);

        const AnnounceMultiplayerRoom::GameInfo game{
            .name = ui->game_list->currentData(Qt::DisplayRole).toString().toStdString(),
            .id = ui->game_list->currentData(GameListItemPath::ProgramIdRole).toULongLong(),
        };
        const auto port =
            ui->port->isModified() ? ui->port->text().toInt() : Network::DefaultRoomPort;
        const auto password = ui->password->text().toStdString();
        const bool is_public = ui->host_type->currentIndex() == 0;
        Network::Room::BanList ban_list{};
        if (ui->load_ban_list->isChecked()) {
            ban_list = UISettings::values.multiplayer_ban_list;
        }
        if (auto room = room_network.GetRoom().lock()) {
            const bool created =
                room->Create(ui->room_name->text().toStdString(),
                             ui->room_description->toPlainText().toStdString(), "", port, password,
                             ui->max_player->value(), Settings::values.yuzu_username.GetValue(),
                             game, CreateVerifyBackend(is_public), ban_list);
            if (!created) {
                NetworkMessage::ErrorManager::ShowError(
                    NetworkMessage::ErrorManager::COULD_NOT_CREATE_ROOM);
                LOG_ERROR(Network, "Could not create room!");
                ui->host->setEnabled(true);
                return;
            }
        }
        // Start the announce session if they chose Public
        if (is_public) {
            if (auto session = announce_multiplayer_session.lock()) {
                // Register the room first to ensure verify_uid is present when we connect
                WebService::WebResult result = session->Register();
                if (result.result_code != WebService::WebResult::Code::Success) {
                    QMessageBox::warning(
                        this, tr("Error"),
                        tr("Failed to announce the room to the public lobby. In order to host a "
                           "room publicly, you must have a valid yuzu account configured in "
                           "Emulation -> Configure -> Web. If you do not want to publish a room in "
                           "the public lobby, then select Unlisted instead.\nDebug Message: ") +
                            QString::fromStdString(result.result_string),
                        QMessageBox::Ok);
                    ui->host->setEnabled(true);
                    if (auto room = room_network.GetRoom().lock()) {
                        room->Destroy();
                    }
                    return;
                }
                session->Start();
            } else {
                LOG_ERROR(Network, "Starting announce session failed");
            }
        }
        std::string token;
#ifdef ENABLE_WEB_SERVICE
        if (is_public) {
            WebService::Client client(Settings::values.web_api_url.GetValue(),
                                      Settings::values.yuzu_username.GetValue(),
                                      Settings::values.yuzu_token.GetValue());
            if (auto room = room_network.GetRoom().lock()) {
                token = client.GetExternalJWT(room->GetVerifyUID()).returned_data;
            }
            if (token.empty()) {
                LOG_ERROR(WebService, "Could not get external JWT, verification may fail");
            } else {
                LOG_INFO(WebService, "Successfully requested external JWT: size={}", token.size());
            }
        }
#endif
        // TODO: Check what to do with this
        member->Join(ui->username->text().toStdString(), "127.0.0.1", port, 0,
                     Network::NoPreferredIP, password, token);

        // Store settings
        UISettings::values.multiplayer_room_nickname = ui->username->text().toStdString();
        UISettings::values.multiplayer_room_name = ui->room_name->text().toStdString();
        UISettings::values.multiplayer_game_id =
            ui->game_list->currentData(GameListItemPath::ProgramIdRole).toLongLong();
        UISettings::values.multiplayer_max_player = ui->max_player->value();

        UISettings::values.multiplayer_host_type = ui->host_type->currentIndex();
        if (ui->port->isModified() && !ui->port->text().isEmpty()) {
            UISettings::values.multiplayer_room_port = ui->port->text().toInt();
        } else {
            UISettings::values.multiplayer_room_port = Network::DefaultRoomPort;
        }
        UISettings::values.multiplayer_room_description =
            ui->room_description->toPlainText().toStdString();
        ui->host->setEnabled(true);
        emit SaveConfig();
        close();
    }
}

QVariant ComboBoxProxyModel::data(const QModelIndex& idx, int role) const {
    if (role != Qt::DisplayRole) {
        auto val = QSortFilterProxyModel::data(idx, role);
        // If its the icon, shrink it to 16x16
        if (role == Qt::DecorationRole)
            val = val.value<QImage>().scaled(16, 16, Qt::KeepAspectRatio);
        return val;
    }
    std::string filename;
    Common::SplitPath(
        QSortFilterProxyModel::data(idx, GameListItemPath::FullPathRole).toString().toStdString(),
        nullptr, &filename, nullptr);
    QString title = QSortFilterProxyModel::data(idx, GameListItemPath::TitleRole).toString();
    return title.isEmpty() ? QString::fromStdString(filename) : title;
}

bool ComboBoxProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const {
    auto leftData = left.data(GameListItemPath::TitleRole).toString();
    auto rightData = right.data(GameListItemPath::TitleRole).toString();
    return leftData.compare(rightData) < 0;
}


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

#pragma once

#include <memory>
#include <QDialog>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
#include <QVariant>
#include "network/network.h"
#include "yuzu/multiplayer/chat_room.h"
#include "yuzu/multiplayer/validation.h"

namespace Ui {
class HostRoom;
}

namespace Core {
class System;
class AnnounceMultiplayerSession;
} // namespace Core

class ConnectionError;
class ComboBoxProxyModel;

class ChatMessage;

namespace Network::VerifyUser {
class Backend;
};

class HostRoomWindow : public QDialog {
    Q_OBJECT

public:
    explicit HostRoomWindow(QWidget* parent, QStandardItemModel* list,
                            std::shared_ptr<Core::AnnounceMultiplayerSession> session,
                            Core::System& system_);
    ~HostRoomWindow();

    /**
     * Updates the dialog with a new game list model.
     * This model should be the original model of the game list.
     */
    void UpdateGameList(QStandardItemModel* list);
    void RetranslateUi();

signals:
    void SaveConfig();

private:
    void Host();
    std::unique_ptr<Network::VerifyUser::Backend> CreateVerifyBackend(bool use_validation) const;

    std::unique_ptr<Ui::HostRoom> ui;
    std::weak_ptr<Core::AnnounceMultiplayerSession> announce_multiplayer_session;
    QStandardItemModel* game_list;
    ComboBoxProxyModel* proxy;
    Validation validation;
    Core::System& system;
    Network::RoomNetwork& room_network;
};

/**
 * Proxy Model for the game list combo box so we can reuse the game list model while still
 * displaying the fields slightly differently
 */
class ComboBoxProxyModel : public QSortFilterProxyModel {
    Q_OBJECT

public:
    int columnCount(const QModelIndex& idx) const override {
        return 1;
    }

    QVariant data(const QModelIndex& idx, int role) const override;

    bool lessThan(const QModelIndex& left, const QModelIndex& right) const override;
};


code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>HostRoom</class>
 <widget class="QWidget" name="HostRoom">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>607</width>
    <height>211</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Create Room</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout_3">
   <item>
    <widget class="QWidget" name="settings" native="true">
     <layout class="QHBoxLayout">
      <property name="leftMargin">
       <number>0</number>
      </property>
      <property name="topMargin">
       <number>0</number>
      </property>
      <property name="rightMargin">
       <number>0</number>
      </property>
      <item>
       <layout class="QFormLayout" name="formLayout_2">
        <property name="labelAlignment">
         <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
        </property>
        <item row="0" column="0">
         <widget class="QLabel" name="label">
          <property name="text">
           <string>Room Name</string>
          </property>
         </widget>
        </item>
        <item row="0" column="1">
         <widget class="QLineEdit" name="room_name">
          <property name="maxLength">
           <number>50</number>
          </property>
         </widget>
        </item>
        <item row="1" column="0">
         <widget class="QLabel" name="label_3">
          <property name="text">
           <string>Preferred Game</string>
          </property>
         </widget>
        </item>
        <item row="1" column="1">
         <widget class="QComboBox" name="game_list"/>
        </item>
        <item row="2" column="0">
         <widget class="QLabel" name="label_2">
          <property name="text">
           <string>Max Players</string>
          </property>
         </widget>
        </item>
        <item row="2" column="1">
         <widget class="QSpinBox" name="max_player">
          <property name="minimum">
           <number>2</number>
          </property>
          <property name="maximum">
           <number>16</number>
          </property>
          <property name="value">
           <number>8</number>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QFormLayout" name="formLayout">
        <property name="labelAlignment">
         <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
        </property>
        <item row="0" column="1">
         <widget class="QLineEdit" name="username"/>
        </item>
        <item row="0" column="0">
         <widget class="QLabel" name="label_6">
          <property name="text">
           <string>Username</string>
          </property>
         </widget>
        </item>
        <item row="1" column="1">
         <widget class="QLineEdit" name="password">
          <property name="echoMode">
           <enum>QLineEdit::PasswordEchoOnEdit</enum>
          </property>
          <property name="placeholderText">
           <string>(Leave blank for open game)</string>
          </property>
         </widget>
        </item>
        <item row="2" column="1">
         <widget class="QLineEdit" name="port">
          <property name="inputMethodHints">
           <set>Qt::ImhDigitsOnly</set>
          </property>
          <property name="maxLength">
           <number>5</number>
          </property>
         </widget>
        </item>
        <item row="1" column="0">
         <widget class="QLabel" name="label_5">
          <property name="text">
           <string>Password</string>
          </property>
         </widget>
        </item>
        <item row="2" column="0">
         <widget class="QLabel" name="label_4">
          <property name="text">
           <string>Port</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </widget>
   </item>
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout_3">
     <item>
      <widget class="QLabel" name="label_7">
       <property name="text">
        <string>Room Description</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QTextEdit" name="room_description"/>
     </item>
    </layout>
   </item>
   <item>
    <layout class="QHBoxLayout">
     <item>
      <widget class="QCheckBox" name="load_ban_list">
       <property name="text">
        <string>Load Previous Ban List</string>
       </property>
       <property name="checked">
        <bool>true</bool>
       </property>
      </widget>
     </item>
    </layout>
   </item>
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <property name="rightMargin">
      <number>0</number>
     </property>
     <item>
      <spacer name="horizontalSpacer">
       <property name="orientation">
        <enum>Qt::Horizontal</enum>
       </property>
       <property name="sizeHint" stdset="0">
        <size>
         <width>40</width>
         <height>20</height>
        </size>
       </property>
      </spacer>
     </item>
     <item>
      <widget class="QComboBox" name="host_type">
       <item>
        <property name="text">
         <string>Public</string>
        </property>
       </item>
       <item>
        <property name="text">
         <string>Unlisted</string>
        </property>
       </item>
      </widget>
     </item>
     <item>
      <widget class="QPushButton" name="host">
       <property name="text">
        <string>Host Room</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>