MainWindow.cs 66 KB

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