bootmanager.cpp 36 KB

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