MainWindow.cs 69 KB

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