main.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cinttypes>
  5. #include <clocale>
  6. #include <memory>
  7. #include <thread>
  8. #include <glad/glad.h>
  9. #define QT_NO_OPENGL
  10. #include <QDesktopWidget>
  11. #include <QFileDialog>
  12. #include <QMessageBox>
  13. #include <QtGui>
  14. #include <QtWidgets>
  15. #include "citra_qt/bootmanager.h"
  16. #include "citra_qt/configuration/config.h"
  17. #include "citra_qt/configuration/configure_dialog.h"
  18. #include "citra_qt/debugger/graphics/graphics.h"
  19. #include "citra_qt/debugger/graphics/graphics_breakpoints.h"
  20. #include "citra_qt/debugger/graphics/graphics_cmdlists.h"
  21. #include "citra_qt/debugger/graphics/graphics_surface.h"
  22. #include "citra_qt/debugger/graphics/graphics_tracing.h"
  23. #include "citra_qt/debugger/graphics/graphics_vertex_shader.h"
  24. #include "citra_qt/debugger/profiler.h"
  25. #include "citra_qt/debugger/registers.h"
  26. #include "citra_qt/debugger/wait_tree.h"
  27. #include "citra_qt/game_list.h"
  28. #include "citra_qt/hotkeys.h"
  29. #include "citra_qt/main.h"
  30. #include "citra_qt/ui_settings.h"
  31. #include "common/logging/backend.h"
  32. #include "common/logging/filter.h"
  33. #include "common/logging/log.h"
  34. #include "common/logging/text_formatter.h"
  35. #include "common/microprofile.h"
  36. #include "common/platform.h"
  37. #include "common/scm_rev.h"
  38. #include "common/scope_exit.h"
  39. #include "common/string_util.h"
  40. #include "core/core.h"
  41. #include "core/file_sys/archive_source_sd_savedata.h"
  42. #include "core/gdbstub/gdbstub.h"
  43. #include "core/loader/loader.h"
  44. #include "core/settings.h"
  45. #ifdef QT_STATICPLUGIN
  46. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  47. #endif
  48. /**
  49. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  50. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  51. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones.
  52. */
  53. enum class CalloutFlag : uint32_t {
  54. Telemetry = 0x1,
  55. };
  56. static void ShowCalloutMessage(const QString& message, CalloutFlag flag) {
  57. if (UISettings::values.callout_flags & static_cast<uint32_t>(flag)) {
  58. return;
  59. }
  60. UISettings::values.callout_flags |= static_cast<uint32_t>(flag);
  61. QMessageBox msg;
  62. msg.setText(message);
  63. msg.setStandardButtons(QMessageBox::Ok);
  64. msg.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  65. msg.setStyleSheet("QLabel{min-width: 900px;}");
  66. msg.exec();
  67. }
  68. void GMainWindow::ShowCallouts() {
  69. static const QString telemetry_message =
  70. tr("To help improve Citra, the Citra Team collects anonymous usage data. No private or "
  71. "personally identifying information is collected. This data helps us to understand how "
  72. "people use Citra and prioritize our efforts. Furthermore, it helps us to more easily "
  73. "identify emulation bugs and performance issues. This data includes:<ul><li>Information"
  74. " about the version of Citra you are using</li><li>Performance data about the games you "
  75. "play</li><li>Your configuration settings</li><li>Information about your computer "
  76. "hardware</li><li>Emulation errors and crash information</li></ul>By default, this "
  77. "feature is enabled. To disable this feature, click 'Emulation' from the menu and then "
  78. "select 'Configure...'. Then, on the 'Web' tab, uncheck 'Share anonymous usage data with"
  79. " the Citra team'. <br/><br/>By using this software, you agree to the above terms.<br/>"
  80. "<br/><a href='https://citra-emu.org/entry/telemetry-and-why-thats-a-good-thing/'>Learn "
  81. "more</a>");
  82. ShowCalloutMessage(telemetry_message, CalloutFlag::Telemetry);
  83. }
  84. GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) {
  85. Pica::g_debug_context = Pica::DebugContext::Construct();
  86. setAcceptDrops(true);
  87. ui.setupUi(this);
  88. statusBar()->hide();
  89. InitializeWidgets();
  90. InitializeDebugWidgets();
  91. InitializeRecentFileMenuActions();
  92. InitializeHotkeys();
  93. SetDefaultUIGeometry();
  94. RestoreUIState();
  95. ConnectMenuEvents();
  96. ConnectWidgetEvents();
  97. setWindowTitle(QString("Citra %1| %2-%3")
  98. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  99. show();
  100. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  101. UpdateUITheme();
  102. // Show one-time "callout" messages to the user
  103. ShowCallouts();
  104. QStringList args = QApplication::arguments();
  105. if (args.length() >= 2) {
  106. BootGame(args[1]);
  107. }
  108. }
  109. GMainWindow::~GMainWindow() {
  110. // will get automatically deleted otherwise
  111. if (render_window->parent() == nullptr)
  112. delete render_window;
  113. Pica::g_debug_context.reset();
  114. }
  115. void GMainWindow::InitializeWidgets() {
  116. render_window = new GRenderWindow(this, emu_thread.get());
  117. render_window->hide();
  118. game_list = new GameList(this);
  119. ui.horizontalLayout->addWidget(game_list);
  120. // Create status bar
  121. message_label = new QLabel();
  122. // Configured separately for left alignment
  123. message_label->setVisible(false);
  124. message_label->setFrameStyle(QFrame::NoFrame);
  125. message_label->setContentsMargins(4, 0, 4, 0);
  126. message_label->setAlignment(Qt::AlignLeft);
  127. statusBar()->addPermanentWidget(message_label, 1);
  128. emu_speed_label = new QLabel();
  129. emu_speed_label->setToolTip(tr("Current emulation speed. Values higher or lower than 100% "
  130. "indicate emulation is running faster or slower than a 3DS."));
  131. game_fps_label = new QLabel();
  132. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  133. "This will vary from game to game and scene to scene."));
  134. emu_frametime_label = new QLabel();
  135. emu_frametime_label->setToolTip(
  136. tr("Time taken to emulate a 3DS frame, not counting framelimiting or v-sync. For "
  137. "full-speed emulation this should be at most 16.67 ms."));
  138. for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
  139. label->setVisible(false);
  140. label->setFrameStyle(QFrame::NoFrame);
  141. label->setContentsMargins(4, 0, 4, 0);
  142. statusBar()->addPermanentWidget(label, 0);
  143. }
  144. statusBar()->setVisible(true);
  145. setStyleSheet("QStatusBar::item{border: none;}");
  146. }
  147. void GMainWindow::InitializeDebugWidgets() {
  148. connect(ui.action_Create_Pica_Surface_Viewer, &QAction::triggered, this,
  149. &GMainWindow::OnCreateGraphicsSurfaceViewer);
  150. QMenu* debug_menu = ui.menu_View_Debugging;
  151. #if MICROPROFILE_ENABLED
  152. microProfileDialog = new MicroProfileDialog(this);
  153. microProfileDialog->hide();
  154. debug_menu->addAction(microProfileDialog->toggleViewAction());
  155. #endif
  156. registersWidget = new RegistersWidget(this);
  157. addDockWidget(Qt::RightDockWidgetArea, registersWidget);
  158. registersWidget->hide();
  159. debug_menu->addAction(registersWidget->toggleViewAction());
  160. connect(this, &GMainWindow::EmulationStarting, registersWidget,
  161. &RegistersWidget::OnEmulationStarting);
  162. connect(this, &GMainWindow::EmulationStopping, registersWidget,
  163. &RegistersWidget::OnEmulationStopping);
  164. graphicsWidget = new GPUCommandStreamWidget(this);
  165. addDockWidget(Qt::RightDockWidgetArea, graphicsWidget);
  166. graphicsWidget->hide();
  167. debug_menu->addAction(graphicsWidget->toggleViewAction());
  168. graphicsCommandsWidget = new GPUCommandListWidget(this);
  169. addDockWidget(Qt::RightDockWidgetArea, graphicsCommandsWidget);
  170. graphicsCommandsWidget->hide();
  171. debug_menu->addAction(graphicsCommandsWidget->toggleViewAction());
  172. graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(Pica::g_debug_context, this);
  173. addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
  174. graphicsBreakpointsWidget->hide();
  175. debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
  176. graphicsVertexShaderWidget = new GraphicsVertexShaderWidget(Pica::g_debug_context, this);
  177. addDockWidget(Qt::RightDockWidgetArea, graphicsVertexShaderWidget);
  178. graphicsVertexShaderWidget->hide();
  179. debug_menu->addAction(graphicsVertexShaderWidget->toggleViewAction());
  180. graphicsTracingWidget = new GraphicsTracingWidget(Pica::g_debug_context, this);
  181. addDockWidget(Qt::RightDockWidgetArea, graphicsTracingWidget);
  182. graphicsTracingWidget->hide();
  183. debug_menu->addAction(graphicsTracingWidget->toggleViewAction());
  184. connect(this, &GMainWindow::EmulationStarting, graphicsTracingWidget,
  185. &GraphicsTracingWidget::OnEmulationStarting);
  186. connect(this, &GMainWindow::EmulationStopping, graphicsTracingWidget,
  187. &GraphicsTracingWidget::OnEmulationStopping);
  188. waitTreeWidget = new WaitTreeWidget(this);
  189. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  190. waitTreeWidget->hide();
  191. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  192. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  193. &WaitTreeWidget::OnEmulationStarting);
  194. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  195. &WaitTreeWidget::OnEmulationStopping);
  196. }
  197. void GMainWindow::InitializeRecentFileMenuActions() {
  198. for (int i = 0; i < max_recent_files_item; ++i) {
  199. actions_recent_files[i] = new QAction(this);
  200. actions_recent_files[i]->setVisible(false);
  201. connect(actions_recent_files[i], SIGNAL(triggered()), this, SLOT(OnMenuRecentFile()));
  202. ui.menu_recent_files->addAction(actions_recent_files[i]);
  203. }
  204. UpdateRecentFiles();
  205. }
  206. void GMainWindow::InitializeHotkeys() {
  207. RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
  208. RegisterHotkey("Main Window", "Swap Screens", QKeySequence::NextChild);
  209. RegisterHotkey("Main Window", "Start Emulation");
  210. LoadHotkeys();
  211. connect(GetHotkey("Main Window", "Load File", this), SIGNAL(activated()), this,
  212. SLOT(OnMenuLoadFile()));
  213. connect(GetHotkey("Main Window", "Start Emulation", this), SIGNAL(activated()), this,
  214. SLOT(OnStartGame()));
  215. connect(GetHotkey("Main Window", "Swap Screens", render_window), SIGNAL(activated()), this,
  216. SLOT(OnSwapScreens()));
  217. }
  218. void GMainWindow::SetDefaultUIGeometry() {
  219. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  220. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  221. const int w = screenRect.width() * 2 / 3;
  222. const int h = screenRect.height() / 2;
  223. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  224. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  225. setGeometry(x, y, w, h);
  226. }
  227. void GMainWindow::RestoreUIState() {
  228. restoreGeometry(UISettings::values.geometry);
  229. restoreState(UISettings::values.state);
  230. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  231. #if MICROPROFILE_ENABLED
  232. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  233. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  234. #endif
  235. game_list->LoadInterfaceLayout();
  236. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  237. ToggleWindowMode();
  238. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  239. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  240. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  241. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  242. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  243. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  244. }
  245. void GMainWindow::ConnectWidgetEvents() {
  246. connect(game_list, SIGNAL(GameChosen(QString)), this, SLOT(OnGameListLoadFile(QString)));
  247. connect(game_list, SIGNAL(OpenSaveFolderRequested(u64)), this,
  248. SLOT(OnGameListOpenSaveFolder(u64)));
  249. connect(this, SIGNAL(EmulationStarting(EmuThread*)), render_window,
  250. SLOT(OnEmulationStarting(EmuThread*)));
  251. connect(this, SIGNAL(EmulationStopping()), render_window, SLOT(OnEmulationStopping()));
  252. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  253. }
  254. void GMainWindow::ConnectMenuEvents() {
  255. // File
  256. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  257. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  258. &GMainWindow::OnMenuSelectGameListRoot);
  259. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  260. // Emulation
  261. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  262. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  263. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  264. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  265. // View
  266. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  267. &GMainWindow::ToggleWindowMode);
  268. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  269. &GMainWindow::OnDisplayTitleBars);
  270. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  271. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  272. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  273. }
  274. void GMainWindow::OnDisplayTitleBars(bool show) {
  275. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  276. if (show) {
  277. for (QDockWidget* widget : widgets) {
  278. QWidget* old = widget->titleBarWidget();
  279. widget->setTitleBarWidget(nullptr);
  280. if (old != nullptr)
  281. delete old;
  282. }
  283. } else {
  284. for (QDockWidget* widget : widgets) {
  285. QWidget* old = widget->titleBarWidget();
  286. widget->setTitleBarWidget(new QWidget());
  287. if (old != nullptr)
  288. delete old;
  289. }
  290. }
  291. }
  292. bool GMainWindow::LoadROM(const QString& filename) {
  293. // Shutdown previous session if the emu thread is still active...
  294. if (emu_thread != nullptr)
  295. ShutdownGame();
  296. render_window->InitRenderTarget();
  297. render_window->MakeCurrent();
  298. if (!gladLoadGL()) {
  299. QMessageBox::critical(this, tr("Error while initializing OpenGL 3.3 Core!"),
  300. tr("Your GPU may not support OpenGL 3.3, or you do not "
  301. "have the latest graphics driver."));
  302. return false;
  303. }
  304. Core::System& system{Core::System::GetInstance()};
  305. const Core::System::ResultStatus result{system.Load(render_window, filename.toStdString())};
  306. if (result != Core::System::ResultStatus::Success) {
  307. switch (result) {
  308. case Core::System::ResultStatus::ErrorGetLoader:
  309. LOG_CRITICAL(Frontend, "Failed to obtain loader for %s!",
  310. filename.toStdString().c_str());
  311. QMessageBox::critical(this, tr("Error while loading ROM!"),
  312. tr("The ROM format is not supported."));
  313. break;
  314. case Core::System::ResultStatus::ErrorSystemMode:
  315. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  316. QMessageBox::critical(this, tr("Error while loading ROM!"),
  317. tr("Could not determine the system mode."));
  318. break;
  319. case Core::System::ResultStatus::ErrorLoader_ErrorEncrypted: {
  320. QMessageBox::critical(
  321. this, tr("Error while loading ROM!"),
  322. tr("The game that you are trying to load must be decrypted before being used with "
  323. "Citra. A real 3DS is required.<br/><br/>"
  324. "For more information on dumping and decrypting games, please see the following "
  325. "wiki pages: <ul>"
  326. "<li><a href='https://citra-emu.org/wiki/dumping-game-cartridges/'>Dumping Game "
  327. "Cartridges</a></li>"
  328. "<li><a href='https://citra-emu.org/wiki/dumping-installed-titles/'>Dumping "
  329. "Installed Titles</a></li>"
  330. "</ul>"));
  331. break;
  332. }
  333. case Core::System::ResultStatus::ErrorLoader_ErrorInvalidFormat:
  334. QMessageBox::critical(this, tr("Error while loading ROM!"),
  335. tr("The ROM format is not supported."));
  336. break;
  337. case Core::System::ResultStatus::ErrorVideoCore:
  338. QMessageBox::critical(
  339. this, tr("An error occured in the video core."),
  340. tr("Citra has encountered an error while running the video core, please see the "
  341. "log for more details."
  342. "For more information on accessing the log, please see the following page: "
  343. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  344. "to "
  345. "Upload the Log File</a>."
  346. "Ensure that you have the latest graphics drivers for your GPU."));
  347. break;
  348. default:
  349. QMessageBox::critical(
  350. this, tr("Error while loading ROM!"),
  351. tr("An unknown error occured. Please see the log for more details."));
  352. break;
  353. }
  354. return false;
  355. }
  356. return true;
  357. }
  358. void GMainWindow::BootGame(const QString& filename) {
  359. LOG_INFO(Frontend, "Citra starting...");
  360. StoreRecentFile(filename); // Put the filename on top of the list
  361. if (!LoadROM(filename))
  362. return;
  363. // Create and start the emulation thread
  364. emu_thread = std::make_unique<EmuThread>(render_window);
  365. emit EmulationStarting(emu_thread.get());
  366. render_window->moveContext();
  367. emu_thread->start();
  368. connect(render_window, SIGNAL(Closed()), this, SLOT(OnStopGame()));
  369. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  370. // before the CPU continues
  371. connect(emu_thread.get(), SIGNAL(DebugModeEntered()), registersWidget,
  372. SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
  373. connect(emu_thread.get(), SIGNAL(DebugModeEntered()), waitTreeWidget,
  374. SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
  375. connect(emu_thread.get(), SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()),
  376. Qt::BlockingQueuedConnection);
  377. connect(emu_thread.get(), SIGNAL(DebugModeLeft()), waitTreeWidget, SLOT(OnDebugModeLeft()),
  378. Qt::BlockingQueuedConnection);
  379. // Update the GUI
  380. registersWidget->OnDebugModeEntered();
  381. if (ui.action_Single_Window_Mode->isChecked()) {
  382. game_list->hide();
  383. }
  384. status_bar_update_timer.start(2000);
  385. render_window->show();
  386. render_window->setFocus();
  387. emulation_running = true;
  388. OnStartGame();
  389. }
  390. void GMainWindow::ShutdownGame() {
  391. emu_thread->RequestStop();
  392. // Release emu threads from any breakpoints
  393. // This belongs after RequestStop() and before wait() because if emulation stops on a GPU
  394. // breakpoint after (or before) RequestStop() is called, the emulation would never be able
  395. // to continue out to the main loop and terminate. Thus wait() would hang forever.
  396. // TODO(bunnei): This function is not thread safe, but it's being used as if it were
  397. Pica::g_debug_context->ClearBreakpoints();
  398. emit EmulationStopping();
  399. // Wait for emulation thread to complete and delete it
  400. emu_thread->wait();
  401. emu_thread = nullptr;
  402. // The emulation is stopped, so closing the window or not does not matter anymore
  403. disconnect(render_window, SIGNAL(Closed()), this, SLOT(OnStopGame()));
  404. // Update the GUI
  405. ui.action_Start->setEnabled(false);
  406. ui.action_Start->setText(tr("Start"));
  407. ui.action_Pause->setEnabled(false);
  408. ui.action_Stop->setEnabled(false);
  409. render_window->hide();
  410. game_list->show();
  411. game_list->setFilterFocus();
  412. // Disable status bar updates
  413. status_bar_update_timer.stop();
  414. message_label->setVisible(false);
  415. emu_speed_label->setVisible(false);
  416. game_fps_label->setVisible(false);
  417. emu_frametime_label->setVisible(false);
  418. emulation_running = false;
  419. }
  420. void GMainWindow::StoreRecentFile(const QString& filename) {
  421. UISettings::values.recent_files.prepend(filename);
  422. UISettings::values.recent_files.removeDuplicates();
  423. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  424. UISettings::values.recent_files.removeLast();
  425. }
  426. UpdateRecentFiles();
  427. }
  428. void GMainWindow::UpdateRecentFiles() {
  429. unsigned int num_recent_files =
  430. std::min(UISettings::values.recent_files.size(), static_cast<int>(max_recent_files_item));
  431. for (unsigned int i = 0; i < num_recent_files; i++) {
  432. QString text = QString("&%1. %2").arg(i + 1).arg(
  433. QFileInfo(UISettings::values.recent_files[i]).fileName());
  434. actions_recent_files[i]->setText(text);
  435. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  436. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  437. actions_recent_files[i]->setVisible(true);
  438. }
  439. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  440. actions_recent_files[j]->setVisible(false);
  441. }
  442. // Grey out the recent files menu if the list is empty
  443. if (num_recent_files == 0) {
  444. ui.menu_recent_files->setEnabled(false);
  445. } else {
  446. ui.menu_recent_files->setEnabled(true);
  447. }
  448. }
  449. void GMainWindow::OnGameListLoadFile(QString game_path) {
  450. BootGame(game_path);
  451. }
  452. void GMainWindow::OnGameListOpenSaveFolder(u64 program_id) {
  453. std::string sdmc_dir = FileUtil::GetUserPath(D_SDMC_IDX);
  454. std::string path = FileSys::ArchiveSource_SDSaveData::GetSaveDataPathFor(sdmc_dir, program_id);
  455. QString qpath = QString::fromStdString(path);
  456. QDir dir(qpath);
  457. if (!dir.exists()) {
  458. QMessageBox::critical(this, tr("Error Opening Save Folder"), tr("Folder does not exist!"));
  459. return;
  460. }
  461. LOG_INFO(Frontend, "Opening save data path for program_id=%" PRIu64, program_id);
  462. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  463. }
  464. void GMainWindow::OnMenuLoadFile() {
  465. QString extensions;
  466. for (const auto& piece : game_list->supported_file_extensions)
  467. extensions += "*." + piece + " ";
  468. QString file_filter = tr("3DS Executable") + " (" + extensions + ")";
  469. file_filter += ";;" + tr("All Files (*.*)");
  470. QString filename = QFileDialog::getOpenFileName(this, tr("Load File"),
  471. UISettings::values.roms_path, file_filter);
  472. if (!filename.isEmpty()) {
  473. UISettings::values.roms_path = QFileInfo(filename).path();
  474. BootGame(filename);
  475. }
  476. }
  477. void GMainWindow::OnMenuSelectGameListRoot() {
  478. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  479. if (!dir_path.isEmpty()) {
  480. UISettings::values.gamedir = dir_path;
  481. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  482. }
  483. }
  484. void GMainWindow::OnMenuRecentFile() {
  485. QAction* action = qobject_cast<QAction*>(sender());
  486. assert(action);
  487. QString filename = action->data().toString();
  488. QFileInfo file_info(filename);
  489. if (file_info.exists()) {
  490. BootGame(filename);
  491. } else {
  492. // Display an error message and remove the file from the list.
  493. QMessageBox::information(this, tr("File not found"),
  494. tr("File \"%1\" not found").arg(filename));
  495. UISettings::values.recent_files.removeOne(filename);
  496. UpdateRecentFiles();
  497. }
  498. }
  499. void GMainWindow::OnStartGame() {
  500. emu_thread->SetRunning(true);
  501. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  502. qRegisterMetaType<std::string>("std::string");
  503. connect(emu_thread.get(), SIGNAL(ErrorThrown(Core::System::ResultStatus, std::string)), this,
  504. SLOT(OnCoreError(Core::System::ResultStatus, std::string)));
  505. ui.action_Start->setEnabled(false);
  506. ui.action_Start->setText(tr("Continue"));
  507. ui.action_Pause->setEnabled(true);
  508. ui.action_Stop->setEnabled(true);
  509. }
  510. void GMainWindow::OnPauseGame() {
  511. emu_thread->SetRunning(false);
  512. ui.action_Start->setEnabled(true);
  513. ui.action_Pause->setEnabled(false);
  514. ui.action_Stop->setEnabled(true);
  515. }
  516. void GMainWindow::OnStopGame() {
  517. ShutdownGame();
  518. }
  519. void GMainWindow::ToggleWindowMode() {
  520. if (ui.action_Single_Window_Mode->isChecked()) {
  521. // Render in the main window...
  522. render_window->BackupGeometry();
  523. ui.horizontalLayout->addWidget(render_window);
  524. render_window->setFocusPolicy(Qt::ClickFocus);
  525. if (emulation_running) {
  526. render_window->setVisible(true);
  527. render_window->setFocus();
  528. game_list->hide();
  529. }
  530. } else {
  531. // Render in a separate window...
  532. ui.horizontalLayout->removeWidget(render_window);
  533. render_window->setParent(nullptr);
  534. render_window->setFocusPolicy(Qt::NoFocus);
  535. if (emulation_running) {
  536. render_window->setVisible(true);
  537. render_window->RestoreGeometry();
  538. game_list->show();
  539. }
  540. }
  541. }
  542. void GMainWindow::OnConfigure() {
  543. ConfigureDialog configureDialog(this);
  544. auto result = configureDialog.exec();
  545. if (result == QDialog::Accepted) {
  546. configureDialog.applyConfiguration();
  547. UpdateUITheme();
  548. config->Save();
  549. }
  550. }
  551. void GMainWindow::OnToggleFilterBar() {
  552. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  553. if (ui.action_Show_Filter_Bar->isChecked()) {
  554. game_list->setFilterFocus();
  555. } else {
  556. game_list->clearFilter();
  557. }
  558. }
  559. void GMainWindow::OnSwapScreens() {
  560. Settings::values.swap_screen = !Settings::values.swap_screen;
  561. Settings::Apply();
  562. }
  563. void GMainWindow::OnCreateGraphicsSurfaceViewer() {
  564. auto graphicsSurfaceViewerWidget = new GraphicsSurfaceWidget(Pica::g_debug_context, this);
  565. addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceViewerWidget);
  566. // TODO: Maybe graphicsSurfaceViewerWidget->setFloating(true);
  567. graphicsSurfaceViewerWidget->show();
  568. }
  569. void GMainWindow::UpdateStatusBar() {
  570. if (emu_thread == nullptr) {
  571. status_bar_update_timer.stop();
  572. return;
  573. }
  574. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  575. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  576. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  577. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  578. emu_speed_label->setVisible(true);
  579. game_fps_label->setVisible(true);
  580. emu_frametime_label->setVisible(true);
  581. }
  582. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  583. QMessageBox::StandardButton answer;
  584. QString status_message;
  585. const QString common_message =
  586. tr("The game you are trying to load requires additional files from your 3DS to be dumped "
  587. "before playing.<br/><br/>For more information on dumping these files, please see the "
  588. "following wiki page: <a "
  589. "href='https://citra-emu.org/wiki/"
  590. "dumping-system-archives-and-the-shared-fonts-from-a-3ds-console/'>Dumping System "
  591. "Archives and the Shared Fonts from a 3DS Console</a>.<br/><br/>Would you like to quit "
  592. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  593. "data, or other bugs.");
  594. switch (result) {
  595. case Core::System::ResultStatus::ErrorSystemFiles: {
  596. QString message = "Citra was unable to locate a 3DS system archive";
  597. if (!details.empty()) {
  598. message.append(tr(": %1. ").arg(details.c_str()));
  599. } else {
  600. message.append(". ");
  601. }
  602. message.append(common_message);
  603. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  604. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  605. status_message = "System Archive Missing";
  606. break;
  607. }
  608. case Core::System::ResultStatus::ErrorSharedFont: {
  609. QString message = tr("Citra was unable to locate the 3DS shared fonts. ");
  610. message.append(common_message);
  611. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  612. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  613. status_message = "Shared Font Missing";
  614. break;
  615. }
  616. default:
  617. answer = QMessageBox::question(
  618. this, tr("Fatal Error"),
  619. tr("Citra has encountered a fatal error, please see the log for more details. "
  620. "For more information on accessing the log, please see the following page: "
  621. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How to "
  622. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game list? "
  623. "Continuing emulation may result in crashes, corrupted save data, or other bugs."),
  624. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  625. status_message = "Fatal Error encountered";
  626. break;
  627. }
  628. if (answer == QMessageBox::Yes) {
  629. if (emu_thread) {
  630. ShutdownGame();
  631. }
  632. } else {
  633. // Only show the message if the game is still running.
  634. if (emu_thread) {
  635. message_label->setText(status_message);
  636. message_label->setVisible(true);
  637. }
  638. }
  639. }
  640. bool GMainWindow::ConfirmClose() {
  641. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  642. return true;
  643. QMessageBox::StandardButton answer =
  644. QMessageBox::question(this, tr("Citra"), tr("Are you sure you want to close Citra?"),
  645. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  646. return answer != QMessageBox::No;
  647. }
  648. void GMainWindow::closeEvent(QCloseEvent* event) {
  649. if (!ConfirmClose()) {
  650. event->ignore();
  651. return;
  652. }
  653. UISettings::values.geometry = saveGeometry();
  654. UISettings::values.state = saveState();
  655. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  656. #if MICROPROFILE_ENABLED
  657. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  658. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  659. #endif
  660. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  661. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  662. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  663. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  664. UISettings::values.first_start = false;
  665. game_list->SaveInterfaceLayout();
  666. SaveHotkeys();
  667. // Shutdown session if the emu thread is active...
  668. if (emu_thread != nullptr)
  669. ShutdownGame();
  670. render_window->close();
  671. QWidget::closeEvent(event);
  672. }
  673. static bool IsSingleFileDropEvent(QDropEvent* event) {
  674. const QMimeData* mimeData = event->mimeData();
  675. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  676. }
  677. void GMainWindow::dropEvent(QDropEvent* event) {
  678. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  679. const QMimeData* mimeData = event->mimeData();
  680. QString filename = mimeData->urls().at(0).toLocalFile();
  681. BootGame(filename);
  682. }
  683. }
  684. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  685. if (IsSingleFileDropEvent(event)) {
  686. event->acceptProposedAction();
  687. }
  688. }
  689. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  690. event->acceptProposedAction();
  691. }
  692. bool GMainWindow::ConfirmChangeGame() {
  693. if (emu_thread == nullptr)
  694. return true;
  695. auto answer = QMessageBox::question(
  696. this, tr("Citra"),
  697. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  698. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  699. return answer != QMessageBox::No;
  700. }
  701. void GMainWindow::filterBarSetChecked(bool state) {
  702. ui.action_Show_Filter_Bar->setChecked(state);
  703. emit(OnToggleFilterBar());
  704. }
  705. void GMainWindow::UpdateUITheme() {
  706. if (UISettings::values.theme != UISettings::themes[0].second) {
  707. QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  708. QFile f(theme_uri);
  709. if (!f.exists()) {
  710. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  711. } else {
  712. f.open(QFile::ReadOnly | QFile::Text);
  713. QTextStream ts(&f);
  714. qApp->setStyleSheet(ts.readAll());
  715. GMainWindow::setStyleSheet(ts.readAll());
  716. }
  717. } else {
  718. qApp->setStyleSheet("");
  719. GMainWindow::setStyleSheet("");
  720. }
  721. }
  722. #ifdef main
  723. #undef main
  724. #endif
  725. int main(int argc, char* argv[]) {
  726. Log::Filter log_filter(Log::Level::Info);
  727. Log::SetFilter(&log_filter);
  728. MicroProfileOnThreadCreate("Frontend");
  729. SCOPE_EXIT({ MicroProfileShutdown(); });
  730. // Init settings params
  731. QCoreApplication::setOrganizationName("Citra team");
  732. QCoreApplication::setApplicationName("Citra");
  733. QApplication::setAttribute(Qt::AA_X11InitThreads);
  734. QApplication app(argc, argv);
  735. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  736. // generating shaders
  737. setlocale(LC_ALL, "C");
  738. GMainWindow main_window;
  739. // After settings have been loaded by GMainWindow, apply the filter
  740. log_filter.ParseFilterString(Settings::values.log_filter);
  741. main_window.show();
  742. return app.exec();
  743. }