bootmanager.cpp 37 KB

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