AppHost.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.ApplicationLifetimes;
  4. using Avalonia.Input;
  5. using Avalonia.Threading;
  6. using LibHac.Tools.FsSystem;
  7. using Ryujinx.Audio.Backends.Dummy;
  8. using Ryujinx.Audio.Backends.OpenAL;
  9. using Ryujinx.Audio.Backends.SDL2;
  10. using Ryujinx.Audio.Backends.SoundIo;
  11. using Ryujinx.Audio.Integration;
  12. using Ryujinx.Ava.Common;
  13. using Ryujinx.Ava.Common.Locale;
  14. using Ryujinx.Ava.Input;
  15. using Ryujinx.Ava.UI.Helpers;
  16. using Ryujinx.Ava.UI.Models;
  17. using Ryujinx.Ava.UI.Renderer;
  18. using Ryujinx.Ava.UI.ViewModels;
  19. using Ryujinx.Ava.UI.Windows;
  20. using Ryujinx.Common;
  21. using Ryujinx.Common.Configuration;
  22. using Ryujinx.Common.Configuration.Multiplayer;
  23. using Ryujinx.Common.Logging;
  24. using Ryujinx.Common.SystemInterop;
  25. using Ryujinx.Common.Utilities;
  26. using Ryujinx.Graphics.GAL;
  27. using Ryujinx.Graphics.GAL.Multithreading;
  28. using Ryujinx.Graphics.Gpu;
  29. using Ryujinx.Graphics.OpenGL;
  30. using Ryujinx.Graphics.Vulkan;
  31. using Ryujinx.HLE;
  32. using Ryujinx.HLE.FileSystem;
  33. using Ryujinx.HLE.HOS;
  34. using Ryujinx.HLE.HOS.Services.Account.Acc;
  35. using Ryujinx.HLE.HOS.SystemState;
  36. using Ryujinx.Input;
  37. using Ryujinx.Input.HLE;
  38. using Ryujinx.UI.App.Common;
  39. using Ryujinx.UI.Common;
  40. using Ryujinx.UI.Common.Configuration;
  41. using Ryujinx.UI.Common.Helper;
  42. using Silk.NET.Vulkan;
  43. using SixLabors.ImageSharp;
  44. using SixLabors.ImageSharp.Formats.Png;
  45. using SixLabors.ImageSharp.PixelFormats;
  46. using SixLabors.ImageSharp.Processing;
  47. using SPB.Graphics.Vulkan;
  48. using System;
  49. using System.Collections.Generic;
  50. using System.Diagnostics;
  51. using System.IO;
  52. using System.Threading;
  53. using System.Threading.Tasks;
  54. using static Ryujinx.Ava.UI.Helpers.Win32NativeInterop;
  55. using AntiAliasing = Ryujinx.Common.Configuration.AntiAliasing;
  56. using Image = SixLabors.ImageSharp.Image;
  57. using InputManager = Ryujinx.Input.HLE.InputManager;
  58. using IRenderer = Ryujinx.Graphics.GAL.IRenderer;
  59. using Key = Ryujinx.Input.Key;
  60. using MouseButton = Ryujinx.Input.MouseButton;
  61. using ScalingFilter = Ryujinx.Common.Configuration.ScalingFilter;
  62. using Size = Avalonia.Size;
  63. using Switch = Ryujinx.HLE.Switch;
  64. namespace Ryujinx.Ava
  65. {
  66. internal class AppHost
  67. {
  68. private const int CursorHideIdleTime = 5; // Hide Cursor seconds.
  69. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  70. private const int TargetFps = 60;
  71. private const float VolumeDelta = 0.05f;
  72. private static readonly Cursor _invisibleCursor = new(StandardCursorType.None);
  73. private readonly IntPtr _invisibleCursorWin;
  74. private readonly IntPtr _defaultCursorWin;
  75. private readonly long _ticksPerFrame;
  76. private readonly Stopwatch _chrono;
  77. private long _ticks;
  78. private readonly AccountManager _accountManager;
  79. private readonly UserChannelPersistence _userChannelPersistence;
  80. private readonly InputManager _inputManager;
  81. private readonly MainWindowViewModel _viewModel;
  82. private readonly IKeyboard _keyboardInterface;
  83. private readonly TopLevel _topLevel;
  84. public RendererHost RendererHost;
  85. private readonly GraphicsDebugLevel _glLogLevel;
  86. private float _newVolume;
  87. private KeyboardHotkeyState _prevHotkeyState;
  88. private long _lastCursorMoveTime;
  89. private bool _isCursorInRenderer = true;
  90. private bool _isStopped;
  91. private bool _isActive;
  92. private bool _renderingStarted;
  93. private readonly ManualResetEvent _gpuDoneEvent;
  94. private IRenderer _renderer;
  95. private readonly Thread _renderingThread;
  96. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  97. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  98. private bool _dialogShown;
  99. private readonly bool _isFirmwareTitle;
  100. private readonly object _lockObject = new();
  101. public event EventHandler AppExit;
  102. public event EventHandler<StatusInitEventArgs> StatusInitEvent;
  103. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  104. public VirtualFileSystem VirtualFileSystem { get; }
  105. public ContentManager ContentManager { get; }
  106. public NpadManager NpadManager { get; }
  107. public TouchScreenManager TouchScreenManager { get; }
  108. public Switch Device { get; set; }
  109. public int Width { get; private set; }
  110. public int Height { get; private set; }
  111. public string ApplicationPath { get; private set; }
  112. public bool ScreenshotRequested { get; set; }
  113. public AppHost(
  114. RendererHost renderer,
  115. InputManager inputManager,
  116. string applicationPath,
  117. VirtualFileSystem virtualFileSystem,
  118. ContentManager contentManager,
  119. AccountManager accountManager,
  120. UserChannelPersistence userChannelPersistence,
  121. MainWindowViewModel viewmodel,
  122. TopLevel topLevel)
  123. {
  124. _viewModel = viewmodel;
  125. _inputManager = inputManager;
  126. _accountManager = accountManager;
  127. _userChannelPersistence = userChannelPersistence;
  128. _renderingThread = new Thread(RenderLoop) { Name = "GUI.RenderThread" };
  129. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  130. _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel;
  131. _topLevel = topLevel;
  132. _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_topLevel, renderer));
  133. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  134. NpadManager = _inputManager.CreateNpadManager();
  135. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  136. ApplicationPath = applicationPath;
  137. VirtualFileSystem = virtualFileSystem;
  138. ContentManager = contentManager;
  139. RendererHost = renderer;
  140. _chrono = new Stopwatch();
  141. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  142. if (ApplicationPath.StartsWith("@SystemContent"))
  143. {
  144. ApplicationPath = VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath);
  145. _isFirmwareTitle = true;
  146. }
  147. ConfigurationState.Instance.HideCursor.Event += HideCursorState_Changed;
  148. _topLevel.PointerMoved += TopLevel_PointerEnteredOrMoved;
  149. _topLevel.PointerEntered += TopLevel_PointerEnteredOrMoved;
  150. _topLevel.PointerExited += TopLevel_PointerExited;
  151. if (OperatingSystem.IsWindows())
  152. {
  153. _invisibleCursorWin = CreateEmptyCursor();
  154. _defaultCursorWin = CreateArrowCursor();
  155. }
  156. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  157. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  158. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  159. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  160. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  161. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  162. ConfigurationState.Instance.Graphics.AntiAliasing.Event += UpdateAntiAliasing;
  163. ConfigurationState.Instance.Graphics.ScalingFilter.Event += UpdateScalingFilter;
  164. ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event += UpdateScalingFilterLevel;
  165. ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Event += UpdateColorSpacePassthrough;
  166. ConfigurationState.Instance.System.EnableInternetAccess.Event += UpdateEnableInternetAccessState;
  167. ConfigurationState.Instance.Multiplayer.LanInterfaceId.Event += UpdateLanInterfaceIdState;
  168. ConfigurationState.Instance.Multiplayer.Mode.Event += UpdateMultiplayerModeState;
  169. _gpuCancellationTokenSource = new CancellationTokenSource();
  170. _gpuDoneEvent = new ManualResetEvent(false);
  171. }
  172. private void TopLevel_PointerEnteredOrMoved(object sender, PointerEventArgs e)
  173. {
  174. if (sender is MainWindow window)
  175. {
  176. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  177. var point = e.GetCurrentPoint(window).Position;
  178. var bounds = RendererHost.EmbeddedWindow.Bounds;
  179. _isCursorInRenderer = point.X >= bounds.X &&
  180. point.X <= bounds.Width + bounds.X &&
  181. point.Y >= bounds.Y &&
  182. point.Y <= bounds.Height + bounds.Y;
  183. }
  184. }
  185. private void TopLevel_PointerExited(object sender, PointerEventArgs e)
  186. {
  187. _isCursorInRenderer = false;
  188. }
  189. private void UpdateScalingFilterLevel(object sender, ReactiveEventArgs<int> e)
  190. {
  191. _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  192. _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  193. }
  194. private void UpdateScalingFilter(object sender, ReactiveEventArgs<ScalingFilter> e)
  195. {
  196. _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  197. _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  198. }
  199. private void UpdateColorSpacePassthrough(object sender, ReactiveEventArgs<bool> e)
  200. {
  201. _renderer.Window?.SetColorSpacePassthrough((bool)ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Value);
  202. }
  203. private void ShowCursor()
  204. {
  205. Dispatcher.UIThread.Post(() =>
  206. {
  207. _viewModel.Cursor = Cursor.Default;
  208. if (OperatingSystem.IsWindows())
  209. {
  210. SetCursor(_defaultCursorWin);
  211. }
  212. });
  213. }
  214. private void HideCursor()
  215. {
  216. Dispatcher.UIThread.Post(() =>
  217. {
  218. _viewModel.Cursor = _invisibleCursor;
  219. if (OperatingSystem.IsWindows())
  220. {
  221. SetCursor(_invisibleCursorWin);
  222. }
  223. });
  224. }
  225. private void SetRendererWindowSize(Size size)
  226. {
  227. if (_renderer != null)
  228. {
  229. double scale = _topLevel.RenderScaling;
  230. _renderer.Window?.SetSize((int)(size.Width * scale), (int)(size.Height * scale));
  231. }
  232. }
  233. private void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  234. {
  235. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  236. {
  237. Task.Run(() =>
  238. {
  239. lock (_lockObject)
  240. {
  241. string applicationName = Device.Processes.ActiveApplication.Name;
  242. string sanitizedApplicationName = FileSystemUtils.SanitizeFileName(applicationName);
  243. DateTime currentTime = DateTime.Now;
  244. string filename = $"{sanitizedApplicationName}_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png";
  245. string directory = AppDataManager.Mode switch
  246. {
  247. AppDataManager.LaunchMode.Portable or AppDataManager.LaunchMode.Custom => Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  248. _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx"),
  249. };
  250. string path = Path.Combine(directory, filename);
  251. try
  252. {
  253. Directory.CreateDirectory(directory);
  254. }
  255. catch (Exception ex)
  256. {
  257. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  258. return;
  259. }
  260. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  261. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  262. if (e.FlipX)
  263. {
  264. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  265. }
  266. if (e.FlipY)
  267. {
  268. image.Mutate(x => x.Flip(FlipMode.Vertical));
  269. }
  270. image.SaveAsPng(path, new PngEncoder
  271. {
  272. ColorType = PngColorType.Rgb,
  273. });
  274. image.Dispose();
  275. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  276. }
  277. });
  278. }
  279. else
  280. {
  281. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  282. }
  283. }
  284. public void Start()
  285. {
  286. if (OperatingSystem.IsWindows())
  287. {
  288. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  289. }
  290. DisplaySleep.Prevent();
  291. NpadManager.Initialize(Device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  292. TouchScreenManager.Initialize(Device);
  293. _viewModel.IsGameRunning = true;
  294. Dispatcher.UIThread.InvokeAsync(() =>
  295. {
  296. _viewModel.Title = TitleHelper.ActiveApplicationTitle(Device.Processes.ActiveApplication, Program.Version);
  297. });
  298. _viewModel.SetUiProgressHandlers(Device);
  299. RendererHost.BoundsChanged += Window_BoundsChanged;
  300. _isActive = true;
  301. _renderingThread.Start();
  302. _viewModel.Volume = ConfigurationState.Instance.System.AudioVolume.Value;
  303. MainLoop();
  304. Exit();
  305. }
  306. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  307. {
  308. if (Device != null)
  309. {
  310. Device.Configuration.IgnoreMissingServices = args.NewValue;
  311. }
  312. }
  313. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  314. {
  315. if (Device != null)
  316. {
  317. Device.Configuration.AspectRatio = args.NewValue;
  318. }
  319. }
  320. private void UpdateAntiAliasing(object sender, ReactiveEventArgs<AntiAliasing> e)
  321. {
  322. _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)e.NewValue);
  323. }
  324. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  325. {
  326. Device?.System.ChangeDockedModeState(e.NewValue);
  327. }
  328. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  329. {
  330. Device?.SetVolume(e.NewValue);
  331. Dispatcher.UIThread.Post(() =>
  332. {
  333. _viewModel.Volume = e.NewValue;
  334. });
  335. }
  336. private void UpdateEnableInternetAccessState(object sender, ReactiveEventArgs<bool> e)
  337. {
  338. Device.Configuration.EnableInternetAccess = e.NewValue;
  339. }
  340. private void UpdateLanInterfaceIdState(object sender, ReactiveEventArgs<string> e)
  341. {
  342. Device.Configuration.MultiplayerLanInterfaceId = e.NewValue;
  343. }
  344. private void UpdateMultiplayerModeState(object sender, ReactiveEventArgs<MultiplayerMode> e)
  345. {
  346. Device.Configuration.MultiplayerMode = e.NewValue;
  347. }
  348. public void ToggleVSync()
  349. {
  350. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  351. _renderer.Window.ChangeVSyncMode(Device.EnableDeviceVsync);
  352. }
  353. public void Stop()
  354. {
  355. _isActive = false;
  356. }
  357. private void Exit()
  358. {
  359. (_keyboardInterface as AvaloniaKeyboard)?.Clear();
  360. if (_isStopped)
  361. {
  362. return;
  363. }
  364. _isStopped = true;
  365. _isActive = false;
  366. }
  367. public void DisposeContext()
  368. {
  369. Dispose();
  370. _isActive = false;
  371. // NOTE: The render loop is allowed to stay alive until the renderer itself is disposed, as it may handle resource dispose.
  372. // We only need to wait for all commands submitted during the main gpu loop to be processed.
  373. _gpuDoneEvent.WaitOne();
  374. _gpuDoneEvent.Dispose();
  375. DisplaySleep.Restore();
  376. NpadManager.Dispose();
  377. TouchScreenManager.Dispose();
  378. Device.Dispose();
  379. DisposeGpu();
  380. AppExit?.Invoke(this, EventArgs.Empty);
  381. }
  382. private void Dispose()
  383. {
  384. if (Device.Processes != null)
  385. {
  386. MainWindowViewModel.UpdateGameMetadata(Device.Processes.ActiveApplication.ProgramIdText);
  387. }
  388. ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState;
  389. ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState;
  390. ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState;
  391. ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState;
  392. ConfigurationState.Instance.Graphics.ScalingFilter.Event -= UpdateScalingFilter;
  393. ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event -= UpdateScalingFilterLevel;
  394. ConfigurationState.Instance.Graphics.AntiAliasing.Event -= UpdateAntiAliasing;
  395. ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Event -= UpdateColorSpacePassthrough;
  396. _topLevel.PointerMoved -= TopLevel_PointerEnteredOrMoved;
  397. _topLevel.PointerEntered -= TopLevel_PointerEnteredOrMoved;
  398. _topLevel.PointerExited -= TopLevel_PointerExited;
  399. _gpuCancellationTokenSource.Cancel();
  400. _gpuCancellationTokenSource.Dispose();
  401. _chrono.Stop();
  402. }
  403. public void DisposeGpu()
  404. {
  405. if (OperatingSystem.IsWindows())
  406. {
  407. _windowsMultimediaTimerResolution?.Dispose();
  408. _windowsMultimediaTimerResolution = null;
  409. }
  410. if (RendererHost.EmbeddedWindow is EmbeddedWindowOpenGL openGlWindow)
  411. {
  412. // Try to bind the OpenGL context before calling the shutdown event.
  413. openGlWindow.MakeCurrent(false, false);
  414. Device.DisposeGpu();
  415. // Unbind context and destroy everything.
  416. openGlWindow.MakeCurrent(true, false);
  417. }
  418. else
  419. {
  420. Device.DisposeGpu();
  421. }
  422. }
  423. private void HideCursorState_Changed(object sender, ReactiveEventArgs<HideCursorMode> state)
  424. {
  425. if (state.NewValue == HideCursorMode.OnIdle)
  426. {
  427. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  428. }
  429. }
  430. public async Task<bool> LoadGuestApplication()
  431. {
  432. InitializeSwitchInstance();
  433. MainWindow.UpdateGraphicsConfig();
  434. SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  435. if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  436. {
  437. if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError))
  438. {
  439. {
  440. if (SetupValidator.CanFixStartApplication(ContentManager, ApplicationPath, userError, out firmwareVersion))
  441. {
  442. if (userError == UserError.NoFirmware)
  443. {
  444. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  445. LocaleManager.Instance[LocaleKeys.DialogFirmwareNoFirmwareInstalledMessage],
  446. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallEmbeddedMessage, firmwareVersion.VersionString),
  447. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  448. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  449. "");
  450. if (result != UserResult.Yes)
  451. {
  452. await UserErrorDialog.ShowUserErrorDialog(userError);
  453. Device.Dispose();
  454. return false;
  455. }
  456. }
  457. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  458. {
  459. await UserErrorDialog.ShowUserErrorDialog(userError);
  460. Device.Dispose();
  461. return false;
  462. }
  463. // Tell the user that we installed a firmware for them.
  464. if (userError == UserError.NoFirmware)
  465. {
  466. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  467. _viewModel.RefreshFirmwareStatus();
  468. await ContentDialogHelper.CreateInfoDialog(
  469. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstalledMessage, firmwareVersion.VersionString),
  470. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallEmbeddedSuccessMessage, firmwareVersion.VersionString),
  471. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  472. "",
  473. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  474. }
  475. }
  476. else
  477. {
  478. await UserErrorDialog.ShowUserErrorDialog(userError);
  479. Device.Dispose();
  480. return false;
  481. }
  482. }
  483. }
  484. }
  485. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  486. if (_isFirmwareTitle)
  487. {
  488. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  489. if (!Device.LoadNca(ApplicationPath))
  490. {
  491. Device.Dispose();
  492. return false;
  493. }
  494. }
  495. else if (Directory.Exists(ApplicationPath))
  496. {
  497. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  498. if (romFsFiles.Length == 0)
  499. {
  500. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  501. }
  502. if (romFsFiles.Length > 0)
  503. {
  504. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  505. if (!Device.LoadCart(ApplicationPath, romFsFiles[0]))
  506. {
  507. Device.Dispose();
  508. return false;
  509. }
  510. }
  511. else
  512. {
  513. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  514. if (!Device.LoadCart(ApplicationPath))
  515. {
  516. Device.Dispose();
  517. return false;
  518. }
  519. }
  520. }
  521. else if (File.Exists(ApplicationPath))
  522. {
  523. switch (Path.GetExtension(ApplicationPath).ToLowerInvariant())
  524. {
  525. case ".xci":
  526. {
  527. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  528. if (!Device.LoadXci(ApplicationPath))
  529. {
  530. Device.Dispose();
  531. return false;
  532. }
  533. break;
  534. }
  535. case ".nca":
  536. {
  537. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  538. if (!Device.LoadNca(ApplicationPath))
  539. {
  540. Device.Dispose();
  541. return false;
  542. }
  543. break;
  544. }
  545. case ".nsp":
  546. case ".pfs0":
  547. {
  548. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  549. if (!Device.LoadNsp(ApplicationPath))
  550. {
  551. Device.Dispose();
  552. return false;
  553. }
  554. break;
  555. }
  556. default:
  557. {
  558. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  559. try
  560. {
  561. if (!Device.LoadProgram(ApplicationPath))
  562. {
  563. Device.Dispose();
  564. return false;
  565. }
  566. }
  567. catch (ArgumentOutOfRangeException)
  568. {
  569. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  570. Device.Dispose();
  571. return false;
  572. }
  573. break;
  574. }
  575. }
  576. }
  577. else
  578. {
  579. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  580. Device.Dispose();
  581. return false;
  582. }
  583. DiscordIntegrationModule.SwitchToPlayingState(Device.Processes.ActiveApplication.ProgramIdText, Device.Processes.ActiveApplication.Name);
  584. ApplicationLibrary.LoadAndSaveMetaData(Device.Processes.ActiveApplication.ProgramIdText, appMetadata =>
  585. {
  586. appMetadata.UpdatePreGame();
  587. });
  588. return true;
  589. }
  590. internal void Resume()
  591. {
  592. Device?.System.TogglePauseEmulation(false);
  593. _viewModel.IsPaused = false;
  594. _viewModel.Title = TitleHelper.ActiveApplicationTitle(Device?.Processes.ActiveApplication, Program.Version);
  595. Logger.Info?.Print(LogClass.Emulation, "Emulation was resumed");
  596. }
  597. internal void Pause()
  598. {
  599. Device?.System.TogglePauseEmulation(true);
  600. _viewModel.IsPaused = true;
  601. _viewModel.Title = TitleHelper.ActiveApplicationTitle(Device?.Processes.ActiveApplication, Program.Version, LocaleManager.Instance[LocaleKeys.Paused]);
  602. Logger.Info?.Print(LogClass.Emulation, "Emulation was paused");
  603. }
  604. private void InitializeSwitchInstance()
  605. {
  606. // Initialize KeySet.
  607. VirtualFileSystem.ReloadKeySet();
  608. // Initialize Renderer.
  609. IRenderer renderer;
  610. if (ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan)
  611. {
  612. renderer = new VulkanRenderer(
  613. Vk.GetApi(),
  614. (RendererHost.EmbeddedWindow as EmbeddedWindowVulkan).CreateSurface,
  615. VulkanHelper.GetRequiredInstanceExtensions,
  616. ConfigurationState.Instance.Graphics.PreferredGpu.Value);
  617. }
  618. else
  619. {
  620. renderer = new OpenGLRenderer();
  621. }
  622. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  623. var isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  624. if (isGALThreaded)
  625. {
  626. renderer = new ThreadedRenderer(renderer);
  627. }
  628. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALThreaded}");
  629. // Initialize Configuration.
  630. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? MemoryConfiguration.MemoryConfiguration6GiB : MemoryConfiguration.MemoryConfiguration4GiB;
  631. HLEConfiguration configuration = new(VirtualFileSystem,
  632. _viewModel.LibHacHorizonManager,
  633. ContentManager,
  634. _accountManager,
  635. _userChannelPersistence,
  636. renderer,
  637. InitializeAudio(),
  638. memoryConfiguration,
  639. _viewModel.UiHandler,
  640. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  641. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  642. ConfigurationState.Instance.Graphics.EnableVsync,
  643. ConfigurationState.Instance.System.EnableDockedMode,
  644. ConfigurationState.Instance.System.EnablePtc,
  645. ConfigurationState.Instance.System.EnableInternetAccess,
  646. ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  647. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  648. ConfigurationState.Instance.System.SystemTimeOffset,
  649. ConfigurationState.Instance.System.TimeZone,
  650. ConfigurationState.Instance.System.MemoryManagerMode,
  651. ConfigurationState.Instance.System.IgnoreMissingServices,
  652. ConfigurationState.Instance.Graphics.AspectRatio,
  653. ConfigurationState.Instance.System.AudioVolume,
  654. ConfigurationState.Instance.System.UseHypervisor,
  655. ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value,
  656. ConfigurationState.Instance.Multiplayer.Mode);
  657. Device = new Switch(configuration);
  658. }
  659. private static IHardwareDeviceDriver InitializeAudio()
  660. {
  661. var availableBackends = new List<AudioBackend>
  662. {
  663. AudioBackend.SDL2,
  664. AudioBackend.SoundIo,
  665. AudioBackend.OpenAl,
  666. AudioBackend.Dummy,
  667. };
  668. AudioBackend preferredBackend = ConfigurationState.Instance.System.AudioBackend.Value;
  669. for (int i = 0; i < availableBackends.Count; i++)
  670. {
  671. if (availableBackends[i] == preferredBackend)
  672. {
  673. availableBackends.RemoveAt(i);
  674. availableBackends.Insert(0, preferredBackend);
  675. break;
  676. }
  677. }
  678. static IHardwareDeviceDriver InitializeAudioBackend<T>(AudioBackend backend, AudioBackend nextBackend) where T : IHardwareDeviceDriver, new()
  679. {
  680. if (T.IsSupported)
  681. {
  682. return new T();
  683. }
  684. Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}.");
  685. return null;
  686. }
  687. IHardwareDeviceDriver deviceDriver = null;
  688. for (int i = 0; i < availableBackends.Count; i++)
  689. {
  690. AudioBackend currentBackend = availableBackends[i];
  691. AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy;
  692. deviceDriver = currentBackend switch
  693. {
  694. AudioBackend.SDL2 => InitializeAudioBackend<SDL2HardwareDeviceDriver>(AudioBackend.SDL2, nextBackend),
  695. AudioBackend.SoundIo => InitializeAudioBackend<SoundIoHardwareDeviceDriver>(AudioBackend.SoundIo, nextBackend),
  696. AudioBackend.OpenAl => InitializeAudioBackend<OpenALHardwareDeviceDriver>(AudioBackend.OpenAl, nextBackend),
  697. _ => new DummyHardwareDeviceDriver(),
  698. };
  699. if (deviceDriver != null)
  700. {
  701. ConfigurationState.Instance.System.AudioBackend.Value = currentBackend;
  702. break;
  703. }
  704. }
  705. MainWindowViewModel.SaveConfig();
  706. return deviceDriver;
  707. }
  708. private void Window_BoundsChanged(object sender, Size e)
  709. {
  710. Width = (int)e.Width;
  711. Height = (int)e.Height;
  712. SetRendererWindowSize(e);
  713. }
  714. private void MainLoop()
  715. {
  716. while (_isActive)
  717. {
  718. UpdateFrame();
  719. // Polling becomes expensive if it's not slept.
  720. Thread.Sleep(1);
  721. }
  722. }
  723. private void RenderLoop()
  724. {
  725. Dispatcher.UIThread.InvokeAsync(() =>
  726. {
  727. if (_viewModel.StartGamesInFullscreen)
  728. {
  729. _viewModel.WindowState = WindowState.FullScreen;
  730. }
  731. if (_viewModel.WindowState == WindowState.FullScreen)
  732. {
  733. _viewModel.ShowMenuAndStatusBar = false;
  734. }
  735. });
  736. _renderer = Device.Gpu.Renderer is ThreadedRenderer tr ? tr.BaseRenderer : Device.Gpu.Renderer;
  737. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  738. (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.InitializeBackgroundContext(_renderer);
  739. Device.Gpu.Renderer.Initialize(_glLogLevel);
  740. _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)ConfigurationState.Instance.Graphics.AntiAliasing.Value);
  741. _renderer?.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  742. _renderer?.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  743. _renderer?.Window?.SetColorSpacePassthrough(ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Value);
  744. Width = (int)RendererHost.Bounds.Width;
  745. Height = (int)RendererHost.Bounds.Height;
  746. _renderer.Window.SetSize((int)(Width * _topLevel.RenderScaling), (int)(Height * _topLevel.RenderScaling));
  747. _chrono.Start();
  748. Device.Gpu.Renderer.RunLoop(() =>
  749. {
  750. Device.Gpu.SetGpuThread();
  751. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  752. _renderer.Window.ChangeVSyncMode(Device.EnableDeviceVsync);
  753. while (_isActive)
  754. {
  755. _ticks += _chrono.ElapsedTicks;
  756. _chrono.Restart();
  757. if (Device.WaitFifo())
  758. {
  759. Device.Statistics.RecordFifoStart();
  760. Device.ProcessFrame();
  761. Device.Statistics.RecordFifoEnd();
  762. }
  763. while (Device.ConsumeFrameAvailable())
  764. {
  765. if (!_renderingStarted)
  766. {
  767. _renderingStarted = true;
  768. _viewModel.SwitchToRenderer(false);
  769. InitStatus();
  770. }
  771. Device.PresentFrame(() => (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.SwapBuffers());
  772. }
  773. if (_ticks >= _ticksPerFrame)
  774. {
  775. UpdateStatus();
  776. }
  777. }
  778. // Make sure all commands in the run loop are fully executed before leaving the loop.
  779. if (Device.Gpu.Renderer is ThreadedRenderer threaded)
  780. {
  781. threaded.FlushThreadedCommands();
  782. }
  783. _gpuDoneEvent.Set();
  784. });
  785. (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(true);
  786. }
  787. public void InitStatus()
  788. {
  789. StatusInitEvent?.Invoke(this, new StatusInitEventArgs(
  790. ConfigurationState.Instance.Graphics.GraphicsBackend.Value switch
  791. {
  792. GraphicsBackend.Vulkan => "Vulkan",
  793. GraphicsBackend.OpenGl => "OpenGL",
  794. _ => throw new NotImplementedException()
  795. },
  796. $"GPU: {_renderer.GetHardwareInfo().GpuDriver}"));
  797. }
  798. public void UpdateStatus()
  799. {
  800. // Run a status update only when a frame is to be drawn. This prevents from updating the ui and wasting a render when no frame is queued.
  801. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? LocaleManager.Instance[LocaleKeys.Docked] : LocaleManager.Instance[LocaleKeys.Handheld];
  802. if (GraphicsConfig.ResScale != 1)
  803. {
  804. dockedMode += $" ({GraphicsConfig.ResScale}x)";
  805. }
  806. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  807. Device.EnableDeviceVsync,
  808. LocaleManager.Instance[LocaleKeys.VolumeShort] + $": {(int)(Device.GetVolume() * 100)}%",
  809. dockedMode,
  810. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  811. LocaleManager.Instance[LocaleKeys.Game] + $": {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  812. $"FIFO: {Device.Statistics.GetFifoPercent():00.00} %"));
  813. }
  814. public async Task ShowExitPrompt()
  815. {
  816. bool shouldExit = !ConfigurationState.Instance.ShowConfirmExit;
  817. if (!shouldExit)
  818. {
  819. if (_dialogShown)
  820. {
  821. return;
  822. }
  823. _dialogShown = true;
  824. shouldExit = await ContentDialogHelper.CreateStopEmulationDialog();
  825. _dialogShown = false;
  826. }
  827. if (shouldExit)
  828. {
  829. Stop();
  830. }
  831. }
  832. private bool UpdateFrame()
  833. {
  834. if (!_isActive)
  835. {
  836. return false;
  837. }
  838. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  839. if (_viewModel.IsActive)
  840. {
  841. if (_isCursorInRenderer)
  842. {
  843. if (ConfigurationState.Instance.Hid.EnableMouse)
  844. {
  845. HideCursor();
  846. }
  847. else
  848. {
  849. switch (ConfigurationState.Instance.HideCursor.Value)
  850. {
  851. case HideCursorMode.Never:
  852. ShowCursor();
  853. break;
  854. case HideCursorMode.OnIdle:
  855. if (Stopwatch.GetTimestamp() - _lastCursorMoveTime >= CursorHideIdleTime * Stopwatch.Frequency)
  856. {
  857. HideCursor();
  858. }
  859. else
  860. {
  861. ShowCursor();
  862. }
  863. break;
  864. case HideCursorMode.Always:
  865. HideCursor();
  866. break;
  867. }
  868. }
  869. }
  870. else
  871. {
  872. ShowCursor();
  873. }
  874. Dispatcher.UIThread.Post(() =>
  875. {
  876. if (_keyboardInterface.GetKeyboardStateSnapshot().IsPressed(Key.Delete) && _viewModel.WindowState != WindowState.FullScreen)
  877. {
  878. Device.Processes.ActiveApplication.DiskCacheLoadState?.Cancel();
  879. }
  880. });
  881. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  882. if (currentHotkeyState != _prevHotkeyState)
  883. {
  884. switch (currentHotkeyState)
  885. {
  886. case KeyboardHotkeyState.ToggleVSync:
  887. ToggleVSync();
  888. break;
  889. case KeyboardHotkeyState.Screenshot:
  890. ScreenshotRequested = true;
  891. break;
  892. case KeyboardHotkeyState.ShowUI:
  893. _viewModel.ShowMenuAndStatusBar = !_viewModel.ShowMenuAndStatusBar;
  894. break;
  895. case KeyboardHotkeyState.Pause:
  896. if (_viewModel.IsPaused)
  897. {
  898. Resume();
  899. }
  900. else
  901. {
  902. Pause();
  903. }
  904. break;
  905. case KeyboardHotkeyState.ToggleMute:
  906. if (Device.IsAudioMuted())
  907. {
  908. Device.SetVolume(_viewModel.VolumeBeforeMute);
  909. }
  910. else
  911. {
  912. _viewModel.VolumeBeforeMute = Device.GetVolume();
  913. Device.SetVolume(0);
  914. }
  915. _viewModel.Volume = Device.GetVolume();
  916. break;
  917. case KeyboardHotkeyState.ResScaleUp:
  918. GraphicsConfig.ResScale = GraphicsConfig.ResScale % MaxResolutionScale + 1;
  919. break;
  920. case KeyboardHotkeyState.ResScaleDown:
  921. GraphicsConfig.ResScale =
  922. (MaxResolutionScale + GraphicsConfig.ResScale - 2) % MaxResolutionScale + 1;
  923. break;
  924. case KeyboardHotkeyState.VolumeUp:
  925. _newVolume = MathF.Round((Device.GetVolume() + VolumeDelta), 2);
  926. Device.SetVolume(_newVolume);
  927. _viewModel.Volume = Device.GetVolume();
  928. break;
  929. case KeyboardHotkeyState.VolumeDown:
  930. _newVolume = MathF.Round((Device.GetVolume() - VolumeDelta), 2);
  931. Device.SetVolume(_newVolume);
  932. _viewModel.Volume = Device.GetVolume();
  933. break;
  934. case KeyboardHotkeyState.None:
  935. (_keyboardInterface as AvaloniaKeyboard).Clear();
  936. break;
  937. }
  938. }
  939. _prevHotkeyState = currentHotkeyState;
  940. if (ScreenshotRequested)
  941. {
  942. ScreenshotRequested = false;
  943. _renderer.Screenshot();
  944. }
  945. }
  946. // Touchscreen.
  947. bool hasTouch = false;
  948. if (_viewModel.IsActive && !ConfigurationState.Instance.Hid.EnableMouse)
  949. {
  950. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as AvaloniaMouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  951. }
  952. if (!hasTouch)
  953. {
  954. Device.Hid.Touchscreen.Update();
  955. }
  956. Device.Hid.DebugPad.Update();
  957. return true;
  958. }
  959. private KeyboardHotkeyState GetHotkeyState()
  960. {
  961. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  962. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  963. {
  964. state = KeyboardHotkeyState.ToggleVSync;
  965. }
  966. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  967. {
  968. state = KeyboardHotkeyState.Screenshot;
  969. }
  970. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI))
  971. {
  972. state = KeyboardHotkeyState.ShowUI;
  973. }
  974. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  975. {
  976. state = KeyboardHotkeyState.Pause;
  977. }
  978. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  979. {
  980. state = KeyboardHotkeyState.ToggleMute;
  981. }
  982. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleUp))
  983. {
  984. state = KeyboardHotkeyState.ResScaleUp;
  985. }
  986. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleDown))
  987. {
  988. state = KeyboardHotkeyState.ResScaleDown;
  989. }
  990. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeUp))
  991. {
  992. state = KeyboardHotkeyState.VolumeUp;
  993. }
  994. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeDown))
  995. {
  996. state = KeyboardHotkeyState.VolumeDown;
  997. }
  998. return state;
  999. }
  1000. }
  1001. }