MainWindow.cs 68 KB

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