MainWindow.cs 45 KB

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