main.cpp 83 KB

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