MainWindow.cs 46 KB

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