MainWindow.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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. DisplaySleep.Prevent();
  462. GlRendererWidget = new GlRenderer(_emulationContext, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  463. Application.Invoke(delegate
  464. {
  465. _viewBox.Remove(_gameTableWindow);
  466. GlRendererWidget.Expand = true;
  467. _viewBox.Child = GlRendererWidget;
  468. GlRendererWidget.ShowAll();
  469. EditFooterForGameRenderer();
  470. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  471. {
  472. ToggleExtraWidgets(false);
  473. }
  474. else if (ConfigurationState.Instance.Ui.StartFullscreen.Value)
  475. {
  476. FullScreen_Toggled(null, null);
  477. }
  478. });
  479. GlRendererWidget.WaitEvent.WaitOne();
  480. GlRendererWidget.Start();
  481. Ptc.Close();
  482. PtcProfiler.Stop();
  483. _emulationContext.Dispose();
  484. _deviceExitStatus.Set();
  485. // NOTE: Everything that is here will not be executed when you close the UI.
  486. Application.Invoke(delegate
  487. {
  488. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  489. {
  490. ToggleExtraWidgets(true);
  491. }
  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. DisplaySleep.Restore();
  501. _viewBox.Remove(GlRendererWidget);
  502. _viewBox.Add(_gameTableWindow);
  503. _gameTableWindow.Expand = true;
  504. Window.Title = $"Ryujinx {Program.Version}";
  505. _emulationContext = null;
  506. _gameLoaded = false;
  507. GlRendererWidget = null;
  508. DiscordIntegrationModule.SwitchToMainMenu();
  509. RecreateFooterForMenu();
  510. UpdateColumns();
  511. UpdateGameTable();
  512. Task.Run(RefreshFirmwareLabel);
  513. Task.Run(HandleRelaunch);
  514. _stopEmulation.Sensitive = false;
  515. _simulateWakeUpMessage.Sensitive = false;
  516. _firmwareInstallFile.Sensitive = true;
  517. _firmwareInstallDirectory.Sensitive = true;
  518. });
  519. }
  520. private void RecreateFooterForMenu()
  521. {
  522. _listStatusBox.Show();
  523. _statusBar.Hide();
  524. }
  525. private void EditFooterForGameRenderer()
  526. {
  527. _listStatusBox.Hide();
  528. _statusBar.Show();
  529. }
  530. public void ToggleExtraWidgets(bool show)
  531. {
  532. if (GlRendererWidget != null)
  533. {
  534. if (show)
  535. {
  536. _menuBar.ShowAll();
  537. _footerBox.Show();
  538. _statusBar.Show();
  539. }
  540. else
  541. {
  542. _menuBar.Hide();
  543. _footerBox.Hide();
  544. }
  545. }
  546. }
  547. private void UpdateGameMetadata(string titleId)
  548. {
  549. if (_gameLoaded)
  550. {
  551. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  552. {
  553. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  554. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  555. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  556. });
  557. }
  558. }
  559. public void UpdateGraphicsConfig()
  560. {
  561. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  562. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  563. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  564. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  565. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  566. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  567. }
  568. public void SaveConfig()
  569. {
  570. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  571. }
  572. private void End()
  573. {
  574. if (_ending)
  575. {
  576. return;
  577. }
  578. _ending = true;
  579. if (_emulationContext != null)
  580. {
  581. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  582. if (GlRendererWidget != null)
  583. {
  584. // We tell the widget that we are exiting.
  585. GlRendererWidget.Exit();
  586. // Wait for the other thread to dispose the HLE context before exiting.
  587. _deviceExitStatus.WaitOne();
  588. GlRendererWidget.Dispose();
  589. }
  590. }
  591. Dispose();
  592. Program.Exit();
  593. Application.Quit();
  594. }
  595. //
  596. // Events
  597. //
  598. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  599. {
  600. Application.Invoke(delegate
  601. {
  602. _tableStore.AppendValues(
  603. args.AppData.Favorite,
  604. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  605. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  606. args.AppData.Developer,
  607. args.AppData.Version,
  608. args.AppData.TimePlayed,
  609. args.AppData.LastPlayed,
  610. args.AppData.FileExtension,
  611. args.AppData.FileSize,
  612. args.AppData.Path,
  613. args.AppData.ControlHolder);
  614. });
  615. }
  616. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  617. {
  618. Application.Invoke(delegate
  619. {
  620. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  621. float barValue = 0;
  622. if (args.NumAppsFound != 0)
  623. {
  624. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  625. }
  626. _progressBar.Value = barValue;
  627. // Reset the vertical scrollbar to the top when titles finish loading
  628. if (args.NumAppsLoaded == args.NumAppsFound)
  629. {
  630. _gameTableWindow.Vadjustment.Value = 0;
  631. }
  632. });
  633. }
  634. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  635. {
  636. Application.Invoke(delegate
  637. {
  638. _gameStatus.Text = args.GameStatus;
  639. _fifoStatus.Text = args.FifoStatus;
  640. _gpuName.Text = args.GpuName;
  641. _dockedMode.Text = args.DockedMode;
  642. _aspectRatio.Text = args.AspectRatio;
  643. if (args.VSyncEnabled)
  644. {
  645. _vSyncStatus.Attributes = new Pango.AttrList();
  646. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  647. }
  648. else
  649. {
  650. _vSyncStatus.Attributes = new Pango.AttrList();
  651. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  652. }
  653. });
  654. }
  655. private void FavToggle_Toggled(object sender, ToggledArgs args)
  656. {
  657. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  658. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  659. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  660. _tableStore.SetValue(treeIter, 0, newToggleValue);
  661. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  662. {
  663. appMetadata.Favorite = newToggleValue;
  664. });
  665. }
  666. private void Column_Clicked(object sender, EventArgs args)
  667. {
  668. TreeViewColumn column = (TreeViewColumn)sender;
  669. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  670. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  671. SaveConfig();
  672. }
  673. private void Row_Activated(object sender, RowActivatedArgs args)
  674. {
  675. _gameTableSelection.GetSelected(out TreeIter treeIter);
  676. string path = (string)_tableStore.GetValue(treeIter, 9);
  677. LoadApplication(path);
  678. }
  679. private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  680. {
  681. _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;
  682. }
  683. private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
  684. {
  685. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  686. }
  687. private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
  688. {
  689. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  690. ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  691. }
  692. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  693. {
  694. if (args.Event.Button != 3 /* Right Click */)
  695. {
  696. return;
  697. }
  698. _gameTableSelection.GetSelected(out TreeIter treeIter);
  699. if (treeIter.UserData == IntPtr.Zero)
  700. {
  701. return;
  702. }
  703. string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString();
  704. string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0];
  705. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  706. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  707. _ = new GameTableContextMenu(this, _virtualFileSystem, titleFilePath, titleName, titleId, controlData);
  708. }
  709. private void Load_Application_File(object sender, EventArgs args)
  710. {
  711. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  712. {
  713. fileChooser.Filter = new FileFilter();
  714. fileChooser.Filter.AddPattern("*.nsp");
  715. fileChooser.Filter.AddPattern("*.pfs0");
  716. fileChooser.Filter.AddPattern("*.xci");
  717. fileChooser.Filter.AddPattern("*.nca");
  718. fileChooser.Filter.AddPattern("*.nro");
  719. fileChooser.Filter.AddPattern("*.nso");
  720. if (fileChooser.Run() == (int)ResponseType.Accept)
  721. {
  722. LoadApplication(fileChooser.Filename);
  723. }
  724. }
  725. }
  726. private void Load_Application_Folder(object sender, EventArgs args)
  727. {
  728. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  729. {
  730. if (fileChooser.Run() == (int)ResponseType.Accept)
  731. {
  732. LoadApplication(fileChooser.Filename);
  733. }
  734. }
  735. }
  736. private void Open_Ryu_Folder(object sender, EventArgs args)
  737. {
  738. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  739. }
  740. private void OpenLogsFolder_Pressed(object sender, EventArgs args)
  741. {
  742. string logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  743. new DirectoryInfo(logPath).Create();
  744. OpenHelper.OpenFolder(logPath);
  745. }
  746. private void Exit_Pressed(object sender, EventArgs args)
  747. {
  748. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  749. {
  750. End();
  751. }
  752. }
  753. private void Window_Close(object sender, DeleteEventArgs args)
  754. {
  755. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  756. {
  757. End();
  758. }
  759. else
  760. {
  761. args.RetVal = true;
  762. }
  763. }
  764. private void StopEmulation_Pressed(object sender, EventArgs args)
  765. {
  766. GlRendererWidget?.Exit();
  767. }
  768. private void Installer_File_Pressed(object o, EventArgs args)
  769. {
  770. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  771. fileChooser.Filter = new FileFilter();
  772. fileChooser.Filter.AddPattern("*.zip");
  773. fileChooser.Filter.AddPattern("*.xci");
  774. HandleInstallerDialog(fileChooser);
  775. }
  776. private void Installer_Directory_Pressed(object o, EventArgs args)
  777. {
  778. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  779. HandleInstallerDialog(directoryChooser);
  780. }
  781. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  782. {
  783. if (fileChooser.Run() == (int)ResponseType.Accept)
  784. {
  785. try
  786. {
  787. string filename = fileChooser.Filename;
  788. fileChooser.Dispose();
  789. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  790. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  791. if (firmwareVersion == null)
  792. {
  793. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  794. return;
  795. }
  796. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  797. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  798. if (currentVersion != null)
  799. {
  800. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  801. }
  802. dialogMessage += "\n\nDo you want to continue?";
  803. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  804. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  805. if (responseInstallDialog == ResponseType.Yes)
  806. {
  807. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  808. Thread thread = new Thread(() =>
  809. {
  810. Application.Invoke(delegate
  811. {
  812. waitingDialog.Run();
  813. });
  814. try
  815. {
  816. _contentManager.InstallFirmware(filename);
  817. Application.Invoke(delegate
  818. {
  819. waitingDialog.Dispose();
  820. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  821. GtkDialog.CreateInfoDialog(dialogTitle, message);
  822. Logger.Info?.Print(LogClass.Application, message);
  823. });
  824. }
  825. catch (Exception ex)
  826. {
  827. Application.Invoke(delegate
  828. {
  829. waitingDialog.Dispose();
  830. GtkDialog.CreateErrorDialog(ex.Message);
  831. });
  832. }
  833. finally
  834. {
  835. RefreshFirmwareLabel();
  836. }
  837. });
  838. thread.Name = "GUI.FirmwareInstallerThread";
  839. thread.Start();
  840. }
  841. }
  842. catch (LibHac.MissingKeyException ex)
  843. {
  844. Logger.Error?.Print(LogClass.Application, ex.ToString());
  845. UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
  846. }
  847. catch (Exception ex)
  848. {
  849. GtkDialog.CreateErrorDialog(ex.Message);
  850. }
  851. }
  852. else
  853. {
  854. fileChooser.Dispose();
  855. }
  856. }
  857. private void RefreshFirmwareLabel()
  858. {
  859. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  860. Application.Invoke(delegate
  861. {
  862. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  863. });
  864. }
  865. private void HandleRelaunch()
  866. {
  867. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  868. {
  869. _userChannelPersistence.ShouldRestart = false;
  870. LoadApplication(_currentEmulatedGamePath);
  871. }
  872. else
  873. {
  874. // otherwise, clear state.
  875. _userChannelPersistence = new UserChannelPersistence();
  876. _currentEmulatedGamePath = null;
  877. }
  878. }
  879. private void FullScreen_Toggled(object sender, EventArgs args)
  880. {
  881. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  882. {
  883. Fullscreen();
  884. ToggleExtraWidgets(false);
  885. }
  886. else
  887. {
  888. Unfullscreen();
  889. ToggleExtraWidgets(true);
  890. }
  891. }
  892. private void StartFullScreen_Toggled(object sender, EventArgs args)
  893. {
  894. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  895. SaveConfig();
  896. }
  897. private void Settings_Pressed(object sender, EventArgs args)
  898. {
  899. new SettingsWindow(this, _virtualFileSystem, _contentManager).Show();
  900. }
  901. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  902. {
  903. if (_emulationContext != null)
  904. {
  905. _emulationContext.System.SimulateWakeUpMessage();
  906. }
  907. }
  908. private void Update_Pressed(object sender, EventArgs args)
  909. {
  910. if (Updater.CanUpdate(true))
  911. {
  912. _ = Updater.BeginParse(this, true);
  913. }
  914. }
  915. private void About_Pressed(object sender, EventArgs args)
  916. {
  917. new AboutWindow().Show();
  918. }
  919. private void Fav_Toggled(object sender, EventArgs args)
  920. {
  921. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  922. SaveConfig();
  923. UpdateColumns();
  924. }
  925. private void Icon_Toggled(object sender, EventArgs args)
  926. {
  927. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  928. SaveConfig();
  929. UpdateColumns();
  930. }
  931. private void Title_Toggled(object sender, EventArgs args)
  932. {
  933. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  934. SaveConfig();
  935. UpdateColumns();
  936. }
  937. private void Developer_Toggled(object sender, EventArgs args)
  938. {
  939. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  940. SaveConfig();
  941. UpdateColumns();
  942. }
  943. private void Version_Toggled(object sender, EventArgs args)
  944. {
  945. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  946. SaveConfig();
  947. UpdateColumns();
  948. }
  949. private void TimePlayed_Toggled(object sender, EventArgs args)
  950. {
  951. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  952. SaveConfig();
  953. UpdateColumns();
  954. }
  955. private void LastPlayed_Toggled(object sender, EventArgs args)
  956. {
  957. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  958. SaveConfig();
  959. UpdateColumns();
  960. }
  961. private void FileExt_Toggled(object sender, EventArgs args)
  962. {
  963. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  964. SaveConfig();
  965. UpdateColumns();
  966. }
  967. private void FileSize_Toggled(object sender, EventArgs args)
  968. {
  969. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  970. SaveConfig();
  971. UpdateColumns();
  972. }
  973. private void Path_Toggled(object sender, EventArgs args)
  974. {
  975. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  976. SaveConfig();
  977. UpdateColumns();
  978. }
  979. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  980. {
  981. UpdateGameTable();
  982. }
  983. }
  984. }