bootmanager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. #include <QApplication>
  2. #include <QHBoxLayout>
  3. #include <QKeyEvent>
  4. #include <QScreen>
  5. #include <QWindow>
  6. #include <fmt/format.h>
  7. #include "common/microprofile.h"
  8. #include "common/scm_rev.h"
  9. #include "core/core.h"
  10. #include "core/frontend/framebuffer_layout.h"
  11. #include "core/settings.h"
  12. #include "input_common/keyboard.h"
  13. #include "input_common/main.h"
  14. #include "input_common/motion_emu.h"
  15. #include "video_core/renderer_base.h"
  16. #include "video_core/video_core.h"
  17. #include "yuzu/bootmanager.h"
  18. #include "yuzu/main.h"
  19. EmuThread::EmuThread(GRenderWindow* render_window) : render_window(render_window) {}
  20. void EmuThread::run() {
  21. render_window->MakeCurrent();
  22. MicroProfileOnThreadCreate("EmuThread");
  23. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  24. Core::System::GetInstance().Renderer().Rasterizer().LoadDiskResources(
  25. stop_run, [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  26. emit LoadProgress(stage, value, total);
  27. });
  28. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  29. if (Settings::values.use_asynchronous_gpu_emulation) {
  30. // Release OpenGL context for the GPU thread
  31. render_window->DoneCurrent();
  32. }
  33. // Holds whether the cpu was running during the last iteration,
  34. // so that the DebugModeLeft signal can be emitted before the
  35. // next execution step
  36. bool was_active = false;
  37. while (!stop_run) {
  38. if (running) {
  39. if (!was_active)
  40. emit DebugModeLeft();
  41. Core::System::ResultStatus result = Core::System::GetInstance().RunLoop();
  42. if (result != Core::System::ResultStatus::Success) {
  43. this->SetRunning(false);
  44. emit ErrorThrown(result, Core::System::GetInstance().GetStatusDetails());
  45. }
  46. was_active = running || exec_step;
  47. if (!was_active && !stop_run)
  48. emit DebugModeEntered();
  49. } else if (exec_step) {
  50. if (!was_active)
  51. emit DebugModeLeft();
  52. exec_step = false;
  53. Core::System::GetInstance().SingleStep();
  54. emit DebugModeEntered();
  55. yieldCurrentThread();
  56. was_active = false;
  57. } else {
  58. std::unique_lock lock{running_mutex};
  59. running_cv.wait(lock, [this] { return IsRunning() || exec_step || stop_run; });
  60. }
  61. }
  62. // Shutdown the core emulation
  63. Core::System::GetInstance().Shutdown();
  64. #if MICROPROFILE_ENABLED
  65. MicroProfileOnThreadExit();
  66. #endif
  67. render_window->moveContext();
  68. }
  69. // This class overrides paintEvent and resizeEvent to prevent the GUI thread from stealing GL
  70. // context.
  71. // The corresponding functionality is handled in EmuThread instead
  72. class GGLWidgetInternal : public QGLWidget {
  73. public:
  74. GGLWidgetInternal(QGLFormat fmt, GRenderWindow* parent)
  75. : QGLWidget(fmt, parent), parent(parent) {}
  76. void paintEvent(QPaintEvent* ev) override {
  77. if (do_painting) {
  78. QPainter painter(this);
  79. }
  80. }
  81. void resizeEvent(QResizeEvent* ev) override {
  82. parent->OnClientAreaResized(ev->size().width(), ev->size().height());
  83. parent->OnFramebufferSizeChanged();
  84. }
  85. void DisablePainting() {
  86. do_painting = false;
  87. }
  88. void EnablePainting() {
  89. do_painting = true;
  90. }
  91. private:
  92. GRenderWindow* parent;
  93. bool do_painting;
  94. };
  95. GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread)
  96. : QWidget(parent), child(nullptr), emu_thread(emu_thread) {
  97. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  98. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  99. setAttribute(Qt::WA_AcceptTouchEvents);
  100. InputCommon::Init();
  101. connect(this, &GRenderWindow::FirstFrameDisplayed, static_cast<GMainWindow*>(parent),
  102. &GMainWindow::OnLoadComplete);
  103. }
  104. GRenderWindow::~GRenderWindow() {
  105. InputCommon::Shutdown();
  106. }
  107. void GRenderWindow::moveContext() {
  108. DoneCurrent();
  109. // If the thread started running, move the GL Context to the new thread. Otherwise, move it
  110. // back.
  111. auto thread = (QThread::currentThread() == qApp->thread() && emu_thread != nullptr)
  112. ? emu_thread
  113. : qApp->thread();
  114. child->context()->moveToThread(thread);
  115. }
  116. void GRenderWindow::SwapBuffers() {
  117. // In our multi-threaded QGLWidget use case we shouldn't need to call `makeCurrent`,
  118. // since we never call `doneCurrent` in this thread.
  119. // However:
  120. // - The Qt debug runtime prints a bogus warning on the console if `makeCurrent` wasn't called
  121. // since the last time `swapBuffers` was executed;
  122. // - On macOS, if `makeCurrent` isn't called explicitely, resizing the buffer breaks.
  123. child->makeCurrent();
  124. child->swapBuffers();
  125. if (!first_frame) {
  126. emit FirstFrameDisplayed();
  127. first_frame = true;
  128. }
  129. }
  130. void GRenderWindow::MakeCurrent() {
  131. child->makeCurrent();
  132. }
  133. void GRenderWindow::DoneCurrent() {
  134. child->doneCurrent();
  135. }
  136. void GRenderWindow::PollEvents() {}
  137. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  138. //
  139. // Older versions get the window size (density independent pixels),
  140. // and hence, do not support DPI scaling ("retina" displays).
  141. // The result will be a viewport that is smaller than the extent of the window.
  142. void GRenderWindow::OnFramebufferSizeChanged() {
  143. // Screen changes potentially incur a change in screen DPI, hence we should update the
  144. // framebuffer size
  145. qreal pixelRatio = windowPixelRatio();
  146. unsigned width = child->QPaintDevice::width() * pixelRatio;
  147. unsigned height = child->QPaintDevice::height() * pixelRatio;
  148. UpdateCurrentFramebufferLayout(width, height);
  149. }
  150. void GRenderWindow::BackupGeometry() {
  151. geometry = ((QGLWidget*)this)->saveGeometry();
  152. }
  153. void GRenderWindow::RestoreGeometry() {
  154. // We don't want to back up the geometry here (obviously)
  155. QWidget::restoreGeometry(geometry);
  156. }
  157. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  158. // Make sure users of this class don't need to deal with backing up the geometry themselves
  159. QWidget::restoreGeometry(geometry);
  160. BackupGeometry();
  161. }
  162. QByteArray GRenderWindow::saveGeometry() {
  163. // If we are a top-level widget, store the current geometry
  164. // otherwise, store the last backup
  165. if (parent() == nullptr)
  166. return ((QGLWidget*)this)->saveGeometry();
  167. else
  168. return geometry;
  169. }
  170. qreal GRenderWindow::windowPixelRatio() const {
  171. // windowHandle() might not be accessible until the window is displayed to screen.
  172. return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f;
  173. }
  174. std::pair<unsigned, unsigned> GRenderWindow::ScaleTouch(const QPointF pos) const {
  175. const qreal pixel_ratio = windowPixelRatio();
  176. return {static_cast<unsigned>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  177. static_cast<unsigned>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  178. }
  179. void GRenderWindow::closeEvent(QCloseEvent* event) {
  180. emit Closed();
  181. QWidget::closeEvent(event);
  182. }
  183. void GRenderWindow::keyPressEvent(QKeyEvent* event) {
  184. InputCommon::GetKeyboard()->PressKey(event->key());
  185. }
  186. void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
  187. InputCommon::GetKeyboard()->ReleaseKey(event->key());
  188. }
  189. void GRenderWindow::mousePressEvent(QMouseEvent* event) {
  190. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  191. return; // touch input is handled in TouchBeginEvent
  192. auto pos = event->pos();
  193. if (event->button() == Qt::LeftButton) {
  194. const auto [x, y] = ScaleTouch(pos);
  195. this->TouchPressed(x, y);
  196. } else if (event->button() == Qt::RightButton) {
  197. InputCommon::GetMotionEmu()->BeginTilt(pos.x(), pos.y());
  198. }
  199. }
  200. void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
  201. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  202. return; // touch input is handled in TouchUpdateEvent
  203. auto pos = event->pos();
  204. const auto [x, y] = ScaleTouch(pos);
  205. this->TouchMoved(x, y);
  206. InputCommon::GetMotionEmu()->Tilt(pos.x(), pos.y());
  207. }
  208. void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
  209. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  210. return; // touch input is handled in TouchEndEvent
  211. if (event->button() == Qt::LeftButton)
  212. this->TouchReleased();
  213. else if (event->button() == Qt::RightButton)
  214. InputCommon::GetMotionEmu()->EndTilt();
  215. }
  216. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  217. // TouchBegin always has exactly one touch point, so take the .first()
  218. const auto [x, y] = ScaleTouch(event->touchPoints().first().pos());
  219. this->TouchPressed(x, y);
  220. }
  221. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  222. QPointF pos;
  223. int active_points = 0;
  224. // average all active touch points
  225. for (const auto tp : event->touchPoints()) {
  226. if (tp.state() & (Qt::TouchPointPressed | Qt::TouchPointMoved | Qt::TouchPointStationary)) {
  227. active_points++;
  228. pos += tp.pos();
  229. }
  230. }
  231. pos /= active_points;
  232. const auto [x, y] = ScaleTouch(pos);
  233. this->TouchMoved(x, y);
  234. }
  235. void GRenderWindow::TouchEndEvent() {
  236. this->TouchReleased();
  237. }
  238. bool GRenderWindow::event(QEvent* event) {
  239. if (event->type() == QEvent::TouchBegin) {
  240. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  241. return true;
  242. } else if (event->type() == QEvent::TouchUpdate) {
  243. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  244. return true;
  245. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  246. TouchEndEvent();
  247. return true;
  248. }
  249. return QWidget::event(event);
  250. }
  251. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  252. QWidget::focusOutEvent(event);
  253. InputCommon::GetKeyboard()->ReleaseAllKeys();
  254. }
  255. void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height) {
  256. NotifyClientAreaSizeChanged(std::make_pair(width, height));
  257. }
  258. void GRenderWindow::InitRenderTarget() {
  259. if (child) {
  260. delete child;
  261. }
  262. if (layout()) {
  263. delete layout();
  264. }
  265. first_frame = false;
  266. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  267. // WA_DontShowOnScreen, WA_DeleteOnClose
  268. QGLFormat fmt;
  269. fmt.setVersion(4, 3);
  270. fmt.setProfile(QGLFormat::CoreProfile);
  271. fmt.setSwapInterval(false);
  272. // Requests a forward-compatible context, which is required to get a 3.2+ context on OS X
  273. fmt.setOption(QGL::NoDeprecatedFunctions);
  274. child = new GGLWidgetInternal(fmt, this);
  275. QBoxLayout* layout = new QHBoxLayout(this);
  276. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  277. layout->addWidget(child);
  278. layout->setMargin(0);
  279. setLayout(layout);
  280. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  281. OnFramebufferSizeChanged();
  282. NotifyClientAreaSizeChanged(std::pair<unsigned, unsigned>(child->width(), child->height()));
  283. BackupGeometry();
  284. }
  285. void GRenderWindow::CaptureScreenshot(u16 res_scale, const QString& screenshot_path) {
  286. auto& renderer = Core::System::GetInstance().Renderer();
  287. if (!res_scale)
  288. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  289. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  290. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  291. renderer.RequestScreenshot(screenshot_image.bits(),
  292. [=] {
  293. screenshot_image.mirrored(false, true).save(screenshot_path);
  294. LOG_INFO(Frontend, "The screenshot is saved.");
  295. },
  296. layout);
  297. }
  298. void GRenderWindow::OnMinimalClientAreaChangeRequest(
  299. const std::pair<unsigned, unsigned>& minimal_size) {
  300. setMinimumSize(minimal_size.first, minimal_size.second);
  301. }
  302. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  303. this->emu_thread = emu_thread;
  304. child->DisablePainting();
  305. }
  306. void GRenderWindow::OnEmulationStopping() {
  307. emu_thread = nullptr;
  308. child->EnablePainting();
  309. }
  310. void GRenderWindow::showEvent(QShowEvent* event) {
  311. QWidget::showEvent(event);
  312. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  313. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  314. Qt::UniqueConnection);
  315. }