MainWindow.cs 67 KB

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