MainWindow.cs 60 KB

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