MainWindow.cs 66 KB

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