MainWindow.cs 67 KB

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