bootmanager.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. const auto [x, y] = ScaleTouch(touch_point.pos());
  693. const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
  694. input_subsystem->GetTouchScreen()->TouchPressed(touch_x, touch_y, touch_point.id());
  695. }
  696. }
  697. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  698. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  699. input_subsystem->GetTouchScreen()->ClearActiveFlag();
  700. for (const auto& touch_point : touch_points) {
  701. const auto [x, y] = ScaleTouch(touch_point.pos());
  702. const auto [touch_x, touch_y] = MapToTouchScreen(x, y);
  703. input_subsystem->GetTouchScreen()->TouchMoved(touch_x, touch_y, touch_point.id());
  704. }
  705. input_subsystem->GetTouchScreen()->ReleaseInactiveTouch();
  706. }
  707. void GRenderWindow::TouchEndEvent() {
  708. input_subsystem->GetTouchScreen()->ReleaseAllTouch();
  709. }
  710. bool GRenderWindow::event(QEvent* event) {
  711. if (event->type() == QEvent::TouchBegin) {
  712. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  713. return true;
  714. } else if (event->type() == QEvent::TouchUpdate) {
  715. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  716. return true;
  717. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  718. TouchEndEvent();
  719. return true;
  720. }
  721. return QWidget::event(event);
  722. }
  723. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  724. QWidget::focusOutEvent(event);
  725. input_subsystem->GetKeyboard()->ReleaseAllKeys();
  726. input_subsystem->GetMouse()->ReleaseAllButtons();
  727. input_subsystem->GetTouchScreen()->ReleaseAllTouch();
  728. }
  729. void GRenderWindow::resizeEvent(QResizeEvent* event) {
  730. QWidget::resizeEvent(event);
  731. OnFramebufferSizeChanged();
  732. }
  733. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  734. #ifdef HAS_OPENGL
  735. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  736. auto c = static_cast<OpenGLSharedContext*>(main_context.get());
  737. // Bind the shared contexts to the main surface in case the backend wants to take over
  738. // presentation
  739. return std::make_unique<OpenGLSharedContext>(c->GetShareContext(),
  740. child_widget->windowHandle());
  741. }
  742. #endif
  743. return std::make_unique<DummyContext>();
  744. }
  745. bool GRenderWindow::InitRenderTarget() {
  746. ReleaseRenderTarget();
  747. {
  748. // Create a dummy render widget so that Qt
  749. // places the render window at the correct position.
  750. const RenderWidget dummy_widget{this};
  751. }
  752. first_frame = false;
  753. switch (Settings::values.renderer_backend.GetValue()) {
  754. case Settings::RendererBackend::OpenGL:
  755. if (!InitializeOpenGL()) {
  756. return false;
  757. }
  758. break;
  759. case Settings::RendererBackend::Vulkan:
  760. if (!InitializeVulkan()) {
  761. return false;
  762. }
  763. break;
  764. }
  765. // Update the Window System information with the new render target
  766. window_info = GetWindowSystemInfo(child_widget->windowHandle());
  767. child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  768. layout()->addWidget(child_widget);
  769. // Reset minimum required size to avoid resizing issues on the main window after restarting.
  770. setMinimumSize(1, 1);
  771. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  772. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  773. OnFramebufferSizeChanged();
  774. BackupGeometry();
  775. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  776. if (!LoadOpenGL()) {
  777. return false;
  778. }
  779. }
  780. return true;
  781. }
  782. void GRenderWindow::ReleaseRenderTarget() {
  783. if (child_widget) {
  784. layout()->removeWidget(child_widget);
  785. child_widget->deleteLater();
  786. child_widget = nullptr;
  787. }
  788. main_context.reset();
  789. }
  790. void GRenderWindow::CaptureScreenshot(const QString& screenshot_path) {
  791. auto& renderer = system.Renderer();
  792. const f32 res_scale = Settings::values.resolution_info.up_factor;
  793. if (renderer.IsScreenshotPending()) {
  794. LOG_WARNING(Render,
  795. "A screenshot is already requested or in progress, ignoring the request");
  796. return;
  797. }
  798. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  799. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  800. renderer.RequestScreenshot(
  801. screenshot_image.bits(),
  802. [=, this](bool invert_y) {
  803. const std::string std_screenshot_path = screenshot_path.toStdString();
  804. if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) {
  805. LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
  806. } else {
  807. LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
  808. }
  809. },
  810. layout);
  811. }
  812. bool GRenderWindow::IsLoadingComplete() const {
  813. return first_frame;
  814. }
  815. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
  816. setMinimumSize(minimal_size.first, minimal_size.second);
  817. }
  818. bool GRenderWindow::InitializeOpenGL() {
  819. #ifdef HAS_OPENGL
  820. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  821. // WA_DontShowOnScreen, WA_DeleteOnClose
  822. auto child = new OpenGLRenderWidget(this);
  823. child_widget = child;
  824. child_widget->windowHandle()->create();
  825. auto context = std::make_shared<OpenGLSharedContext>(child->windowHandle());
  826. main_context = context;
  827. child->SetContext(
  828. std::make_unique<OpenGLSharedContext>(context->GetShareContext(), child->windowHandle()));
  829. return true;
  830. #else
  831. QMessageBox::warning(this, tr("OpenGL not available!"),
  832. tr("yuzu has not been compiled with OpenGL support."));
  833. return false;
  834. #endif
  835. }
  836. bool GRenderWindow::InitializeVulkan() {
  837. auto child = new VulkanRenderWidget(this);
  838. child_widget = child;
  839. child_widget->windowHandle()->create();
  840. main_context = std::make_unique<DummyContext>();
  841. return true;
  842. }
  843. bool GRenderWindow::LoadOpenGL() {
  844. auto context = CreateSharedContext();
  845. auto scope = context->Acquire();
  846. if (!gladLoadGL()) {
  847. QMessageBox::warning(
  848. this, tr("Error while initializing OpenGL!"),
  849. tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver."));
  850. return false;
  851. }
  852. const QString renderer =
  853. QString::fromUtf8(reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
  854. if (!GLAD_GL_VERSION_4_6) {
  855. LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString());
  856. QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"),
  857. tr("Your GPU may not support OpenGL 4.6, or you do not have the "
  858. "latest graphics driver.<br><br>GL Renderer:<br>%1")
  859. .arg(renderer));
  860. return false;
  861. }
  862. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  863. if (!unsupported_gl_extensions.empty()) {
  864. QMessageBox::warning(
  865. this, tr("Error while initializing OpenGL!"),
  866. tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you "
  867. "have the latest graphics driver.<br><br>GL Renderer:<br>%1<br><br>Unsupported "
  868. "extensions:<br>%2")
  869. .arg(renderer)
  870. .arg(unsupported_gl_extensions.join(QStringLiteral("<br>"))));
  871. return false;
  872. }
  873. return true;
  874. }
  875. QStringList GRenderWindow::GetUnsupportedGLExtensions() const {
  876. QStringList unsupported_ext;
  877. // Extensions required to support some texture formats.
  878. if (!GLAD_GL_EXT_texture_compression_s3tc) {
  879. unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc"));
  880. }
  881. if (!GLAD_GL_ARB_texture_compression_rgtc) {
  882. unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc"));
  883. }
  884. if (!unsupported_ext.empty()) {
  885. LOG_ERROR(Frontend, "GPU does not support all required extensions: {}",
  886. glGetString(GL_RENDERER));
  887. }
  888. for (const QString& ext : unsupported_ext) {
  889. LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  890. }
  891. return unsupported_ext;
  892. }
  893. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  894. this->emu_thread = emu_thread;
  895. }
  896. void GRenderWindow::OnEmulationStopping() {
  897. emu_thread = nullptr;
  898. }
  899. void GRenderWindow::showEvent(QShowEvent* event) {
  900. QWidget::showEvent(event);
  901. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  902. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  903. Qt::UniqueConnection);
  904. }
  905. bool GRenderWindow::eventFilter(QObject* object, QEvent* event) {
  906. if (event->type() == QEvent::HoverMove) {
  907. if (Settings::values.mouse_panning || Settings::values.mouse_enabled) {
  908. auto* hover_event = static_cast<QMouseEvent*>(event);
  909. mouseMoveEvent(hover_event);
  910. return false;
  911. }
  912. emit MouseActivity();
  913. }
  914. return false;
  915. }