MainWindow.cs 61 KB

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