MainWindow.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using Gtk;
  4. using LibHac.Common;
  5. using LibHac.Ns;
  6. using Ryujinx.Audio;
  7. using Ryujinx.Common.Configuration;
  8. using Ryujinx.Common.Logging;
  9. using Ryujinx.Common.System;
  10. using Ryujinx.Configuration;
  11. using Ryujinx.Graphics.GAL;
  12. using Ryujinx.Graphics.OpenGL;
  13. using Ryujinx.HLE.FileSystem;
  14. using Ryujinx.HLE.FileSystem.Content;
  15. using Ryujinx.HLE.HOS;
  16. using Ryujinx.Modules;
  17. using Ryujinx.Ui.App;
  18. using Ryujinx.Ui.Applet;
  19. using Ryujinx.Ui.Helper;
  20. using Ryujinx.Ui.Widgets;
  21. using Ryujinx.Ui.Windows;
  22. using System;
  23. using System.Diagnostics;
  24. using System.IO;
  25. using System.Reflection;
  26. using System.Runtime.InteropServices;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using GUI = Gtk.Builder.ObjectAttribute;
  30. namespace Ryujinx.Ui
  31. {
  32. public class MainWindow : Window
  33. {
  34. private readonly VirtualFileSystem _virtualFileSystem;
  35. private readonly ContentManager _contentManager;
  36. private UserChannelPersistence _userChannelPersistence;
  37. private HLE.Switch _emulationContext;
  38. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  39. private readonly ApplicationLibrary _applicationLibrary;
  40. private readonly GtkHostUiHandler _uiHandler;
  41. private readonly AutoResetEvent _deviceExitStatus;
  42. private readonly ListStore _tableStore;
  43. private bool _updatingGameTable;
  44. private bool _gameLoaded;
  45. private bool _ending;
  46. private string _currentEmulatedGamePath = null;
  47. public GlRenderer GlRendererWidget;
  48. #pragma warning disable CS0169, CS0649, IDE0044
  49. [GUI] public MenuItem ExitMenuItem;
  50. [GUI] public MenuItem UpdateMenuItem;
  51. [GUI] MenuBar _menuBar;
  52. [GUI] Box _footerBox;
  53. [GUI] Box _statusBar;
  54. [GUI] MenuItem _stopEmulation;
  55. [GUI] MenuItem _simulateWakeUpMessage;
  56. [GUI] MenuItem _fullScreen;
  57. [GUI] CheckMenuItem _startFullScreen;
  58. [GUI] CheckMenuItem _favToggle;
  59. [GUI] MenuItem _firmwareInstallDirectory;
  60. [GUI] MenuItem _firmwareInstallFile;
  61. [GUI] Label _fifoStatus;
  62. [GUI] CheckMenuItem _iconToggle;
  63. [GUI] CheckMenuItem _developerToggle;
  64. [GUI] CheckMenuItem _appToggle;
  65. [GUI] CheckMenuItem _timePlayedToggle;
  66. [GUI] CheckMenuItem _versionToggle;
  67. [GUI] CheckMenuItem _lastPlayedToggle;
  68. [GUI] CheckMenuItem _fileExtToggle;
  69. [GUI] CheckMenuItem _pathToggle;
  70. [GUI] CheckMenuItem _fileSizeToggle;
  71. [GUI] Label _dockedMode;
  72. [GUI] Label _aspectRatio;
  73. [GUI] Label _gameStatus;
  74. [GUI] TreeView _gameTable;
  75. [GUI] TreeSelection _gameTableSelection;
  76. [GUI] ScrolledWindow _gameTableWindow;
  77. [GUI] Label _gpuName;
  78. [GUI] Label _progressLabel;
  79. [GUI] Label _firmwareVersionLabel;
  80. [GUI] LevelBar _progressBar;
  81. [GUI] Box _viewBox;
  82. [GUI] Label _vSyncStatus;
  83. [GUI] Box _listStatusBox;
  84. #pragma warning restore CS0649, IDE0044, CS0169
  85. public MainWindow() : this(new Builder("Ryujinx.Ui.MainWindow.glade")) { }
  86. private MainWindow(Builder builder) : base(builder.GetObject("_mainWin").Handle)
  87. {
  88. builder.Autoconnect(this);
  89. // Apply custom theme if needed.
  90. ThemeHelper.ApplyTheme();
  91. // Sets overridden fields.
  92. int monitorWidth = Display.PrimaryMonitor.Geometry.Width * Display.PrimaryMonitor.ScaleFactor;
  93. int monitorHeight = Display.PrimaryMonitor.Geometry.Height * Display.PrimaryMonitor.ScaleFactor;
  94. DefaultWidth = monitorWidth < 1280 ? monitorWidth : 1280;
  95. DefaultHeight = monitorHeight < 760 ? monitorHeight : 760;
  96. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.Resources.Logo_Ryujinx.png");
  97. Title = $"Ryujinx {Program.Version}";
  98. // Hide emulation context status bar.
  99. _statusBar.Hide();
  100. // Instanciate HLE objects.
  101. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  102. _contentManager = new ContentManager(_virtualFileSystem);
  103. _userChannelPersistence = new UserChannelPersistence();
  104. // Instanciate GUI objects.
  105. _applicationLibrary = new ApplicationLibrary(_virtualFileSystem);
  106. _uiHandler = new GtkHostUiHandler(this);
  107. _deviceExitStatus = new AutoResetEvent(false);
  108. WindowStateEvent += WindowStateEvent_Changed;
  109. DeleteEvent += Window_Close;
  110. _applicationLibrary.ApplicationAdded += Application_Added;
  111. _applicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated;
  112. _gameTable.ButtonReleaseEvent += Row_Clicked;
  113. _fullScreen.Activated += FullScreen_Toggled;
  114. GlRenderer.StatusUpdatedEvent += Update_StatusBar;
  115. if (ConfigurationState.Instance.Ui.StartFullscreen)
  116. {
  117. _startFullScreen.Active = true;
  118. }
  119. _stopEmulation.Sensitive = false;
  120. _simulateWakeUpMessage.Sensitive = false;
  121. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true;
  122. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true;
  123. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true;
  124. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true;
  125. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true;
  126. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true;
  127. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true;
  128. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true;
  129. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true;
  130. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true;
  131. _gameTable.Model = _tableStore = new ListStore(
  132. typeof(bool),
  133. typeof(Gdk.Pixbuf),
  134. typeof(string),
  135. typeof(string),
  136. typeof(string),
  137. typeof(string),
  138. typeof(string),
  139. typeof(string),
  140. typeof(string),
  141. typeof(string),
  142. typeof(BlitStruct<ApplicationControlProperty>));
  143. _tableStore.SetSortFunc(5, SortHelper.TimePlayedSort);
  144. _tableStore.SetSortFunc(6, SortHelper.LastPlayedSort);
  145. _tableStore.SetSortFunc(8, SortHelper.FileSizeSort);
  146. int columnId = ConfigurationState.Instance.Ui.ColumnSort.SortColumnId;
  147. bool ascending = ConfigurationState.Instance.Ui.ColumnSort.SortAscending;
  148. _tableStore.SetSortColumnId(columnId, ascending ? SortType.Ascending : SortType.Descending);
  149. _gameTable.EnableSearch = true;
  150. _gameTable.SearchColumn = 2;
  151. UpdateColumns();
  152. UpdateGameTable();
  153. ConfigurationState.Instance.Ui.GameDirs.Event += (sender, args) =>
  154. {
  155. if (args.OldValue != args.NewValue)
  156. {
  157. UpdateGameTable();
  158. }
  159. };
  160. Task.Run(RefreshFirmwareLabel);
  161. }
  162. private void WindowStateEvent_Changed(object o, WindowStateEventArgs args)
  163. {
  164. _fullScreen.Label = args.Event.NewWindowState.HasFlag(Gdk.WindowState.Fullscreen) ? "Exit Fullscreen" : "Enter Fullscreen";
  165. }
  166. private void UpdateColumns()
  167. {
  168. foreach (TreeViewColumn column in _gameTable.Columns)
  169. {
  170. _gameTable.RemoveColumn(column);
  171. }
  172. CellRendererToggle favToggle = new CellRendererToggle();
  173. favToggle.Toggled += FavToggle_Toggled;
  174. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0);
  175. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
  176. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
  177. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
  178. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
  179. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
  180. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
  181. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
  182. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
  183. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
  184. foreach (TreeViewColumn column in _gameTable.Columns)
  185. {
  186. switch (column.Title)
  187. {
  188. case "Fav":
  189. column.SortColumnId = 0;
  190. column.Clicked += Column_Clicked;
  191. break;
  192. case "Application":
  193. column.SortColumnId = 2;
  194. column.Clicked += Column_Clicked;
  195. break;
  196. case "Developer":
  197. column.SortColumnId = 3;
  198. column.Clicked += Column_Clicked;
  199. break;
  200. case "Version":
  201. column.SortColumnId = 4;
  202. column.Clicked += Column_Clicked;
  203. break;
  204. case "Time Played":
  205. column.SortColumnId = 5;
  206. column.Clicked += Column_Clicked;
  207. break;
  208. case "Last Played":
  209. column.SortColumnId = 6;
  210. column.Clicked += Column_Clicked;
  211. break;
  212. case "File Ext":
  213. column.SortColumnId = 7;
  214. column.Clicked += Column_Clicked;
  215. break;
  216. case "File Size":
  217. column.SortColumnId = 8;
  218. column.Clicked += Column_Clicked;
  219. break;
  220. case "Path":
  221. column.SortColumnId = 9;
  222. column.Clicked += Column_Clicked;
  223. break;
  224. }
  225. }
  226. }
  227. private void InitializeSwitchInstance()
  228. {
  229. _virtualFileSystem.Reload();
  230. IRenderer renderer = new Renderer();
  231. IAalOutput audioEngine = new DummyAudioOut();
  232. if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
  233. {
  234. if (SoundIoAudioOut.IsSupported)
  235. {
  236. audioEngine = new SoundIoAudioOut();
  237. }
  238. else
  239. {
  240. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  241. }
  242. }
  243. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
  244. {
  245. if (OpenALAudioOut.IsSupported)
  246. {
  247. audioEngine = new OpenALAudioOut();
  248. }
  249. else
  250. {
  251. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");
  252. if (SoundIoAudioOut.IsSupported)
  253. {
  254. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  255. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  256. SaveConfig();
  257. audioEngine = new SoundIoAudioOut();
  258. }
  259. else
  260. {
  261. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  262. }
  263. }
  264. }
  265. _emulationContext = new HLE.Switch(_virtualFileSystem, _contentManager, _userChannelPersistence, renderer, audioEngine)
  266. {
  267. UiHandler = _uiHandler
  268. };
  269. _emulationContext.Initialize();
  270. }
  271. public void UpdateGameTable()
  272. {
  273. if (_updatingGameTable || _gameLoaded)
  274. {
  275. return;
  276. }
  277. _updatingGameTable = true;
  278. _tableStore.Clear();
  279. Thread applicationLibraryThread = new Thread(() =>
  280. {
  281. _applicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs, ConfigurationState.Instance.System.Language);
  282. _updatingGameTable = false;
  283. });
  284. applicationLibraryThread.Name = "GUI.ApplicationLibraryThread";
  285. applicationLibraryThread.IsBackground = true;
  286. applicationLibraryThread.Start();
  287. }
  288. [Conditional("RELEASE")]
  289. public void PerformanceCheck()
  290. {
  291. if (ConfigurationState.Instance.Logger.EnableDebug.Value)
  292. {
  293. MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  294. {
  295. Title = "Ryujinx - Warning",
  296. Text = "You have debug logging enabled, which is designed to be used by developers only.",
  297. SecondaryText = "For optimal performance, it's recommended to disable debug logging. Would you like to disable debug logging now?"
  298. };
  299. if (debugWarningDialog.Run() == (int)ResponseType.Yes)
  300. {
  301. ConfigurationState.Instance.Logger.EnableDebug.Value = false;
  302. SaveConfig();
  303. }
  304. debugWarningDialog.Dispose();
  305. }
  306. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  307. {
  308. MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  309. {
  310. Title = "Ryujinx - Warning",
  311. Text = "You have shader dumping enabled, which is designed to be used by developers only.",
  312. SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
  313. };
  314. if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
  315. {
  316. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  317. SaveConfig();
  318. }
  319. shadersDumpWarningDialog.Dispose();
  320. }
  321. }
  322. public void LoadApplication(string path)
  323. {
  324. if (_gameLoaded)
  325. {
  326. GtkDialog.CreateInfoDialog("A game has already been loaded", "Please close it first and try again.");
  327. }
  328. else
  329. {
  330. PerformanceCheck();
  331. Logger.RestartTime();
  332. InitializeSwitchInstance();
  333. UpdateGraphicsConfig();
  334. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  335. bool isDirectory = Directory.Exists(path);
  336. if (!SetupValidator.CanStartApplication(_contentManager, path, out UserError userError))
  337. {
  338. if (SetupValidator.CanFixStartApplication(_contentManager, path, userError, out firmwareVersion))
  339. {
  340. if (userError == UserError.NoFirmware)
  341. {
  342. string message = $"Would you like to install the firmware embedded in this game? (Firmware {firmwareVersion.VersionString})";
  343. ResponseType responseDialog = (ResponseType)GtkDialog.CreateConfirmationDialog("No Firmware Installed", message).Run();
  344. if (responseDialog != ResponseType.Yes)
  345. {
  346. UserErrorDialog.CreateUserErrorDialog(userError);
  347. _emulationContext.Dispose();
  348. return;
  349. }
  350. }
  351. if (!SetupValidator.TryFixStartApplication(_contentManager, path, userError, out _))
  352. {
  353. UserErrorDialog.CreateUserErrorDialog(userError);
  354. _emulationContext.Dispose();
  355. return;
  356. }
  357. // Tell the user that we installed a firmware for them.
  358. if (userError == UserError.NoFirmware)
  359. {
  360. firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  361. RefreshFirmwareLabel();
  362. string message = $"No installed firmware was found but Ryujinx was able to install firmware {firmwareVersion.VersionString} from the provided game.\nThe emulator will now start.";
  363. GtkDialog.CreateInfoDialog($"Firmware {firmwareVersion.VersionString} was installed", message);
  364. }
  365. }
  366. else
  367. {
  368. UserErrorDialog.CreateUserErrorDialog(userError);
  369. _emulationContext.Dispose();
  370. return;
  371. }
  372. }
  373. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  374. if (Directory.Exists(path))
  375. {
  376. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  377. if (romFsFiles.Length == 0)
  378. {
  379. romFsFiles = Directory.GetFiles(path, "*.romfs");
  380. }
  381. if (romFsFiles.Length > 0)
  382. {
  383. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  384. _emulationContext.LoadCart(path, romFsFiles[0]);
  385. }
  386. else
  387. {
  388. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  389. _emulationContext.LoadCart(path);
  390. }
  391. }
  392. else if (File.Exists(path))
  393. {
  394. switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
  395. {
  396. case ".xci":
  397. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  398. _emulationContext.LoadXci(path);
  399. break;
  400. case ".nca":
  401. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  402. _emulationContext.LoadNca(path);
  403. break;
  404. case ".nsp":
  405. case ".pfs0":
  406. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  407. _emulationContext.LoadNsp(path);
  408. break;
  409. default:
  410. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  411. try
  412. {
  413. _emulationContext.LoadProgram(path);
  414. }
  415. catch (ArgumentOutOfRangeException)
  416. {
  417. Logger.Error?.Print(LogClass.Application, "The file which you have specified is unsupported by Ryujinx.");
  418. }
  419. break;
  420. }
  421. }
  422. else
  423. {
  424. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  425. _emulationContext.Dispose();
  426. return;
  427. }
  428. _currentEmulatedGamePath = path;
  429. _deviceExitStatus.Reset();
  430. Translator.IsReadyForTranslation.Reset();
  431. #if MACOS_BUILD
  432. CreateGameWindow();
  433. #else
  434. Thread windowThread = new Thread(() =>
  435. {
  436. CreateGameWindow();
  437. })
  438. {
  439. Name = "GUI.WindowThread"
  440. };
  441. windowThread.Start();
  442. #endif
  443. _gameLoaded = true;
  444. _stopEmulation.Sensitive = true;
  445. _simulateWakeUpMessage.Sensitive = true;
  446. _firmwareInstallFile.Sensitive = false;
  447. _firmwareInstallDirectory.Sensitive = false;
  448. DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Application.TitleIdText, _emulationContext.Application.TitleName);
  449. _applicationLibrary.LoadAndSaveMetaData(_emulationContext.Application.TitleIdText, appMetadata =>
  450. {
  451. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  452. });
  453. }
  454. }
  455. private void CreateGameWindow()
  456. {
  457. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  458. {
  459. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  460. }
  461. GlRendererWidget = new GlRenderer(_emulationContext, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  462. Application.Invoke(delegate
  463. {
  464. _viewBox.Remove(_gameTableWindow);
  465. GlRendererWidget.Expand = true;
  466. _viewBox.Child = GlRendererWidget;
  467. GlRendererWidget.ShowAll();
  468. EditFooterForGameRenderer();
  469. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  470. {
  471. ToggleExtraWidgets(false);
  472. }
  473. else if (ConfigurationState.Instance.Ui.StartFullscreen.Value)
  474. {
  475. FullScreen_Toggled(null, null);
  476. }
  477. });
  478. GlRendererWidget.WaitEvent.WaitOne();
  479. GlRendererWidget.Start();
  480. Ptc.Close();
  481. PtcProfiler.Stop();
  482. _emulationContext.Dispose();
  483. _deviceExitStatus.Set();
  484. // NOTE: Everything that is here will not be executed when you close the UI.
  485. Application.Invoke(delegate
  486. {
  487. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  488. {
  489. ToggleExtraWidgets(true);
  490. }
  491. GlRendererWidget.Exit();
  492. if(GlRendererWidget.Window != Window && GlRendererWidget.Window != null)
  493. {
  494. GlRendererWidget.Window.Dispose();
  495. }
  496. GlRendererWidget.Dispose();
  497. _windowsMultimediaTimerResolution?.Dispose();
  498. _windowsMultimediaTimerResolution = null;
  499. _viewBox.Remove(GlRendererWidget);
  500. _viewBox.Add(_gameTableWindow);
  501. _gameTableWindow.Expand = true;
  502. Window.Title = $"Ryujinx {Program.Version}";
  503. _emulationContext = null;
  504. _gameLoaded = false;
  505. GlRendererWidget = null;
  506. DiscordIntegrationModule.SwitchToMainMenu();
  507. RecreateFooterForMenu();
  508. UpdateColumns();
  509. UpdateGameTable();
  510. Task.Run(RefreshFirmwareLabel);
  511. Task.Run(HandleRelaunch);
  512. _stopEmulation.Sensitive = false;
  513. _simulateWakeUpMessage.Sensitive = false;
  514. _firmwareInstallFile.Sensitive = true;
  515. _firmwareInstallDirectory.Sensitive = true;
  516. });
  517. }
  518. private void RecreateFooterForMenu()
  519. {
  520. _listStatusBox.Show();
  521. _statusBar.Hide();
  522. }
  523. private void EditFooterForGameRenderer()
  524. {
  525. _listStatusBox.Hide();
  526. _statusBar.Show();
  527. }
  528. public void ToggleExtraWidgets(bool show)
  529. {
  530. if (GlRendererWidget != null)
  531. {
  532. if (show)
  533. {
  534. _menuBar.ShowAll();
  535. _footerBox.Show();
  536. _statusBar.Show();
  537. }
  538. else
  539. {
  540. _menuBar.Hide();
  541. _footerBox.Hide();
  542. }
  543. }
  544. }
  545. private void UpdateGameMetadata(string titleId)
  546. {
  547. if (_gameLoaded)
  548. {
  549. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  550. {
  551. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  552. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  553. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  554. });
  555. }
  556. }
  557. public void UpdateGraphicsConfig()
  558. {
  559. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  560. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  561. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  562. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  563. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  564. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  565. }
  566. public void SaveConfig()
  567. {
  568. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  569. }
  570. private void End()
  571. {
  572. if (_ending)
  573. {
  574. return;
  575. }
  576. _ending = true;
  577. if (_emulationContext != null)
  578. {
  579. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  580. if (GlRendererWidget != null)
  581. {
  582. // We tell the widget that we are exiting.
  583. GlRendererWidget.Exit();
  584. // Wait for the other thread to dispose the HLE context before exiting.
  585. _deviceExitStatus.WaitOne();
  586. GlRendererWidget.Dispose();
  587. }
  588. }
  589. Dispose();
  590. Program.Exit();
  591. Application.Quit();
  592. }
  593. //
  594. // Events
  595. //
  596. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  597. {
  598. Application.Invoke(delegate
  599. {
  600. _tableStore.AppendValues(
  601. args.AppData.Favorite,
  602. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  603. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  604. args.AppData.Developer,
  605. args.AppData.Version,
  606. args.AppData.TimePlayed,
  607. args.AppData.LastPlayed,
  608. args.AppData.FileExtension,
  609. args.AppData.FileSize,
  610. args.AppData.Path,
  611. args.AppData.ControlHolder);
  612. });
  613. }
  614. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  615. {
  616. Application.Invoke(delegate
  617. {
  618. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  619. float barValue = 0;
  620. if (args.NumAppsFound != 0)
  621. {
  622. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  623. }
  624. _progressBar.Value = barValue;
  625. // Reset the vertical scrollbar to the top when titles finish loading
  626. if (args.NumAppsLoaded == args.NumAppsFound)
  627. {
  628. _gameTableWindow.Vadjustment.Value = 0;
  629. }
  630. });
  631. }
  632. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  633. {
  634. Application.Invoke(delegate
  635. {
  636. _gameStatus.Text = args.GameStatus;
  637. _fifoStatus.Text = args.FifoStatus;
  638. _gpuName.Text = args.GpuName;
  639. _dockedMode.Text = args.DockedMode;
  640. _aspectRatio.Text = args.AspectRatio;
  641. if (args.VSyncEnabled)
  642. {
  643. _vSyncStatus.Attributes = new Pango.AttrList();
  644. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  645. }
  646. else
  647. {
  648. _vSyncStatus.Attributes = new Pango.AttrList();
  649. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  650. }
  651. });
  652. }
  653. private void FavToggle_Toggled(object sender, ToggledArgs args)
  654. {
  655. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  656. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  657. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  658. _tableStore.SetValue(treeIter, 0, newToggleValue);
  659. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  660. {
  661. appMetadata.Favorite = newToggleValue;
  662. });
  663. }
  664. private void Column_Clicked(object sender, EventArgs args)
  665. {
  666. TreeViewColumn column = (TreeViewColumn)sender;
  667. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  668. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  669. SaveConfig();
  670. }
  671. private void Row_Activated(object sender, RowActivatedArgs args)
  672. {
  673. _gameTableSelection.GetSelected(out TreeIter treeIter);
  674. string path = (string)_tableStore.GetValue(treeIter, 9);
  675. LoadApplication(path);
  676. }
  677. private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  678. {
  679. _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;
  680. }
  681. private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
  682. {
  683. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  684. }
  685. private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
  686. {
  687. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  688. ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  689. }
  690. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  691. {
  692. if (args.Event.Button != 3 /* Right Click */)
  693. {
  694. return;
  695. }
  696. _gameTableSelection.GetSelected(out TreeIter treeIter);
  697. if (treeIter.UserData == IntPtr.Zero)
  698. {
  699. return;
  700. }
  701. string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString();
  702. string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0];
  703. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  704. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  705. _ = new GameTableContextMenu(this, _virtualFileSystem, titleFilePath, titleName, titleId, controlData);
  706. }
  707. private void Load_Application_File(object sender, EventArgs args)
  708. {
  709. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  710. {
  711. fileChooser.Filter = new FileFilter();
  712. fileChooser.Filter.AddPattern("*.nsp");
  713. fileChooser.Filter.AddPattern("*.pfs0");
  714. fileChooser.Filter.AddPattern("*.xci");
  715. fileChooser.Filter.AddPattern("*.nca");
  716. fileChooser.Filter.AddPattern("*.nro");
  717. fileChooser.Filter.AddPattern("*.nso");
  718. if (fileChooser.Run() == (int)ResponseType.Accept)
  719. {
  720. LoadApplication(fileChooser.Filename);
  721. }
  722. }
  723. }
  724. private void Load_Application_Folder(object sender, EventArgs args)
  725. {
  726. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  727. {
  728. if (fileChooser.Run() == (int)ResponseType.Accept)
  729. {
  730. LoadApplication(fileChooser.Filename);
  731. }
  732. }
  733. }
  734. private void Open_Ryu_Folder(object sender, EventArgs args)
  735. {
  736. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  737. }
  738. private void OpenLogsFolder_Pressed(object sender, EventArgs args)
  739. {
  740. string logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  741. new DirectoryInfo(logPath).Create();
  742. OpenHelper.OpenFolder(logPath);
  743. }
  744. private void Exit_Pressed(object sender, EventArgs args)
  745. {
  746. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  747. {
  748. End();
  749. }
  750. }
  751. private void Window_Close(object sender, DeleteEventArgs args)
  752. {
  753. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  754. {
  755. End();
  756. }
  757. else
  758. {
  759. args.RetVal = true;
  760. }
  761. }
  762. private void StopEmulation_Pressed(object sender, EventArgs args)
  763. {
  764. GlRendererWidget?.Exit();
  765. }
  766. private void Installer_File_Pressed(object o, EventArgs args)
  767. {
  768. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  769. fileChooser.Filter = new FileFilter();
  770. fileChooser.Filter.AddPattern("*.zip");
  771. fileChooser.Filter.AddPattern("*.xci");
  772. HandleInstallerDialog(fileChooser);
  773. }
  774. private void Installer_Directory_Pressed(object o, EventArgs args)
  775. {
  776. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  777. HandleInstallerDialog(directoryChooser);
  778. }
  779. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  780. {
  781. if (fileChooser.Run() == (int)ResponseType.Accept)
  782. {
  783. try
  784. {
  785. string filename = fileChooser.Filename;
  786. fileChooser.Dispose();
  787. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  788. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  789. if (firmwareVersion == null)
  790. {
  791. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  792. return;
  793. }
  794. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  795. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  796. if (currentVersion != null)
  797. {
  798. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  799. }
  800. dialogMessage += "\n\nDo you want to continue?";
  801. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  802. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  803. if (responseInstallDialog == ResponseType.Yes)
  804. {
  805. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  806. Thread thread = new Thread(() =>
  807. {
  808. Application.Invoke(delegate
  809. {
  810. waitingDialog.Run();
  811. });
  812. try
  813. {
  814. _contentManager.InstallFirmware(filename);
  815. Application.Invoke(delegate
  816. {
  817. waitingDialog.Dispose();
  818. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  819. GtkDialog.CreateInfoDialog(dialogTitle, message);
  820. Logger.Info?.Print(LogClass.Application, message);
  821. });
  822. }
  823. catch (Exception ex)
  824. {
  825. Application.Invoke(delegate
  826. {
  827. waitingDialog.Dispose();
  828. GtkDialog.CreateErrorDialog(ex.Message);
  829. });
  830. }
  831. finally
  832. {
  833. RefreshFirmwareLabel();
  834. }
  835. });
  836. thread.Name = "GUI.FirmwareInstallerThread";
  837. thread.Start();
  838. }
  839. }
  840. catch (Exception ex)
  841. {
  842. GtkDialog.CreateErrorDialog(ex.Message);
  843. }
  844. }
  845. else
  846. {
  847. fileChooser.Dispose();
  848. }
  849. }
  850. private void RefreshFirmwareLabel()
  851. {
  852. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  853. Application.Invoke(delegate
  854. {
  855. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  856. });
  857. }
  858. private void HandleRelaunch()
  859. {
  860. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  861. {
  862. _userChannelPersistence.ShouldRestart = false;
  863. LoadApplication(_currentEmulatedGamePath);
  864. }
  865. else
  866. {
  867. // otherwise, clear state.
  868. _userChannelPersistence = new UserChannelPersistence();
  869. _currentEmulatedGamePath = null;
  870. }
  871. }
  872. private void FullScreen_Toggled(object sender, EventArgs args)
  873. {
  874. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  875. {
  876. Fullscreen();
  877. ToggleExtraWidgets(false);
  878. }
  879. else
  880. {
  881. Unfullscreen();
  882. ToggleExtraWidgets(true);
  883. }
  884. }
  885. private void StartFullScreen_Toggled(object sender, EventArgs args)
  886. {
  887. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  888. SaveConfig();
  889. }
  890. private void Settings_Pressed(object sender, EventArgs args)
  891. {
  892. new SettingsWindow(this, _virtualFileSystem, _contentManager).Show();
  893. }
  894. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  895. {
  896. if (_emulationContext != null)
  897. {
  898. _emulationContext.System.SimulateWakeUpMessage();
  899. }
  900. }
  901. private void Update_Pressed(object sender, EventArgs args)
  902. {
  903. if (Updater.CanUpdate(true))
  904. {
  905. _ = Updater.BeginParse(this, true);
  906. }
  907. }
  908. private void About_Pressed(object sender, EventArgs args)
  909. {
  910. new AboutWindow().Show();
  911. }
  912. private void Fav_Toggled(object sender, EventArgs args)
  913. {
  914. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  915. SaveConfig();
  916. UpdateColumns();
  917. }
  918. private void Icon_Toggled(object sender, EventArgs args)
  919. {
  920. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  921. SaveConfig();
  922. UpdateColumns();
  923. }
  924. private void Title_Toggled(object sender, EventArgs args)
  925. {
  926. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  927. SaveConfig();
  928. UpdateColumns();
  929. }
  930. private void Developer_Toggled(object sender, EventArgs args)
  931. {
  932. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  933. SaveConfig();
  934. UpdateColumns();
  935. }
  936. private void Version_Toggled(object sender, EventArgs args)
  937. {
  938. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  939. SaveConfig();
  940. UpdateColumns();
  941. }
  942. private void TimePlayed_Toggled(object sender, EventArgs args)
  943. {
  944. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  945. SaveConfig();
  946. UpdateColumns();
  947. }
  948. private void LastPlayed_Toggled(object sender, EventArgs args)
  949. {
  950. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  951. SaveConfig();
  952. UpdateColumns();
  953. }
  954. private void FileExt_Toggled(object sender, EventArgs args)
  955. {
  956. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  957. SaveConfig();
  958. UpdateColumns();
  959. }
  960. private void FileSize_Toggled(object sender, EventArgs args)
  961. {
  962. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  963. SaveConfig();
  964. UpdateColumns();
  965. }
  966. private void Path_Toggled(object sender, EventArgs args)
  967. {
  968. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  969. SaveConfig();
  970. UpdateColumns();
  971. }
  972. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  973. {
  974. UpdateGameTable();
  975. }
  976. }
  977. }