MainWindow.cs 69 KB

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