MainWindow.cs 65 KB

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