MainWindow.cs 60 KB

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