MainWindow.cs 45 KB

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