MainWindow.cs 64 KB

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