MainWindow.cs 47 KB

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