MainWindow.cs 56 KB

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