MainWindow.cs 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using Gtk;
  4. using LibHac.Common;
  5. using LibHac.Common.Keys;
  6. using LibHac.FsSystem;
  7. using LibHac.Ncm;
  8. using LibHac.Ns;
  9. using LibHac.Tools.FsSystem;
  10. using Ryujinx.Audio.Backends.Dummy;
  11. using Ryujinx.Audio.Backends.OpenAL;
  12. using Ryujinx.Audio.Backends.SDL2;
  13. using Ryujinx.Audio.Backends.SoundIo;
  14. using Ryujinx.Audio.Integration;
  15. using Ryujinx.Common;
  16. using Ryujinx.Common.Configuration;
  17. using Ryujinx.Common.Logging;
  18. using Ryujinx.Common.System;
  19. using Ryujinx.Graphics.GAL;
  20. using Ryujinx.Graphics.GAL.Multithreading;
  21. using Ryujinx.Graphics.OpenGL;
  22. using Ryujinx.Graphics.Vulkan;
  23. using Ryujinx.HLE.FileSystem;
  24. using Ryujinx.HLE.HOS;
  25. using Ryujinx.HLE.HOS.Services.Account.Acc;
  26. using Ryujinx.HLE.HOS.SystemState;
  27. using Ryujinx.Input.GTK3;
  28. using Ryujinx.Input.HLE;
  29. using Ryujinx.Input.SDL2;
  30. using Ryujinx.Modules;
  31. using Ryujinx.Ui.App.Common;
  32. using Ryujinx.Ui.Applet;
  33. using Ryujinx.Ui.Common;
  34. using Ryujinx.Ui.Common.Configuration;
  35. using Ryujinx.Ui.Common.Helper;
  36. using Ryujinx.Ui.Helper;
  37. using Ryujinx.Ui.Widgets;
  38. using Ryujinx.Ui.Windows;
  39. using Silk.NET.Vulkan;
  40. using SPB.Graphics.Vulkan;
  41. using System;
  42. using System.Diagnostics;
  43. using System.IO;
  44. using System.Reflection;
  45. using System.Threading;
  46. using System.Threading.Tasks;
  47. using GUI = Gtk.Builder.ObjectAttribute;
  48. using PtcLoadingState = ARMeilleure.Translation.PTC.PtcLoadingState;
  49. using ShaderCacheLoadingState = Ryujinx.Graphics.Gpu.Shader.ShaderCacheState;
  50. namespace Ryujinx.Ui
  51. {
  52. public class MainWindow : Window
  53. {
  54. private readonly VirtualFileSystem _virtualFileSystem;
  55. private readonly ContentManager _contentManager;
  56. private readonly AccountManager _accountManager;
  57. private readonly LibHacHorizonManager _libHacHorizonManager;
  58. private UserChannelPersistence _userChannelPersistence;
  59. private HLE.Switch _emulationContext;
  60. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  61. private readonly ApplicationLibrary _applicationLibrary;
  62. private readonly GtkHostUiHandler _uiHandler;
  63. private readonly AutoResetEvent _deviceExitStatus;
  64. private readonly ListStore _tableStore;
  65. private bool _updatingGameTable;
  66. private bool _gameLoaded;
  67. private bool _ending;
  68. private string _currentEmulatedGamePath = null;
  69. private string _lastScannedAmiiboId = "";
  70. private bool _lastScannedAmiiboShowAll = false;
  71. public RendererWidgetBase RendererWidget;
  72. public InputManager InputManager;
  73. public bool IsFocused;
  74. #pragma warning disable CS0169, CS0649, IDE0044
  75. [GUI] public MenuItem ExitMenuItem;
  76. [GUI] public MenuItem UpdateMenuItem;
  77. [GUI] MenuBar _menuBar;
  78. [GUI] Box _footerBox;
  79. [GUI] Box _statusBar;
  80. [GUI] MenuItem _optionMenu;
  81. [GUI] MenuItem _manageUserProfiles;
  82. [GUI] MenuItem _fileMenu;
  83. [GUI] MenuItem _loadApplicationFile;
  84. [GUI] MenuItem _loadApplicationFolder;
  85. [GUI] MenuItem _appletMenu;
  86. [GUI] MenuItem _actionMenu;
  87. [GUI] MenuItem _pauseEmulation;
  88. [GUI] MenuItem _resumeEmulation;
  89. [GUI] MenuItem _stopEmulation;
  90. [GUI] MenuItem _simulateWakeUpMessage;
  91. [GUI] MenuItem _scanAmiibo;
  92. [GUI] MenuItem _takeScreenshot;
  93. [GUI] MenuItem _hideUi;
  94. [GUI] MenuItem _fullScreen;
  95. [GUI] CheckMenuItem _startFullScreen;
  96. [GUI] CheckMenuItem _showConsole;
  97. [GUI] CheckMenuItem _favToggle;
  98. [GUI] MenuItem _firmwareInstallDirectory;
  99. [GUI] MenuItem _firmwareInstallFile;
  100. [GUI] Label _fifoStatus;
  101. [GUI] CheckMenuItem _iconToggle;
  102. [GUI] CheckMenuItem _developerToggle;
  103. [GUI] CheckMenuItem _appToggle;
  104. [GUI] CheckMenuItem _timePlayedToggle;
  105. [GUI] CheckMenuItem _versionToggle;
  106. [GUI] CheckMenuItem _lastPlayedToggle;
  107. [GUI] CheckMenuItem _fileExtToggle;
  108. [GUI] CheckMenuItem _pathToggle;
  109. [GUI] CheckMenuItem _fileSizeToggle;
  110. [GUI] Label _gpuBackend;
  111. [GUI] Label _dockedMode;
  112. [GUI] Label _aspectRatio;
  113. [GUI] Label _gameStatus;
  114. [GUI] TreeView _gameTable;
  115. [GUI] TreeSelection _gameTableSelection;
  116. [GUI] ScrolledWindow _gameTableWindow;
  117. [GUI] Label _gpuName;
  118. [GUI] Label _progressLabel;
  119. [GUI] Label _firmwareVersionLabel;
  120. [GUI] Gtk.ProgressBar _progressBar;
  121. [GUI] Box _viewBox;
  122. [GUI] Label _vSyncStatus;
  123. [GUI] Label _volumeStatus;
  124. [GUI] Box _listStatusBox;
  125. [GUI] Label _loadingStatusLabel;
  126. [GUI] Gtk.ProgressBar _loadingStatusBar;
  127. #pragma warning restore CS0649, IDE0044, CS0169
  128. public MainWindow() : this(new Builder("Ryujinx.Ui.MainWindow.glade")) { }
  129. private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("_mainWin"))
  130. {
  131. builder.Autoconnect(this);
  132. // Apply custom theme if needed.
  133. ThemeHelper.ApplyTheme();
  134. Gdk.Monitor monitor = Display.GetMonitor(0);
  135. // Sets overridden fields.
  136. int monitorWidth = monitor.Geometry.Width * monitor.ScaleFactor;
  137. int monitorHeight = monitor.Geometry.Height * monitor.ScaleFactor;
  138. DefaultWidth = monitorWidth < 1280 ? monitorWidth : 1280;
  139. DefaultHeight = monitorHeight < 760 ? monitorHeight : 760;
  140. Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png");
  141. Title = $"Ryujinx {Program.Version}";
  142. // Hide emulation context status bar.
  143. _statusBar.Hide();
  144. // Instantiate HLE objects.
  145. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  146. _libHacHorizonManager = new LibHacHorizonManager();
  147. _libHacHorizonManager.InitializeFsServer(_virtualFileSystem);
  148. _libHacHorizonManager.InitializeArpServer();
  149. _libHacHorizonManager.InitializeBcatServer();
  150. _libHacHorizonManager.InitializeSystemClients();
  151. // Save data created before we supported extra data in directory save data will not work properly if
  152. // given empty extra data. Luckily some of that extra data can be created using the data from the
  153. // save data indexer, which should be enough to check access permissions for user saves.
  154. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  155. // Consider removing this at some point in the future when we don't need to worry about old saves.
  156. VirtualFileSystem.FixExtraData(_libHacHorizonManager.RyujinxClient);
  157. _contentManager = new ContentManager(_virtualFileSystem);
  158. _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient, CommandLineState.Profile);
  159. _userChannelPersistence = new UserChannelPersistence();
  160. // Instantiate GUI objects.
  161. _applicationLibrary = new ApplicationLibrary(_virtualFileSystem);
  162. _uiHandler = new GtkHostUiHandler(this);
  163. _deviceExitStatus = new AutoResetEvent(false);
  164. WindowStateEvent += WindowStateEvent_Changed;
  165. DeleteEvent += Window_Close;
  166. FocusInEvent += MainWindow_FocusInEvent;
  167. FocusOutEvent += MainWindow_FocusOutEvent;
  168. _applicationLibrary.ApplicationAdded += Application_Added;
  169. _applicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated;
  170. _fileMenu.StateChanged += FileMenu_StateChanged;
  171. _actionMenu.StateChanged += ActionMenu_StateChanged;
  172. _optionMenu.StateChanged += OptionMenu_StateChanged;
  173. _gameTable.ButtonReleaseEvent += Row_Clicked;
  174. _fullScreen.Activated += FullScreen_Toggled;
  175. RendererWidgetBase.StatusUpdatedEvent += Update_StatusBar;
  176. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  177. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  178. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  179. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  180. if (ConfigurationState.Instance.Ui.StartFullscreen)
  181. {
  182. _startFullScreen.Active = true;
  183. }
  184. _showConsole.Active = ConfigurationState.Instance.Ui.ShowConsole.Value;
  185. _showConsole.Visible = ConsoleHelper.SetConsoleWindowStateSupported;
  186. _actionMenu.Sensitive = false;
  187. _pauseEmulation.Sensitive = false;
  188. _resumeEmulation.Sensitive = false;
  189. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true;
  190. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true;
  191. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true;
  192. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true;
  193. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true;
  194. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true;
  195. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true;
  196. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true;
  197. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true;
  198. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true;
  199. _favToggle.Toggled += Fav_Toggled;
  200. _iconToggle.Toggled += Icon_Toggled;
  201. _appToggle.Toggled += App_Toggled;
  202. _developerToggle.Toggled += Developer_Toggled;
  203. _versionToggle.Toggled += Version_Toggled;
  204. _timePlayedToggle.Toggled += TimePlayed_Toggled;
  205. _lastPlayedToggle.Toggled += LastPlayed_Toggled;
  206. _fileExtToggle.Toggled += FileExt_Toggled;
  207. _fileSizeToggle.Toggled += FileSize_Toggled;
  208. _pathToggle.Toggled += Path_Toggled;
  209. _gameTable.Model = _tableStore = new ListStore(
  210. typeof(bool),
  211. typeof(Gdk.Pixbuf),
  212. typeof(string),
  213. typeof(string),
  214. typeof(string),
  215. typeof(string),
  216. typeof(string),
  217. typeof(string),
  218. typeof(string),
  219. typeof(string),
  220. typeof(BlitStruct<ApplicationControlProperty>));
  221. _tableStore.SetSortFunc(5, SortHelper.TimePlayedSort);
  222. _tableStore.SetSortFunc(6, SortHelper.LastPlayedSort);
  223. _tableStore.SetSortFunc(8, SortHelper.FileSizeSort);
  224. int columnId = ConfigurationState.Instance.Ui.ColumnSort.SortColumnId;
  225. bool ascending = ConfigurationState.Instance.Ui.ColumnSort.SortAscending;
  226. _tableStore.SetSortColumnId(columnId, ascending ? SortType.Ascending : SortType.Descending);
  227. _gameTable.EnableSearch = true;
  228. _gameTable.SearchColumn = 2;
  229. _gameTable.SearchEqualFunc = (model, col, key, iter) => !((string)model.GetValue(iter, col)).Contains(key, StringComparison.InvariantCultureIgnoreCase);
  230. _hideUi.Label = _hideUi.Label.Replace("SHOWUIKEY", ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi.ToString());
  231. UpdateColumns();
  232. UpdateGameTable();
  233. ConfigurationState.Instance.Ui.GameDirs.Event += (sender, args) =>
  234. {
  235. if (args.OldValue != args.NewValue)
  236. {
  237. UpdateGameTable();
  238. }
  239. };
  240. Task.Run(RefreshFirmwareLabel);
  241. InputManager = new InputManager(new GTK3KeyboardDriver(this), new SDL2GamepadDriver());
  242. }
  243. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  244. {
  245. if (_emulationContext != null)
  246. {
  247. _emulationContext.Configuration.IgnoreMissingServices = args.NewValue;
  248. }
  249. }
  250. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  251. {
  252. if (_emulationContext != null)
  253. {
  254. _emulationContext.Configuration.AspectRatio = args.NewValue;
  255. }
  256. }
  257. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  258. {
  259. if (_emulationContext != null)
  260. {
  261. _emulationContext.System.ChangeDockedModeState(e.NewValue);
  262. }
  263. }
  264. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  265. {
  266. _emulationContext?.SetVolume(e.NewValue);
  267. }
  268. private void WindowStateEvent_Changed(object o, WindowStateEventArgs args)
  269. {
  270. _fullScreen.Label = args.Event.NewWindowState.HasFlag(Gdk.WindowState.Fullscreen) ? "Exit Fullscreen" : "Enter Fullscreen";
  271. }
  272. private void MainWindow_FocusOutEvent(object o, FocusOutEventArgs args)
  273. {
  274. IsFocused = false;
  275. }
  276. private void MainWindow_FocusInEvent(object o, FocusInEventArgs args)
  277. {
  278. IsFocused = true;
  279. }
  280. private void UpdateColumns()
  281. {
  282. foreach (TreeViewColumn column in _gameTable.Columns)
  283. {
  284. _gameTable.RemoveColumn(column);
  285. }
  286. CellRendererToggle favToggle = new CellRendererToggle();
  287. favToggle.Toggled += FavToggle_Toggled;
  288. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0);
  289. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
  290. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
  291. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
  292. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
  293. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
  294. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
  295. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
  296. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
  297. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
  298. foreach (TreeViewColumn column in _gameTable.Columns)
  299. {
  300. switch (column.Title)
  301. {
  302. case "Fav":
  303. column.SortColumnId = 0;
  304. column.Clicked += Column_Clicked;
  305. break;
  306. case "Application":
  307. column.SortColumnId = 2;
  308. column.Clicked += Column_Clicked;
  309. break;
  310. case "Developer":
  311. column.SortColumnId = 3;
  312. column.Clicked += Column_Clicked;
  313. break;
  314. case "Version":
  315. column.SortColumnId = 4;
  316. column.Clicked += Column_Clicked;
  317. break;
  318. case "Time Played":
  319. column.SortColumnId = 5;
  320. column.Clicked += Column_Clicked;
  321. break;
  322. case "Last Played":
  323. column.SortColumnId = 6;
  324. column.Clicked += Column_Clicked;
  325. break;
  326. case "File Ext":
  327. column.SortColumnId = 7;
  328. column.Clicked += Column_Clicked;
  329. break;
  330. case "File Size":
  331. column.SortColumnId = 8;
  332. column.Clicked += Column_Clicked;
  333. break;
  334. case "Path":
  335. column.SortColumnId = 9;
  336. column.Clicked += Column_Clicked;
  337. break;
  338. }
  339. }
  340. }
  341. protected override void OnDestroyed()
  342. {
  343. InputManager.Dispose();
  344. }
  345. private void InitializeSwitchInstance()
  346. {
  347. _virtualFileSystem.ReloadKeySet();
  348. IRenderer renderer;
  349. if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
  350. {
  351. string preferredGpu = ConfigurationState.Instance.Graphics.PreferredGpu.Value;
  352. renderer = new VulkanRenderer(CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu);
  353. }
  354. else
  355. {
  356. renderer = new OpenGLRenderer();
  357. }
  358. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  359. bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  360. if (threadedGAL)
  361. {
  362. renderer = new ThreadedRenderer(renderer);
  363. }
  364. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {threadedGAL}");
  365. IHardwareDeviceDriver deviceDriver = new DummyHardwareDeviceDriver();
  366. if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SDL2)
  367. {
  368. if (SDL2HardwareDeviceDriver.IsSupported)
  369. {
  370. deviceDriver = new SDL2HardwareDeviceDriver();
  371. }
  372. else
  373. {
  374. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  375. if (OpenALHardwareDeviceDriver.IsSupported)
  376. {
  377. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  378. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  379. SaveConfig();
  380. deviceDriver = new OpenALHardwareDeviceDriver();
  381. }
  382. else
  383. {
  384. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");
  385. if (SoundIoHardwareDeviceDriver.IsSupported)
  386. {
  387. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  388. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  389. SaveConfig();
  390. deviceDriver = new SoundIoHardwareDeviceDriver();
  391. }
  392. else
  393. {
  394. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  395. }
  396. }
  397. }
  398. }
  399. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
  400. {
  401. if (SoundIoHardwareDeviceDriver.IsSupported)
  402. {
  403. deviceDriver = new SoundIoHardwareDeviceDriver();
  404. }
  405. else
  406. {
  407. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, trying to fall back to SDL2.");
  408. if (SDL2HardwareDeviceDriver.IsSupported)
  409. {
  410. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  411. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  412. SaveConfig();
  413. deviceDriver = new SDL2HardwareDeviceDriver();
  414. }
  415. else
  416. {
  417. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  418. if (OpenALHardwareDeviceDriver.IsSupported)
  419. {
  420. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  421. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  422. SaveConfig();
  423. deviceDriver = new OpenALHardwareDeviceDriver();
  424. }
  425. else
  426. {
  427. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, falling back to dummy audio out.");
  428. }
  429. }
  430. }
  431. }
  432. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
  433. {
  434. if (OpenALHardwareDeviceDriver.IsSupported)
  435. {
  436. deviceDriver = new OpenALHardwareDeviceDriver();
  437. }
  438. else
  439. {
  440. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SDL2.");
  441. if (SDL2HardwareDeviceDriver.IsSupported)
  442. {
  443. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  444. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  445. SaveConfig();
  446. deviceDriver = new SDL2HardwareDeviceDriver();
  447. }
  448. else
  449. {
  450. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to SoundIO.");
  451. if (SoundIoHardwareDeviceDriver.IsSupported)
  452. {
  453. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  454. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  455. SaveConfig();
  456. deviceDriver = new SoundIoHardwareDeviceDriver();
  457. }
  458. else
  459. {
  460. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  461. }
  462. }
  463. }
  464. }
  465. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value
  466. ? HLE.MemoryConfiguration.MemoryConfiguration6GiB
  467. : HLE.MemoryConfiguration.MemoryConfiguration4GiB;
  468. IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None;
  469. HLE.HLEConfiguration configuration = new HLE.HLEConfiguration(_virtualFileSystem,
  470. _libHacHorizonManager,
  471. _contentManager,
  472. _accountManager,
  473. _userChannelPersistence,
  474. renderer,
  475. deviceDriver,
  476. memoryConfiguration,
  477. _uiHandler,
  478. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  479. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  480. ConfigurationState.Instance.Graphics.EnableVsync,
  481. ConfigurationState.Instance.System.EnableDockedMode,
  482. ConfigurationState.Instance.System.EnablePtc,
  483. ConfigurationState.Instance.System.EnableInternetAccess,
  484. fsIntegrityCheckLevel,
  485. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  486. ConfigurationState.Instance.System.SystemTimeOffset,
  487. ConfigurationState.Instance.System.TimeZone,
  488. ConfigurationState.Instance.System.MemoryManagerMode,
  489. ConfigurationState.Instance.System.IgnoreMissingServices,
  490. ConfigurationState.Instance.Graphics.AspectRatio,
  491. ConfigurationState.Instance.System.AudioVolume);
  492. _emulationContext = new HLE.Switch(configuration);
  493. }
  494. private SurfaceKHR CreateVulkanSurface(Instance instance, Vk vk)
  495. {
  496. return new SurfaceKHR((ulong)((VKRenderer)RendererWidget).CreateWindowSurface(instance.Handle));
  497. }
  498. private void SetupProgressUiHandlers()
  499. {
  500. Ptc.PtcStateChanged -= ProgressHandler;
  501. Ptc.PtcStateChanged += ProgressHandler;
  502. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  503. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  504. }
  505. private void ProgressHandler<T>(T state, int current, int total) where T : Enum
  506. {
  507. bool visible;
  508. string label;
  509. switch (state)
  510. {
  511. case PtcLoadingState ptcState:
  512. visible = ptcState != PtcLoadingState.Loaded;
  513. label = $"PTC : {current}/{total}";
  514. break;
  515. case ShaderCacheLoadingState shaderCacheState:
  516. visible = shaderCacheState != ShaderCacheLoadingState.Loaded;
  517. label = $"Shaders : {current}/{total}";
  518. break;
  519. default:
  520. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  521. }
  522. Application.Invoke(delegate
  523. {
  524. _loadingStatusLabel.Text = label;
  525. _loadingStatusBar.Fraction = total > 0 ? (double)current / total : 0;
  526. _loadingStatusBar.Visible = visible;
  527. _loadingStatusLabel.Visible = visible;
  528. });
  529. }
  530. public void UpdateGameTable()
  531. {
  532. if (_updatingGameTable || _gameLoaded)
  533. {
  534. return;
  535. }
  536. _updatingGameTable = true;
  537. _tableStore.Clear();
  538. Thread applicationLibraryThread = new Thread(() =>
  539. {
  540. _applicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs, ConfigurationState.Instance.System.Language);
  541. _updatingGameTable = false;
  542. });
  543. applicationLibraryThread.Name = "GUI.ApplicationLibraryThread";
  544. applicationLibraryThread.IsBackground = true;
  545. applicationLibraryThread.Start();
  546. }
  547. [Conditional("RELEASE")]
  548. public void PerformanceCheck()
  549. {
  550. if (ConfigurationState.Instance.Logger.EnableTrace.Value)
  551. {
  552. MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  553. {
  554. Title = "Ryujinx - Warning",
  555. Text = "You have trace logging enabled, which is designed to be used by developers only.",
  556. SecondaryText = "For optimal performance, it's recommended to disable trace logging. Would you like to disable trace logging now?"
  557. };
  558. if (debugWarningDialog.Run() == (int)ResponseType.Yes)
  559. {
  560. ConfigurationState.Instance.Logger.EnableTrace.Value = false;
  561. SaveConfig();
  562. }
  563. debugWarningDialog.Dispose();
  564. }
  565. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  566. {
  567. MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  568. {
  569. Title = "Ryujinx - Warning",
  570. Text = "You have shader dumping enabled, which is designed to be used by developers only.",
  571. SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
  572. };
  573. if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
  574. {
  575. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  576. SaveConfig();
  577. }
  578. shadersDumpWarningDialog.Dispose();
  579. }
  580. }
  581. public void LoadApplication(string path, bool startFullscreen = false)
  582. {
  583. if (_gameLoaded)
  584. {
  585. GtkDialog.CreateInfoDialog("A game has already been loaded", "Please stop emulation or close the emulator before launching another game.");
  586. }
  587. else
  588. {
  589. PerformanceCheck();
  590. Logger.RestartTime();
  591. RendererWidget = CreateRendererWidget();
  592. SwitchToRenderWidget(startFullscreen);
  593. InitializeSwitchInstance();
  594. UpdateGraphicsConfig();
  595. SetupProgressUiHandlers();
  596. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  597. bool isDirectory = Directory.Exists(path);
  598. bool isFirmwareTitle = false;
  599. if (path.StartsWith("@SystemContent"))
  600. {
  601. path = _virtualFileSystem.SwitchPathToSystemPath(path);
  602. isFirmwareTitle = true;
  603. }
  604. if (!SetupValidator.CanStartApplication(_contentManager, path, out UserError userError))
  605. {
  606. if (SetupValidator.CanFixStartApplication(_contentManager, path, userError, out firmwareVersion))
  607. {
  608. if (userError == UserError.NoFirmware)
  609. {
  610. string message = $"Would you like to install the firmware embedded in this game? (Firmware {firmwareVersion.VersionString})";
  611. ResponseType responseDialog = (ResponseType)GtkDialog.CreateConfirmationDialog("No Firmware Installed", message).Run();
  612. if (responseDialog != ResponseType.Yes)
  613. {
  614. UserErrorDialog.CreateUserErrorDialog(userError);
  615. _emulationContext.Dispose();
  616. SwitchToGameTable();
  617. return;
  618. }
  619. }
  620. if (!SetupValidator.TryFixStartApplication(_contentManager, path, userError, out _))
  621. {
  622. UserErrorDialog.CreateUserErrorDialog(userError);
  623. _emulationContext.Dispose();
  624. SwitchToGameTable();
  625. return;
  626. }
  627. // Tell the user that we installed a firmware for them.
  628. if (userError == UserError.NoFirmware)
  629. {
  630. firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  631. RefreshFirmwareLabel();
  632. 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.";
  633. GtkDialog.CreateInfoDialog($"Firmware {firmwareVersion.VersionString} was installed", message);
  634. }
  635. }
  636. else
  637. {
  638. UserErrorDialog.CreateUserErrorDialog(userError);
  639. _emulationContext.Dispose();
  640. SwitchToGameTable();
  641. return;
  642. }
  643. }
  644. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  645. if (isFirmwareTitle)
  646. {
  647. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  648. _emulationContext.LoadNca(path);
  649. }
  650. else if (Directory.Exists(path))
  651. {
  652. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  653. if (romFsFiles.Length == 0)
  654. {
  655. romFsFiles = Directory.GetFiles(path, "*.romfs");
  656. }
  657. if (romFsFiles.Length > 0)
  658. {
  659. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  660. _emulationContext.LoadCart(path, romFsFiles[0]);
  661. }
  662. else
  663. {
  664. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  665. _emulationContext.LoadCart(path);
  666. }
  667. }
  668. else if (File.Exists(path))
  669. {
  670. switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
  671. {
  672. case ".xci":
  673. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  674. _emulationContext.LoadXci(path);
  675. break;
  676. case ".nca":
  677. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  678. _emulationContext.LoadNca(path);
  679. break;
  680. case ".nsp":
  681. case ".pfs0":
  682. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  683. _emulationContext.LoadNsp(path);
  684. break;
  685. default:
  686. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  687. try
  688. {
  689. _emulationContext.LoadProgram(path);
  690. }
  691. catch (ArgumentOutOfRangeException)
  692. {
  693. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  694. }
  695. break;
  696. }
  697. }
  698. else
  699. {
  700. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  701. _emulationContext.Dispose();
  702. RendererWidget.Dispose();
  703. return;
  704. }
  705. _currentEmulatedGamePath = path;
  706. _deviceExitStatus.Reset();
  707. Translator.IsReadyForTranslation.Reset();
  708. Thread windowThread = new Thread(() =>
  709. {
  710. CreateGameWindow();
  711. })
  712. {
  713. Name = "GUI.WindowThread"
  714. };
  715. windowThread.Start();
  716. _gameLoaded = true;
  717. _actionMenu.Sensitive = true;
  718. UpdateMenuItem.Sensitive = false;
  719. _lastScannedAmiiboId = "";
  720. _firmwareInstallFile.Sensitive = false;
  721. _firmwareInstallDirectory.Sensitive = false;
  722. DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Application.TitleIdText, _emulationContext.Application.TitleName);
  723. _applicationLibrary.LoadAndSaveMetaData(_emulationContext.Application.TitleIdText, appMetadata =>
  724. {
  725. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  726. });
  727. }
  728. }
  729. private RendererWidgetBase CreateRendererWidget()
  730. {
  731. if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
  732. {
  733. return new VKRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  734. }
  735. else
  736. {
  737. return new GlRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  738. }
  739. }
  740. private void SwitchToRenderWidget(bool startFullscreen = false)
  741. {
  742. _viewBox.Remove(_gameTableWindow);
  743. RendererWidget.Expand = true;
  744. _viewBox.Child = RendererWidget;
  745. RendererWidget.ShowAll();
  746. EditFooterForGameRenderer();
  747. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  748. {
  749. ToggleExtraWidgets(false);
  750. }
  751. else if (startFullscreen || ConfigurationState.Instance.Ui.StartFullscreen.Value)
  752. {
  753. FullScreen_Toggled(null, null);
  754. }
  755. }
  756. private void SwitchToGameTable()
  757. {
  758. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  759. {
  760. ToggleExtraWidgets(true);
  761. }
  762. RendererWidget.Exit();
  763. if (RendererWidget.Window != Window && RendererWidget.Window != null)
  764. {
  765. RendererWidget.Window.Dispose();
  766. }
  767. RendererWidget.Dispose();
  768. if (OperatingSystem.IsWindows())
  769. {
  770. _windowsMultimediaTimerResolution?.Dispose();
  771. _windowsMultimediaTimerResolution = null;
  772. }
  773. DisplaySleep.Restore();
  774. _viewBox.Remove(RendererWidget);
  775. _viewBox.Add(_gameTableWindow);
  776. _gameTableWindow.Expand = true;
  777. Window.Title = $"Ryujinx {Program.Version}";
  778. _emulationContext = null;
  779. _gameLoaded = false;
  780. RendererWidget = null;
  781. DiscordIntegrationModule.SwitchToMainMenu();
  782. RecreateFooterForMenu();
  783. UpdateColumns();
  784. UpdateGameTable();
  785. RefreshFirmwareLabel();
  786. HandleRelaunch();
  787. }
  788. private void CreateGameWindow()
  789. {
  790. if (OperatingSystem.IsWindows())
  791. {
  792. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  793. }
  794. DisplaySleep.Prevent();
  795. RendererWidget.Initialize(_emulationContext);
  796. RendererWidget.WaitEvent.WaitOne();
  797. RendererWidget.Start();
  798. Ptc.Close();
  799. PtcProfiler.Stop();
  800. _emulationContext.Dispose();
  801. _deviceExitStatus.Set();
  802. // NOTE: Everything that is here will not be executed when you close the UI.
  803. Application.Invoke(delegate
  804. {
  805. SwitchToGameTable();
  806. });
  807. }
  808. private void RecreateFooterForMenu()
  809. {
  810. _listStatusBox.Show();
  811. _statusBar.Hide();
  812. }
  813. private void EditFooterForGameRenderer()
  814. {
  815. _listStatusBox.Hide();
  816. _statusBar.Show();
  817. }
  818. public void ToggleExtraWidgets(bool show)
  819. {
  820. if (RendererWidget != null)
  821. {
  822. if (show)
  823. {
  824. _menuBar.ShowAll();
  825. _footerBox.Show();
  826. _statusBar.Show();
  827. }
  828. else
  829. {
  830. _menuBar.Hide();
  831. _footerBox.Hide();
  832. }
  833. }
  834. }
  835. private void UpdateGameMetadata(string titleId)
  836. {
  837. if (_gameLoaded)
  838. {
  839. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  840. {
  841. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  842. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  843. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  844. });
  845. }
  846. }
  847. public void UpdateGraphicsConfig()
  848. {
  849. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  850. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  851. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  852. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  853. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  854. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  855. Graphics.Gpu.GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression;
  856. Graphics.Gpu.GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE;
  857. }
  858. public void SaveConfig()
  859. {
  860. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  861. }
  862. private void End()
  863. {
  864. if (_ending)
  865. {
  866. return;
  867. }
  868. _ending = true;
  869. if (_emulationContext != null)
  870. {
  871. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  872. if (RendererWidget != null)
  873. {
  874. // We tell the widget that we are exiting.
  875. RendererWidget.Exit();
  876. // Wait for the other thread to dispose the HLE context before exiting.
  877. _deviceExitStatus.WaitOne();
  878. RendererWidget.Dispose();
  879. }
  880. }
  881. Dispose();
  882. Program.Exit();
  883. Application.Quit();
  884. }
  885. //
  886. // Events
  887. //
  888. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  889. {
  890. Application.Invoke(delegate
  891. {
  892. _tableStore.AppendValues(
  893. args.AppData.Favorite,
  894. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  895. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  896. args.AppData.Developer,
  897. args.AppData.Version,
  898. args.AppData.TimePlayed,
  899. args.AppData.LastPlayed,
  900. args.AppData.FileExtension,
  901. args.AppData.FileSize,
  902. args.AppData.Path,
  903. args.AppData.ControlHolder);
  904. });
  905. }
  906. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  907. {
  908. Application.Invoke(delegate
  909. {
  910. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  911. float barValue = 0;
  912. if (args.NumAppsFound != 0)
  913. {
  914. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  915. }
  916. _progressBar.Fraction = barValue;
  917. // Reset the vertical scrollbar to the top when titles finish loading
  918. if (args.NumAppsLoaded == args.NumAppsFound)
  919. {
  920. _gameTableWindow.Vadjustment.Value = 0;
  921. }
  922. });
  923. }
  924. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  925. {
  926. Application.Invoke(delegate
  927. {
  928. _gameStatus.Text = args.GameStatus;
  929. _fifoStatus.Text = args.FifoStatus;
  930. _gpuName.Text = args.GpuName;
  931. _dockedMode.Text = args.DockedMode;
  932. _aspectRatio.Text = args.AspectRatio;
  933. _gpuBackend.Text = args.GpuBackend;
  934. _volumeStatus.Text = GetVolumeLabelText(args.Volume);
  935. if (args.VSyncEnabled)
  936. {
  937. _vSyncStatus.Attributes = new Pango.AttrList();
  938. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  939. }
  940. else
  941. {
  942. _vSyncStatus.Attributes = new Pango.AttrList();
  943. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  944. }
  945. });
  946. }
  947. private void FavToggle_Toggled(object sender, ToggledArgs args)
  948. {
  949. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  950. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  951. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  952. _tableStore.SetValue(treeIter, 0, newToggleValue);
  953. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  954. {
  955. appMetadata.Favorite = newToggleValue;
  956. });
  957. }
  958. private void Column_Clicked(object sender, EventArgs args)
  959. {
  960. TreeViewColumn column = (TreeViewColumn)sender;
  961. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  962. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  963. SaveConfig();
  964. }
  965. private void Row_Activated(object sender, RowActivatedArgs args)
  966. {
  967. _gameTableSelection.GetSelected(out TreeIter treeIter);
  968. string path = (string)_tableStore.GetValue(treeIter, 9);
  969. LoadApplication(path);
  970. }
  971. private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  972. {
  973. _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;
  974. Logger.Info?.Print(LogClass.Application, $"VSync toggled to: {_emulationContext.EnableDeviceVsync}");
  975. }
  976. private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
  977. {
  978. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  979. }
  980. private string GetVolumeLabelText(float volume)
  981. {
  982. string icon = volume == 0 ? "🔇" : "🔊";
  983. return $"{icon} {(int)(volume * 100)}%";
  984. }
  985. private void VolumeStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  986. {
  987. if (_emulationContext != null)
  988. {
  989. if (_emulationContext.IsAudioMuted())
  990. {
  991. _emulationContext.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  992. }
  993. else
  994. {
  995. _emulationContext.SetVolume(0);
  996. }
  997. }
  998. }
  999. private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
  1000. {
  1001. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  1002. ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames<AspectRatio>().Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  1003. }
  1004. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  1005. {
  1006. if (args.Event.Button != 3 /* Right Click */)
  1007. {
  1008. return;
  1009. }
  1010. _gameTableSelection.GetSelected(out TreeIter treeIter);
  1011. if (treeIter.UserData == IntPtr.Zero)
  1012. {
  1013. return;
  1014. }
  1015. string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString();
  1016. string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0];
  1017. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  1018. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  1019. _ = new GameTableContextMenu(this, _virtualFileSystem, _accountManager, _libHacHorizonManager.RyujinxClient, titleFilePath, titleName, titleId, controlData);
  1020. }
  1021. private void Load_Application_File(object sender, EventArgs args)
  1022. {
  1023. using (FileChooserNative fileChooser = new FileChooserNative("Choose the file to open", this, FileChooserAction.Open, "Open", "Cancel"))
  1024. {
  1025. FileFilter filter = new FileFilter()
  1026. {
  1027. Name = "Switch Executables"
  1028. };
  1029. filter.AddPattern("*.xci");
  1030. filter.AddPattern("*.nsp");
  1031. filter.AddPattern("*.pfs0");
  1032. filter.AddPattern("*.nca");
  1033. filter.AddPattern("*.nro");
  1034. filter.AddPattern("*.nso");
  1035. fileChooser.AddFilter(filter);
  1036. if (fileChooser.Run() == (int)ResponseType.Accept)
  1037. {
  1038. LoadApplication(fileChooser.Filename);
  1039. }
  1040. }
  1041. }
  1042. private void Load_Application_Folder(object sender, EventArgs args)
  1043. {
  1044. using (FileChooserNative fileChooser = new FileChooserNative("Choose the folder to open", this, FileChooserAction.SelectFolder, "Open", "Cancel"))
  1045. {
  1046. if (fileChooser.Run() == (int)ResponseType.Accept)
  1047. {
  1048. LoadApplication(fileChooser.Filename);
  1049. }
  1050. }
  1051. }
  1052. private void FileMenu_StateChanged(object o, StateChangedArgs args)
  1053. {
  1054. _appletMenu.Sensitive = _emulationContext == null && _contentManager.GetCurrentFirmwareVersion() != null && _contentManager.GetCurrentFirmwareVersion().Major > 3;
  1055. _loadApplicationFile.Sensitive = _emulationContext == null;
  1056. _loadApplicationFolder.Sensitive = _emulationContext == null;
  1057. }
  1058. private void Load_Mii_Edit_Applet(object sender, EventArgs args)
  1059. {
  1060. string contentPath = _contentManager.GetInstalledContentPath(0x0100000000001009, StorageId.BuiltInSystem, NcaContentType.Program);
  1061. LoadApplication(contentPath);
  1062. }
  1063. private void Open_Ryu_Folder(object sender, EventArgs args)
  1064. {
  1065. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  1066. }
  1067. private void OpenLogsFolder_Pressed(object sender, EventArgs args)
  1068. {
  1069. string logPath = System.IO.Path.Combine(ReleaseInformations.GetBaseApplicationDirectory(), "Logs");
  1070. new DirectoryInfo(logPath).Create();
  1071. OpenHelper.OpenFolder(logPath);
  1072. }
  1073. private void Exit_Pressed(object sender, EventArgs args)
  1074. {
  1075. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  1076. {
  1077. End();
  1078. }
  1079. }
  1080. private void Window_Close(object sender, DeleteEventArgs args)
  1081. {
  1082. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  1083. {
  1084. End();
  1085. }
  1086. else
  1087. {
  1088. args.RetVal = true;
  1089. }
  1090. }
  1091. private void StopEmulation_Pressed(object sender, EventArgs args)
  1092. {
  1093. if (_emulationContext != null)
  1094. {
  1095. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  1096. }
  1097. _pauseEmulation.Sensitive = false;
  1098. _resumeEmulation.Sensitive = false;
  1099. UpdateMenuItem.Sensitive = true;
  1100. RendererWidget?.Exit();
  1101. }
  1102. private void PauseEmulation_Pressed(object sender, EventArgs args)
  1103. {
  1104. _pauseEmulation.Sensitive = false;
  1105. _resumeEmulation.Sensitive = true;
  1106. _emulationContext.System.TogglePauseEmulation(true);
  1107. }
  1108. private void ResumeEmulation_Pressed(object sender, EventArgs args)
  1109. {
  1110. _pauseEmulation.Sensitive = true;
  1111. _resumeEmulation.Sensitive = false;
  1112. _emulationContext.System.TogglePauseEmulation(false);
  1113. }
  1114. public void ActivatePauseMenu()
  1115. {
  1116. _pauseEmulation.Sensitive = true;
  1117. _resumeEmulation.Sensitive = false;
  1118. }
  1119. public void TogglePause()
  1120. {
  1121. _pauseEmulation.Sensitive ^= true;
  1122. _resumeEmulation.Sensitive ^= true;
  1123. _emulationContext.System.TogglePauseEmulation(_resumeEmulation.Sensitive);
  1124. }
  1125. private void Installer_File_Pressed(object o, EventArgs args)
  1126. {
  1127. FileChooserNative fileChooser = new FileChooserNative("Choose the firmware file to open", this, FileChooserAction.Open, "Open", "Cancel");
  1128. FileFilter filter = new FileFilter
  1129. {
  1130. Name = "Switch Firmware Files"
  1131. };
  1132. filter.AddPattern("*.zip");
  1133. filter.AddPattern("*.xci");
  1134. fileChooser.AddFilter(filter);
  1135. HandleInstallerDialog(fileChooser);
  1136. }
  1137. private void Installer_Directory_Pressed(object o, EventArgs args)
  1138. {
  1139. FileChooserNative directoryChooser = new FileChooserNative("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Open", "Cancel");
  1140. HandleInstallerDialog(directoryChooser);
  1141. }
  1142. private void HandleInstallerDialog(FileChooserNative fileChooser)
  1143. {
  1144. if (fileChooser.Run() == (int)ResponseType.Accept)
  1145. {
  1146. try
  1147. {
  1148. string filename = fileChooser.Filename;
  1149. fileChooser.Dispose();
  1150. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  1151. if (firmwareVersion is null)
  1152. {
  1153. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  1154. return;
  1155. }
  1156. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  1157. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  1158. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  1159. if (currentVersion != null)
  1160. {
  1161. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  1162. }
  1163. dialogMessage += "\n\nDo you want to continue?";
  1164. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  1165. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  1166. if (responseInstallDialog == ResponseType.Yes)
  1167. {
  1168. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  1169. Thread thread = new Thread(() =>
  1170. {
  1171. Application.Invoke(delegate
  1172. {
  1173. waitingDialog.Run();
  1174. });
  1175. try
  1176. {
  1177. _contentManager.InstallFirmware(filename);
  1178. Application.Invoke(delegate
  1179. {
  1180. waitingDialog.Dispose();
  1181. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  1182. GtkDialog.CreateInfoDialog(dialogTitle, message);
  1183. Logger.Info?.Print(LogClass.Application, message);
  1184. // Purge Applet Cache.
  1185. DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));
  1186. if (miiEditorCacheFolder.Exists)
  1187. {
  1188. miiEditorCacheFolder.Delete(true);
  1189. }
  1190. });
  1191. }
  1192. catch (Exception ex)
  1193. {
  1194. Application.Invoke(delegate
  1195. {
  1196. waitingDialog.Dispose();
  1197. GtkDialog.CreateErrorDialog(ex.Message);
  1198. });
  1199. }
  1200. finally
  1201. {
  1202. RefreshFirmwareLabel();
  1203. }
  1204. });
  1205. thread.Name = "GUI.FirmwareInstallerThread";
  1206. thread.Start();
  1207. }
  1208. }
  1209. catch (MissingKeyException ex)
  1210. {
  1211. Logger.Error?.Print(LogClass.Application, ex.ToString());
  1212. UserErrorDialog.CreateUserErrorDialog(UserError.FirmwareParsingFailed);
  1213. }
  1214. catch (Exception ex)
  1215. {
  1216. GtkDialog.CreateErrorDialog(ex.Message);
  1217. }
  1218. }
  1219. else
  1220. {
  1221. fileChooser.Dispose();
  1222. }
  1223. }
  1224. private void RefreshFirmwareLabel()
  1225. {
  1226. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  1227. Application.Invoke(delegate
  1228. {
  1229. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  1230. });
  1231. }
  1232. private void HandleRelaunch()
  1233. {
  1234. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  1235. {
  1236. _userChannelPersistence.ShouldRestart = false;
  1237. LoadApplication(_currentEmulatedGamePath);
  1238. }
  1239. else
  1240. {
  1241. // otherwise, clear state.
  1242. _userChannelPersistence = new UserChannelPersistence();
  1243. _currentEmulatedGamePath = null;
  1244. _actionMenu.Sensitive = false;
  1245. _firmwareInstallFile.Sensitive = true;
  1246. _firmwareInstallDirectory.Sensitive = true;
  1247. }
  1248. }
  1249. private void FullScreen_Toggled(object sender, EventArgs args)
  1250. {
  1251. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  1252. {
  1253. Fullscreen();
  1254. ToggleExtraWidgets(false);
  1255. }
  1256. else
  1257. {
  1258. Unfullscreen();
  1259. ToggleExtraWidgets(true);
  1260. }
  1261. }
  1262. private void StartFullScreen_Toggled(object sender, EventArgs args)
  1263. {
  1264. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  1265. SaveConfig();
  1266. }
  1267. private void ShowConsole_Toggled(object sender, EventArgs args)
  1268. {
  1269. ConfigurationState.Instance.Ui.ShowConsole.Value = _showConsole.Active;
  1270. SaveConfig();
  1271. }
  1272. private void OptionMenu_StateChanged(object o, StateChangedArgs args)
  1273. {
  1274. _manageUserProfiles.Sensitive = _emulationContext == null;
  1275. }
  1276. private void Settings_Pressed(object sender, EventArgs args)
  1277. {
  1278. SettingsWindow settingsWindow = new SettingsWindow(this, _virtualFileSystem, _contentManager);
  1279. settingsWindow.SetSizeRequest((int)(settingsWindow.DefaultWidth * Program.WindowScaleFactor), (int)(settingsWindow.DefaultHeight * Program.WindowScaleFactor));
  1280. settingsWindow.Show();
  1281. }
  1282. private void HideUi_Pressed(object sender, EventArgs args)
  1283. {
  1284. ToggleExtraWidgets(false);
  1285. }
  1286. private void ManageCheats_Pressed(object sender, EventArgs args)
  1287. {
  1288. var window = new CheatWindow(_virtualFileSystem, _emulationContext.Application.TitleId, _emulationContext.Application.TitleName);
  1289. window.Destroyed += CheatWindow_Destroyed;
  1290. window.Show();
  1291. }
  1292. private void CheatWindow_Destroyed(object sender, EventArgs e)
  1293. {
  1294. _emulationContext.EnableCheats();
  1295. (sender as CheatWindow).Destroyed -= CheatWindow_Destroyed;
  1296. }
  1297. private void ManageUserProfiles_Pressed(object sender, EventArgs args)
  1298. {
  1299. UserProfilesManagerWindow userProfilesManagerWindow = new UserProfilesManagerWindow(_accountManager, _contentManager, _virtualFileSystem);
  1300. userProfilesManagerWindow.SetSizeRequest((int)(userProfilesManagerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(userProfilesManagerWindow.DefaultHeight * Program.WindowScaleFactor));
  1301. userProfilesManagerWindow.Show();
  1302. }
  1303. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  1304. {
  1305. if (_emulationContext != null)
  1306. {
  1307. _emulationContext.System.SimulateWakeUpMessage();
  1308. }
  1309. }
  1310. private void ActionMenu_StateChanged(object o, StateChangedArgs args)
  1311. {
  1312. _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _);
  1313. _takeScreenshot.Sensitive = _emulationContext != null;
  1314. }
  1315. private void Scan_Amiibo(object sender, EventArgs args)
  1316. {
  1317. if (_emulationContext.System.SearchingForAmiibo(out int deviceId))
  1318. {
  1319. AmiiboWindow amiiboWindow = new AmiiboWindow
  1320. {
  1321. LastScannedAmiiboShowAll = _lastScannedAmiiboShowAll,
  1322. LastScannedAmiiboId = _lastScannedAmiiboId,
  1323. DeviceId = deviceId,
  1324. TitleId = _emulationContext.Application.TitleIdText.ToUpper()
  1325. };
  1326. amiiboWindow.DeleteEvent += AmiiboWindow_DeleteEvent;
  1327. amiiboWindow.Show();
  1328. }
  1329. else
  1330. {
  1331. GtkDialog.CreateInfoDialog($"Amiibo", "The game is currently not ready to receive Amiibo scan data. Ensure that you have an Amiibo-compatible game open and ready to receive Amiibo scan data.");
  1332. }
  1333. }
  1334. private void Take_Screenshot(object sender, EventArgs args)
  1335. {
  1336. if (_emulationContext != null && RendererWidget != null)
  1337. {
  1338. RendererWidget.ScreenshotRequested = true;
  1339. }
  1340. }
  1341. private void AmiiboWindow_DeleteEvent(object sender, DeleteEventArgs args)
  1342. {
  1343. if (((AmiiboWindow)sender).AmiiboId != "" && ((AmiiboWindow)sender).Response == ResponseType.Ok)
  1344. {
  1345. _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId;
  1346. _lastScannedAmiiboShowAll = ((AmiiboWindow)sender).LastScannedAmiiboShowAll;
  1347. _emulationContext.System.ScanAmiibo(((AmiiboWindow)sender).DeviceId, ((AmiiboWindow)sender).AmiiboId, ((AmiiboWindow)sender).UseRandomUuid);
  1348. }
  1349. }
  1350. private void Update_Pressed(object sender, EventArgs args)
  1351. {
  1352. if (Updater.CanUpdate(true))
  1353. {
  1354. Updater.BeginParse(this, true).ContinueWith(task =>
  1355. {
  1356. Logger.Error?.Print(LogClass.Application, $"Updater error: {task.Exception}");
  1357. }, TaskContinuationOptions.OnlyOnFaulted);
  1358. }
  1359. }
  1360. private void About_Pressed(object sender, EventArgs args)
  1361. {
  1362. AboutWindow aboutWindow = new AboutWindow();
  1363. aboutWindow.SetSizeRequest((int)(aboutWindow.DefaultWidth * Program.WindowScaleFactor), (int)(aboutWindow.DefaultHeight * Program.WindowScaleFactor));
  1364. aboutWindow.Show();
  1365. }
  1366. private void Fav_Toggled(object sender, EventArgs args)
  1367. {
  1368. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  1369. SaveConfig();
  1370. UpdateColumns();
  1371. }
  1372. private void Icon_Toggled(object sender, EventArgs args)
  1373. {
  1374. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  1375. SaveConfig();
  1376. UpdateColumns();
  1377. }
  1378. private void App_Toggled(object sender, EventArgs args)
  1379. {
  1380. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  1381. SaveConfig();
  1382. UpdateColumns();
  1383. }
  1384. private void Developer_Toggled(object sender, EventArgs args)
  1385. {
  1386. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  1387. SaveConfig();
  1388. UpdateColumns();
  1389. }
  1390. private void Version_Toggled(object sender, EventArgs args)
  1391. {
  1392. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  1393. SaveConfig();
  1394. UpdateColumns();
  1395. }
  1396. private void TimePlayed_Toggled(object sender, EventArgs args)
  1397. {
  1398. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  1399. SaveConfig();
  1400. UpdateColumns();
  1401. }
  1402. private void LastPlayed_Toggled(object sender, EventArgs args)
  1403. {
  1404. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  1405. SaveConfig();
  1406. UpdateColumns();
  1407. }
  1408. private void FileExt_Toggled(object sender, EventArgs args)
  1409. {
  1410. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  1411. SaveConfig();
  1412. UpdateColumns();
  1413. }
  1414. private void FileSize_Toggled(object sender, EventArgs args)
  1415. {
  1416. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  1417. SaveConfig();
  1418. UpdateColumns();
  1419. }
  1420. private void Path_Toggled(object sender, EventArgs args)
  1421. {
  1422. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  1423. SaveConfig();
  1424. UpdateColumns();
  1425. }
  1426. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  1427. {
  1428. UpdateGameTable();
  1429. }
  1430. }
  1431. }