MainWindow.cs 67 KB

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