MainWindow.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. DisplaySleep.Prevent();
  462. GlRendererWidget = new GlRenderer(_emulationContext, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  463. Application.Invoke(delegate
  464. {
  465. _viewBox.Remove(_gameTableWindow);
  466. GlRendererWidget.Expand = true;
  467. _viewBox.Child = GlRendererWidget;
  468. GlRendererWidget.ShowAll();
  469. EditFooterForGameRenderer();
  470. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  471. {
  472. ToggleExtraWidgets(false);
  473. }
  474. else if (ConfigurationState.Instance.Ui.StartFullscreen.Value)
  475. {
  476. FullScreen_Toggled(null, null);
  477. }
  478. });
  479. GlRendererWidget.WaitEvent.WaitOne();
  480. GlRendererWidget.Start();
  481. Ptc.Close();
  482. PtcProfiler.Stop();
  483. _emulationContext.Dispose();
  484. _deviceExitStatus.Set();
  485. // NOTE: Everything that is here will not be executed when you close the UI.
  486. Application.Invoke(delegate
  487. {
  488. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  489. {
  490. ToggleExtraWidgets(true);
  491. }
  492. GlRendererWidget.Exit();
  493. if(GlRendererWidget.Window != Window && GlRendererWidget.Window != null)
  494. {
  495. GlRendererWidget.Window.Dispose();
  496. }
  497. GlRendererWidget.Dispose();
  498. _windowsMultimediaTimerResolution?.Dispose();
  499. _windowsMultimediaTimerResolution = null;
  500. DisplaySleep.Restore();
  501. _viewBox.Remove(GlRendererWidget);
  502. _viewBox.Add(_gameTableWindow);
  503. _gameTableWindow.Expand = true;
  504. Window.Title = $"Ryujinx {Program.Version}";
  505. _emulationContext = null;
  506. _gameLoaded = false;
  507. GlRendererWidget = null;
  508. DiscordIntegrationModule.SwitchToMainMenu();
  509. RecreateFooterForMenu();
  510. UpdateColumns();
  511. UpdateGameTable();
  512. Task.Run(RefreshFirmwareLabel);
  513. Task.Run(HandleRelaunch);
  514. _stopEmulation.Sensitive = false;
  515. _simulateWakeUpMessage.Sensitive = false;
  516. _firmwareInstallFile.Sensitive = true;
  517. _firmwareInstallDirectory.Sensitive = true;
  518. });
  519. }
  520. private void RecreateFooterForMenu()
  521. {
  522. _listStatusBox.Show();
  523. _statusBar.Hide();
  524. }
  525. private void EditFooterForGameRenderer()
  526. {
  527. _listStatusBox.Hide();
  528. _statusBar.Show();
  529. }
  530. public void ToggleExtraWidgets(bool show)
  531. {
  532. if (GlRendererWidget != null)
  533. {
  534. if (show)
  535. {
  536. _menuBar.ShowAll();
  537. _footerBox.Show();
  538. _statusBar.Show();
  539. }
  540. else
  541. {
  542. _menuBar.Hide();
  543. _footerBox.Hide();
  544. }
  545. }
  546. }
  547. private void UpdateGameMetadata(string titleId)
  548. {
  549. if (_gameLoaded)
  550. {
  551. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  552. {
  553. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  554. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  555. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  556. });
  557. }
  558. }
  559. public void UpdateGraphicsConfig()
  560. {
  561. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  562. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  563. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  564. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  565. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  566. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  567. }
  568. public void SaveConfig()
  569. {
  570. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  571. }
  572. private void End()
  573. {
  574. if (_ending)
  575. {
  576. return;
  577. }
  578. _ending = true;
  579. if (_emulationContext != null)
  580. {
  581. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  582. if (GlRendererWidget != null)
  583. {
  584. // We tell the widget that we are exiting.
  585. GlRendererWidget.Exit();
  586. // Wait for the other thread to dispose the HLE context before exiting.
  587. _deviceExitStatus.WaitOne();
  588. GlRendererWidget.Dispose();
  589. }
  590. }
  591. Dispose();
  592. Program.Exit();
  593. Application.Quit();
  594. }
  595. //
  596. // Events
  597. //
  598. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  599. {
  600. Application.Invoke(delegate
  601. {
  602. _tableStore.AppendValues(
  603. args.AppData.Favorite,
  604. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  605. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  606. args.AppData.Developer,
  607. args.AppData.Version,
  608. args.AppData.TimePlayed,
  609. args.AppData.LastPlayed,
  610. args.AppData.FileExtension,
  611. args.AppData.FileSize,
  612. args.AppData.Path,
  613. args.AppData.ControlHolder);
  614. });
  615. }
  616. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  617. {
  618. Application.Invoke(delegate
  619. {
  620. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  621. float barValue = 0;
  622. if (args.NumAppsFound != 0)
  623. {
  624. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  625. }
  626. _progressBar.Value = barValue;
  627. // Reset the vertical scrollbar to the top when titles finish loading
  628. if (args.NumAppsLoaded == args.NumAppsFound)
  629. {
  630. _gameTableWindow.Vadjustment.Value = 0;
  631. }
  632. });
  633. }
  634. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  635. {
  636. Application.Invoke(delegate
  637. {
  638. _gameStatus.Text = args.GameStatus;
  639. _fifoStatus.Text = args.FifoStatus;
  640. _gpuName.Text = args.GpuName;
  641. _dockedMode.Text = args.DockedMode;
  642. _aspectRatio.Text = args.AspectRatio;
  643. if (args.VSyncEnabled)
  644. {
  645. _vSyncStatus.Attributes = new Pango.AttrList();
  646. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  647. }
  648. else
  649. {
  650. _vSyncStatus.Attributes = new Pango.AttrList();
  651. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  652. }
  653. });
  654. }
  655. private void FavToggle_Toggled(object sender, ToggledArgs args)
  656. {
  657. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  658. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  659. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  660. _tableStore.SetValue(treeIter, 0, newToggleValue);
  661. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  662. {
  663. appMetadata.Favorite = newToggleValue;
  664. });
  665. }
  666. private void Column_Clicked(object sender, EventArgs args)
  667. {
  668. TreeViewColumn column = (TreeViewColumn)sender;
  669. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  670. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  671. SaveConfig();
  672. }
  673. private void Row_Activated(object sender, RowActivatedArgs args)
  674. {
  675. _gameTableSelection.GetSelected(out TreeIter treeIter);
  676. string path = (string)_tableStore.GetValue(treeIter, 9);
  677. LoadApplication(path);
  678. }
  679. private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  680. {
  681. _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;
  682. }
  683. private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
  684. {
  685. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  686. }
  687. private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
  688. {
  689. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  690. ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  691. }
  692. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  693. {
  694. if (args.Event.Button != 3 /* Right Click */)
  695. {
  696. return;
  697. }
  698. _gameTableSelection.GetSelected(out TreeIter treeIter);
  699. if (treeIter.UserData == IntPtr.Zero)
  700. {
  701. return;
  702. }
  703. string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString();
  704. string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0];
  705. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  706. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  707. _ = new GameTableContextMenu(this, _virtualFileSystem, titleFilePath, titleName, titleId, controlData);
  708. }
  709. private void Load_Application_File(object sender, EventArgs args)
  710. {
  711. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  712. {
  713. fileChooser.Filter = new FileFilter();
  714. fileChooser.Filter.AddPattern("*.nsp");
  715. fileChooser.Filter.AddPattern("*.pfs0");
  716. fileChooser.Filter.AddPattern("*.xci");
  717. fileChooser.Filter.AddPattern("*.nca");
  718. fileChooser.Filter.AddPattern("*.nro");
  719. fileChooser.Filter.AddPattern("*.nso");
  720. if (fileChooser.Run() == (int)ResponseType.Accept)
  721. {
  722. LoadApplication(fileChooser.Filename);
  723. }
  724. }
  725. }
  726. private void Load_Application_Folder(object sender, EventArgs args)
  727. {
  728. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  729. {
  730. if (fileChooser.Run() == (int)ResponseType.Accept)
  731. {
  732. LoadApplication(fileChooser.Filename);
  733. }
  734. }
  735. }
  736. private void Open_Ryu_Folder(object sender, EventArgs args)
  737. {
  738. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  739. }
  740. private void OpenLogsFolder_Pressed(object sender, EventArgs args)
  741. {
  742. string logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  743. new DirectoryInfo(logPath).Create();
  744. OpenHelper.OpenFolder(logPath);
  745. }
  746. private void Exit_Pressed(object sender, EventArgs args)
  747. {
  748. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  749. {
  750. End();
  751. }
  752. }
  753. private void Window_Close(object sender, DeleteEventArgs args)
  754. {
  755. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  756. {
  757. End();
  758. }
  759. else
  760. {
  761. args.RetVal = true;
  762. }
  763. }
  764. private void StopEmulation_Pressed(object sender, EventArgs args)
  765. {
  766. GlRendererWidget?.Exit();
  767. }
  768. private void Installer_File_Pressed(object o, EventArgs args)
  769. {
  770. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  771. fileChooser.Filter = new FileFilter();
  772. fileChooser.Filter.AddPattern("*.zip");
  773. fileChooser.Filter.AddPattern("*.xci");
  774. HandleInstallerDialog(fileChooser);
  775. }
  776. private void Installer_Directory_Pressed(object o, EventArgs args)
  777. {
  778. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  779. HandleInstallerDialog(directoryChooser);
  780. }
  781. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  782. {
  783. if (fileChooser.Run() == (int)ResponseType.Accept)
  784. {
  785. try
  786. {
  787. string filename = fileChooser.Filename;
  788. fileChooser.Dispose();
  789. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  790. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  791. if (firmwareVersion == null)
  792. {
  793. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  794. return;
  795. }
  796. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  797. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  798. if (currentVersion != null)
  799. {
  800. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  801. }
  802. dialogMessage += "\n\nDo you want to continue?";
  803. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  804. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  805. if (responseInstallDialog == ResponseType.Yes)
  806. {
  807. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  808. Thread thread = new Thread(() =>
  809. {
  810. Application.Invoke(delegate
  811. {
  812. waitingDialog.Run();
  813. });
  814. try
  815. {
  816. _contentManager.InstallFirmware(filename);
  817. Application.Invoke(delegate
  818. {
  819. waitingDialog.Dispose();
  820. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  821. GtkDialog.CreateInfoDialog(dialogTitle, message);
  822. Logger.Info?.Print(LogClass.Application, message);
  823. });
  824. }
  825. catch (Exception ex)
  826. {
  827. Application.Invoke(delegate
  828. {
  829. waitingDialog.Dispose();
  830. GtkDialog.CreateErrorDialog(ex.Message);
  831. });
  832. }
  833. finally
  834. {
  835. RefreshFirmwareLabel();
  836. }
  837. });
  838. thread.Name = "GUI.FirmwareInstallerThread";
  839. thread.Start();
  840. }
  841. }
  842. catch (Exception ex)
  843. {
  844. GtkDialog.CreateErrorDialog(ex.Message);
  845. }
  846. }
  847. else
  848. {
  849. fileChooser.Dispose();
  850. }
  851. }
  852. private void RefreshFirmwareLabel()
  853. {
  854. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  855. Application.Invoke(delegate
  856. {
  857. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  858. });
  859. }
  860. private void HandleRelaunch()
  861. {
  862. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  863. {
  864. _userChannelPersistence.ShouldRestart = false;
  865. LoadApplication(_currentEmulatedGamePath);
  866. }
  867. else
  868. {
  869. // otherwise, clear state.
  870. _userChannelPersistence = new UserChannelPersistence();
  871. _currentEmulatedGamePath = null;
  872. }
  873. }
  874. private void FullScreen_Toggled(object sender, EventArgs args)
  875. {
  876. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  877. {
  878. Fullscreen();
  879. ToggleExtraWidgets(false);
  880. }
  881. else
  882. {
  883. Unfullscreen();
  884. ToggleExtraWidgets(true);
  885. }
  886. }
  887. private void StartFullScreen_Toggled(object sender, EventArgs args)
  888. {
  889. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  890. SaveConfig();
  891. }
  892. private void Settings_Pressed(object sender, EventArgs args)
  893. {
  894. new SettingsWindow(this, _virtualFileSystem, _contentManager).Show();
  895. }
  896. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  897. {
  898. if (_emulationContext != null)
  899. {
  900. _emulationContext.System.SimulateWakeUpMessage();
  901. }
  902. }
  903. private void Update_Pressed(object sender, EventArgs args)
  904. {
  905. if (Updater.CanUpdate(true))
  906. {
  907. _ = Updater.BeginParse(this, true);
  908. }
  909. }
  910. private void About_Pressed(object sender, EventArgs args)
  911. {
  912. new AboutWindow().Show();
  913. }
  914. private void Fav_Toggled(object sender, EventArgs args)
  915. {
  916. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  917. SaveConfig();
  918. UpdateColumns();
  919. }
  920. private void Icon_Toggled(object sender, EventArgs args)
  921. {
  922. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  923. SaveConfig();
  924. UpdateColumns();
  925. }
  926. private void Title_Toggled(object sender, EventArgs args)
  927. {
  928. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  929. SaveConfig();
  930. UpdateColumns();
  931. }
  932. private void Developer_Toggled(object sender, EventArgs args)
  933. {
  934. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  935. SaveConfig();
  936. UpdateColumns();
  937. }
  938. private void Version_Toggled(object sender, EventArgs args)
  939. {
  940. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  941. SaveConfig();
  942. UpdateColumns();
  943. }
  944. private void TimePlayed_Toggled(object sender, EventArgs args)
  945. {
  946. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  947. SaveConfig();
  948. UpdateColumns();
  949. }
  950. private void LastPlayed_Toggled(object sender, EventArgs args)
  951. {
  952. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  953. SaveConfig();
  954. UpdateColumns();
  955. }
  956. private void FileExt_Toggled(object sender, EventArgs args)
  957. {
  958. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  959. SaveConfig();
  960. UpdateColumns();
  961. }
  962. private void FileSize_Toggled(object sender, EventArgs args)
  963. {
  964. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  965. SaveConfig();
  966. UpdateColumns();
  967. }
  968. private void Path_Toggled(object sender, EventArgs args)
  969. {
  970. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  971. SaveConfig();
  972. UpdateColumns();
  973. }
  974. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  975. {
  976. UpdateGameTable();
  977. }
  978. }
  979. }