MainWindow.cs 66 KB

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