main.cpp 85 KB

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