main.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  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. // VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
  9. #include "applets/profile_select.h"
  10. #include "applets/software_keyboard.h"
  11. #include "applets/web_browser.h"
  12. #include "configuration/configure_per_general.h"
  13. #include "core/file_sys/vfs.h"
  14. #include "core/file_sys/vfs_real.h"
  15. #include "core/hle/service/acc/profile_manager.h"
  16. #include "core/hle/service/am/applets/applets.h"
  17. #include "core/hle/service/hid/controllers/npad.h"
  18. #include "core/hle/service/hid/hid.h"
  19. // These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
  20. // defines.
  21. static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
  22. const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
  23. return vfs->CreateDirectory(path, mode);
  24. }
  25. static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir,
  26. const std::string& path) {
  27. return dir->CreateFile(path);
  28. }
  29. #include <fmt/ostream.h>
  30. #include <glad/glad.h>
  31. #define QT_NO_OPENGL
  32. #include <QDesktopWidget>
  33. #include <QDialogButtonBox>
  34. #include <QFile>
  35. #include <QFileDialog>
  36. #include <QMessageBox>
  37. #include <QtConcurrent/QtConcurrent>
  38. #include <QtGui>
  39. #include <QtWidgets>
  40. #include <fmt/format.h>
  41. #include "common/common_paths.h"
  42. #include "common/detached_tasks.h"
  43. #include "common/file_util.h"
  44. #include "common/logging/backend.h"
  45. #include "common/logging/filter.h"
  46. #include "common/logging/log.h"
  47. #include "common/microprofile.h"
  48. #include "common/scm_rev.h"
  49. #include "common/scope_exit.h"
  50. #include "common/string_util.h"
  51. #include "common/telemetry.h"
  52. #include "core/core.h"
  53. #include "core/crypto/key_manager.h"
  54. #include "core/file_sys/bis_factory.h"
  55. #include "core/file_sys/card_image.h"
  56. #include "core/file_sys/content_archive.h"
  57. #include "core/file_sys/control_metadata.h"
  58. #include "core/file_sys/patch_manager.h"
  59. #include "core/file_sys/registered_cache.h"
  60. #include "core/file_sys/romfs.h"
  61. #include "core/file_sys/savedata_factory.h"
  62. #include "core/file_sys/submission_package.h"
  63. #include "core/frontend/applets/software_keyboard.h"
  64. #include "core/hle/kernel/process.h"
  65. #include "core/hle/service/filesystem/filesystem.h"
  66. #include "core/hle/service/filesystem/fsp_ldr.h"
  67. #include "core/hle/service/nfp/nfp.h"
  68. #include "core/hle/service/sm/sm.h"
  69. #include "core/loader/loader.h"
  70. #include "core/perf_stats.h"
  71. #include "core/settings.h"
  72. #include "core/telemetry_session.h"
  73. #include "video_core/debug_utils/debug_utils.h"
  74. #include "yuzu/about_dialog.h"
  75. #include "yuzu/bootmanager.h"
  76. #include "yuzu/compatdb.h"
  77. #include "yuzu/compatibility_list.h"
  78. #include "yuzu/configuration/config.h"
  79. #include "yuzu/configuration/configure_dialog.h"
  80. #include "yuzu/debugger/console.h"
  81. #include "yuzu/debugger/graphics/graphics_breakpoints.h"
  82. #include "yuzu/debugger/graphics/graphics_surface.h"
  83. #include "yuzu/debugger/profiler.h"
  84. #include "yuzu/debugger/wait_tree.h"
  85. #include "yuzu/discord.h"
  86. #include "yuzu/game_list.h"
  87. #include "yuzu/game_list_p.h"
  88. #include "yuzu/hotkeys.h"
  89. #include "yuzu/loading_screen.h"
  90. #include "yuzu/main.h"
  91. #include "yuzu/ui_settings.h"
  92. #ifdef USE_DISCORD_PRESENCE
  93. #include "yuzu/discord_impl.h"
  94. #endif
  95. #ifdef YUZU_USE_QT_WEB_ENGINE
  96. #include <QWebEngineProfile>
  97. #include <QWebEngineScript>
  98. #include <QWebEngineScriptCollection>
  99. #include <QWebEngineSettings>
  100. #include <QWebEngineView>
  101. #endif
  102. #ifdef QT_STATICPLUGIN
  103. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  104. #endif
  105. #ifdef _WIN32
  106. extern "C" {
  107. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  108. // graphics
  109. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  110. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  111. }
  112. #endif
  113. constexpr u64 DLC_BASE_TITLE_ID_MASK = 0xFFFFFFFFFFFFE000;
  114. /**
  115. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  116. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  117. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones.
  118. */
  119. enum class CalloutFlag : uint32_t {
  120. Telemetry = 0x1,
  121. DRDDeprecation = 0x2,
  122. };
  123. void GMainWindow::ShowTelemetryCallout() {
  124. if (UISettings::values.callout_flags & static_cast<uint32_t>(CalloutFlag::Telemetry)) {
  125. return;
  126. }
  127. UISettings::values.callout_flags |= static_cast<uint32_t>(CalloutFlag::Telemetry);
  128. const QString telemetry_message =
  129. tr("<a href='https://yuzu-emu.org/help/feature/telemetry/'>Anonymous "
  130. "data is collected</a> to help improve yuzu. "
  131. "<br/><br/>Would you like to share your usage data with us?");
  132. if (QMessageBox::question(this, tr("Telemetry"), telemetry_message) != QMessageBox::Yes) {
  133. Settings::values.enable_telemetry = false;
  134. Settings::Apply();
  135. }
  136. }
  137. const int GMainWindow::max_recent_files_item;
  138. static void InitializeLogging() {
  139. Log::Filter log_filter;
  140. log_filter.ParseFilterString(Settings::values.log_filter);
  141. Log::SetGlobalFilter(log_filter);
  142. const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
  143. FileUtil::CreateFullPath(log_dir);
  144. Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
  145. #ifdef _WIN32
  146. Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
  147. #endif
  148. }
  149. GMainWindow::GMainWindow()
  150. : config(new Config()), emu_thread(nullptr),
  151. vfs(std::make_shared<FileSys::RealVfsFilesystem>()) {
  152. InitializeLogging();
  153. debug_context = Tegra::DebugContext::Construct();
  154. setAcceptDrops(true);
  155. ui.setupUi(this);
  156. statusBar()->hide();
  157. default_theme_paths = QIcon::themeSearchPaths();
  158. UpdateUITheme();
  159. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  160. discord_rpc->Update();
  161. InitializeWidgets();
  162. InitializeDebugWidgets();
  163. InitializeRecentFileMenuActions();
  164. InitializeHotkeys();
  165. SetDefaultUIGeometry();
  166. RestoreUIState();
  167. ConnectMenuEvents();
  168. ConnectWidgetEvents();
  169. LOG_INFO(Frontend, "yuzu Version: {} | {}-{}", Common::g_build_fullname, Common::g_scm_branch,
  170. Common::g_scm_desc);
  171. setWindowTitle(QString("yuzu %1| %2-%3")
  172. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  173. show();
  174. // Gen keys if necessary
  175. OnReinitializeKeys(ReinitializeKeyBehavior::NoWarning);
  176. // Necessary to load titles from nand in gamelist.
  177. Service::FileSystem::CreateFactories(*vfs);
  178. game_list->LoadCompatibilityList();
  179. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  180. // Show one-time "callout" messages to the user
  181. ShowTelemetryCallout();
  182. QStringList args = QApplication::arguments();
  183. if (args.length() >= 2) {
  184. BootGame(args[1]);
  185. }
  186. }
  187. GMainWindow::~GMainWindow() {
  188. // will get automatically deleted otherwise
  189. if (render_window->parent() == nullptr)
  190. delete render_window;
  191. }
  192. void GMainWindow::ProfileSelectorSelectProfile() {
  193. QtProfileSelectionDialog dialog(this);
  194. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  195. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  196. dialog.setWindowModality(Qt::WindowModal);
  197. dialog.exec();
  198. if (!dialog.GetStatus()) {
  199. emit ProfileSelectorFinishedSelection(std::nullopt);
  200. return;
  201. }
  202. Service::Account::ProfileManager manager;
  203. const auto uuid = manager.GetUser(dialog.GetIndex());
  204. if (!uuid.has_value()) {
  205. emit ProfileSelectorFinishedSelection(std::nullopt);
  206. return;
  207. }
  208. emit ProfileSelectorFinishedSelection(uuid);
  209. }
  210. void GMainWindow::SoftwareKeyboardGetText(
  211. const Core::Frontend::SoftwareKeyboardParameters& parameters) {
  212. QtSoftwareKeyboardDialog dialog(this, parameters);
  213. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  214. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  215. dialog.setWindowModality(Qt::WindowModal);
  216. dialog.exec();
  217. if (!dialog.GetStatus()) {
  218. emit SoftwareKeyboardFinishedText(std::nullopt);
  219. return;
  220. }
  221. emit SoftwareKeyboardFinishedText(dialog.GetText());
  222. }
  223. void GMainWindow::SoftwareKeyboardInvokeCheckDialog(std::u16string error_message) {
  224. QMessageBox::warning(this, tr("Text Check Failed"), QString::fromStdU16String(error_message));
  225. emit SoftwareKeyboardFinishedCheckDialog();
  226. }
  227. #ifdef YUZU_USE_QT_WEB_ENGINE
  228. void GMainWindow::WebBrowserOpenPage(std::string_view filename, std::string_view additional_args) {
  229. NXInputWebEngineView web_browser_view(this);
  230. // Scope to contain the QProgressDialog for initalization
  231. {
  232. QProgressDialog progress(this);
  233. progress.setMinimumDuration(200);
  234. progress.setLabelText(tr("Loading Web Applet..."));
  235. progress.setRange(0, 4);
  236. progress.setValue(0);
  237. progress.show();
  238. auto future = QtConcurrent::run([this] { emit WebBrowserUnpackRomFS(); });
  239. while (!future.isFinished())
  240. QApplication::processEvents();
  241. progress.setValue(1);
  242. // Load the special shim script to handle input and exit.
  243. QWebEngineScript nx_shim;
  244. nx_shim.setSourceCode(GetNXShimInjectionScript());
  245. nx_shim.setWorldId(QWebEngineScript::MainWorld);
  246. nx_shim.setName("nx_inject.js");
  247. nx_shim.setInjectionPoint(QWebEngineScript::DocumentCreation);
  248. nx_shim.setRunsOnSubFrames(true);
  249. web_browser_view.page()->profile()->scripts()->insert(nx_shim);
  250. web_browser_view.load(
  251. QUrl(QUrl::fromLocalFile(QString::fromStdString(std::string(filename))).toString() +
  252. QString::fromStdString(std::string(additional_args))));
  253. progress.setValue(2);
  254. render_window->hide();
  255. web_browser_view.setFocus();
  256. const auto& layout = render_window->GetFramebufferLayout();
  257. web_browser_view.resize(layout.screen.GetWidth(), layout.screen.GetHeight());
  258. web_browser_view.move(layout.screen.left, layout.screen.top + menuBar()->height());
  259. web_browser_view.setZoomFactor(static_cast<qreal>(layout.screen.GetWidth()) /
  260. Layout::ScreenUndocked::Width);
  261. web_browser_view.settings()->setAttribute(
  262. QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
  263. web_browser_view.show();
  264. progress.setValue(3);
  265. QApplication::processEvents();
  266. progress.setValue(4);
  267. }
  268. bool finished = false;
  269. QAction* exit_action = new QAction(tr("Exit Web Applet"), this);
  270. connect(exit_action, &QAction::triggered, this, [&finished] { finished = true; });
  271. ui.menubar->addAction(exit_action);
  272. auto& npad =
  273. Core::System::GetInstance()
  274. .ServiceManager()
  275. .GetService<Service::HID::Hid>("hid")
  276. ->GetAppletResource()
  277. ->GetController<Service::HID::Controller_NPad>(Service::HID::HidController::NPad);
  278. const auto fire_js_keypress = [&web_browser_view](u32 key_code) {
  279. web_browser_view.page()->runJavaScript(
  280. QStringLiteral("document.dispatchEvent(new KeyboardEvent('keydown', {'key': %1}));")
  281. .arg(QString::fromStdString(std::to_string(key_code))));
  282. };
  283. bool running_exit_check = false;
  284. while (!finished) {
  285. QApplication::processEvents();
  286. if (!running_exit_check) {
  287. web_browser_view.page()->runJavaScript(QStringLiteral("applet_done;"),
  288. [&](const QVariant& res) {
  289. running_exit_check = false;
  290. if (res.toBool())
  291. finished = true;
  292. });
  293. running_exit_check = true;
  294. }
  295. const auto input = npad.GetAndResetPressState();
  296. for (std::size_t i = 0; i < Settings::NativeButton::NumButtons; ++i) {
  297. if ((input & (1 << i)) != 0) {
  298. LOG_DEBUG(Frontend, "firing input for button id={:02X}", i);
  299. web_browser_view.page()->runJavaScript(
  300. QStringLiteral("yuzu_key_callbacks[%1]();").arg(i));
  301. }
  302. }
  303. if (input & 0x00888000) // RStick Down | LStick Down | DPad Down
  304. fire_js_keypress(40); // Down Arrow Key
  305. else if (input & 0x00444000) // RStick Right | LStick Right | DPad Right
  306. fire_js_keypress(39); // Right Arrow Key
  307. else if (input & 0x00222000) // RStick Up | LStick Up | DPad Up
  308. fire_js_keypress(38); // Up Arrow Key
  309. else if (input & 0x00111000) // RStick Left | LStick Left | DPad Left
  310. fire_js_keypress(37); // Left Arrow Key
  311. else if (input & 0x00000001) // A Button
  312. fire_js_keypress(13); // Enter Key
  313. }
  314. web_browser_view.hide();
  315. render_window->show();
  316. render_window->setFocus();
  317. ui.menubar->removeAction(exit_action);
  318. // Needed to update render window focus/show and remove menubar action
  319. QApplication::processEvents();
  320. emit WebBrowserFinishedBrowsing();
  321. }
  322. #else
  323. void GMainWindow::WebBrowserOpenPage(std::string_view filename, std::string_view additional_args) {
  324. QMessageBox::warning(
  325. this, tr("Web Applet"),
  326. tr("This version of yuzu was built without QtWebEngine support, meaning that yuzu cannot "
  327. "properly display the game manual or web page requested."),
  328. QMessageBox::Ok, QMessageBox::Ok);
  329. LOG_INFO(Frontend,
  330. "(STUBBED) called - Missing QtWebEngine dependency needed to open website page at "
  331. "'{}' with arguments '{}'!",
  332. filename, additional_args);
  333. emit WebBrowserFinishedBrowsing();
  334. }
  335. #endif
  336. void GMainWindow::InitializeWidgets() {
  337. #ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
  338. ui.action_Report_Compatibility->setVisible(true);
  339. #endif
  340. render_window = new GRenderWindow(this, emu_thread.get());
  341. render_window->hide();
  342. game_list = new GameList(vfs, this);
  343. ui.horizontalLayout->addWidget(game_list);
  344. loading_screen = new LoadingScreen(this);
  345. loading_screen->hide();
  346. ui.horizontalLayout->addWidget(loading_screen);
  347. connect(loading_screen, &LoadingScreen::Hidden, [&] {
  348. loading_screen->Clear();
  349. if (emulation_running) {
  350. render_window->show();
  351. render_window->setFocus();
  352. }
  353. });
  354. // Create status bar
  355. message_label = new QLabel();
  356. // Configured separately for left alignment
  357. message_label->setVisible(false);
  358. message_label->setFrameStyle(QFrame::NoFrame);
  359. message_label->setContentsMargins(4, 0, 4, 0);
  360. message_label->setAlignment(Qt::AlignLeft);
  361. statusBar()->addPermanentWidget(message_label, 1);
  362. emu_speed_label = new QLabel();
  363. emu_speed_label->setToolTip(
  364. tr("Current emulation speed. Values higher or lower than 100% "
  365. "indicate emulation is running faster or slower than a Switch."));
  366. game_fps_label = new QLabel();
  367. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  368. "This will vary from game to game and scene to scene."));
  369. emu_frametime_label = new QLabel();
  370. emu_frametime_label->setToolTip(
  371. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  372. "full-speed emulation this should be at most 16.67 ms."));
  373. for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
  374. label->setVisible(false);
  375. label->setFrameStyle(QFrame::NoFrame);
  376. label->setContentsMargins(4, 0, 4, 0);
  377. statusBar()->addPermanentWidget(label, 0);
  378. }
  379. statusBar()->setVisible(true);
  380. setStyleSheet("QStatusBar::item{border: none;}");
  381. }
  382. void GMainWindow::InitializeDebugWidgets() {
  383. QMenu* debug_menu = ui.menu_View_Debugging;
  384. #if MICROPROFILE_ENABLED
  385. microProfileDialog = new MicroProfileDialog(this);
  386. microProfileDialog->hide();
  387. debug_menu->addAction(microProfileDialog->toggleViewAction());
  388. #endif
  389. graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(debug_context, this);
  390. addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
  391. graphicsBreakpointsWidget->hide();
  392. debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
  393. graphicsSurfaceWidget = new GraphicsSurfaceWidget(debug_context, this);
  394. addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceWidget);
  395. graphicsSurfaceWidget->hide();
  396. debug_menu->addAction(graphicsSurfaceWidget->toggleViewAction());
  397. waitTreeWidget = new WaitTreeWidget(this);
  398. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  399. waitTreeWidget->hide();
  400. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  401. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  402. &WaitTreeWidget::OnEmulationStarting);
  403. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  404. &WaitTreeWidget::OnEmulationStopping);
  405. }
  406. void GMainWindow::InitializeRecentFileMenuActions() {
  407. for (int i = 0; i < max_recent_files_item; ++i) {
  408. actions_recent_files[i] = new QAction(this);
  409. actions_recent_files[i]->setVisible(false);
  410. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  411. ui.menu_recent_files->addAction(actions_recent_files[i]);
  412. }
  413. ui.menu_recent_files->addSeparator();
  414. QAction* action_clear_recent_files = new QAction(this);
  415. action_clear_recent_files->setText(tr("Clear Recent Files"));
  416. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  417. UISettings::values.recent_files.clear();
  418. UpdateRecentFiles();
  419. });
  420. ui.menu_recent_files->addAction(action_clear_recent_files);
  421. UpdateRecentFiles();
  422. }
  423. void GMainWindow::InitializeHotkeys() {
  424. hotkey_registry.RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
  425. hotkey_registry.RegisterHotkey("Main Window", "Start Emulation");
  426. hotkey_registry.RegisterHotkey("Main Window", "Continue/Pause", QKeySequence(Qt::Key_F4));
  427. hotkey_registry.RegisterHotkey("Main Window", "Restart", QKeySequence(Qt::Key_F5));
  428. hotkey_registry.RegisterHotkey("Main Window", "Fullscreen", QKeySequence::FullScreen);
  429. hotkey_registry.RegisterHotkey("Main Window", "Exit Fullscreen", QKeySequence(Qt::Key_Escape),
  430. Qt::ApplicationShortcut);
  431. hotkey_registry.RegisterHotkey("Main Window", "Toggle Speed Limit", QKeySequence("CTRL+Z"),
  432. Qt::ApplicationShortcut);
  433. hotkey_registry.RegisterHotkey("Main Window", "Increase Speed Limit", QKeySequence("+"),
  434. Qt::ApplicationShortcut);
  435. hotkey_registry.RegisterHotkey("Main Window", "Decrease Speed Limit", QKeySequence("-"),
  436. Qt::ApplicationShortcut);
  437. hotkey_registry.RegisterHotkey("Main Window", "Load Amiibo", QKeySequence(Qt::Key_F2),
  438. Qt::ApplicationShortcut);
  439. hotkey_registry.RegisterHotkey("Main Window", "Capture Screenshot",
  440. QKeySequence(QKeySequence::Print));
  441. hotkey_registry.LoadHotkeys();
  442. connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
  443. this, &GMainWindow::OnMenuLoadFile);
  444. connect(hotkey_registry.GetHotkey("Main Window", "Start Emulation", this),
  445. &QShortcut::activated, this, &GMainWindow::OnStartGame);
  446. connect(hotkey_registry.GetHotkey("Main Window", "Continue/Pause", this), &QShortcut::activated,
  447. this, [&] {
  448. if (emulation_running) {
  449. if (emu_thread->IsRunning()) {
  450. OnPauseGame();
  451. } else {
  452. OnStartGame();
  453. }
  454. }
  455. });
  456. connect(hotkey_registry.GetHotkey("Main Window", "Restart", this), &QShortcut::activated, this,
  457. [this] {
  458. if (!Core::System::GetInstance().IsPoweredOn())
  459. return;
  460. BootGame(QString(game_path));
  461. });
  462. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  463. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  464. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  465. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  466. connect(hotkey_registry.GetHotkey("Main Window", "Exit Fullscreen", this),
  467. &QShortcut::activated, this, [&] {
  468. if (emulation_running) {
  469. ui.action_Fullscreen->setChecked(false);
  470. ToggleFullscreen();
  471. }
  472. });
  473. connect(hotkey_registry.GetHotkey("Main Window", "Toggle Speed Limit", this),
  474. &QShortcut::activated, this, [&] {
  475. Settings::values.use_frame_limit = !Settings::values.use_frame_limit;
  476. UpdateStatusBar();
  477. });
  478. constexpr u16 SPEED_LIMIT_STEP = 5;
  479. connect(hotkey_registry.GetHotkey("Main Window", "Increase Speed Limit", this),
  480. &QShortcut::activated, this, [&] {
  481. if (Settings::values.frame_limit < 9999 - SPEED_LIMIT_STEP) {
  482. Settings::values.frame_limit += SPEED_LIMIT_STEP;
  483. UpdateStatusBar();
  484. }
  485. });
  486. connect(hotkey_registry.GetHotkey("Main Window", "Decrease Speed Limit", this),
  487. &QShortcut::activated, this, [&] {
  488. if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
  489. Settings::values.frame_limit -= SPEED_LIMIT_STEP;
  490. UpdateStatusBar();
  491. }
  492. });
  493. connect(hotkey_registry.GetHotkey("Main Window", "Load Amiibo", this), &QShortcut::activated,
  494. this, [&] {
  495. if (ui.action_Load_Amiibo->isEnabled()) {
  496. OnLoadAmiibo();
  497. }
  498. });
  499. connect(hotkey_registry.GetHotkey("Main Window", "Capture Screenshot", this),
  500. &QShortcut::activated, this, [&] {
  501. if (emu_thread->IsRunning()) {
  502. OnCaptureScreenshot();
  503. }
  504. });
  505. }
  506. void GMainWindow::SetDefaultUIGeometry() {
  507. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  508. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  509. const int w = screenRect.width() * 2 / 3;
  510. const int h = screenRect.height() / 2;
  511. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  512. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  513. setGeometry(x, y, w, h);
  514. }
  515. void GMainWindow::RestoreUIState() {
  516. restoreGeometry(UISettings::values.geometry);
  517. restoreState(UISettings::values.state);
  518. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  519. #if MICROPROFILE_ENABLED
  520. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  521. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  522. #endif
  523. game_list->LoadInterfaceLayout();
  524. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  525. ToggleWindowMode();
  526. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  527. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  528. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  529. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  530. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  531. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  532. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  533. Debugger::ToggleConsole();
  534. }
  535. void GMainWindow::ConnectWidgetEvents() {
  536. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  537. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  538. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  539. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  540. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  541. &GMainWindow::OnGameListNavigateToGamedbEntry);
  542. connect(game_list, &GameList::OpenPerGameGeneralRequested, this,
  543. &GMainWindow::OnGameListOpenPerGameProperties);
  544. connect(this, &GMainWindow::EmulationStarting, render_window,
  545. &GRenderWindow::OnEmulationStarting);
  546. connect(this, &GMainWindow::EmulationStopping, render_window,
  547. &GRenderWindow::OnEmulationStopping);
  548. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  549. }
  550. void GMainWindow::ConnectMenuEvents() {
  551. // File
  552. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  553. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  554. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  555. &GMainWindow::OnMenuInstallToNAND);
  556. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  557. &GMainWindow::OnMenuSelectGameListRoot);
  558. connect(ui.action_Select_NAND_Directory, &QAction::triggered, this,
  559. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::NAND); });
  560. connect(ui.action_Select_SDMC_Directory, &QAction::triggered, this,
  561. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::SDMC); });
  562. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  563. connect(ui.action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
  564. // Emulation
  565. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  566. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  567. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  568. connect(ui.action_Report_Compatibility, &QAction::triggered, this,
  569. &GMainWindow::OnMenuReportCompatibility);
  570. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  571. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  572. // View
  573. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  574. &GMainWindow::ToggleWindowMode);
  575. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  576. &GMainWindow::OnDisplayTitleBars);
  577. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  578. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  579. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  580. // Fullscreen
  581. ui.action_Fullscreen->setShortcut(
  582. hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
  583. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  584. // Movie
  585. connect(ui.action_Capture_Screenshot, &QAction::triggered, this,
  586. &GMainWindow::OnCaptureScreenshot);
  587. // Help
  588. connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
  589. connect(ui.action_Rederive, &QAction::triggered, this,
  590. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  591. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  592. }
  593. void GMainWindow::OnDisplayTitleBars(bool show) {
  594. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  595. if (show) {
  596. for (QDockWidget* widget : widgets) {
  597. QWidget* old = widget->titleBarWidget();
  598. widget->setTitleBarWidget(nullptr);
  599. if (old != nullptr)
  600. delete old;
  601. }
  602. } else {
  603. for (QDockWidget* widget : widgets) {
  604. QWidget* old = widget->titleBarWidget();
  605. widget->setTitleBarWidget(new QWidget());
  606. if (old != nullptr)
  607. delete old;
  608. }
  609. }
  610. }
  611. QStringList GMainWindow::GetUnsupportedGLExtensions() {
  612. QStringList unsupported_ext;
  613. if (!GLAD_GL_ARB_direct_state_access)
  614. unsupported_ext.append("ARB_direct_state_access");
  615. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  616. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  617. if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
  618. unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
  619. if (!GLAD_GL_ARB_multi_bind)
  620. unsupported_ext.append("ARB_multi_bind");
  621. // Extensions required to support some texture formats.
  622. if (!GLAD_GL_EXT_texture_compression_s3tc)
  623. unsupported_ext.append("EXT_texture_compression_s3tc");
  624. if (!GLAD_GL_ARB_texture_compression_rgtc)
  625. unsupported_ext.append("ARB_texture_compression_rgtc");
  626. if (!GLAD_GL_ARB_depth_buffer_float)
  627. unsupported_ext.append("ARB_depth_buffer_float");
  628. for (const QString& ext : unsupported_ext)
  629. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  630. return unsupported_ext;
  631. }
  632. bool GMainWindow::LoadROM(const QString& filename) {
  633. // Shutdown previous session if the emu thread is still active...
  634. if (emu_thread != nullptr)
  635. ShutdownGame();
  636. render_window->InitRenderTarget();
  637. render_window->MakeCurrent();
  638. if (!gladLoadGL()) {
  639. QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
  640. tr("Your GPU may not support OpenGL 4.3, or you do not "
  641. "have the latest graphics driver."));
  642. return false;
  643. }
  644. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  645. if (!unsupported_gl_extensions.empty()) {
  646. QMessageBox::critical(this, tr("Error while initializing OpenGL Core!"),
  647. tr("Your GPU may not support one or more required OpenGL"
  648. "extensions. Please ensure you have the latest graphics "
  649. "driver.<br><br>Unsupported extensions:<br>") +
  650. unsupported_gl_extensions.join("<br>"));
  651. return false;
  652. }
  653. Core::System& system{Core::System::GetInstance()};
  654. system.SetFilesystem(vfs);
  655. system.SetGPUDebugContext(debug_context);
  656. system.SetProfileSelector(std::make_unique<QtProfileSelector>(*this));
  657. system.SetSoftwareKeyboard(std::make_unique<QtSoftwareKeyboard>(*this));
  658. system.SetWebBrowser(std::make_unique<QtWebBrowser>(*this));
  659. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  660. const auto drd_callout =
  661. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  662. if (result == Core::System::ResultStatus::Success &&
  663. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  664. drd_callout) {
  665. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  666. QMessageBox::warning(
  667. this, tr("Warning Outdated Game Format"),
  668. tr("You are using the deconstructed ROM directory format for this game, which is an "
  669. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  670. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  671. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  672. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  673. "wiki</a>. This message will not be shown again."));
  674. }
  675. render_window->DoneCurrent();
  676. if (result != Core::System::ResultStatus::Success) {
  677. switch (result) {
  678. case Core::System::ResultStatus::ErrorGetLoader:
  679. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  680. QMessageBox::critical(this, tr("Error while loading ROM!"),
  681. tr("The ROM format is not supported."));
  682. break;
  683. case Core::System::ResultStatus::ErrorSystemMode:
  684. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  685. QMessageBox::critical(this, tr("Error while loading ROM!"),
  686. tr("Could not determine the system mode."));
  687. break;
  688. case Core::System::ResultStatus::ErrorVideoCore:
  689. QMessageBox::critical(
  690. this, tr("An error occurred initializing the video core."),
  691. tr("yuzu has encountered an error while running the video core, please see the "
  692. "log for more details."
  693. "For more information on accessing the log, please see the following page: "
  694. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  695. "to "
  696. "Upload the Log File</a>."
  697. "Ensure that you have the latest graphics drivers for your GPU."));
  698. break;
  699. default:
  700. if (static_cast<u32>(result) >
  701. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  702. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  703. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  704. const u16 error_id = static_cast<u16>(result) - loader_id;
  705. QMessageBox::critical(
  706. this, tr("Error while loading ROM!"),
  707. QString::fromStdString(fmt::format(
  708. "While attempting to load the ROM requested, an error occured. Please "
  709. "refer to the yuzu wiki for more information or the yuzu discord for "
  710. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  711. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id))));
  712. } else {
  713. QMessageBox::critical(
  714. this, tr("Error while loading ROM!"),
  715. tr("An unknown error occurred. Please see the log for more details."));
  716. }
  717. break;
  718. }
  719. return false;
  720. }
  721. game_path = filename;
  722. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  723. return true;
  724. }
  725. void GMainWindow::SelectAndSetCurrentUser() {
  726. QtProfileSelectionDialog dialog(this);
  727. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  728. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  729. dialog.setWindowModality(Qt::WindowModal);
  730. dialog.exec();
  731. if (dialog.GetStatus()) {
  732. Settings::values.current_user = static_cast<s32>(dialog.GetIndex());
  733. }
  734. }
  735. void GMainWindow::BootGame(const QString& filename) {
  736. LOG_INFO(Frontend, "yuzu starting...");
  737. StoreRecentFile(filename); // Put the filename on top of the list
  738. if (UISettings::values.select_user_on_boot) {
  739. SelectAndSetCurrentUser();
  740. }
  741. if (!LoadROM(filename))
  742. return;
  743. // Create and start the emulation thread
  744. emu_thread = std::make_unique<EmuThread>(render_window);
  745. emit EmulationStarting(emu_thread.get());
  746. render_window->moveContext();
  747. emu_thread->start();
  748. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  749. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  750. // before the CPU continues
  751. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  752. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  753. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  754. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  755. // Update the GUI
  756. if (ui.action_Single_Window_Mode->isChecked()) {
  757. game_list->hide();
  758. }
  759. status_bar_update_timer.start(2000);
  760. std::string title_name;
  761. const auto res = Core::System::GetInstance().GetGameName(title_name);
  762. if (res != Loader::ResultStatus::Success) {
  763. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  764. const auto [nacp, icon_file] = FileSys::PatchManager(title_id).GetControlMetadata();
  765. if (nacp != nullptr)
  766. title_name = nacp->GetApplicationName();
  767. if (title_name.empty())
  768. title_name = FileUtil::GetFilename(filename.toStdString());
  769. }
  770. setWindowTitle(QString("yuzu %1| %4 | %2-%3")
  771. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc,
  772. QString::fromStdString(title_name)));
  773. loading_screen->Prepare(Core::System::GetInstance().GetAppLoader());
  774. loading_screen->show();
  775. emulation_running = true;
  776. if (ui.action_Fullscreen->isChecked()) {
  777. ShowFullscreen();
  778. }
  779. OnStartGame();
  780. }
  781. void GMainWindow::ShutdownGame() {
  782. discord_rpc->Pause();
  783. emu_thread->RequestStop();
  784. emit EmulationStopping();
  785. // Wait for emulation thread to complete and delete it
  786. emu_thread->wait();
  787. emu_thread = nullptr;
  788. discord_rpc->Update();
  789. // The emulation is stopped, so closing the window or not does not matter anymore
  790. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  791. // Update the GUI
  792. ui.action_Start->setEnabled(false);
  793. ui.action_Start->setText(tr("Start"));
  794. ui.action_Pause->setEnabled(false);
  795. ui.action_Stop->setEnabled(false);
  796. ui.action_Restart->setEnabled(false);
  797. ui.action_Report_Compatibility->setEnabled(false);
  798. ui.action_Load_Amiibo->setEnabled(false);
  799. ui.action_Capture_Screenshot->setEnabled(false);
  800. render_window->hide();
  801. loading_screen->hide();
  802. loading_screen->Clear();
  803. game_list->show();
  804. game_list->setFilterFocus();
  805. setWindowTitle(QString("yuzu %1| %2-%3")
  806. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  807. // Disable status bar updates
  808. status_bar_update_timer.stop();
  809. message_label->setVisible(false);
  810. emu_speed_label->setVisible(false);
  811. game_fps_label->setVisible(false);
  812. emu_frametime_label->setVisible(false);
  813. emulation_running = false;
  814. game_path.clear();
  815. }
  816. void GMainWindow::StoreRecentFile(const QString& filename) {
  817. UISettings::values.recent_files.prepend(filename);
  818. UISettings::values.recent_files.removeDuplicates();
  819. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  820. UISettings::values.recent_files.removeLast();
  821. }
  822. UpdateRecentFiles();
  823. }
  824. void GMainWindow::UpdateRecentFiles() {
  825. const int num_recent_files =
  826. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  827. for (int i = 0; i < num_recent_files; i++) {
  828. const QString text = QString("&%1. %2").arg(i + 1).arg(
  829. QFileInfo(UISettings::values.recent_files[i]).fileName());
  830. actions_recent_files[i]->setText(text);
  831. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  832. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  833. actions_recent_files[i]->setVisible(true);
  834. }
  835. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  836. actions_recent_files[j]->setVisible(false);
  837. }
  838. // Enable the recent files menu if the list isn't empty
  839. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  840. }
  841. void GMainWindow::OnGameListLoadFile(QString game_path) {
  842. BootGame(game_path);
  843. }
  844. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  845. std::string path;
  846. std::string open_target;
  847. switch (target) {
  848. case GameListOpenTarget::SaveData: {
  849. open_target = "Save Data";
  850. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  851. ASSERT(program_id != 0);
  852. const auto select_profile = [this]() -> s32 {
  853. QtProfileSelectionDialog dialog(this);
  854. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  855. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  856. dialog.setWindowModality(Qt::WindowModal);
  857. dialog.exec();
  858. if (!dialog.GetStatus()) {
  859. return -1;
  860. }
  861. return dialog.GetIndex();
  862. };
  863. const auto index = select_profile();
  864. if (index == -1)
  865. return;
  866. Service::Account::ProfileManager manager;
  867. const auto user_id = manager.GetUser(index);
  868. ASSERT(user_id);
  869. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  870. FileSys::SaveDataType::SaveData,
  871. program_id, user_id->uuid, 0);
  872. if (!FileUtil::Exists(path)) {
  873. FileUtil::CreateFullPath(path);
  874. FileUtil::CreateDir(path);
  875. }
  876. break;
  877. }
  878. case GameListOpenTarget::ModData: {
  879. open_target = "Mod Data";
  880. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  881. path = fmt::format("{}{:016X}", load_dir, program_id);
  882. break;
  883. }
  884. default:
  885. UNIMPLEMENTED();
  886. }
  887. const QString qpath = QString::fromStdString(path);
  888. const QDir dir(qpath);
  889. if (!dir.exists()) {
  890. QMessageBox::warning(this,
  891. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  892. tr("Folder does not exist!"));
  893. return;
  894. }
  895. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  896. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  897. }
  898. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  899. std::size_t out = 0;
  900. for (const auto& subdir : dir->GetSubdirectories()) {
  901. out += 1 + CalculateRomFSEntrySize(subdir, full);
  902. }
  903. return out + (full ? dir->GetFiles().size() : 0);
  904. }
  905. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  906. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  907. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  908. return false;
  909. if (dialog.wasCanceled())
  910. return false;
  911. if (full) {
  912. for (const auto& file : src->GetFiles()) {
  913. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  914. if (!FileSys::VfsRawCopy(file, out, block_size))
  915. return false;
  916. dialog.setValue(dialog.value() + 1);
  917. if (dialog.wasCanceled())
  918. return false;
  919. }
  920. }
  921. for (const auto& dir : src->GetSubdirectories()) {
  922. const auto out = dest->CreateSubdirectory(dir->GetName());
  923. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  924. return false;
  925. dialog.setValue(dialog.value() + 1);
  926. if (dialog.wasCanceled())
  927. return false;
  928. }
  929. return true;
  930. }
  931. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  932. const auto failed = [this] {
  933. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  934. tr("There was an error copying the RomFS files or the user "
  935. "cancelled the operation."));
  936. };
  937. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  938. if (loader == nullptr) {
  939. failed();
  940. return;
  941. }
  942. FileSys::VirtualFile file;
  943. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  944. failed();
  945. return;
  946. }
  947. const auto installed = Service::FileSystem::GetUnionContents();
  948. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  949. if (!romfs_title_id) {
  950. failed();
  951. return;
  952. }
  953. const auto path = fmt::format(
  954. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  955. FileSys::VirtualFile romfs;
  956. if (*romfs_title_id == program_id) {
  957. romfs = file;
  958. } else {
  959. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  960. }
  961. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  962. if (extracted == nullptr) {
  963. failed();
  964. return;
  965. }
  966. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  967. if (out == nullptr) {
  968. failed();
  969. vfs->DeleteDirectory(path);
  970. return;
  971. }
  972. bool ok;
  973. const auto res = QInputDialog::getItem(
  974. this, tr("Select RomFS Dump Mode"),
  975. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  976. "files into the new directory while <br>skeleton will only create the directory "
  977. "structure."),
  978. {"Full", "Skeleton"}, 0, false, &ok);
  979. if (!ok) {
  980. failed();
  981. vfs->DeleteDirectory(path);
  982. return;
  983. }
  984. const auto full = res == "Full";
  985. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  986. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  987. static_cast<s32>(entry_size), this);
  988. progress.setWindowModality(Qt::WindowModal);
  989. progress.setMinimumDuration(100);
  990. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  991. progress.close();
  992. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  993. tr("The operation completed successfully."));
  994. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  995. } else {
  996. progress.close();
  997. failed();
  998. vfs->DeleteDirectory(path);
  999. }
  1000. }
  1001. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1002. QClipboard* clipboard = QGuiApplication::clipboard();
  1003. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1004. }
  1005. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1006. const CompatibilityList& compatibility_list) {
  1007. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1008. QString directory;
  1009. if (it != compatibility_list.end())
  1010. directory = it->second.second;
  1011. QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
  1012. }
  1013. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1014. u64 title_id{};
  1015. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1016. const auto loader = Loader::GetLoader(v_file);
  1017. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1018. QMessageBox::information(this, tr("Properties"),
  1019. tr("The game properties could not be loaded."));
  1020. return;
  1021. }
  1022. ConfigurePerGameGeneral dialog(this, title_id);
  1023. dialog.loadFromFile(v_file);
  1024. auto result = dialog.exec();
  1025. if (result == QDialog::Accepted) {
  1026. dialog.applyConfiguration();
  1027. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1028. if (reload) {
  1029. game_list->PopulateAsync(UISettings::values.gamedir,
  1030. UISettings::values.gamedir_deepscan);
  1031. }
  1032. config->Save();
  1033. }
  1034. }
  1035. void GMainWindow::OnMenuLoadFile() {
  1036. const QString extensions =
  1037. QString("*.").append(GameList::supported_file_extensions.join(" *.")).append(" main");
  1038. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1039. "%1 is an identifier for the Switch executable file extensions.")
  1040. .arg(extensions);
  1041. const QString filename = QFileDialog::getOpenFileName(
  1042. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1043. if (filename.isEmpty()) {
  1044. return;
  1045. }
  1046. UISettings::values.roms_path = QFileInfo(filename).path();
  1047. BootGame(filename);
  1048. }
  1049. void GMainWindow::OnMenuLoadFolder() {
  1050. const QString dir_path =
  1051. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1052. if (dir_path.isNull()) {
  1053. return;
  1054. }
  1055. const QDir dir{dir_path};
  1056. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  1057. if (matching_main.size() == 1) {
  1058. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  1059. } else {
  1060. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1061. tr("The directory you have selected does not contain a 'main' file."));
  1062. }
  1063. }
  1064. void GMainWindow::OnMenuInstallToNAND() {
  1065. const QString file_filter =
  1066. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1067. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  1068. "Image (*.xci)");
  1069. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  1070. UISettings::values.roms_path, file_filter);
  1071. if (filename.isEmpty()) {
  1072. return;
  1073. }
  1074. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1075. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1076. if (src == nullptr || dest == nullptr)
  1077. return false;
  1078. if (!dest->Resize(src->GetSize()))
  1079. return false;
  1080. std::array<u8, 0x1000> buffer{};
  1081. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  1082. QProgressDialog progress(
  1083. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  1084. tr("Cancel"), 0, progress_maximum, this);
  1085. progress.setWindowModality(Qt::WindowModal);
  1086. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1087. if (progress.wasCanceled()) {
  1088. dest->Resize(0);
  1089. return false;
  1090. }
  1091. const int progress_value = static_cast<int>(i / buffer.size());
  1092. progress.setValue(progress_value);
  1093. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1094. dest->Write(buffer.data(), read, i);
  1095. }
  1096. return true;
  1097. };
  1098. const auto success = [this]() {
  1099. QMessageBox::information(this, tr("Successfully Installed"),
  1100. tr("The file was successfully installed."));
  1101. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1102. };
  1103. const auto failed = [this]() {
  1104. QMessageBox::warning(
  1105. this, tr("Failed to Install"),
  1106. tr("There was an error while attempting to install the provided file. It "
  1107. "could have an incorrect format or be missing metadata. Please "
  1108. "double-check your file and try again."));
  1109. };
  1110. const auto overwrite = [this]() {
  1111. return QMessageBox::question(this, tr("Failed to Install"),
  1112. tr("The file you are attempting to install already exists "
  1113. "in the cache. Would you like to overwrite it?")) ==
  1114. QMessageBox::Yes;
  1115. };
  1116. if (filename.endsWith("xci", Qt::CaseInsensitive) ||
  1117. filename.endsWith("nsp", Qt::CaseInsensitive)) {
  1118. std::shared_ptr<FileSys::NSP> nsp;
  1119. if (filename.endsWith("nsp", Qt::CaseInsensitive)) {
  1120. nsp = std::make_shared<FileSys::NSP>(
  1121. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1122. if (nsp->IsExtractedType())
  1123. failed();
  1124. } else {
  1125. const auto xci = std::make_shared<FileSys::XCI>(
  1126. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1127. nsp = xci->GetSecurePartitionNSP();
  1128. }
  1129. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1130. failed();
  1131. return;
  1132. }
  1133. const auto res =
  1134. Service::FileSystem::GetUserNANDContents()->InstallEntry(*nsp, false, qt_raw_copy);
  1135. if (res == FileSys::InstallResult::Success) {
  1136. success();
  1137. } else {
  1138. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1139. if (overwrite()) {
  1140. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1141. *nsp, true, qt_raw_copy);
  1142. if (res2 == FileSys::InstallResult::Success) {
  1143. success();
  1144. } else {
  1145. failed();
  1146. }
  1147. }
  1148. } else {
  1149. failed();
  1150. }
  1151. }
  1152. } else {
  1153. const auto nca = std::make_shared<FileSys::NCA>(
  1154. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1155. const auto id = nca->GetStatus();
  1156. // Game updates necessary are missing base RomFS
  1157. if (id != Loader::ResultStatus::Success &&
  1158. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1159. failed();
  1160. return;
  1161. }
  1162. const QStringList tt_options{tr("System Application"),
  1163. tr("System Archive"),
  1164. tr("System Application Update"),
  1165. tr("Firmware Package (Type A)"),
  1166. tr("Firmware Package (Type B)"),
  1167. tr("Game"),
  1168. tr("Game Update"),
  1169. tr("Game DLC"),
  1170. tr("Delta Title")};
  1171. bool ok;
  1172. const auto item = QInputDialog::getItem(
  1173. this, tr("Select NCA Install Type..."),
  1174. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1175. "most instances, the default 'Game' is fine.)"),
  1176. tt_options, 5, false, &ok);
  1177. auto index = tt_options.indexOf(item);
  1178. if (!ok || index == -1) {
  1179. QMessageBox::warning(this, tr("Failed to Install"),
  1180. tr("The title type you selected for the NCA is invalid."));
  1181. return;
  1182. }
  1183. // If index is equal to or past Game, add the jump in TitleType.
  1184. if (index >= 5) {
  1185. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1186. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1187. }
  1188. FileSys::InstallResult res;
  1189. if (index >= static_cast<size_t>(FileSys::TitleType::Application)) {
  1190. res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1191. *nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  1192. } else {
  1193. res = Service::FileSystem::GetSystemNANDContents()->InstallEntry(
  1194. *nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  1195. }
  1196. if (res == FileSys::InstallResult::Success) {
  1197. success();
  1198. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1199. if (overwrite()) {
  1200. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1201. *nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1202. if (res2 == FileSys::InstallResult::Success) {
  1203. success();
  1204. } else {
  1205. failed();
  1206. }
  1207. }
  1208. } else {
  1209. failed();
  1210. }
  1211. }
  1212. }
  1213. void GMainWindow::OnMenuSelectGameListRoot() {
  1214. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1215. if (!dir_path.isEmpty()) {
  1216. UISettings::values.gamedir = dir_path;
  1217. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  1218. }
  1219. }
  1220. void GMainWindow::OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget target) {
  1221. const auto res = QMessageBox::information(
  1222. this, tr("Changing Emulated Directory"),
  1223. tr("You are about to change the emulated %1 directory of the system. Please note "
  1224. "that this does not also move the contents of the previous directory to the "
  1225. "new one and you will have to do that yourself.")
  1226. .arg(target == EmulatedDirectoryTarget::SDMC ? tr("SD card") : tr("NAND")),
  1227. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1228. if (res == QMessageBox::Cancel)
  1229. return;
  1230. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1231. if (!dir_path.isEmpty()) {
  1232. FileUtil::GetUserPath(target == EmulatedDirectoryTarget::SDMC ? FileUtil::UserPath::SDMCDir
  1233. : FileUtil::UserPath::NANDDir,
  1234. dir_path.toStdString());
  1235. Service::FileSystem::CreateFactories(*vfs);
  1236. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1237. }
  1238. }
  1239. void GMainWindow::OnMenuRecentFile() {
  1240. QAction* action = qobject_cast<QAction*>(sender());
  1241. assert(action);
  1242. const QString filename = action->data().toString();
  1243. if (QFileInfo::exists(filename)) {
  1244. BootGame(filename);
  1245. } else {
  1246. // Display an error message and remove the file from the list.
  1247. QMessageBox::information(this, tr("File not found"),
  1248. tr("File \"%1\" not found").arg(filename));
  1249. UISettings::values.recent_files.removeOne(filename);
  1250. UpdateRecentFiles();
  1251. }
  1252. }
  1253. void GMainWindow::OnStartGame() {
  1254. emu_thread->SetRunning(true);
  1255. qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
  1256. "Core::Frontend::SoftwareKeyboardParameters");
  1257. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1258. qRegisterMetaType<std::string>("std::string");
  1259. qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
  1260. qRegisterMetaType<std::string_view>("std::string_view");
  1261. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1262. ui.action_Start->setEnabled(false);
  1263. ui.action_Start->setText(tr("Continue"));
  1264. ui.action_Pause->setEnabled(true);
  1265. ui.action_Stop->setEnabled(true);
  1266. ui.action_Restart->setEnabled(true);
  1267. ui.action_Report_Compatibility->setEnabled(true);
  1268. discord_rpc->Update();
  1269. ui.action_Load_Amiibo->setEnabled(true);
  1270. ui.action_Capture_Screenshot->setEnabled(true);
  1271. }
  1272. void GMainWindow::OnPauseGame() {
  1273. emu_thread->SetRunning(false);
  1274. ui.action_Start->setEnabled(true);
  1275. ui.action_Pause->setEnabled(false);
  1276. ui.action_Stop->setEnabled(true);
  1277. ui.action_Capture_Screenshot->setEnabled(false);
  1278. }
  1279. void GMainWindow::OnStopGame() {
  1280. ShutdownGame();
  1281. }
  1282. void GMainWindow::OnLoadComplete() {
  1283. loading_screen->OnLoadComplete();
  1284. }
  1285. void GMainWindow::OnMenuReportCompatibility() {
  1286. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1287. CompatDB compatdb{this};
  1288. compatdb.exec();
  1289. } else {
  1290. QMessageBox::critical(
  1291. this, tr("Missing yuzu Account"),
  1292. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1293. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1294. "&gt; "
  1295. "Web."));
  1296. }
  1297. }
  1298. void GMainWindow::ToggleFullscreen() {
  1299. if (!emulation_running) {
  1300. return;
  1301. }
  1302. if (ui.action_Fullscreen->isChecked()) {
  1303. ShowFullscreen();
  1304. } else {
  1305. HideFullscreen();
  1306. }
  1307. }
  1308. void GMainWindow::ShowFullscreen() {
  1309. if (ui.action_Single_Window_Mode->isChecked()) {
  1310. UISettings::values.geometry = saveGeometry();
  1311. ui.menubar->hide();
  1312. statusBar()->hide();
  1313. showFullScreen();
  1314. } else {
  1315. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1316. render_window->showFullScreen();
  1317. }
  1318. }
  1319. void GMainWindow::HideFullscreen() {
  1320. if (ui.action_Single_Window_Mode->isChecked()) {
  1321. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1322. ui.menubar->show();
  1323. showNormal();
  1324. restoreGeometry(UISettings::values.geometry);
  1325. } else {
  1326. render_window->showNormal();
  1327. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1328. }
  1329. }
  1330. void GMainWindow::ToggleWindowMode() {
  1331. if (ui.action_Single_Window_Mode->isChecked()) {
  1332. // Render in the main window...
  1333. render_window->BackupGeometry();
  1334. ui.horizontalLayout->addWidget(render_window);
  1335. render_window->setFocusPolicy(Qt::ClickFocus);
  1336. if (emulation_running) {
  1337. render_window->setVisible(true);
  1338. render_window->setFocus();
  1339. game_list->hide();
  1340. }
  1341. } else {
  1342. // Render in a separate window...
  1343. ui.horizontalLayout->removeWidget(render_window);
  1344. render_window->setParent(nullptr);
  1345. render_window->setFocusPolicy(Qt::NoFocus);
  1346. if (emulation_running) {
  1347. render_window->setVisible(true);
  1348. render_window->RestoreGeometry();
  1349. game_list->show();
  1350. }
  1351. }
  1352. }
  1353. void GMainWindow::OnConfigure() {
  1354. ConfigureDialog configureDialog(this, hotkey_registry);
  1355. auto old_theme = UISettings::values.theme;
  1356. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1357. auto result = configureDialog.exec();
  1358. if (result == QDialog::Accepted) {
  1359. configureDialog.applyConfiguration();
  1360. if (UISettings::values.theme != old_theme)
  1361. UpdateUITheme();
  1362. if (UISettings::values.enable_discord_presence != old_discord_presence)
  1363. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1364. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1365. if (reload) {
  1366. game_list->PopulateAsync(UISettings::values.gamedir,
  1367. UISettings::values.gamedir_deepscan);
  1368. }
  1369. config->Save();
  1370. }
  1371. }
  1372. void GMainWindow::OnLoadAmiibo() {
  1373. const QString extensions{"*.bin"};
  1374. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1375. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), "", file_filter);
  1376. if (filename.isEmpty()) {
  1377. return;
  1378. }
  1379. Core::System& system{Core::System::GetInstance()};
  1380. Service::SM::ServiceManager& sm = system.ServiceManager();
  1381. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1382. if (nfc == nullptr) {
  1383. return;
  1384. }
  1385. QFile nfc_file{filename};
  1386. if (!nfc_file.open(QIODevice::ReadOnly)) {
  1387. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  1388. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  1389. return;
  1390. }
  1391. const u64 nfc_file_size = nfc_file.size();
  1392. std::vector<u8> buffer(nfc_file_size);
  1393. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  1394. if (nfc_file_size != read_size) {
  1395. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  1396. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  1397. "was only able to read %2 bytes.")
  1398. .arg(nfc_file_size)
  1399. .arg(read_size));
  1400. return;
  1401. }
  1402. if (!nfc->LoadAmiibo(buffer)) {
  1403. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  1404. tr("Unable to load Amiibo data."));
  1405. }
  1406. }
  1407. void GMainWindow::OnOpenYuzuFolder() {
  1408. QDesktopServices::openUrl(QUrl::fromLocalFile(
  1409. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
  1410. }
  1411. void GMainWindow::OnAbout() {
  1412. AboutDialog aboutDialog(this);
  1413. aboutDialog.exec();
  1414. }
  1415. void GMainWindow::OnToggleFilterBar() {
  1416. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1417. if (ui.action_Show_Filter_Bar->isChecked()) {
  1418. game_list->setFilterFocus();
  1419. } else {
  1420. game_list->clearFilter();
  1421. }
  1422. }
  1423. void GMainWindow::OnCaptureScreenshot() {
  1424. OnPauseGame();
  1425. const QString path =
  1426. QFileDialog::getSaveFileName(this, tr("Capture Screenshot"),
  1427. UISettings::values.screenshot_path, tr("PNG Image (*.png)"));
  1428. if (!path.isEmpty()) {
  1429. UISettings::values.screenshot_path = QFileInfo(path).path();
  1430. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
  1431. }
  1432. OnStartGame();
  1433. }
  1434. void GMainWindow::UpdateStatusBar() {
  1435. if (emu_thread == nullptr) {
  1436. status_bar_update_timer.stop();
  1437. return;
  1438. }
  1439. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  1440. if (Settings::values.use_frame_limit) {
  1441. emu_speed_label->setText(tr("Speed: %1% / %2%")
  1442. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  1443. .arg(Settings::values.frame_limit));
  1444. } else {
  1445. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  1446. }
  1447. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  1448. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  1449. emu_speed_label->setVisible(true);
  1450. game_fps_label->setVisible(true);
  1451. emu_frametime_label->setVisible(true);
  1452. }
  1453. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  1454. QMessageBox::StandardButton answer;
  1455. QString status_message;
  1456. const QString common_message =
  1457. tr("The game you are trying to load requires additional files from your Switch to be "
  1458. "dumped "
  1459. "before playing.<br/><br/>For more information on dumping these files, please see the "
  1460. "following wiki page: <a "
  1461. "href='https://yuzu-emu.org/wiki/"
  1462. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  1463. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  1464. "quit "
  1465. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  1466. "data, or other bugs.");
  1467. switch (result) {
  1468. case Core::System::ResultStatus::ErrorSystemFiles: {
  1469. QString message = "yuzu was unable to locate a Switch system archive";
  1470. if (!details.empty()) {
  1471. message.append(tr(": %1. ").arg(details.c_str()));
  1472. } else {
  1473. message.append(". ");
  1474. }
  1475. message.append(common_message);
  1476. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  1477. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1478. status_message = "System Archive Missing";
  1479. break;
  1480. }
  1481. case Core::System::ResultStatus::ErrorSharedFont: {
  1482. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  1483. message.append(common_message);
  1484. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  1485. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1486. status_message = "Shared Font Missing";
  1487. break;
  1488. }
  1489. default:
  1490. answer = QMessageBox::question(
  1491. this, tr("Fatal Error"),
  1492. tr("yuzu has encountered a fatal error, please see the log for more details. "
  1493. "For more information on accessing the log, please see the following page: "
  1494. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1495. "to "
  1496. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  1497. "list? "
  1498. "Continuing emulation may result in crashes, corrupted save data, or other "
  1499. "bugs."),
  1500. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1501. status_message = "Fatal Error encountered";
  1502. break;
  1503. }
  1504. if (answer == QMessageBox::Yes) {
  1505. if (emu_thread) {
  1506. ShutdownGame();
  1507. }
  1508. } else {
  1509. // Only show the message if the game is still running.
  1510. if (emu_thread) {
  1511. emu_thread->SetRunning(true);
  1512. message_label->setText(status_message);
  1513. message_label->setVisible(true);
  1514. }
  1515. }
  1516. }
  1517. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  1518. if (behavior == ReinitializeKeyBehavior::Warning) {
  1519. const auto res = QMessageBox::information(
  1520. this, tr("Confirm Key Rederivation"),
  1521. tr("You are about to force rederive all of your keys. \nIf you do not know what this "
  1522. "means or what you are doing, \nthis is a potentially destructive action. \nPlease "
  1523. "make sure this is what you want \nand optionally make backups.\n\nThis will delete "
  1524. "your autogenerated key files and re-run the key derivation module."),
  1525. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1526. if (res == QMessageBox::Cancel)
  1527. return;
  1528. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1529. "prod.keys_autogenerated");
  1530. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1531. "console.keys_autogenerated");
  1532. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1533. "title.keys_autogenerated");
  1534. }
  1535. Core::Crypto::KeyManager keys{};
  1536. if (keys.BaseDeriveNecessary()) {
  1537. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  1538. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  1539. const auto function = [this, &keys, &pdm] {
  1540. keys.PopulateFromPartitionData(pdm);
  1541. Service::FileSystem::CreateFactories(*vfs);
  1542. keys.DeriveETicket(pdm);
  1543. };
  1544. QString errors;
  1545. if (!pdm.HasFuses())
  1546. errors += tr("- Missing fuses - Cannot derive SBK\n");
  1547. if (!pdm.HasBoot0())
  1548. errors += tr("- Missing BOOT0 - Cannot derive master keys\n");
  1549. if (!pdm.HasPackage2())
  1550. errors += tr("- Missing BCPKG2-1-Normal-Main - Cannot derive general keys\n");
  1551. if (!pdm.HasProdInfo())
  1552. errors += tr("- Missing PRODINFO - Cannot derive title keys\n");
  1553. if (!errors.isEmpty()) {
  1554. QMessageBox::warning(
  1555. this, tr("Warning Missing Derivation Components"),
  1556. tr("The following are missing from your configuration that may hinder key "
  1557. "derivation. It will be attempted but may not complete.<br><br>") +
  1558. errors +
  1559. tr("<br><br>You can get all of these and dump all of your games easily by "
  1560. "following <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1561. "quickstart guide</a>. Alternatively, you can use another method of dumping"
  1562. "to obtain all of your keys."));
  1563. }
  1564. QProgressDialog prog;
  1565. prog.setRange(0, 0);
  1566. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  1567. "system's performance."));
  1568. prog.setWindowTitle(tr("Deriving Keys"));
  1569. prog.show();
  1570. auto future = QtConcurrent::run(function);
  1571. while (!future.isFinished()) {
  1572. QCoreApplication::processEvents();
  1573. }
  1574. prog.close();
  1575. }
  1576. Service::FileSystem::CreateFactories(*vfs);
  1577. if (behavior == ReinitializeKeyBehavior::Warning) {
  1578. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1579. }
  1580. }
  1581. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(
  1582. const FileSys::RegisteredCacheUnion& installed, u64 program_id) {
  1583. const auto dlc_entries =
  1584. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1585. std::vector<FileSys::RegisteredCacheEntry> dlc_match;
  1586. dlc_match.reserve(dlc_entries.size());
  1587. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  1588. [&program_id, &installed](const FileSys::RegisteredCacheEntry& entry) {
  1589. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  1590. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  1591. });
  1592. std::vector<u64> romfs_tids;
  1593. romfs_tids.push_back(program_id);
  1594. for (const auto& entry : dlc_match)
  1595. romfs_tids.push_back(entry.title_id);
  1596. if (romfs_tids.size() > 1) {
  1597. QStringList list{"Base"};
  1598. for (std::size_t i = 1; i < romfs_tids.size(); ++i)
  1599. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  1600. bool ok;
  1601. const auto res = QInputDialog::getItem(
  1602. this, tr("Select RomFS Dump Target"),
  1603. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  1604. if (!ok) {
  1605. return {};
  1606. }
  1607. return romfs_tids[list.indexOf(res)];
  1608. }
  1609. return program_id;
  1610. }
  1611. bool GMainWindow::ConfirmClose() {
  1612. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1613. return true;
  1614. QMessageBox::StandardButton answer =
  1615. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1616. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1617. return answer != QMessageBox::No;
  1618. }
  1619. void GMainWindow::closeEvent(QCloseEvent* event) {
  1620. if (!ConfirmClose()) {
  1621. event->ignore();
  1622. return;
  1623. }
  1624. if (!ui.action_Fullscreen->isChecked()) {
  1625. UISettings::values.geometry = saveGeometry();
  1626. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1627. }
  1628. UISettings::values.state = saveState();
  1629. #if MICROPROFILE_ENABLED
  1630. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1631. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1632. #endif
  1633. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1634. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1635. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1636. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1637. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1638. UISettings::values.first_start = false;
  1639. game_list->SaveInterfaceLayout();
  1640. hotkey_registry.SaveHotkeys();
  1641. // Shutdown session if the emu thread is active...
  1642. if (emu_thread != nullptr)
  1643. ShutdownGame();
  1644. render_window->close();
  1645. QWidget::closeEvent(event);
  1646. }
  1647. static bool IsSingleFileDropEvent(QDropEvent* event) {
  1648. const QMimeData* mimeData = event->mimeData();
  1649. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  1650. }
  1651. void GMainWindow::dropEvent(QDropEvent* event) {
  1652. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  1653. const QMimeData* mimeData = event->mimeData();
  1654. QString filename = mimeData->urls().at(0).toLocalFile();
  1655. BootGame(filename);
  1656. }
  1657. }
  1658. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  1659. if (IsSingleFileDropEvent(event)) {
  1660. event->acceptProposedAction();
  1661. }
  1662. }
  1663. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  1664. event->acceptProposedAction();
  1665. }
  1666. bool GMainWindow::ConfirmChangeGame() {
  1667. if (emu_thread == nullptr)
  1668. return true;
  1669. auto answer = QMessageBox::question(
  1670. this, tr("yuzu"),
  1671. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  1672. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1673. return answer != QMessageBox::No;
  1674. }
  1675. void GMainWindow::filterBarSetChecked(bool state) {
  1676. ui.action_Show_Filter_Bar->setChecked(state);
  1677. emit(OnToggleFilterBar());
  1678. }
  1679. void GMainWindow::UpdateUITheme() {
  1680. QStringList theme_paths(default_theme_paths);
  1681. if (UISettings::values.theme != UISettings::themes[0].second &&
  1682. !UISettings::values.theme.isEmpty()) {
  1683. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  1684. QFile f(theme_uri);
  1685. if (f.open(QFile::ReadOnly | QFile::Text)) {
  1686. QTextStream ts(&f);
  1687. qApp->setStyleSheet(ts.readAll());
  1688. GMainWindow::setStyleSheet(ts.readAll());
  1689. } else {
  1690. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  1691. }
  1692. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  1693. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  1694. } else {
  1695. qApp->setStyleSheet("");
  1696. GMainWindow::setStyleSheet("");
  1697. theme_paths.append(QStringList{":/icons/default"});
  1698. QIcon::setThemeName(":/icons/default");
  1699. }
  1700. QIcon::setThemeSearchPaths(theme_paths);
  1701. emit UpdateThemedIcons();
  1702. }
  1703. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  1704. #ifdef USE_DISCORD_PRESENCE
  1705. if (state) {
  1706. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  1707. } else {
  1708. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1709. }
  1710. #else
  1711. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1712. #endif
  1713. discord_rpc->Update();
  1714. }
  1715. #ifdef main
  1716. #undef main
  1717. #endif
  1718. int main(int argc, char* argv[]) {
  1719. Common::DetachedTasks detached_tasks;
  1720. MicroProfileOnThreadCreate("Frontend");
  1721. SCOPE_EXIT({ MicroProfileShutdown(); });
  1722. // Init settings params
  1723. QCoreApplication::setOrganizationName("yuzu team");
  1724. QCoreApplication::setApplicationName("yuzu");
  1725. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1726. QApplication app(argc, argv);
  1727. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1728. // generating shaders
  1729. setlocale(LC_ALL, "C");
  1730. GMainWindow main_window;
  1731. // After settings have been loaded by GMainWindow, apply the filter
  1732. main_window.show();
  1733. Settings::LogSettings();
  1734. int result = app.exec();
  1735. detached_tasks.WaitForAllTasks();
  1736. return result;
  1737. }