MainWindow.cs 57 KB

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