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. // Sets overridden fields.
  135. int monitorWidth = Display.PrimaryMonitor.Geometry.Width * Display.PrimaryMonitor.ScaleFactor;
  136. int monitorHeight = Display.PrimaryMonitor.Geometry.Height * Display.PrimaryMonitor.ScaleFactor;
  137. DefaultWidth = monitorWidth < 1280 ? monitorWidth : 1280;
  138. DefaultHeight = monitorHeight < 760 ? monitorHeight : 760;
  139. Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png");
  140. Title = $"Ryujinx {Program.Version}";
  141. // Hide emulation context status bar.
  142. _statusBar.Hide();
  143. // Instantiate HLE objects.
  144. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  145. _libHacHorizonManager = new LibHacHorizonManager();
  146. _libHacHorizonManager.InitializeFsServer(_virtualFileSystem);
  147. _libHacHorizonManager.InitializeArpServer();
  148. _libHacHorizonManager.InitializeBcatServer();
  149. _libHacHorizonManager.InitializeSystemClients();
  150. // Save data created before we supported extra data in directory save data will not work properly if
  151. // given empty extra data. Luckily some of that extra data can be created using the data from the
  152. // save data indexer, which should be enough to check access permissions for user saves.
  153. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  154. // Consider removing this at some point in the future when we don't need to worry about old saves.
  155. VirtualFileSystem.FixExtraData(_libHacHorizonManager.RyujinxClient);
  156. _contentManager = new ContentManager(_virtualFileSystem);
  157. _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient, Program.CommandLineProfile);
  158. _userChannelPersistence = new UserChannelPersistence();
  159. // Instantiate GUI objects.
  160. _applicationLibrary = new ApplicationLibrary(_virtualFileSystem);
  161. _uiHandler = new GtkHostUiHandler(this);
  162. _deviceExitStatus = new AutoResetEvent(false);
  163. WindowStateEvent += WindowStateEvent_Changed;
  164. DeleteEvent += Window_Close;
  165. FocusInEvent += MainWindow_FocusInEvent;
  166. FocusOutEvent += MainWindow_FocusOutEvent;
  167. _applicationLibrary.ApplicationAdded += Application_Added;
  168. _applicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated;
  169. _fileMenu.StateChanged += FileMenu_StateChanged;
  170. _actionMenu.StateChanged += ActionMenu_StateChanged;
  171. _optionMenu.StateChanged += OptionMenu_StateChanged;
  172. _gameTable.ButtonReleaseEvent += Row_Clicked;
  173. _fullScreen.Activated += FullScreen_Toggled;
  174. RendererWidgetBase.StatusUpdatedEvent += Update_StatusBar;
  175. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  176. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  177. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  178. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  179. if (ConfigurationState.Instance.Ui.StartFullscreen)
  180. {
  181. _startFullScreen.Active = true;
  182. }
  183. _showConsole.Active = ConfigurationState.Instance.Ui.ShowConsole.Value;
  184. _showConsole.Visible = ConsoleHelper.SetConsoleWindowStateSupported;
  185. _actionMenu.Sensitive = false;
  186. _pauseEmulation.Sensitive = false;
  187. _resumeEmulation.Sensitive = false;
  188. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true;
  189. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true;
  190. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true;
  191. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true;
  192. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true;
  193. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true;
  194. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true;
  195. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true;
  196. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true;
  197. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true;
  198. _favToggle.Toggled += Fav_Toggled;
  199. _iconToggle.Toggled += Icon_Toggled;
  200. _appToggle.Toggled += App_Toggled;
  201. _developerToggle.Toggled += Developer_Toggled;
  202. _versionToggle.Toggled += Version_Toggled;
  203. _timePlayedToggle.Toggled += TimePlayed_Toggled;
  204. _lastPlayedToggle.Toggled += LastPlayed_Toggled;
  205. _fileExtToggle.Toggled += FileExt_Toggled;
  206. _fileSizeToggle.Toggled += FileSize_Toggled;
  207. _pathToggle.Toggled += Path_Toggled;
  208. _gameTable.Model = _tableStore = new ListStore(
  209. typeof(bool),
  210. typeof(Gdk.Pixbuf),
  211. typeof(string),
  212. typeof(string),
  213. typeof(string),
  214. typeof(string),
  215. typeof(string),
  216. typeof(string),
  217. typeof(string),
  218. typeof(string),
  219. typeof(BlitStruct<ApplicationControlProperty>));
  220. _tableStore.SetSortFunc(5, SortHelper.TimePlayedSort);
  221. _tableStore.SetSortFunc(6, SortHelper.LastPlayedSort);
  222. _tableStore.SetSortFunc(8, SortHelper.FileSizeSort);
  223. int columnId = ConfigurationState.Instance.Ui.ColumnSort.SortColumnId;
  224. bool ascending = ConfigurationState.Instance.Ui.ColumnSort.SortAscending;
  225. _tableStore.SetSortColumnId(columnId, ascending ? SortType.Ascending : SortType.Descending);
  226. _gameTable.EnableSearch = true;
  227. _gameTable.SearchColumn = 2;
  228. _gameTable.SearchEqualFunc = (model, col, key, iter) => !((string)model.GetValue(iter, col)).Contains(key, StringComparison.InvariantCultureIgnoreCase);
  229. _hideUi.Label = _hideUi.Label.Replace("SHOWUIKEY", ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi.ToString());
  230. UpdateColumns();
  231. UpdateGameTable();
  232. ConfigurationState.Instance.Ui.GameDirs.Event += (sender, args) =>
  233. {
  234. if (args.OldValue != args.NewValue)
  235. {
  236. UpdateGameTable();
  237. }
  238. };
  239. Task.Run(RefreshFirmwareLabel);
  240. InputManager = new InputManager(new GTK3KeyboardDriver(this), new SDL2GamepadDriver());
  241. }
  242. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  243. {
  244. if (_emulationContext != null)
  245. {
  246. _emulationContext.Configuration.IgnoreMissingServices = args.NewValue;
  247. }
  248. }
  249. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  250. {
  251. if (_emulationContext != null)
  252. {
  253. _emulationContext.Configuration.AspectRatio = args.NewValue;
  254. }
  255. }
  256. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  257. {
  258. if (_emulationContext != null)
  259. {
  260. _emulationContext.System.ChangeDockedModeState(e.NewValue);
  261. }
  262. }
  263. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  264. {
  265. _emulationContext?.SetVolume(e.NewValue);
  266. }
  267. private void WindowStateEvent_Changed(object o, WindowStateEventArgs args)
  268. {
  269. _fullScreen.Label = args.Event.NewWindowState.HasFlag(Gdk.WindowState.Fullscreen) ? "Exit Fullscreen" : "Enter Fullscreen";
  270. }
  271. private void MainWindow_FocusOutEvent(object o, FocusOutEventArgs args)
  272. {
  273. IsFocused = false;
  274. }
  275. private void MainWindow_FocusInEvent(object o, FocusInEventArgs args)
  276. {
  277. IsFocused = true;
  278. }
  279. private void UpdateColumns()
  280. {
  281. foreach (TreeViewColumn column in _gameTable.Columns)
  282. {
  283. _gameTable.RemoveColumn(column);
  284. }
  285. CellRendererToggle favToggle = new CellRendererToggle();
  286. favToggle.Toggled += FavToggle_Toggled;
  287. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0);
  288. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
  289. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
  290. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
  291. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
  292. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
  293. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
  294. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
  295. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
  296. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
  297. foreach (TreeViewColumn column in _gameTable.Columns)
  298. {
  299. switch (column.Title)
  300. {
  301. case "Fav":
  302. column.SortColumnId = 0;
  303. column.Clicked += Column_Clicked;
  304. break;
  305. case "Application":
  306. column.SortColumnId = 2;
  307. column.Clicked += Column_Clicked;
  308. break;
  309. case "Developer":
  310. column.SortColumnId = 3;
  311. column.Clicked += Column_Clicked;
  312. break;
  313. case "Version":
  314. column.SortColumnId = 4;
  315. column.Clicked += Column_Clicked;
  316. break;
  317. case "Time Played":
  318. column.SortColumnId = 5;
  319. column.Clicked += Column_Clicked;
  320. break;
  321. case "Last Played":
  322. column.SortColumnId = 6;
  323. column.Clicked += Column_Clicked;
  324. break;
  325. case "File Ext":
  326. column.SortColumnId = 7;
  327. column.Clicked += Column_Clicked;
  328. break;
  329. case "File Size":
  330. column.SortColumnId = 8;
  331. column.Clicked += Column_Clicked;
  332. break;
  333. case "Path":
  334. column.SortColumnId = 9;
  335. column.Clicked += Column_Clicked;
  336. break;
  337. }
  338. }
  339. }
  340. protected override void OnDestroyed()
  341. {
  342. InputManager.Dispose();
  343. }
  344. private void InitializeSwitchInstance()
  345. {
  346. _virtualFileSystem.ReloadKeySet();
  347. IRenderer renderer;
  348. if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
  349. {
  350. string preferredGpu = ConfigurationState.Instance.Graphics.PreferredGpu.Value;
  351. renderer = new VulkanRenderer(CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu);
  352. }
  353. else
  354. {
  355. renderer = new OpenGLRenderer();
  356. }
  357. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  358. bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  359. if (threadedGAL)
  360. {
  361. renderer = new ThreadedRenderer(renderer);
  362. }
  363. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {threadedGAL}");
  364. IHardwareDeviceDriver deviceDriver = new DummyHardwareDeviceDriver();
  365. if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SDL2)
  366. {
  367. if (SDL2HardwareDeviceDriver.IsSupported)
  368. {
  369. deviceDriver = new SDL2HardwareDeviceDriver();
  370. }
  371. else
  372. {
  373. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  374. if (OpenALHardwareDeviceDriver.IsSupported)
  375. {
  376. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  377. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  378. SaveConfig();
  379. deviceDriver = new OpenALHardwareDeviceDriver();
  380. }
  381. else
  382. {
  383. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");
  384. if (SoundIoHardwareDeviceDriver.IsSupported)
  385. {
  386. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  387. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  388. SaveConfig();
  389. deviceDriver = new SoundIoHardwareDeviceDriver();
  390. }
  391. else
  392. {
  393. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  394. }
  395. }
  396. }
  397. }
  398. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
  399. {
  400. if (SoundIoHardwareDeviceDriver.IsSupported)
  401. {
  402. deviceDriver = new SoundIoHardwareDeviceDriver();
  403. }
  404. else
  405. {
  406. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, trying to fall back to SDL2.");
  407. if (SDL2HardwareDeviceDriver.IsSupported)
  408. {
  409. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  410. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  411. SaveConfig();
  412. deviceDriver = new SDL2HardwareDeviceDriver();
  413. }
  414. else
  415. {
  416. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  417. if (OpenALHardwareDeviceDriver.IsSupported)
  418. {
  419. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  420. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  421. SaveConfig();
  422. deviceDriver = new OpenALHardwareDeviceDriver();
  423. }
  424. else
  425. {
  426. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, falling back to dummy audio out.");
  427. }
  428. }
  429. }
  430. }
  431. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
  432. {
  433. if (OpenALHardwareDeviceDriver.IsSupported)
  434. {
  435. deviceDriver = new OpenALHardwareDeviceDriver();
  436. }
  437. else
  438. {
  439. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SDL2.");
  440. if (SDL2HardwareDeviceDriver.IsSupported)
  441. {
  442. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  443. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  444. SaveConfig();
  445. deviceDriver = new SDL2HardwareDeviceDriver();
  446. }
  447. else
  448. {
  449. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to SoundIO.");
  450. if (SoundIoHardwareDeviceDriver.IsSupported)
  451. {
  452. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  453. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  454. SaveConfig();
  455. deviceDriver = new SoundIoHardwareDeviceDriver();
  456. }
  457. else
  458. {
  459. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  460. }
  461. }
  462. }
  463. }
  464. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value
  465. ? HLE.MemoryConfiguration.MemoryConfiguration6GB
  466. : HLE.MemoryConfiguration.MemoryConfiguration4GB;
  467. IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None;
  468. HLE.HLEConfiguration configuration = new HLE.HLEConfiguration(_virtualFileSystem,
  469. _libHacHorizonManager,
  470. _contentManager,
  471. _accountManager,
  472. _userChannelPersistence,
  473. renderer,
  474. deviceDriver,
  475. memoryConfiguration,
  476. _uiHandler,
  477. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  478. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  479. ConfigurationState.Instance.Graphics.EnableVsync,
  480. ConfigurationState.Instance.System.EnableDockedMode,
  481. ConfigurationState.Instance.System.EnablePtc,
  482. ConfigurationState.Instance.System.EnableInternetAccess,
  483. fsIntegrityCheckLevel,
  484. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  485. ConfigurationState.Instance.System.SystemTimeOffset,
  486. ConfigurationState.Instance.System.TimeZone,
  487. ConfigurationState.Instance.System.MemoryManagerMode,
  488. ConfigurationState.Instance.System.IgnoreMissingServices,
  489. ConfigurationState.Instance.Graphics.AspectRatio,
  490. ConfigurationState.Instance.System.AudioVolume);
  491. _emulationContext = new HLE.Switch(configuration);
  492. }
  493. private SurfaceKHR CreateVulkanSurface(Instance instance, Vk vk)
  494. {
  495. return new SurfaceKHR((ulong)((VKRenderer)RendererWidget).CreateWindowSurface(instance.Handle));
  496. }
  497. private void SetupProgressUiHandlers()
  498. {
  499. Ptc.PtcStateChanged -= ProgressHandler;
  500. Ptc.PtcStateChanged += ProgressHandler;
  501. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  502. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  503. }
  504. private void ProgressHandler<T>(T state, int current, int total) where T : Enum
  505. {
  506. bool visible;
  507. string label;
  508. switch (state)
  509. {
  510. case PtcLoadingState ptcState:
  511. visible = ptcState != PtcLoadingState.Loaded;
  512. label = $"PTC : {current}/{total}";
  513. break;
  514. case ShaderCacheLoadingState shaderCacheState:
  515. visible = shaderCacheState != ShaderCacheLoadingState.Loaded;
  516. label = $"Shaders : {current}/{total}";
  517. break;
  518. default:
  519. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  520. }
  521. Application.Invoke(delegate
  522. {
  523. _loadingStatusLabel.Text = label;
  524. _loadingStatusBar.Fraction = total > 0 ? (double)current / total : 0;
  525. _loadingStatusBar.Visible = visible;
  526. _loadingStatusLabel.Visible = visible;
  527. });
  528. }
  529. public void UpdateGameTable()
  530. {
  531. if (_updatingGameTable || _gameLoaded)
  532. {
  533. return;
  534. }
  535. _updatingGameTable = true;
  536. _tableStore.Clear();
  537. Thread applicationLibraryThread = new Thread(() =>
  538. {
  539. _applicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs, ConfigurationState.Instance.System.Language);
  540. _updatingGameTable = false;
  541. });
  542. applicationLibraryThread.Name = "GUI.ApplicationLibraryThread";
  543. applicationLibraryThread.IsBackground = true;
  544. applicationLibraryThread.Start();
  545. }
  546. [Conditional("RELEASE")]
  547. public void PerformanceCheck()
  548. {
  549. if (ConfigurationState.Instance.Logger.EnableTrace.Value)
  550. {
  551. MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  552. {
  553. Title = "Ryujinx - Warning",
  554. Text = "You have trace logging enabled, which is designed to be used by developers only.",
  555. SecondaryText = "For optimal performance, it's recommended to disable trace logging. Would you like to disable trace logging now?"
  556. };
  557. if (debugWarningDialog.Run() == (int)ResponseType.Yes)
  558. {
  559. ConfigurationState.Instance.Logger.EnableTrace.Value = false;
  560. SaveConfig();
  561. }
  562. debugWarningDialog.Dispose();
  563. }
  564. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  565. {
  566. MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  567. {
  568. Title = "Ryujinx - Warning",
  569. Text = "You have shader dumping enabled, which is designed to be used by developers only.",
  570. SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
  571. };
  572. if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
  573. {
  574. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  575. SaveConfig();
  576. }
  577. shadersDumpWarningDialog.Dispose();
  578. }
  579. }
  580. public void LoadApplication(string path, bool startFullscreen = false)
  581. {
  582. if (_gameLoaded)
  583. {
  584. GtkDialog.CreateInfoDialog("A game has already been loaded", "Please stop emulation or close the emulator before launching another game.");
  585. }
  586. else
  587. {
  588. PerformanceCheck();
  589. Logger.RestartTime();
  590. RendererWidget = CreateRendererWidget();
  591. SwitchToRenderWidget(startFullscreen);
  592. InitializeSwitchInstance();
  593. UpdateGraphicsConfig();
  594. SetupProgressUiHandlers();
  595. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  596. bool isDirectory = Directory.Exists(path);
  597. bool isFirmwareTitle = false;
  598. if (path.StartsWith("@SystemContent"))
  599. {
  600. path = _virtualFileSystem.SwitchPathToSystemPath(path);
  601. isFirmwareTitle = true;
  602. }
  603. if (!SetupValidator.CanStartApplication(_contentManager, path, out UserError userError))
  604. {
  605. if (SetupValidator.CanFixStartApplication(_contentManager, path, userError, out firmwareVersion))
  606. {
  607. if (userError == UserError.NoFirmware)
  608. {
  609. string message = $"Would you like to install the firmware embedded in this game? (Firmware {firmwareVersion.VersionString})";
  610. ResponseType responseDialog = (ResponseType)GtkDialog.CreateConfirmationDialog("No Firmware Installed", message).Run();
  611. if (responseDialog != ResponseType.Yes)
  612. {
  613. UserErrorDialog.CreateUserErrorDialog(userError);
  614. _emulationContext.Dispose();
  615. SwitchToGameTable();
  616. RendererWidget.Dispose();
  617. return;
  618. }
  619. }
  620. if (!SetupValidator.TryFixStartApplication(_contentManager, path, userError, out _))
  621. {
  622. UserErrorDialog.CreateUserErrorDialog(userError);
  623. _emulationContext.Dispose();
  624. SwitchToGameTable();
  625. RendererWidget.Dispose();
  626. return;
  627. }
  628. // Tell the user that we installed a firmware for them.
  629. if (userError == UserError.NoFirmware)
  630. {
  631. firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  632. RefreshFirmwareLabel();
  633. 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.";
  634. GtkDialog.CreateInfoDialog($"Firmware {firmwareVersion.VersionString} was installed", message);
  635. }
  636. }
  637. else
  638. {
  639. UserErrorDialog.CreateUserErrorDialog(userError);
  640. _emulationContext.Dispose();
  641. SwitchToGameTable();
  642. RendererWidget.Dispose();
  643. return;
  644. }
  645. }
  646. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  647. if (isFirmwareTitle)
  648. {
  649. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  650. _emulationContext.LoadNca(path);
  651. }
  652. else if (Directory.Exists(path))
  653. {
  654. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  655. if (romFsFiles.Length == 0)
  656. {
  657. romFsFiles = Directory.GetFiles(path, "*.romfs");
  658. }
  659. if (romFsFiles.Length > 0)
  660. {
  661. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  662. _emulationContext.LoadCart(path, romFsFiles[0]);
  663. }
  664. else
  665. {
  666. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  667. _emulationContext.LoadCart(path);
  668. }
  669. }
  670. else if (File.Exists(path))
  671. {
  672. switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
  673. {
  674. case ".xci":
  675. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  676. _emulationContext.LoadXci(path);
  677. break;
  678. case ".nca":
  679. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  680. _emulationContext.LoadNca(path);
  681. break;
  682. case ".nsp":
  683. case ".pfs0":
  684. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  685. _emulationContext.LoadNsp(path);
  686. break;
  687. default:
  688. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  689. try
  690. {
  691. _emulationContext.LoadProgram(path);
  692. }
  693. catch (ArgumentOutOfRangeException)
  694. {
  695. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  696. }
  697. break;
  698. }
  699. }
  700. else
  701. {
  702. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  703. _emulationContext.Dispose();
  704. RendererWidget.Dispose();
  705. return;
  706. }
  707. _currentEmulatedGamePath = path;
  708. _deviceExitStatus.Reset();
  709. Translator.IsReadyForTranslation.Reset();
  710. #if MACOS_BUILD
  711. CreateGameWindow();
  712. #else
  713. Thread windowThread = new Thread(() =>
  714. {
  715. CreateGameWindow();
  716. })
  717. {
  718. Name = "GUI.WindowThread"
  719. };
  720. windowThread.Start();
  721. #endif
  722. _gameLoaded = true;
  723. _actionMenu.Sensitive = true;
  724. _lastScannedAmiiboId = "";
  725. _firmwareInstallFile.Sensitive = false;
  726. _firmwareInstallDirectory.Sensitive = false;
  727. DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Application.TitleIdText, _emulationContext.Application.TitleName);
  728. _applicationLibrary.LoadAndSaveMetaData(_emulationContext.Application.TitleIdText, appMetadata =>
  729. {
  730. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  731. });
  732. }
  733. }
  734. private RendererWidgetBase CreateRendererWidget()
  735. {
  736. if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
  737. {
  738. return new VKRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  739. }
  740. else
  741. {
  742. return new GlRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  743. }
  744. }
  745. private void SwitchToRenderWidget(bool startFullscreen = false)
  746. {
  747. _viewBox.Remove(_gameTableWindow);
  748. RendererWidget.Expand = true;
  749. _viewBox.Child = RendererWidget;
  750. RendererWidget.ShowAll();
  751. EditFooterForGameRenderer();
  752. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  753. {
  754. ToggleExtraWidgets(false);
  755. }
  756. else if (startFullscreen || ConfigurationState.Instance.Ui.StartFullscreen.Value)
  757. {
  758. FullScreen_Toggled(null, null);
  759. }
  760. }
  761. private void SwitchToGameTable()
  762. {
  763. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  764. {
  765. ToggleExtraWidgets(true);
  766. }
  767. RendererWidget.Exit();
  768. if (RendererWidget.Window != Window && RendererWidget.Window != null)
  769. {
  770. RendererWidget.Window.Dispose();
  771. }
  772. RendererWidget.Dispose();
  773. if (OperatingSystem.IsWindows())
  774. {
  775. _windowsMultimediaTimerResolution?.Dispose();
  776. _windowsMultimediaTimerResolution = null;
  777. }
  778. DisplaySleep.Restore();
  779. _viewBox.Remove(RendererWidget);
  780. _viewBox.Add(_gameTableWindow);
  781. _gameTableWindow.Expand = true;
  782. Window.Title = $"Ryujinx {Program.Version}";
  783. _emulationContext = null;
  784. _gameLoaded = false;
  785. RendererWidget = null;
  786. DiscordIntegrationModule.SwitchToMainMenu();
  787. RecreateFooterForMenu();
  788. UpdateColumns();
  789. UpdateGameTable();
  790. RefreshFirmwareLabel();
  791. HandleRelaunch();
  792. }
  793. private void CreateGameWindow()
  794. {
  795. if (OperatingSystem.IsWindows())
  796. {
  797. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  798. }
  799. DisplaySleep.Prevent();
  800. RendererWidget.Initialize(_emulationContext);
  801. RendererWidget.WaitEvent.WaitOne();
  802. RendererWidget.Start();
  803. Ptc.Close();
  804. PtcProfiler.Stop();
  805. _emulationContext.Dispose();
  806. _deviceExitStatus.Set();
  807. // NOTE: Everything that is here will not be executed when you close the UI.
  808. Application.Invoke(delegate
  809. {
  810. SwitchToGameTable();
  811. });
  812. }
  813. private void RecreateFooterForMenu()
  814. {
  815. _listStatusBox.Show();
  816. _statusBar.Hide();
  817. }
  818. private void EditFooterForGameRenderer()
  819. {
  820. _listStatusBox.Hide();
  821. _statusBar.Show();
  822. }
  823. public void ToggleExtraWidgets(bool show)
  824. {
  825. if (RendererWidget != null)
  826. {
  827. if (show)
  828. {
  829. _menuBar.ShowAll();
  830. _footerBox.Show();
  831. _statusBar.Show();
  832. }
  833. else
  834. {
  835. _menuBar.Hide();
  836. _footerBox.Hide();
  837. }
  838. }
  839. }
  840. private void UpdateGameMetadata(string titleId)
  841. {
  842. if (_gameLoaded)
  843. {
  844. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  845. {
  846. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  847. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  848. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  849. });
  850. }
  851. }
  852. public void UpdateGraphicsConfig()
  853. {
  854. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  855. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  856. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  857. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  858. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  859. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  860. Graphics.Gpu.GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression;
  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. RendererWidget?.Exit();
  1104. }
  1105. private void PauseEmulation_Pressed(object sender, EventArgs args)
  1106. {
  1107. _pauseEmulation.Sensitive = false;
  1108. _resumeEmulation.Sensitive = true;
  1109. _emulationContext.System.TogglePauseEmulation(true);
  1110. }
  1111. private void ResumeEmulation_Pressed(object sender, EventArgs args)
  1112. {
  1113. _pauseEmulation.Sensitive = true;
  1114. _resumeEmulation.Sensitive = false;
  1115. _emulationContext.System.TogglePauseEmulation(false);
  1116. }
  1117. public void ActivatePauseMenu()
  1118. {
  1119. _pauseEmulation.Sensitive = true;
  1120. _resumeEmulation.Sensitive = false;
  1121. }
  1122. public void TogglePause()
  1123. {
  1124. _pauseEmulation.Sensitive ^= true;
  1125. _resumeEmulation.Sensitive ^= true;
  1126. _emulationContext.System.TogglePauseEmulation(_resumeEmulation.Sensitive);
  1127. }
  1128. private void Installer_File_Pressed(object o, EventArgs args)
  1129. {
  1130. FileChooserNative fileChooser = new FileChooserNative("Choose the firmware file to open", this, FileChooserAction.Open, "Open", "Cancel");
  1131. FileFilter filter = new FileFilter
  1132. {
  1133. Name = "Switch Firmware Files"
  1134. };
  1135. filter.AddPattern("*.zip");
  1136. filter.AddPattern("*.xci");
  1137. fileChooser.AddFilter(filter);
  1138. HandleInstallerDialog(fileChooser);
  1139. }
  1140. private void Installer_Directory_Pressed(object o, EventArgs args)
  1141. {
  1142. FileChooserNative directoryChooser = new FileChooserNative("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Open", "Cancel");
  1143. HandleInstallerDialog(directoryChooser);
  1144. }
  1145. private void HandleInstallerDialog(FileChooserNative fileChooser)
  1146. {
  1147. if (fileChooser.Run() == (int)ResponseType.Accept)
  1148. {
  1149. try
  1150. {
  1151. string filename = fileChooser.Filename;
  1152. fileChooser.Dispose();
  1153. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  1154. if (firmwareVersion is null)
  1155. {
  1156. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  1157. return;
  1158. }
  1159. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  1160. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  1161. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  1162. if (currentVersion != null)
  1163. {
  1164. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  1165. }
  1166. dialogMessage += "\n\nDo you want to continue?";
  1167. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  1168. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  1169. if (responseInstallDialog == ResponseType.Yes)
  1170. {
  1171. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  1172. Thread thread = new Thread(() =>
  1173. {
  1174. Application.Invoke(delegate
  1175. {
  1176. waitingDialog.Run();
  1177. });
  1178. try
  1179. {
  1180. _contentManager.InstallFirmware(filename);
  1181. Application.Invoke(delegate
  1182. {
  1183. waitingDialog.Dispose();
  1184. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  1185. GtkDialog.CreateInfoDialog(dialogTitle, message);
  1186. Logger.Info?.Print(LogClass.Application, message);
  1187. // Purge Applet Cache.
  1188. DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));
  1189. if (miiEditorCacheFolder.Exists)
  1190. {
  1191. miiEditorCacheFolder.Delete(true);
  1192. }
  1193. });
  1194. }
  1195. catch (Exception ex)
  1196. {
  1197. Application.Invoke(delegate
  1198. {
  1199. waitingDialog.Dispose();
  1200. GtkDialog.CreateErrorDialog(ex.Message);
  1201. });
  1202. }
  1203. finally
  1204. {
  1205. RefreshFirmwareLabel();
  1206. }
  1207. });
  1208. thread.Name = "GUI.FirmwareInstallerThread";
  1209. thread.Start();
  1210. }
  1211. }
  1212. catch (MissingKeyException ex)
  1213. {
  1214. Logger.Error?.Print(LogClass.Application, ex.ToString());
  1215. UserErrorDialog.CreateUserErrorDialog(UserError.FirmwareParsingFailed);
  1216. }
  1217. catch (Exception ex)
  1218. {
  1219. GtkDialog.CreateErrorDialog(ex.Message);
  1220. }
  1221. }
  1222. else
  1223. {
  1224. fileChooser.Dispose();
  1225. }
  1226. }
  1227. private void RefreshFirmwareLabel()
  1228. {
  1229. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  1230. Application.Invoke(delegate
  1231. {
  1232. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  1233. });
  1234. }
  1235. private void HandleRelaunch()
  1236. {
  1237. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  1238. {
  1239. _userChannelPersistence.ShouldRestart = false;
  1240. LoadApplication(_currentEmulatedGamePath);
  1241. }
  1242. else
  1243. {
  1244. // otherwise, clear state.
  1245. _userChannelPersistence = new UserChannelPersistence();
  1246. _currentEmulatedGamePath = null;
  1247. _actionMenu.Sensitive = false;
  1248. _firmwareInstallFile.Sensitive = true;
  1249. _firmwareInstallDirectory.Sensitive = true;
  1250. }
  1251. }
  1252. private void FullScreen_Toggled(object sender, EventArgs args)
  1253. {
  1254. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  1255. {
  1256. Fullscreen();
  1257. ToggleExtraWidgets(false);
  1258. }
  1259. else
  1260. {
  1261. Unfullscreen();
  1262. ToggleExtraWidgets(true);
  1263. }
  1264. }
  1265. private void StartFullScreen_Toggled(object sender, EventArgs args)
  1266. {
  1267. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  1268. SaveConfig();
  1269. }
  1270. private void ShowConsole_Toggled(object sender, EventArgs args)
  1271. {
  1272. ConfigurationState.Instance.Ui.ShowConsole.Value = _showConsole.Active;
  1273. SaveConfig();
  1274. }
  1275. private void OptionMenu_StateChanged(object o, StateChangedArgs args)
  1276. {
  1277. _manageUserProfiles.Sensitive = _emulationContext == null;
  1278. }
  1279. private void Settings_Pressed(object sender, EventArgs args)
  1280. {
  1281. SettingsWindow settingsWindow = new SettingsWindow(this, _virtualFileSystem, _contentManager);
  1282. settingsWindow.SetSizeRequest((int)(settingsWindow.DefaultWidth * Program.WindowScaleFactor), (int)(settingsWindow.DefaultHeight * Program.WindowScaleFactor));
  1283. settingsWindow.Show();
  1284. }
  1285. private void HideUi_Pressed(object sender, EventArgs args)
  1286. {
  1287. ToggleExtraWidgets(false);
  1288. }
  1289. private void ManageCheats_Pressed(object sender, EventArgs args)
  1290. {
  1291. var window = new CheatWindow(_virtualFileSystem, _emulationContext.Application.TitleId, _emulationContext.Application.TitleName);
  1292. window.Destroyed += CheatWindow_Destroyed;
  1293. window.Show();
  1294. }
  1295. private void CheatWindow_Destroyed(object sender, EventArgs e)
  1296. {
  1297. _emulationContext.EnableCheats();
  1298. (sender as CheatWindow).Destroyed -= CheatWindow_Destroyed;
  1299. }
  1300. private void ManageUserProfiles_Pressed(object sender, EventArgs args)
  1301. {
  1302. UserProfilesManagerWindow userProfilesManagerWindow = new UserProfilesManagerWindow(_accountManager, _contentManager, _virtualFileSystem);
  1303. userProfilesManagerWindow.SetSizeRequest((int)(userProfilesManagerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(userProfilesManagerWindow.DefaultHeight * Program.WindowScaleFactor));
  1304. userProfilesManagerWindow.Show();
  1305. }
  1306. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  1307. {
  1308. if (_emulationContext != null)
  1309. {
  1310. _emulationContext.System.SimulateWakeUpMessage();
  1311. }
  1312. }
  1313. private void ActionMenu_StateChanged(object o, StateChangedArgs args)
  1314. {
  1315. _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _);
  1316. _takeScreenshot.Sensitive = _emulationContext != null;
  1317. }
  1318. private void Scan_Amiibo(object sender, EventArgs args)
  1319. {
  1320. if (_emulationContext.System.SearchingForAmiibo(out int deviceId))
  1321. {
  1322. AmiiboWindow amiiboWindow = new AmiiboWindow
  1323. {
  1324. LastScannedAmiiboShowAll = _lastScannedAmiiboShowAll,
  1325. LastScannedAmiiboId = _lastScannedAmiiboId,
  1326. DeviceId = deviceId,
  1327. TitleId = _emulationContext.Application.TitleIdText.ToUpper()
  1328. };
  1329. amiiboWindow.DeleteEvent += AmiiboWindow_DeleteEvent;
  1330. amiiboWindow.Show();
  1331. }
  1332. else
  1333. {
  1334. 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.");
  1335. }
  1336. }
  1337. private void Take_Screenshot(object sender, EventArgs args)
  1338. {
  1339. if (_emulationContext != null && RendererWidget != null)
  1340. {
  1341. RendererWidget.ScreenshotRequested = true;
  1342. }
  1343. }
  1344. private void AmiiboWindow_DeleteEvent(object sender, DeleteEventArgs args)
  1345. {
  1346. if (((AmiiboWindow)sender).AmiiboId != "" && ((AmiiboWindow)sender).Response == ResponseType.Ok)
  1347. {
  1348. _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId;
  1349. _lastScannedAmiiboShowAll = ((AmiiboWindow)sender).LastScannedAmiiboShowAll;
  1350. _emulationContext.System.ScanAmiibo(((AmiiboWindow)sender).DeviceId, ((AmiiboWindow)sender).AmiiboId, ((AmiiboWindow)sender).UseRandomUuid);
  1351. }
  1352. }
  1353. private void Update_Pressed(object sender, EventArgs args)
  1354. {
  1355. if (Updater.CanUpdate(true))
  1356. {
  1357. Updater.BeginParse(this, true).ContinueWith(task =>
  1358. {
  1359. Logger.Error?.Print(LogClass.Application, $"Updater error: {task.Exception}");
  1360. }, TaskContinuationOptions.OnlyOnFaulted);
  1361. }
  1362. }
  1363. private void About_Pressed(object sender, EventArgs args)
  1364. {
  1365. AboutWindow aboutWindow = new AboutWindow();
  1366. aboutWindow.SetSizeRequest((int)(aboutWindow.DefaultWidth * Program.WindowScaleFactor), (int)(aboutWindow.DefaultHeight * Program.WindowScaleFactor));
  1367. aboutWindow.Show();
  1368. }
  1369. private void Fav_Toggled(object sender, EventArgs args)
  1370. {
  1371. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  1372. SaveConfig();
  1373. UpdateColumns();
  1374. }
  1375. private void Icon_Toggled(object sender, EventArgs args)
  1376. {
  1377. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  1378. SaveConfig();
  1379. UpdateColumns();
  1380. }
  1381. private void App_Toggled(object sender, EventArgs args)
  1382. {
  1383. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  1384. SaveConfig();
  1385. UpdateColumns();
  1386. }
  1387. private void Developer_Toggled(object sender, EventArgs args)
  1388. {
  1389. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  1390. SaveConfig();
  1391. UpdateColumns();
  1392. }
  1393. private void Version_Toggled(object sender, EventArgs args)
  1394. {
  1395. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  1396. SaveConfig();
  1397. UpdateColumns();
  1398. }
  1399. private void TimePlayed_Toggled(object sender, EventArgs args)
  1400. {
  1401. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  1402. SaveConfig();
  1403. UpdateColumns();
  1404. }
  1405. private void LastPlayed_Toggled(object sender, EventArgs args)
  1406. {
  1407. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  1408. SaveConfig();
  1409. UpdateColumns();
  1410. }
  1411. private void FileExt_Toggled(object sender, EventArgs args)
  1412. {
  1413. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  1414. SaveConfig();
  1415. UpdateColumns();
  1416. }
  1417. private void FileSize_Toggled(object sender, EventArgs args)
  1418. {
  1419. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  1420. SaveConfig();
  1421. UpdateColumns();
  1422. }
  1423. private void Path_Toggled(object sender, EventArgs args)
  1424. {
  1425. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  1426. SaveConfig();
  1427. UpdateColumns();
  1428. }
  1429. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  1430. {
  1431. UpdateGameTable();
  1432. }
  1433. }
  1434. }