MainWindow.cs 69 KB

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