MainWindow.cs 68 KB

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