MainWindow.cs 60 KB

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