bootmanager.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. // SPDX-FileCopyrightText: 2014 Citra Emulator Project & 2024 suyu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <string>
  8. #include <tuple>
  9. #include <type_traits>
  10. #include <glad/glad.h>
  11. #include <QtCore/qglobal.h>
  12. #include "common/settings_enums.h"
  13. #include "uisettings.h"
  14. #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUYU_USE_QT_MULTIMEDIA
  15. #include <QCamera>
  16. #include <QCameraImageCapture>
  17. #include <QCameraInfo>
  18. #endif
  19. #include <QCursor>
  20. #include <QEvent>
  21. #include <QGuiApplication>
  22. #include <QHBoxLayout>
  23. #include <QKeyEvent>
  24. #include <QLayout>
  25. #include <QList>
  26. #include <QMessageBox>
  27. #include <QScreen>
  28. #include <QSize>
  29. #include <QStringLiteral>
  30. #include <QSurfaceFormat>
  31. #include <QWindow>
  32. #include <QtCore/qobjectdefs.h>
  33. #ifdef HAS_OPENGL
  34. #include <QOffscreenSurface>
  35. #include <QOpenGLContext>
  36. #endif
  37. #include "common/microprofile.h"
  38. #include "common/polyfill_thread.h"
  39. #include "common/scm_rev.h"
  40. #include "common/settings.h"
  41. #include "common/settings_input.h"
  42. #include "common/thread.h"
  43. #include "core/core.h"
  44. #include "core/cpu_manager.h"
  45. #include "core/frontend/framebuffer_layout.h"
  46. #include "core/frontend/graphics_context.h"
  47. #include "input_common/drivers/camera.h"
  48. #include "input_common/drivers/keyboard.h"
  49. #include "input_common/drivers/mouse.h"
  50. #include "input_common/drivers/tas_input.h"
  51. #include "input_common/drivers/touch_screen.h"
  52. #include "input_common/main.h"
  53. #include "video_core/gpu.h"
  54. #include "video_core/rasterizer_interface.h"
  55. #include "video_core/renderer_base.h"
  56. #include "yuzu/bootmanager.h"
  57. #include "yuzu/main.h"
  58. #include "yuzu/qt_common.h"
  59. class QObject;
  60. class QPaintEngine;
  61. class QSurface;
  62. constexpr int default_mouse_constrain_timeout = 10;
  63. EmuThread::EmuThread(Core::System& system) : m_system{system} {}
  64. EmuThread::~EmuThread() = default;
  65. void EmuThread::run() {
  66. const char* name = "EmuControlThread";
  67. MicroProfileOnThreadCreate(name);
  68. Common::SetCurrentThreadName(name);
  69. auto& gpu = m_system.GPU();
  70. auto stop_token = m_stop_source.get_token();
  71. m_system.RegisterHostThread();
  72. // Main process has been loaded. Make the context current to this thread and begin GPU and CPU
  73. // execution.
  74. gpu.ObtainContext();
  75. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  76. if (Settings::values.use_disk_shader_cache.GetValue()) {
  77. m_system.Renderer().ReadRasterizer()->LoadDiskResources(
  78. m_system.GetApplicationProcessProgramID(), stop_token,
  79. [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  80. emit LoadProgress(stage, value, total);
  81. });
  82. }
  83. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  84. gpu.ReleaseContext();
  85. gpu.Start();
  86. m_system.GetCpuManager().OnGpuReady();
  87. if (m_system.DebuggerEnabled()) {
  88. m_system.InitializeDebugger();
  89. }
  90. while (!stop_token.stop_requested()) {
  91. std::unique_lock lk{m_should_run_mutex};
  92. if (m_should_run) {
  93. m_system.Run();
  94. m_stopped.Reset();
  95. Common::CondvarWait(m_should_run_cv, lk, stop_token, [&] { return !m_should_run; });
  96. } else {
  97. m_system.Pause();
  98. m_stopped.Set();
  99. EmulationPaused(lk);
  100. Common::CondvarWait(m_should_run_cv, lk, stop_token, [&] { return m_should_run; });
  101. EmulationResumed(lk);
  102. }
  103. }
  104. // Shutdown the main emulated process
  105. m_system.DetachDebugger();
  106. m_system.ShutdownMainProcess();
  107. #if MICROPROFILE_ENABLED
  108. MicroProfileOnThreadExit();
  109. #endif
  110. }
  111. // Unlock while emitting signals so that the main thread can
  112. // continue pumping events.
  113. void EmuThread::EmulationPaused(std::unique_lock<std::mutex>& lk) {
  114. lk.unlock();
  115. emit DebugModeEntered();
  116. lk.lock();
  117. }
  118. void EmuThread::EmulationResumed(std::unique_lock<std::mutex>& lk) {
  119. lk.unlock();
  120. emit DebugModeLeft();
  121. lk.lock();
  122. }
  123. #ifdef HAS_OPENGL
  124. class OpenGLSharedContext : public Core::Frontend::GraphicsContext {
  125. public:
  126. /// Create the original context that should be shared from
  127. explicit OpenGLSharedContext(QSurface* surface_) : surface{surface_} {
  128. QSurfaceFormat format;
  129. format.setVersion(4, 6);
  130. format.setProfile(QSurfaceFormat::CompatibilityProfile);
  131. format.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions);
  132. if (Settings::values.renderer_debug) {
  133. format.setOption(QSurfaceFormat::FormatOption::DebugContext);
  134. }
  135. // TODO: expose a setting for buffer value (ie default/single/double/triple)
  136. format.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
  137. format.setSwapInterval(0);
  138. context = std::make_unique<QOpenGLContext>();
  139. context->setFormat(format);
  140. if (!context->create()) {
  141. LOG_ERROR(Frontend, "Unable to create main openGL context");
  142. }
  143. }
  144. /// Create the shared contexts for rendering and presentation
  145. explicit OpenGLSharedContext(QOpenGLContext* share_context, QSurface* main_surface = nullptr) {
  146. // disable vsync for any shared contexts
  147. auto format = share_context->format();
  148. const int swap_interval =
  149. Settings::values.vsync_mode.GetValue() == Settings::VSyncMode::Immediate ? 0 : 1;
  150. format.setSwapInterval(main_surface ? swap_interval : 0);
  151. context = std::make_unique<QOpenGLContext>();
  152. context->setShareContext(share_context);
  153. context->setFormat(format);
  154. if (!context->create()) {
  155. LOG_ERROR(Frontend, "Unable to create shared openGL context");
  156. }
  157. if (!main_surface) {
  158. offscreen_surface = std::make_unique<QOffscreenSurface>(nullptr);
  159. offscreen_surface->setFormat(format);
  160. offscreen_surface->create();
  161. surface = offscreen_surface.get();
  162. } else {
  163. surface = main_surface;
  164. }
  165. }
  166. ~OpenGLSharedContext() {
  167. DoneCurrent();
  168. }
  169. void SwapBuffers() override {
  170. context->swapBuffers(surface);
  171. }
  172. void MakeCurrent() override {
  173. // We can't track the current state of the underlying context in this wrapper class because
  174. // Qt may make the underlying context not current for one reason or another. In particular,
  175. // the WebBrowser uses GL, so it seems to conflict if we aren't careful.
  176. // Instead of always just making the context current (which does not have any caching to
  177. // check if the underlying context is already current) we can check for the current context
  178. // in the thread local data by calling `currentContext()` and checking if its ours.
  179. if (QOpenGLContext::currentContext() != context.get()) {
  180. context->makeCurrent(surface);
  181. }
  182. }
  183. void DoneCurrent() override {
  184. context->doneCurrent();
  185. }
  186. QOpenGLContext* GetShareContext() {
  187. return context.get();
  188. }
  189. const QOpenGLContext* GetShareContext() const {
  190. return context.get();
  191. }
  192. private:
  193. // Avoid using Qt parent system here since we might move the QObjects to new threads
  194. // As a note, this means we should avoid using slots/signals with the objects too
  195. std::unique_ptr<QOpenGLContext> context;
  196. std::unique_ptr<QOffscreenSurface> offscreen_surface{};
  197. QSurface* surface;
  198. };
  199. #endif
  200. class DummyContext : public Core::Frontend::GraphicsContext {};
  201. class RenderWidget : public QWidget {
  202. public:
  203. explicit RenderWidget(GRenderWindow* parent) : QWidget(parent), render_window(parent) {
  204. setAttribute(Qt::WA_NativeWindow);
  205. setAttribute(Qt::WA_PaintOnScreen);
  206. if (QtCommon::GetWindowSystemType() == Core::Frontend::WindowSystemType::Wayland) {
  207. setAttribute(Qt::WA_DontCreateNativeAncestors);
  208. }
  209. }
  210. virtual ~RenderWidget() = default;
  211. QPaintEngine* paintEngine() const override {
  212. return nullptr;
  213. }
  214. private:
  215. GRenderWindow* render_window;
  216. };
  217. struct OpenGLRenderWidget : public RenderWidget {
  218. explicit OpenGLRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
  219. windowHandle()->setSurfaceType(QWindow::OpenGLSurface);
  220. }
  221. void SetContext(std::unique_ptr<Core::Frontend::GraphicsContext>&& context_) {
  222. context = std::move(context_);
  223. }
  224. private:
  225. std::unique_ptr<Core::Frontend::GraphicsContext> context;
  226. };
  227. struct VulkanRenderWidget : public RenderWidget {
  228. explicit VulkanRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
  229. windowHandle()->setSurfaceType(QWindow::VulkanSurface);
  230. }
  231. };
  232. struct NullRenderWidget : public RenderWidget {
  233. explicit NullRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {}
  234. };
  235. GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_,
  236. std::shared_ptr<InputCommon::InputSubsystem> input_subsystem_,
  237. Core::System& system_)
  238. : QWidget(parent),
  239. emu_thread(emu_thread_), input_subsystem{std::move(input_subsystem_)}, system{system_} {
  240. setWindowTitle(QStringLiteral("suyu %1 | %2-%3")
  241. .arg(QString::fromUtf8(Common::g_build_name),
  242. QString::fromUtf8(Common::g_scm_branch),
  243. QString::fromUtf8(Common::g_scm_desc)));
  244. setAttribute(Qt::WA_AcceptTouchEvents);
  245. auto* layout = new QHBoxLayout(this);
  246. layout->setContentsMargins(0, 0, 0, 0);
  247. setLayout(layout);
  248. input_subsystem->Initialize();
  249. this->setMouseTracking(true);
  250. strict_context_required = QGuiApplication::platformName() == QStringLiteral("wayland") ||
  251. QGuiApplication::platformName() == QStringLiteral("wayland-egl");
  252. connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete);
  253. connect(this, &GRenderWindow::ExecuteProgramSignal, parent, &GMainWindow::OnExecuteProgram,
  254. Qt::QueuedConnection);
  255. connect(this, &GRenderWindow::ExitSignal, parent, &GMainWindow::OnExit, Qt::QueuedConnection);
  256. connect(this, &GRenderWindow::TasPlaybackStateChanged, parent, &GMainWindow::OnTasStateChanged);
  257. mouse_constrain_timer.setInterval(default_mouse_constrain_timeout);
  258. connect(&mouse_constrain_timer, &QTimer::timeout, this, &GRenderWindow::ConstrainMouse);
  259. }
  260. void GRenderWindow::ExecuteProgram(std::size_t program_index) {
  261. emit ExecuteProgramSignal(program_index);
  262. }
  263. void GRenderWindow::Exit() {
  264. emit ExitSignal();
  265. }
  266. GRenderWindow::~GRenderWindow() {
  267. input_subsystem->Shutdown();
  268. }
  269. void GRenderWindow::OnFrameDisplayed() {
  270. input_subsystem->GetTas()->UpdateThread();
  271. const InputCommon::TasInput::TasState new_tas_state =
  272. std::get<0>(input_subsystem->GetTas()->GetStatus());
  273. if (!first_frame) {
  274. last_tas_state = new_tas_state;
  275. first_frame = true;
  276. emit FirstFrameDisplayed();
  277. }
  278. if (new_tas_state != last_tas_state) {
  279. last_tas_state = new_tas_state;
  280. emit TasPlaybackStateChanged();
  281. }
  282. }
  283. bool GRenderWindow::IsShown() const {
  284. return !isMinimized();
  285. }
  286. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  287. //
  288. // Older versions get the window size (density independent pixels),
  289. // and hence, do not support DPI scaling ("retina" displays).
  290. // The result will be a viewport that is smaller than the extent of the window.
  291. void GRenderWindow::OnFramebufferSizeChanged() {
  292. // Screen changes potentially incur a change in screen DPI, hence we should update the
  293. // framebuffer size
  294. const qreal pixel_ratio = windowPixelRatio();
  295. const u32 width = this->width() * pixel_ratio;
  296. const u32 height = this->height() * pixel_ratio;
  297. UpdateCurrentFramebufferLayout(width, height);
  298. }
  299. void GRenderWindow::BackupGeometry() {
  300. geometry = QWidget::saveGeometry();
  301. }
  302. void GRenderWindow::RestoreGeometry() {
  303. // We don't want to back up the geometry here (obviously)
  304. QWidget::restoreGeometry(geometry);
  305. }
  306. void GRenderWindow::restoreGeometry(const QByteArray& geometry_) {
  307. // Make sure users of this class don't need to deal with backing up the geometry themselves
  308. QWidget::restoreGeometry(geometry_);
  309. BackupGeometry();
  310. }
  311. QByteArray GRenderWindow::saveGeometry() {
  312. // If we are a top-level widget, store the current geometry
  313. // otherwise, store the last backup
  314. if (parent() == nullptr) {
  315. return QWidget::saveGeometry();
  316. }
  317. return geometry;
  318. }
  319. qreal GRenderWindow::windowPixelRatio() const {
  320. return devicePixelRatioF();
  321. }
  322. std::pair<u32, u32> GRenderWindow::ScaleTouch(const QPointF& pos) const {
  323. const qreal pixel_ratio = windowPixelRatio();
  324. return {static_cast<u32>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  325. static_cast<u32>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  326. }
  327. void GRenderWindow::closeEvent(QCloseEvent* event) {
  328. emit Closed();
  329. QWidget::closeEvent(event);
  330. }
  331. void GRenderWindow::leaveEvent(QEvent* event) {
  332. if (Settings::values.mouse_panning) {
  333. const QRect& rect = QWidget::geometry();
  334. QPoint position = QCursor::pos();
  335. qint32 x = qBound(rect.left(), position.x(), rect.right());
  336. qint32 y = qBound(rect.top(), position.y(), rect.bottom());
  337. // Only start the timer if the mouse has left the window bound.
  338. // The leave event is also triggered when the window looses focus.
  339. if (x != position.x() || y != position.y()) {
  340. mouse_constrain_timer.start();
  341. }
  342. event->accept();
  343. }
  344. }
  345. int GRenderWindow::QtKeyToSwitchKey(Qt::Key qt_key) {
  346. static constexpr std::array<std::pair<Qt::Key, Settings::NativeKeyboard::Keys>, 106> key_map = {
  347. std::pair<Qt::Key, Settings::NativeKeyboard::Keys>{Qt::Key_A, Settings::NativeKeyboard::A},
  348. {Qt::Key_A, Settings::NativeKeyboard::A},
  349. {Qt::Key_B, Settings::NativeKeyboard::B},
  350. {Qt::Key_C, Settings::NativeKeyboard::C},
  351. {Qt::Key_D, Settings::NativeKeyboard::D},
  352. {Qt::Key_E, Settings::NativeKeyboard::E},
  353. {Qt::Key_F, Settings::NativeKeyboard::F},
  354. {Qt::Key_G, Settings::NativeKeyboard::G},
  355. {Qt::Key_H, Settings::NativeKeyboard::H},
  356. {Qt::Key_I, Settings::NativeKeyboard::I},
  357. {Qt::Key_J, Settings::NativeKeyboard::J},
  358. {Qt::Key_K, Settings::NativeKeyboard::K},
  359. {Qt::Key_L, Settings::NativeKeyboard::L},
  360. {Qt::Key_M, Settings::NativeKeyboard::M},
  361. {Qt::Key_N, Settings::NativeKeyboard::N},
  362. {Qt::Key_O, Settings::NativeKeyboard::O},
  363. {Qt::Key_P, Settings::NativeKeyboard::P},
  364. {Qt::Key_Q, Settings::NativeKeyboard::Q},
  365. {Qt::Key_R, Settings::NativeKeyboard::R},
  366. {Qt::Key_S, Settings::NativeKeyboard::S},
  367. {Qt::Key_T, Settings::NativeKeyboard::T},
  368. {Qt::Key_U, Settings::NativeKeyboard::U},
  369. {Qt::Key_V, Settings::NativeKeyboard::V},
  370. {Qt::Key_W, Settings::NativeKeyboard::W},
  371. {Qt::Key_X, Settings::NativeKeyboard::X},
  372. {Qt::Key_Y, Settings::NativeKeyboard::Y},
  373. {Qt::Key_Z, Settings::NativeKeyboard::Z},
  374. {Qt::Key_1, Settings::NativeKeyboard::N1},
  375. {Qt::Key_2, Settings::NativeKeyboard::N2},
  376. {Qt::Key_3, Settings::NativeKeyboard::N3},
  377. {Qt::Key_4, Settings::NativeKeyboard::N4},
  378. {Qt::Key_5, Settings::NativeKeyboard::N5},
  379. {Qt::Key_6, Settings::NativeKeyboard::N6},
  380. {Qt::Key_7, Settings::NativeKeyboard::N7},
  381. {Qt::Key_8, Settings::NativeKeyboard::N8},
  382. {Qt::Key_9, Settings::NativeKeyboard::N9},
  383. {Qt::Key_0, Settings::NativeKeyboard::N0},
  384. {Qt::Key_Return, Settings::NativeKeyboard::Return},
  385. {Qt::Key_Escape, Settings::NativeKeyboard::Escape},
  386. {Qt::Key_Backspace, Settings::NativeKeyboard::Backspace},
  387. {Qt::Key_Tab, Settings::NativeKeyboard::Tab},
  388. {Qt::Key_Space, Settings::NativeKeyboard::Space},
  389. {Qt::Key_Minus, Settings::NativeKeyboard::Minus},
  390. {Qt::Key_Plus, Settings::NativeKeyboard::Plus},
  391. {Qt::Key_questiondown, Settings::NativeKeyboard::Plus},
  392. {Qt::Key_BracketLeft, Settings::NativeKeyboard::OpenBracket},
  393. {Qt::Key_BraceLeft, Settings::NativeKeyboard::OpenBracket},
  394. {Qt::Key_BracketRight, Settings::NativeKeyboard::CloseBracket},
  395. {Qt::Key_BraceRight, Settings::NativeKeyboard::CloseBracket},
  396. {Qt::Key_Bar, Settings::NativeKeyboard::Pipe},
  397. {Qt::Key_Dead_Tilde, Settings::NativeKeyboard::Tilde},
  398. {Qt::Key_Ntilde, Settings::NativeKeyboard::Semicolon},
  399. {Qt::Key_Semicolon, Settings::NativeKeyboard::Semicolon},
  400. {Qt::Key_Apostrophe, Settings::NativeKeyboard::Quote},
  401. {Qt::Key_Dead_Grave, Settings::NativeKeyboard::Backquote},
  402. {Qt::Key_Comma, Settings::NativeKeyboard::Comma},
  403. {Qt::Key_Period, Settings::NativeKeyboard::Period},
  404. {Qt::Key_Slash, Settings::NativeKeyboard::Slash},
  405. {Qt::Key_CapsLock, Settings::NativeKeyboard::CapsLockKey},
  406. {Qt::Key_F1, Settings::NativeKeyboard::F1},
  407. {Qt::Key_F2, Settings::NativeKeyboard::F2},
  408. {Qt::Key_F3, Settings::NativeKeyboard::F3},
  409. {Qt::Key_F4, Settings::NativeKeyboard::F4},
  410. {Qt::Key_F5, Settings::NativeKeyboard::F5},
  411. {Qt::Key_F6, Settings::NativeKeyboard::F6},
  412. {Qt::Key_F7, Settings::NativeKeyboard::F7},
  413. {Qt::Key_F8, Settings::NativeKeyboard::F8},
  414. {Qt::Key_F9, Settings::NativeKeyboard::F9},
  415. {Qt::Key_F10, Settings::NativeKeyboard::F10},
  416. {Qt::Key_F11, Settings::NativeKeyboard::F11},
  417. {Qt::Key_F12, Settings::NativeKeyboard::F12},
  418. {Qt::Key_Print, Settings::NativeKeyboard::PrintScreen},
  419. {Qt::Key_ScrollLock, Settings::NativeKeyboard::ScrollLockKey},
  420. {Qt::Key_Pause, Settings::NativeKeyboard::Pause},
  421. {Qt::Key_Insert, Settings::NativeKeyboard::Insert},
  422. {Qt::Key_Home, Settings::NativeKeyboard::Home},
  423. {Qt::Key_PageUp, Settings::NativeKeyboard::PageUp},
  424. {Qt::Key_Delete, Settings::NativeKeyboard::Delete},
  425. {Qt::Key_End, Settings::NativeKeyboard::End},
  426. {Qt::Key_PageDown, Settings::NativeKeyboard::PageDown},
  427. {Qt::Key_Right, Settings::NativeKeyboard::Right},
  428. {Qt::Key_Left, Settings::NativeKeyboard::Left},
  429. {Qt::Key_Down, Settings::NativeKeyboard::Down},
  430. {Qt::Key_Up, Settings::NativeKeyboard::Up},
  431. {Qt::Key_NumLock, Settings::NativeKeyboard::NumLockKey},
  432. // Numpad keys are missing here
  433. {Qt::Key_F13, Settings::NativeKeyboard::F13},
  434. {Qt::Key_F14, Settings::NativeKeyboard::F14},
  435. {Qt::Key_F15, Settings::NativeKeyboard::F15},
  436. {Qt::Key_F16, Settings::NativeKeyboard::F16},
  437. {Qt::Key_F17, Settings::NativeKeyboard::F17},
  438. {Qt::Key_F18, Settings::NativeKeyboard::F18},
  439. {Qt::Key_F19, Settings::NativeKeyboard::F19},
  440. {Qt::Key_F20, Settings::NativeKeyboard::F20},
  441. {Qt::Key_F21, Settings::NativeKeyboard::F21},
  442. {Qt::Key_F22, Settings::NativeKeyboard::F22},
  443. {Qt::Key_F23, Settings::NativeKeyboard::F23},
  444. {Qt::Key_F24, Settings::NativeKeyboard::F24},
  445. // {Qt::..., Settings::NativeKeyboard::KPComma},
  446. // {Qt::..., Settings::NativeKeyboard::Ro},
  447. {Qt::Key_Hiragana_Katakana, Settings::NativeKeyboard::KatakanaHiragana},
  448. {Qt::Key_yen, Settings::NativeKeyboard::Yen},
  449. {Qt::Key_Henkan, Settings::NativeKeyboard::Henkan},
  450. {Qt::Key_Muhenkan, Settings::NativeKeyboard::Muhenkan},
  451. // {Qt::..., Settings::NativeKeyboard::NumPadCommaPc98},
  452. {Qt::Key_Hangul, Settings::NativeKeyboard::HangulEnglish},
  453. {Qt::Key_Hangul_Hanja, Settings::NativeKeyboard::Hanja},
  454. {Qt::Key_Katakana, Settings::NativeKeyboard::KatakanaKey},
  455. {Qt::Key_Hiragana, Settings::NativeKeyboard::HiraganaKey},
  456. {Qt::Key_Zenkaku_Hankaku, Settings::NativeKeyboard::ZenkakuHankaku},
  457. // Modifier keys are handled by the modifier property
  458. };
  459. for (const auto& [qkey, nkey] : key_map) {
  460. if (qt_key == qkey) {
  461. return nkey;
  462. }
  463. }
  464. return Settings::NativeKeyboard::None;
  465. }
  466. int GRenderWindow::QtModifierToSwitchModifier(Qt::KeyboardModifiers qt_modifiers) {
  467. int modifier = 0;
  468. if ((qt_modifiers & Qt::KeyboardModifier::ShiftModifier) != 0) {
  469. modifier |= 1 << Settings::NativeKeyboard::LeftShift;
  470. }
  471. if ((qt_modifiers & Qt::KeyboardModifier::ControlModifier) != 0) {
  472. modifier |= 1 << Settings::NativeKeyboard::LeftControl;
  473. }
  474. if ((qt_modifiers & Qt::KeyboardModifier::AltModifier) != 0) {
  475. modifier |= 1 << Settings::NativeKeyboard::LeftAlt;
  476. }
  477. if ((qt_modifiers & Qt::KeyboardModifier::MetaModifier) != 0) {
  478. modifier |= 1 << Settings::NativeKeyboard::LeftMeta;
  479. }
  480. // TODO: These keys can't be obtained with Qt::KeyboardModifier
  481. // if ((qt_modifiers & 0x10) != 0) {
  482. // modifier |= 1 << Settings::NativeKeyboard::RightShift;
  483. // }
  484. // if ((qt_modifiers & 0x20) != 0) {
  485. // modifier |= 1 << Settings::NativeKeyboard::RightControl;
  486. // }
  487. // if ((qt_modifiers & 0x40) != 0) {
  488. // modifier |= 1 << Settings::NativeKeyboard::RightAlt;
  489. // }
  490. // if ((qt_modifiers & 0x80) != 0) {
  491. // modifier |= 1 << Settings::NativeKeyboard::RightMeta;
  492. // }
  493. // if ((qt_modifiers & 0x100) != 0) {
  494. // modifier |= 1 << Settings::NativeKeyboard::CapsLock;
  495. // }
  496. // if ((qt_modifiers & 0x200) != 0) {
  497. // modifier |= 1 << Settings::NativeKeyboard::NumLock;
  498. // }
  499. // if ((qt_modifiers & ???) != 0) {
  500. // modifier |= 1 << Settings::NativeKeyboard::ScrollLock;
  501. // }
  502. // if ((qt_modifiers & ???) != 0) {
  503. // modifier |= 1 << Settings::NativeKeyboard::Katakana;
  504. // }
  505. // if ((qt_modifiers & ???) != 0) {
  506. // modifier |= 1 << Settings::NativeKeyboard::Hiragana;
  507. // }
  508. return modifier;
  509. }
  510. void GRenderWindow::keyPressEvent(QKeyEvent* event) {
  511. /**
  512. * This feature can be enhanced with the following functions, but they do not provide
  513. * cross-platform behavior.
  514. *
  515. * event->nativeVirtualKey() can distinguish between keys on the numpad.
  516. * event->nativeModifiers() can distinguish between left and right keys and numlock,
  517. * capslock, scroll lock.
  518. */
  519. if (!event->isAutoRepeat()) {
  520. const auto modifier = QtModifierToSwitchModifier(event->modifiers());
  521. const auto key = QtKeyToSwitchKey(Qt::Key(event->key()));
  522. input_subsystem->GetKeyboard()->SetKeyboardModifiers(modifier);
  523. input_subsystem->GetKeyboard()->PressKeyboardKey(key);
  524. // This is used for gamepads that can have any key mapped
  525. input_subsystem->GetKeyboard()->PressKey(event->key());
  526. }
  527. }
  528. void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
  529. /**
  530. * This feature can be enhanced with the following functions, but they do not provide
  531. * cross-platform behavior.
  532. *
  533. * event->nativeVirtualKey() can distinguish between keys on the numpad.
  534. * event->nativeModifiers() can distinguish between left and right buttons and numlock,
  535. * capslock, scroll lock.
  536. */
  537. if (!event->isAutoRepeat()) {
  538. const auto modifier = QtModifierToSwitchModifier(event->modifiers());
  539. const auto key = QtKeyToSwitchKey(Qt::Key(event->key()));
  540. input_subsystem->GetKeyboard()->SetKeyboardModifiers(modifier);
  541. input_subsystem->GetKeyboard()->ReleaseKeyboardKey(key);
  542. // This is used for gamepads that can have any key mapped
  543. input_subsystem->GetKeyboard()->ReleaseKey(event->key());
  544. }
  545. }
  546. InputCommon::MouseButton GRenderWindow::QtButtonToMouseButton(Qt::MouseButton button) {
  547. switch (button) {
  548. case Qt::LeftButton:
  549. return InputCommon::MouseButton::Left;
  550. case Qt::RightButton:
  551. return InputCommon::MouseButton::Right;
  552. case Qt::MiddleButton:
  553. return InputCommon::MouseButton::Wheel;
  554. case Qt::BackButton:
  555. return InputCommon::MouseButton::Backward;
  556. case Qt::ForwardButton:
  557. return InputCommon::MouseButton::Forward;
  558. case Qt::TaskButton:
  559. return InputCommon::MouseButton::Task;
  560. default:
  561. return InputCommon::MouseButton::Extra;
  562. }
  563. }
  564. void GRenderWindow::mousePressEvent(QMouseEvent* event) {
  565. // Touch input is handled in TouchBeginEvent
  566. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  567. return;
  568. }
  569. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  570. // coordinates and map them to the current render area
  571. const auto pos = mapFromGlobal(QCursor::pos());
  572. const auto [x, y] = ScaleTouch(pos);
  573. const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
  574. const auto button = QtButtonToMouseButton(event->button());
  575. input_subsystem->GetMouse()->PressMouseButton(button);
  576. input_subsystem->GetMouse()->PressButton(pos.x(), pos.y(), button);
  577. input_subsystem->GetMouse()->PressTouchButton(touch_x, touch_y, button);
  578. emit MouseActivity();
  579. }
  580. void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
  581. // Touch input is handled in TouchUpdateEvent
  582. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  583. return;
  584. }
  585. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  586. // coordinates and map them to the current render area
  587. const auto pos = mapFromGlobal(QCursor::pos());
  588. const auto [x, y] = ScaleTouch(pos);
  589. const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
  590. const int center_x = width() / 2;
  591. const int center_y = height() / 2;
  592. input_subsystem->GetMouse()->MouseMove(touch_x, touch_y);
  593. input_subsystem->GetMouse()->TouchMove(touch_x, touch_y);
  594. input_subsystem->GetMouse()->Move(pos.x(), pos.y(), center_x, center_y);
  595. // Center mouse for mouse panning
  596. if (Settings::values.mouse_panning && !Settings::values.mouse_enabled) {
  597. QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
  598. }
  599. // Constrain mouse for mouse emulation with mouse panning
  600. if (Settings::values.mouse_panning && Settings::values.mouse_enabled) {
  601. const auto [clamped_mouse_x, clamped_mouse_y] = ClipToTouchScreen(x, y);
  602. QCursor::setPos(mapToGlobal(
  603. QPoint{static_cast<int>(clamped_mouse_x), static_cast<int>(clamped_mouse_y)}));
  604. }
  605. mouse_constrain_timer.stop();
  606. emit MouseActivity();
  607. }
  608. void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
  609. // Touch input is handled in TouchEndEvent
  610. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  611. return;
  612. }
  613. const auto button = QtButtonToMouseButton(event->button());
  614. input_subsystem->GetMouse()->ReleaseButton(button);
  615. }
  616. void GRenderWindow::ConstrainMouse() {
  617. if (emu_thread == nullptr || !Settings::values.mouse_panning) {
  618. mouse_constrain_timer.stop();
  619. return;
  620. }
  621. if (!this->isActiveWindow()) {
  622. mouse_constrain_timer.stop();
  623. return;
  624. }
  625. if (Settings::values.mouse_enabled) {
  626. const auto pos = mapFromGlobal(QCursor::pos());
  627. const int new_pos_x = std::clamp(pos.x(), 0, width());
  628. const int new_pos_y = std::clamp(pos.y(), 0, height());
  629. QCursor::setPos(mapToGlobal(QPoint{new_pos_x, new_pos_y}));
  630. return;
  631. }
  632. const int center_x = width() / 2;
  633. const int center_y = height() / 2;
  634. QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
  635. }
  636. void GRenderWindow::wheelEvent(QWheelEvent* event) {
  637. const int x = event->angleDelta().x();
  638. const int y = event->angleDelta().y();
  639. input_subsystem->GetMouse()->MouseWheelChange(x, y);
  640. }
  641. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  642. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  643. for (const auto& touch_point : touch_points) {
  644. const auto [x, y] = ScaleTouch(touch_point.pos());
  645. const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
  646. input_subsystem->GetTouchScreen()->TouchPressed(touch_x, touch_y, touch_point.id());
  647. }
  648. }
  649. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  650. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  651. input_subsystem->GetTouchScreen()->ClearActiveFlag();
  652. for (const auto& touch_point : touch_points) {
  653. const auto [x, y] = ScaleTouch(touch_point.pos());
  654. const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
  655. input_subsystem->GetTouchScreen()->TouchMoved(touch_x, touch_y, touch_point.id());
  656. }
  657. input_subsystem->GetTouchScreen()->ReleaseInactiveTouch();
  658. }
  659. void GRenderWindow::TouchEndEvent() {
  660. input_subsystem->GetTouchScreen()->ReleaseAllTouch();
  661. }
  662. void GRenderWindow::InitializeCamera() {
  663. #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUYU_USE_QT_MULTIMEDIA
  664. constexpr auto camera_update_ms = std::chrono::milliseconds{50}; // (50ms, 20Hz)
  665. if (!Settings::values.enable_ir_sensor) {
  666. return;
  667. }
  668. bool camera_found = false;
  669. const QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
  670. for (const QCameraInfo& cameraInfo : cameras) {
  671. if (Settings::values.ir_sensor_device.GetValue() == cameraInfo.deviceName().toStdString() ||
  672. Settings::values.ir_sensor_device.GetValue() == "Auto") {
  673. camera = std::make_unique<QCamera>(cameraInfo);
  674. if (!camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder) &&
  675. !camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) {
  676. LOG_ERROR(Frontend,
  677. "Camera doesn't support CaptureViewfinder or CaptureStillImage");
  678. continue;
  679. }
  680. camera_found = true;
  681. break;
  682. }
  683. }
  684. if (!camera_found) {
  685. return;
  686. }
  687. camera_capture = std::make_unique<QCameraImageCapture>(camera.get());
  688. if (!camera_capture->isCaptureDestinationSupported(
  689. QCameraImageCapture::CaptureDestination::CaptureToBuffer)) {
  690. LOG_ERROR(Frontend, "Camera doesn't support saving to buffer");
  691. return;
  692. }
  693. const auto camera_width = input_subsystem->GetCamera()->getImageWidth();
  694. const auto camera_height = input_subsystem->GetCamera()->getImageHeight();
  695. camera_data.resize(camera_width * camera_height);
  696. camera_capture->setCaptureDestination(QCameraImageCapture::CaptureDestination::CaptureToBuffer);
  697. connect(camera_capture.get(), &QCameraImageCapture::imageCaptured, this,
  698. &GRenderWindow::OnCameraCapture);
  699. camera->unload();
  700. if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder)) {
  701. camera->setCaptureMode(QCamera::CaptureViewfinder);
  702. } else if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) {
  703. camera->setCaptureMode(QCamera::CaptureStillImage);
  704. }
  705. camera->load();
  706. camera->start();
  707. pending_camera_snapshots = 0;
  708. is_virtual_camera = false;
  709. camera_timer = std::make_unique<QTimer>();
  710. connect(camera_timer.get(), &QTimer::timeout, [this] { RequestCameraCapture(); });
  711. // This timer should be dependent of camera resolution 5ms for every 100 pixels
  712. camera_timer->start(camera_update_ms);
  713. #endif
  714. }
  715. void GRenderWindow::FinalizeCamera() {
  716. #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUYU_USE_QT_MULTIMEDIA
  717. if (camera_timer) {
  718. camera_timer->stop();
  719. }
  720. if (camera) {
  721. camera->unload();
  722. }
  723. #endif
  724. }
  725. void GRenderWindow::RequestCameraCapture() {
  726. #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUYU_USE_QT_MULTIMEDIA
  727. if (!Settings::values.enable_ir_sensor) {
  728. return;
  729. }
  730. // If the camera doesn't capture, test for virtual cameras
  731. if (pending_camera_snapshots > 5) {
  732. is_virtual_camera = true;
  733. }
  734. // Virtual cameras like obs need to reset the camera every capture
  735. if (is_virtual_camera) {
  736. camera->stop();
  737. camera->start();
  738. }
  739. pending_camera_snapshots++;
  740. camera_capture->capture();
  741. #endif
  742. }
  743. void GRenderWindow::OnCameraCapture(int requestId, const QImage& img) {
  744. #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUYU_USE_QT_MULTIMEDIA
  745. // TODO: Capture directly in the format and resolution needed
  746. const auto camera_width = input_subsystem->GetCamera()->getImageWidth();
  747. const auto camera_height = input_subsystem->GetCamera()->getImageHeight();
  748. const auto converted =
  749. img.scaled(static_cast<int>(camera_width), static_cast<int>(camera_height),
  750. Qt::AspectRatioMode::IgnoreAspectRatio,
  751. Qt::TransformationMode::SmoothTransformation)
  752. .mirrored(false, true);
  753. if (camera_data.size() != camera_width * camera_height) {
  754. camera_data.resize(camera_width * camera_height);
  755. }
  756. std::memcpy(camera_data.data(), converted.bits(), camera_width * camera_height * sizeof(u32));
  757. input_subsystem->GetCamera()->SetCameraData(camera_width, camera_height, camera_data);
  758. pending_camera_snapshots = 0;
  759. #endif
  760. }
  761. bool GRenderWindow::event(QEvent* event) {
  762. if (event->type() == QEvent::TouchBegin) {
  763. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  764. return true;
  765. } else if (event->type() == QEvent::TouchUpdate) {
  766. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  767. return true;
  768. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  769. TouchEndEvent();
  770. return true;
  771. }
  772. return QWidget::event(event);
  773. }
  774. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  775. QWidget::focusOutEvent(event);
  776. input_subsystem->GetKeyboard()->ReleaseAllKeys();
  777. input_subsystem->GetMouse()->ReleaseAllButtons();
  778. input_subsystem->GetTouchScreen()->ReleaseAllTouch();
  779. }
  780. void GRenderWindow::resizeEvent(QResizeEvent* event) {
  781. QWidget::resizeEvent(event);
  782. OnFramebufferSizeChanged();
  783. }
  784. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  785. #ifdef HAS_OPENGL
  786. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  787. auto c = static_cast<OpenGLSharedContext*>(main_context.get());
  788. // Bind the shared contexts to the main surface in case the backend wants to take over
  789. // presentation
  790. return std::make_unique<OpenGLSharedContext>(c->GetShareContext(),
  791. child_widget->windowHandle());
  792. }
  793. #endif
  794. return std::make_unique<DummyContext>();
  795. }
  796. bool GRenderWindow::InitRenderTarget() {
  797. ReleaseRenderTarget();
  798. {
  799. // Create a dummy render widget so that Qt
  800. // places the render window at the correct position.
  801. const RenderWidget dummy_widget{this};
  802. }
  803. first_frame = false;
  804. switch (Settings::values.renderer_backend.GetValue()) {
  805. case Settings::RendererBackend::OpenGL:
  806. if (!InitializeOpenGL()) {
  807. return false;
  808. }
  809. break;
  810. case Settings::RendererBackend::Vulkan:
  811. if (!InitializeVulkan()) {
  812. return false;
  813. }
  814. break;
  815. case Settings::RendererBackend::Null:
  816. InitializeNull();
  817. break;
  818. }
  819. // Update the Window System information with the new render target
  820. window_info = QtCommon::GetWindowSystemInfo(child_widget->windowHandle());
  821. child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  822. layout()->addWidget(child_widget);
  823. // Reset minimum required size to avoid resizing issues on the main window after restarting.
  824. setMinimumSize(1, 1);
  825. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  826. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  827. OnFramebufferSizeChanged();
  828. BackupGeometry();
  829. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  830. if (!LoadOpenGL()) {
  831. return false;
  832. }
  833. }
  834. return true;
  835. }
  836. void GRenderWindow::ReleaseRenderTarget() {
  837. if (child_widget) {
  838. layout()->removeWidget(child_widget);
  839. child_widget->deleteLater();
  840. child_widget = nullptr;
  841. }
  842. main_context.reset();
  843. }
  844. void GRenderWindow::CaptureScreenshot(const QString& screenshot_path) {
  845. auto& renderer = system.Renderer();
  846. if (renderer.IsScreenshotPending()) {
  847. LOG_WARNING(Render,
  848. "A screenshot is already requested or in progress, ignoring the request");
  849. return;
  850. }
  851. const Layout::FramebufferLayout layout{[]() {
  852. u32 height = UISettings::values.screenshot_height.GetValue();
  853. if (height == 0) {
  854. height = Settings::IsDockedMode() ? Layout::ScreenDocked::Height
  855. : Layout::ScreenUndocked::Height;
  856. height *= Settings::values.resolution_info.up_factor;
  857. }
  858. const u32 width =
  859. UISettings::CalculateWidth(height, Settings::values.aspect_ratio.GetValue());
  860. return Layout::DefaultFrameLayout(width, height);
  861. }()};
  862. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  863. renderer.RequestScreenshot(
  864. screenshot_image.bits(),
  865. [=, this](bool invert_y) {
  866. const std::string std_screenshot_path = screenshot_path.toStdString();
  867. if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) {
  868. LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
  869. } else {
  870. LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
  871. }
  872. },
  873. layout);
  874. }
  875. bool GRenderWindow::IsLoadingComplete() const {
  876. return first_frame;
  877. }
  878. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
  879. setMinimumSize(minimal_size.first, minimal_size.second);
  880. }
  881. bool GRenderWindow::InitializeOpenGL() {
  882. #ifdef HAS_OPENGL
  883. if (!QOpenGLContext::supportsThreadedOpenGL()) {
  884. QMessageBox::warning(this, tr("OpenGL not available!"),
  885. tr("OpenGL shared contexts are not supported."));
  886. return false;
  887. }
  888. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  889. // WA_DontShowOnScreen, WA_DeleteOnClose
  890. auto child = new OpenGLRenderWidget(this);
  891. child_widget = child;
  892. child_widget->windowHandle()->create();
  893. auto context = std::make_shared<OpenGLSharedContext>(child->windowHandle());
  894. main_context = context;
  895. child->SetContext(
  896. std::make_unique<OpenGLSharedContext>(context->GetShareContext(), child->windowHandle()));
  897. return true;
  898. #else
  899. QMessageBox::warning(this, tr("OpenGL not available!"),
  900. tr("yusu has not been compiled with OpenGL support."));
  901. return false;
  902. #endif
  903. }
  904. bool GRenderWindow::InitializeVulkan() {
  905. auto child = new VulkanRenderWidget(this);
  906. child_widget = child;
  907. child_widget->windowHandle()->create();
  908. main_context = std::make_unique<DummyContext>();
  909. return true;
  910. }
  911. void GRenderWindow::InitializeNull() {
  912. child_widget = new NullRenderWidget(this);
  913. main_context = std::make_unique<DummyContext>();
  914. }
  915. bool GRenderWindow::LoadOpenGL() {
  916. auto context = CreateSharedContext();
  917. auto scope = context->Acquire();
  918. if (!gladLoadGL()) {
  919. QMessageBox::warning(
  920. this, tr("Error while initializing OpenGL!"),
  921. tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver."));
  922. return false;
  923. }
  924. const QString renderer =
  925. QString::fromUtf8(reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
  926. if (!GLAD_GL_VERSION_4_6) {
  927. LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString());
  928. QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"),
  929. tr("Your GPU may not support OpenGL 4.6, or you do not have the "
  930. "latest graphics driver.<br><br>GL Renderer:<br>%1")
  931. .arg(renderer));
  932. return false;
  933. }
  934. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  935. if (!unsupported_gl_extensions.empty()) {
  936. QMessageBox::warning(
  937. this, tr("Error while initializing OpenGL!"),
  938. tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you "
  939. "have the latest graphics driver.<br><br>GL Renderer:<br>%1<br><br>Unsupported "
  940. "extensions:<br>%2")
  941. .arg(renderer)
  942. .arg(unsupported_gl_extensions.join(QStringLiteral("<br>"))));
  943. return false;
  944. }
  945. return true;
  946. }
  947. QStringList GRenderWindow::GetUnsupportedGLExtensions() const {
  948. QStringList unsupported_ext;
  949. // Extensions required to support some texture formats.
  950. if (!GLAD_GL_EXT_texture_compression_s3tc) {
  951. unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc"));
  952. }
  953. if (!GLAD_GL_ARB_texture_compression_rgtc) {
  954. unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc"));
  955. }
  956. if (!unsupported_ext.empty()) {
  957. const std::string gl_renderer{reinterpret_cast<const char*>(glGetString(GL_RENDERER))};
  958. LOG_ERROR(Frontend, "GPU does not support all required extensions: {}", gl_renderer);
  959. }
  960. for (const QString& ext : unsupported_ext) {
  961. LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  962. }
  963. return unsupported_ext;
  964. }
  965. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread_) {
  966. emu_thread = emu_thread_;
  967. }
  968. void GRenderWindow::OnEmulationStopping() {
  969. emu_thread = nullptr;
  970. }
  971. void GRenderWindow::showEvent(QShowEvent* event) {
  972. QWidget::showEvent(event);
  973. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  974. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  975. Qt::UniqueConnection);
  976. }
  977. bool GRenderWindow::eventFilter(QObject* object, QEvent* event) {
  978. if (event->type() == QEvent::HoverMove) {
  979. if (Settings::values.mouse_panning || Settings::values.mouse_enabled) {
  980. auto* hover_event = static_cast<QMouseEvent*>(event);
  981. mouseMoveEvent(hover_event);
  982. return false;
  983. }
  984. emit MouseActivity();
  985. }
  986. return false;
  987. }