MainWindow.cs 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  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.GetObject("_mainWin").Handle)
  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. #if MACOS_BUILD
  709. CreateGameWindow();
  710. #else
  711. Thread windowThread = new Thread(() =>
  712. {
  713. CreateGameWindow();
  714. })
  715. {
  716. Name = "GUI.WindowThread"
  717. };
  718. windowThread.Start();
  719. #endif
  720. _gameLoaded = true;
  721. _actionMenu.Sensitive = true;
  722. UpdateMenuItem.Sensitive = false;
  723. _lastScannedAmiiboId = "";
  724. _firmwareInstallFile.Sensitive = false;
  725. _firmwareInstallDirectory.Sensitive = false;
  726. DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Application.TitleIdText, _emulationContext.Application.TitleName);
  727. _applicationLibrary.LoadAndSaveMetaData(_emulationContext.Application.TitleIdText, appMetadata =>
  728. {
  729. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  730. });
  731. }
  732. }
  733. private RendererWidgetBase CreateRendererWidget()
  734. {
  735. if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
  736. {
  737. return new VKRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  738. }
  739. else
  740. {
  741. return new GlRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  742. }
  743. }
  744. private void SwitchToRenderWidget(bool startFullscreen = false)
  745. {
  746. _viewBox.Remove(_gameTableWindow);
  747. RendererWidget.Expand = true;
  748. _viewBox.Child = RendererWidget;
  749. RendererWidget.ShowAll();
  750. EditFooterForGameRenderer();
  751. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  752. {
  753. ToggleExtraWidgets(false);
  754. }
  755. else if (startFullscreen || ConfigurationState.Instance.Ui.StartFullscreen.Value)
  756. {
  757. FullScreen_Toggled(null, null);
  758. }
  759. }
  760. private void SwitchToGameTable()
  761. {
  762. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  763. {
  764. ToggleExtraWidgets(true);
  765. }
  766. RendererWidget.Exit();
  767. if (RendererWidget.Window != Window && RendererWidget.Window != null)
  768. {
  769. RendererWidget.Window.Dispose();
  770. }
  771. RendererWidget.Dispose();
  772. if (OperatingSystem.IsWindows())
  773. {
  774. _windowsMultimediaTimerResolution?.Dispose();
  775. _windowsMultimediaTimerResolution = null;
  776. }
  777. DisplaySleep.Restore();
  778. _viewBox.Remove(RendererWidget);
  779. _viewBox.Add(_gameTableWindow);
  780. _gameTableWindow.Expand = true;
  781. Window.Title = $"Ryujinx {Program.Version}";
  782. _emulationContext = null;
  783. _gameLoaded = false;
  784. RendererWidget = null;
  785. DiscordIntegrationModule.SwitchToMainMenu();
  786. RecreateFooterForMenu();
  787. UpdateColumns();
  788. UpdateGameTable();
  789. RefreshFirmwareLabel();
  790. HandleRelaunch();
  791. }
  792. private void CreateGameWindow()
  793. {
  794. if (OperatingSystem.IsWindows())
  795. {
  796. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  797. }
  798. DisplaySleep.Prevent();
  799. RendererWidget.Initialize(_emulationContext);
  800. RendererWidget.WaitEvent.WaitOne();
  801. RendererWidget.Start();
  802. Ptc.Close();
  803. PtcProfiler.Stop();
  804. _emulationContext.Dispose();
  805. _deviceExitStatus.Set();
  806. // NOTE: Everything that is here will not be executed when you close the UI.
  807. Application.Invoke(delegate
  808. {
  809. SwitchToGameTable();
  810. });
  811. }
  812. private void RecreateFooterForMenu()
  813. {
  814. _listStatusBox.Show();
  815. _statusBar.Hide();
  816. }
  817. private void EditFooterForGameRenderer()
  818. {
  819. _listStatusBox.Hide();
  820. _statusBar.Show();
  821. }
  822. public void ToggleExtraWidgets(bool show)
  823. {
  824. if (RendererWidget != null)
  825. {
  826. if (show)
  827. {
  828. _menuBar.ShowAll();
  829. _footerBox.Show();
  830. _statusBar.Show();
  831. }
  832. else
  833. {
  834. _menuBar.Hide();
  835. _footerBox.Hide();
  836. }
  837. }
  838. }
  839. private void UpdateGameMetadata(string titleId)
  840. {
  841. if (_gameLoaded)
  842. {
  843. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  844. {
  845. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  846. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  847. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  848. });
  849. }
  850. }
  851. public void UpdateGraphicsConfig()
  852. {
  853. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  854. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  855. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  856. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  857. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  858. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  859. Graphics.Gpu.GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression;
  860. Graphics.Gpu.GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE;
  861. }
  862. public void SaveConfig()
  863. {
  864. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  865. }
  866. private void End()
  867. {
  868. if (_ending)
  869. {
  870. return;
  871. }
  872. _ending = true;
  873. if (_emulationContext != null)
  874. {
  875. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  876. if (RendererWidget != null)
  877. {
  878. // We tell the widget that we are exiting.
  879. RendererWidget.Exit();
  880. // Wait for the other thread to dispose the HLE context before exiting.
  881. _deviceExitStatus.WaitOne();
  882. RendererWidget.Dispose();
  883. }
  884. }
  885. Dispose();
  886. Program.Exit();
  887. Application.Quit();
  888. }
  889. //
  890. // Events
  891. //
  892. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  893. {
  894. Application.Invoke(delegate
  895. {
  896. _tableStore.AppendValues(
  897. args.AppData.Favorite,
  898. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  899. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  900. args.AppData.Developer,
  901. args.AppData.Version,
  902. args.AppData.TimePlayed,
  903. args.AppData.LastPlayed,
  904. args.AppData.FileExtension,
  905. args.AppData.FileSize,
  906. args.AppData.Path,
  907. args.AppData.ControlHolder);
  908. });
  909. }
  910. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  911. {
  912. Application.Invoke(delegate
  913. {
  914. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  915. float barValue = 0;
  916. if (args.NumAppsFound != 0)
  917. {
  918. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  919. }
  920. _progressBar.Fraction = barValue;
  921. // Reset the vertical scrollbar to the top when titles finish loading
  922. if (args.NumAppsLoaded == args.NumAppsFound)
  923. {
  924. _gameTableWindow.Vadjustment.Value = 0;
  925. }
  926. });
  927. }
  928. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  929. {
  930. Application.Invoke(delegate
  931. {
  932. _gameStatus.Text = args.GameStatus;
  933. _fifoStatus.Text = args.FifoStatus;
  934. _gpuName.Text = args.GpuName;
  935. _dockedMode.Text = args.DockedMode;
  936. _aspectRatio.Text = args.AspectRatio;
  937. _gpuBackend.Text = args.GpuBackend;
  938. _volumeStatus.Text = GetVolumeLabelText(args.Volume);
  939. if (args.VSyncEnabled)
  940. {
  941. _vSyncStatus.Attributes = new Pango.AttrList();
  942. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  943. }
  944. else
  945. {
  946. _vSyncStatus.Attributes = new Pango.AttrList();
  947. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  948. }
  949. });
  950. }
  951. private void FavToggle_Toggled(object sender, ToggledArgs args)
  952. {
  953. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  954. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  955. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  956. _tableStore.SetValue(treeIter, 0, newToggleValue);
  957. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  958. {
  959. appMetadata.Favorite = newToggleValue;
  960. });
  961. }
  962. private void Column_Clicked(object sender, EventArgs args)
  963. {
  964. TreeViewColumn column = (TreeViewColumn)sender;
  965. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  966. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  967. SaveConfig();
  968. }
  969. private void Row_Activated(object sender, RowActivatedArgs args)
  970. {
  971. _gameTableSelection.GetSelected(out TreeIter treeIter);
  972. string path = (string)_tableStore.GetValue(treeIter, 9);
  973. LoadApplication(path);
  974. }
  975. private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  976. {
  977. _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;
  978. Logger.Info?.Print(LogClass.Application, $"VSync toggled to: {_emulationContext.EnableDeviceVsync}");
  979. }
  980. private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
  981. {
  982. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  983. }
  984. private string GetVolumeLabelText(float volume)
  985. {
  986. string icon = volume == 0 ? "🔇" : "🔊";
  987. return $"{icon} {(int)(volume * 100)}%";
  988. }
  989. private void VolumeStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  990. {
  991. if (_emulationContext != null)
  992. {
  993. if (_emulationContext.IsAudioMuted())
  994. {
  995. _emulationContext.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  996. }
  997. else
  998. {
  999. _emulationContext.SetVolume(0);
  1000. }
  1001. }
  1002. }
  1003. private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
  1004. {
  1005. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  1006. ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames<AspectRatio>().Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  1007. }
  1008. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  1009. {
  1010. if (args.Event.Button != 3 /* Right Click */)
  1011. {
  1012. return;
  1013. }
  1014. _gameTableSelection.GetSelected(out TreeIter treeIter);
  1015. if (treeIter.UserData == IntPtr.Zero)
  1016. {
  1017. return;
  1018. }
  1019. string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString();
  1020. string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0];
  1021. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  1022. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  1023. _ = new GameTableContextMenu(this, _virtualFileSystem, _accountManager, _libHacHorizonManager.RyujinxClient, titleFilePath, titleName, titleId, controlData);
  1024. }
  1025. private void Load_Application_File(object sender, EventArgs args)
  1026. {
  1027. using (FileChooserNative fileChooser = new FileChooserNative("Choose the file to open", this, FileChooserAction.Open, "Open", "Cancel"))
  1028. {
  1029. FileFilter filter = new FileFilter()
  1030. {
  1031. Name = "Switch Executables"
  1032. };
  1033. filter.AddPattern("*.xci");
  1034. filter.AddPattern("*.nsp");
  1035. filter.AddPattern("*.pfs0");
  1036. filter.AddPattern("*.nca");
  1037. filter.AddPattern("*.nro");
  1038. filter.AddPattern("*.nso");
  1039. fileChooser.AddFilter(filter);
  1040. if (fileChooser.Run() == (int)ResponseType.Accept)
  1041. {
  1042. LoadApplication(fileChooser.Filename);
  1043. }
  1044. }
  1045. }
  1046. private void Load_Application_Folder(object sender, EventArgs args)
  1047. {
  1048. using (FileChooserNative fileChooser = new FileChooserNative("Choose the folder to open", this, FileChooserAction.SelectFolder, "Open", "Cancel"))
  1049. {
  1050. if (fileChooser.Run() == (int)ResponseType.Accept)
  1051. {
  1052. LoadApplication(fileChooser.Filename);
  1053. }
  1054. }
  1055. }
  1056. private void FileMenu_StateChanged(object o, StateChangedArgs args)
  1057. {
  1058. _appletMenu.Sensitive = _emulationContext == null && _contentManager.GetCurrentFirmwareVersion() != null && _contentManager.GetCurrentFirmwareVersion().Major > 3;
  1059. _loadApplicationFile.Sensitive = _emulationContext == null;
  1060. _loadApplicationFolder.Sensitive = _emulationContext == null;
  1061. }
  1062. private void Load_Mii_Edit_Applet(object sender, EventArgs args)
  1063. {
  1064. string contentPath = _contentManager.GetInstalledContentPath(0x0100000000001009, StorageId.BuiltInSystem, NcaContentType.Program);
  1065. LoadApplication(contentPath);
  1066. }
  1067. private void Open_Ryu_Folder(object sender, EventArgs args)
  1068. {
  1069. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  1070. }
  1071. private void OpenLogsFolder_Pressed(object sender, EventArgs args)
  1072. {
  1073. string logPath = System.IO.Path.Combine(ReleaseInformations.GetBaseApplicationDirectory(), "Logs");
  1074. new DirectoryInfo(logPath).Create();
  1075. OpenHelper.OpenFolder(logPath);
  1076. }
  1077. private void Exit_Pressed(object sender, EventArgs args)
  1078. {
  1079. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  1080. {
  1081. End();
  1082. }
  1083. }
  1084. private void Window_Close(object sender, DeleteEventArgs args)
  1085. {
  1086. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  1087. {
  1088. End();
  1089. }
  1090. else
  1091. {
  1092. args.RetVal = true;
  1093. }
  1094. }
  1095. private void StopEmulation_Pressed(object sender, EventArgs args)
  1096. {
  1097. if (_emulationContext != null)
  1098. {
  1099. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  1100. }
  1101. _pauseEmulation.Sensitive = false;
  1102. _resumeEmulation.Sensitive = false;
  1103. UpdateMenuItem.Sensitive = true;
  1104. RendererWidget?.Exit();
  1105. }
  1106. private void PauseEmulation_Pressed(object sender, EventArgs args)
  1107. {
  1108. _pauseEmulation.Sensitive = false;
  1109. _resumeEmulation.Sensitive = true;
  1110. _emulationContext.System.TogglePauseEmulation(true);
  1111. }
  1112. private void ResumeEmulation_Pressed(object sender, EventArgs args)
  1113. {
  1114. _pauseEmulation.Sensitive = true;
  1115. _resumeEmulation.Sensitive = false;
  1116. _emulationContext.System.TogglePauseEmulation(false);
  1117. }
  1118. public void ActivatePauseMenu()
  1119. {
  1120. _pauseEmulation.Sensitive = true;
  1121. _resumeEmulation.Sensitive = false;
  1122. }
  1123. public void TogglePause()
  1124. {
  1125. _pauseEmulation.Sensitive ^= true;
  1126. _resumeEmulation.Sensitive ^= true;
  1127. _emulationContext.System.TogglePauseEmulation(_resumeEmulation.Sensitive);
  1128. }
  1129. private void Installer_File_Pressed(object o, EventArgs args)
  1130. {
  1131. FileChooserNative fileChooser = new FileChooserNative("Choose the firmware file to open", this, FileChooserAction.Open, "Open", "Cancel");
  1132. FileFilter filter = new FileFilter
  1133. {
  1134. Name = "Switch Firmware Files"
  1135. };
  1136. filter.AddPattern("*.zip");
  1137. filter.AddPattern("*.xci");
  1138. fileChooser.AddFilter(filter);
  1139. HandleInstallerDialog(fileChooser);
  1140. }
  1141. private void Installer_Directory_Pressed(object o, EventArgs args)
  1142. {
  1143. FileChooserNative directoryChooser = new FileChooserNative("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Open", "Cancel");
  1144. HandleInstallerDialog(directoryChooser);
  1145. }
  1146. private void HandleInstallerDialog(FileChooserNative fileChooser)
  1147. {
  1148. if (fileChooser.Run() == (int)ResponseType.Accept)
  1149. {
  1150. try
  1151. {
  1152. string filename = fileChooser.Filename;
  1153. fileChooser.Dispose();
  1154. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  1155. if (firmwareVersion is null)
  1156. {
  1157. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  1158. return;
  1159. }
  1160. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  1161. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  1162. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  1163. if (currentVersion != null)
  1164. {
  1165. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  1166. }
  1167. dialogMessage += "\n\nDo you want to continue?";
  1168. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  1169. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  1170. if (responseInstallDialog == ResponseType.Yes)
  1171. {
  1172. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  1173. Thread thread = new Thread(() =>
  1174. {
  1175. Application.Invoke(delegate
  1176. {
  1177. waitingDialog.Run();
  1178. });
  1179. try
  1180. {
  1181. _contentManager.InstallFirmware(filename);
  1182. Application.Invoke(delegate
  1183. {
  1184. waitingDialog.Dispose();
  1185. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  1186. GtkDialog.CreateInfoDialog(dialogTitle, message);
  1187. Logger.Info?.Print(LogClass.Application, message);
  1188. // Purge Applet Cache.
  1189. DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));
  1190. if (miiEditorCacheFolder.Exists)
  1191. {
  1192. miiEditorCacheFolder.Delete(true);
  1193. }
  1194. });
  1195. }
  1196. catch (Exception ex)
  1197. {
  1198. Application.Invoke(delegate
  1199. {
  1200. waitingDialog.Dispose();
  1201. GtkDialog.CreateErrorDialog(ex.Message);
  1202. });
  1203. }
  1204. finally
  1205. {
  1206. RefreshFirmwareLabel();
  1207. }
  1208. });
  1209. thread.Name = "GUI.FirmwareInstallerThread";
  1210. thread.Start();
  1211. }
  1212. }
  1213. catch (MissingKeyException ex)
  1214. {
  1215. Logger.Error?.Print(LogClass.Application, ex.ToString());
  1216. UserErrorDialog.CreateUserErrorDialog(UserError.FirmwareParsingFailed);
  1217. }
  1218. catch (Exception ex)
  1219. {
  1220. GtkDialog.CreateErrorDialog(ex.Message);
  1221. }
  1222. }
  1223. else
  1224. {
  1225. fileChooser.Dispose();
  1226. }
  1227. }
  1228. private void RefreshFirmwareLabel()
  1229. {
  1230. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  1231. Application.Invoke(delegate
  1232. {
  1233. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  1234. });
  1235. }
  1236. private void HandleRelaunch()
  1237. {
  1238. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  1239. {
  1240. _userChannelPersistence.ShouldRestart = false;
  1241. LoadApplication(_currentEmulatedGamePath);
  1242. }
  1243. else
  1244. {
  1245. // otherwise, clear state.
  1246. _userChannelPersistence = new UserChannelPersistence();
  1247. _currentEmulatedGamePath = null;
  1248. _actionMenu.Sensitive = false;
  1249. _firmwareInstallFile.Sensitive = true;
  1250. _firmwareInstallDirectory.Sensitive = true;
  1251. }
  1252. }
  1253. private void FullScreen_Toggled(object sender, EventArgs args)
  1254. {
  1255. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  1256. {
  1257. Fullscreen();
  1258. ToggleExtraWidgets(false);
  1259. }
  1260. else
  1261. {
  1262. Unfullscreen();
  1263. ToggleExtraWidgets(true);
  1264. }
  1265. }
  1266. private void StartFullScreen_Toggled(object sender, EventArgs args)
  1267. {
  1268. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  1269. SaveConfig();
  1270. }
  1271. private void ShowConsole_Toggled(object sender, EventArgs args)
  1272. {
  1273. ConfigurationState.Instance.Ui.ShowConsole.Value = _showConsole.Active;
  1274. SaveConfig();
  1275. }
  1276. private void OptionMenu_StateChanged(object o, StateChangedArgs args)
  1277. {
  1278. _manageUserProfiles.Sensitive = _emulationContext == null;
  1279. }
  1280. private void Settings_Pressed(object sender, EventArgs args)
  1281. {
  1282. SettingsWindow settingsWindow = new SettingsWindow(this, _virtualFileSystem, _contentManager);
  1283. settingsWindow.SetSizeRequest((int)(settingsWindow.DefaultWidth * Program.WindowScaleFactor), (int)(settingsWindow.DefaultHeight * Program.WindowScaleFactor));
  1284. settingsWindow.Show();
  1285. }
  1286. private void HideUi_Pressed(object sender, EventArgs args)
  1287. {
  1288. ToggleExtraWidgets(false);
  1289. }
  1290. private void ManageCheats_Pressed(object sender, EventArgs args)
  1291. {
  1292. var window = new CheatWindow(_virtualFileSystem, _emulationContext.Application.TitleId, _emulationContext.Application.TitleName);
  1293. window.Destroyed += CheatWindow_Destroyed;
  1294. window.Show();
  1295. }
  1296. private void CheatWindow_Destroyed(object sender, EventArgs e)
  1297. {
  1298. _emulationContext.EnableCheats();
  1299. (sender as CheatWindow).Destroyed -= CheatWindow_Destroyed;
  1300. }
  1301. private void ManageUserProfiles_Pressed(object sender, EventArgs args)
  1302. {
  1303. UserProfilesManagerWindow userProfilesManagerWindow = new UserProfilesManagerWindow(_accountManager, _contentManager, _virtualFileSystem);
  1304. userProfilesManagerWindow.SetSizeRequest((int)(userProfilesManagerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(userProfilesManagerWindow.DefaultHeight * Program.WindowScaleFactor));
  1305. userProfilesManagerWindow.Show();
  1306. }
  1307. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  1308. {
  1309. if (_emulationContext != null)
  1310. {
  1311. _emulationContext.System.SimulateWakeUpMessage();
  1312. }
  1313. }
  1314. private void ActionMenu_StateChanged(object o, StateChangedArgs args)
  1315. {
  1316. _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _);
  1317. _takeScreenshot.Sensitive = _emulationContext != null;
  1318. }
  1319. private void Scan_Amiibo(object sender, EventArgs args)
  1320. {
  1321. if (_emulationContext.System.SearchingForAmiibo(out int deviceId))
  1322. {
  1323. AmiiboWindow amiiboWindow = new AmiiboWindow
  1324. {
  1325. LastScannedAmiiboShowAll = _lastScannedAmiiboShowAll,
  1326. LastScannedAmiiboId = _lastScannedAmiiboId,
  1327. DeviceId = deviceId,
  1328. TitleId = _emulationContext.Application.TitleIdText.ToUpper()
  1329. };
  1330. amiiboWindow.DeleteEvent += AmiiboWindow_DeleteEvent;
  1331. amiiboWindow.Show();
  1332. }
  1333. else
  1334. {
  1335. 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.");
  1336. }
  1337. }
  1338. private void Take_Screenshot(object sender, EventArgs args)
  1339. {
  1340. if (_emulationContext != null && RendererWidget != null)
  1341. {
  1342. RendererWidget.ScreenshotRequested = true;
  1343. }
  1344. }
  1345. private void AmiiboWindow_DeleteEvent(object sender, DeleteEventArgs args)
  1346. {
  1347. if (((AmiiboWindow)sender).AmiiboId != "" && ((AmiiboWindow)sender).Response == ResponseType.Ok)
  1348. {
  1349. _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId;
  1350. _lastScannedAmiiboShowAll = ((AmiiboWindow)sender).LastScannedAmiiboShowAll;
  1351. _emulationContext.System.ScanAmiibo(((AmiiboWindow)sender).DeviceId, ((AmiiboWindow)sender).AmiiboId, ((AmiiboWindow)sender).UseRandomUuid);
  1352. }
  1353. }
  1354. private void Update_Pressed(object sender, EventArgs args)
  1355. {
  1356. if (Updater.CanUpdate(true))
  1357. {
  1358. Updater.BeginParse(this, true).ContinueWith(task =>
  1359. {
  1360. Logger.Error?.Print(LogClass.Application, $"Updater error: {task.Exception}");
  1361. }, TaskContinuationOptions.OnlyOnFaulted);
  1362. }
  1363. }
  1364. private void About_Pressed(object sender, EventArgs args)
  1365. {
  1366. AboutWindow aboutWindow = new AboutWindow();
  1367. aboutWindow.SetSizeRequest((int)(aboutWindow.DefaultWidth * Program.WindowScaleFactor), (int)(aboutWindow.DefaultHeight * Program.WindowScaleFactor));
  1368. aboutWindow.Show();
  1369. }
  1370. private void Fav_Toggled(object sender, EventArgs args)
  1371. {
  1372. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  1373. SaveConfig();
  1374. UpdateColumns();
  1375. }
  1376. private void Icon_Toggled(object sender, EventArgs args)
  1377. {
  1378. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  1379. SaveConfig();
  1380. UpdateColumns();
  1381. }
  1382. private void App_Toggled(object sender, EventArgs args)
  1383. {
  1384. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  1385. SaveConfig();
  1386. UpdateColumns();
  1387. }
  1388. private void Developer_Toggled(object sender, EventArgs args)
  1389. {
  1390. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  1391. SaveConfig();
  1392. UpdateColumns();
  1393. }
  1394. private void Version_Toggled(object sender, EventArgs args)
  1395. {
  1396. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  1397. SaveConfig();
  1398. UpdateColumns();
  1399. }
  1400. private void TimePlayed_Toggled(object sender, EventArgs args)
  1401. {
  1402. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  1403. SaveConfig();
  1404. UpdateColumns();
  1405. }
  1406. private void LastPlayed_Toggled(object sender, EventArgs args)
  1407. {
  1408. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  1409. SaveConfig();
  1410. UpdateColumns();
  1411. }
  1412. private void FileExt_Toggled(object sender, EventArgs args)
  1413. {
  1414. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  1415. SaveConfig();
  1416. UpdateColumns();
  1417. }
  1418. private void FileSize_Toggled(object sender, EventArgs args)
  1419. {
  1420. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  1421. SaveConfig();
  1422. UpdateColumns();
  1423. }
  1424. private void Path_Toggled(object sender, EventArgs args)
  1425. {
  1426. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  1427. SaveConfig();
  1428. UpdateColumns();
  1429. }
  1430. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  1431. {
  1432. UpdateGameTable();
  1433. }
  1434. }
  1435. }