MainWindow.cs 59 KB

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