MainWindow.cs 64 KB

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