MainWindow.cs 66 KB

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