MainWindow.cs 44 KB

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