main.cpp 89 KB

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