MainWindow.cs 68 KB

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