From 9012afc534a4e8735fc7ea799c9442eb4addb250 Mon Sep 17 00:00:00 2001 From: Connor McLaughlin Date: Sat, 20 Aug 2022 22:08:15 +1000 Subject: [PATCH] Qt: Forward text input to ImGui --- pcsx2-qt/DisplayWidget.cpp | 11 +++++++++++ pcsx2/Frontend/ImGuiManager.cpp | 21 +++++++++++++++++++++ pcsx2/Frontend/ImGuiManager.h | 6 ++++++ 3 files changed, 38 insertions(+) diff --git a/pcsx2-qt/DisplayWidget.cpp b/pcsx2-qt/DisplayWidget.cpp index 3b2ae0739f..cfd820eaff 100644 --- a/pcsx2-qt/DisplayWidget.cpp +++ b/pcsx2-qt/DisplayWidget.cpp @@ -17,6 +17,8 @@ #include "common/Assertions.h" +#include "pcsx2/Frontend/ImGuiManager.h" + #include "DisplayWidget.h" #include "EmuThread.h" #include "MainWindow.h" @@ -224,6 +226,15 @@ bool DisplayWidget::event(QEvent* event) case QEvent::KeyRelease: { const QKeyEvent* key_event = static_cast(event); + + // Forward text input to imgui. + if (ImGuiManager::WantsTextInput() && key_event->type() == QEvent::KeyPress) + { + const QString text(key_event->text()); + if (!text.isEmpty()) + ImGuiManager::AddTextInput(text.toStdString()); + } + if (key_event->isAutoRepeat()) return true; diff --git a/pcsx2/Frontend/ImGuiManager.cpp b/pcsx2/Frontend/ImGuiManager.cpp index 1b7fe09599..d0aa12b345 100644 --- a/pcsx2/Frontend/ImGuiManager.cpp +++ b/pcsx2/Frontend/ImGuiManager.cpp @@ -778,6 +778,27 @@ ImFont* ImGuiManager::GetFixedFont() #ifdef PCSX2_CORE +bool ImGuiManager::WantsTextInput() +{ + return s_imgui_wants_keyboard.load(std::memory_order_acquire); +} + +void ImGuiManager::AddTextInput(std::string str) +{ + if (!s_imgui_wants_keyboard.load(std::memory_order_acquire)) + return; + + // Has to go through the CPU -> GS thread :( + Host::RunOnCPUThread([str = std::move(str)]() { + GetMTGS().RunOnGSThread([str = std::move(str)]() { + if (!ImGui::GetCurrentContext()) + return; + + ImGui::GetIO().AddInputCharactersUTF8(str.c_str()); + }); + }); +} + void ImGuiManager::UpdateMousePosition(float x, float y) { if (!ImGui::GetCurrentContext()) diff --git a/pcsx2/Frontend/ImGuiManager.h b/pcsx2/Frontend/ImGuiManager.h index 10d931cf8c..54473083e8 100644 --- a/pcsx2/Frontend/ImGuiManager.h +++ b/pcsx2/Frontend/ImGuiManager.h @@ -50,6 +50,12 @@ namespace ImGuiManager ImFont* GetFixedFont(); #ifdef PCSX2_CORE + /// Returns true if imgui wants to intercept text input. + bool WantsTextInput(); + + /// Called on the UI or CPU thread in response to a key press. String is UTF-8. + void AddTextInput(std::string str); + /// Called on the UI or CPU thread in response to mouse movement. void UpdateMousePosition(float x, float y);