MainWindow.cs 57 KB

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