MainWindow.axaml.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Primitives;
  4. using Avalonia.Interactivity;
  5. using Avalonia.Threading;
  6. using FluentAvalonia.UI.Controls;
  7. using Ryujinx.Ava.Common;
  8. using Ryujinx.Ava.Common.Locale;
  9. using Ryujinx.Ava.Input;
  10. using Ryujinx.Ava.UI.Applet;
  11. using Ryujinx.Ava.UI.Helpers;
  12. using Ryujinx.Ava.UI.ViewModels;
  13. using Ryujinx.Common.Logging;
  14. using Ryujinx.Graphics.Gpu;
  15. using Ryujinx.HLE.FileSystem;
  16. using Ryujinx.HLE.HOS;
  17. using Ryujinx.HLE.HOS.Services.Account.Acc;
  18. using Ryujinx.Input.HLE;
  19. using Ryujinx.Input.SDL2;
  20. using Ryujinx.Modules;
  21. using Ryujinx.UI.App.Common;
  22. using Ryujinx.UI.Common;
  23. using Ryujinx.UI.Common.Configuration;
  24. using Ryujinx.UI.Common.Helper;
  25. using System;
  26. using System.IO;
  27. using System.Runtime.Versioning;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. namespace Ryujinx.Ava.UI.Windows
  31. {
  32. public partial class MainWindow : StyleableWindow
  33. {
  34. internal static MainWindowViewModel MainWindowViewModel { get; private set; }
  35. private bool _isLoading;
  36. private UserChannelPersistence _userChannelPersistence;
  37. private static bool _deferLoad;
  38. private static string _launchPath;
  39. private static bool _startFullscreen;
  40. internal readonly AvaHostUIHandler UiHandler;
  41. public VirtualFileSystem VirtualFileSystem { get; private set; }
  42. public ContentManager ContentManager { get; private set; }
  43. public AccountManager AccountManager { get; private set; }
  44. public LibHacHorizonManager LibHacHorizonManager { get; private set; }
  45. public InputManager InputManager { get; private set; }
  46. internal MainWindowViewModel ViewModel { get; private set; }
  47. public SettingsWindow SettingsWindow { get; set; }
  48. public static bool ShowKeyErrorOnLoad { get; set; }
  49. public ApplicationLibrary ApplicationLibrary { get; set; }
  50. public MainWindow()
  51. {
  52. ViewModel = new MainWindowViewModel();
  53. MainWindowViewModel = ViewModel;
  54. DataContext = ViewModel;
  55. SetWindowSizePosition();
  56. InitializeComponent();
  57. Load();
  58. UiHandler = new AvaHostUIHandler(this);
  59. ViewModel.Title = $"Ryujinx {Program.Version}";
  60. // NOTE: Height of MenuBar and StatusBar is not usable here, since it would still be 0 at this point.
  61. double barHeight = MenuBar.MinHeight + StatusBarView.StatusBar.MinHeight;
  62. Height = ((Height - barHeight) / Program.WindowScaleFactor) + barHeight;
  63. Width /= Program.WindowScaleFactor;
  64. if (Program.PreviewerDetached)
  65. {
  66. InputManager = new InputManager(new AvaloniaKeyboardDriver(this), new SDL2GamepadDriver());
  67. this.GetObservable(IsActiveProperty).Subscribe(IsActiveChanged);
  68. this.ScalingChanged += OnScalingChanged;
  69. }
  70. }
  71. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  72. {
  73. base.OnApplyTemplate(e);
  74. NotificationHelper.SetNotificationManager(this);
  75. }
  76. private void IsActiveChanged(bool obj)
  77. {
  78. ViewModel.IsActive = obj;
  79. }
  80. private void OnScalingChanged(object sender, EventArgs e)
  81. {
  82. Program.DesktopScaleFactor = this.RenderScaling;
  83. }
  84. private void ApplicationLibrary_ApplicationAdded(object sender, ApplicationAddedEventArgs e)
  85. {
  86. Dispatcher.UIThread.Post(() =>
  87. {
  88. ViewModel.Applications.Add(e.AppData);
  89. });
  90. }
  91. private void ApplicationLibrary_ApplicationCountUpdated(object sender, ApplicationCountUpdatedEventArgs e)
  92. {
  93. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarGamesLoaded, e.NumAppsLoaded, e.NumAppsFound);
  94. Dispatcher.UIThread.Post(() =>
  95. {
  96. ViewModel.StatusBarProgressValue = e.NumAppsLoaded;
  97. ViewModel.StatusBarProgressMaximum = e.NumAppsFound;
  98. if (e.NumAppsFound == 0)
  99. {
  100. StatusBarView.LoadProgressBar.IsVisible = false;
  101. }
  102. if (e.NumAppsLoaded == e.NumAppsFound)
  103. {
  104. StatusBarView.LoadProgressBar.IsVisible = false;
  105. }
  106. });
  107. }
  108. public void Application_Opened(object sender, ApplicationOpenedEventArgs args)
  109. {
  110. if (args.Application != null)
  111. {
  112. ViewModel.SelectedIcon = args.Application.Icon;
  113. string path = new FileInfo(args.Application.Path).FullName;
  114. ViewModel.LoadApplication(path).Wait();
  115. }
  116. args.Handled = true;
  117. }
  118. internal static void DeferLoadApplication(string launchPathArg, bool startFullscreenArg)
  119. {
  120. _deferLoad = true;
  121. _launchPath = launchPathArg;
  122. _startFullscreen = startFullscreenArg;
  123. }
  124. public void SwitchToGameControl(bool startFullscreen = false)
  125. {
  126. ViewModel.ShowLoadProgress = false;
  127. ViewModel.ShowContent = true;
  128. ViewModel.IsLoadingIndeterminate = false;
  129. if (startFullscreen && ViewModel.WindowState != WindowState.FullScreen)
  130. {
  131. ViewModel.ToggleFullscreen();
  132. }
  133. }
  134. public void ShowLoading(bool startFullscreen = false)
  135. {
  136. ViewModel.ShowContent = false;
  137. ViewModel.ShowLoadProgress = true;
  138. ViewModel.IsLoadingIndeterminate = true;
  139. if (startFullscreen && ViewModel.WindowState != WindowState.FullScreen)
  140. {
  141. ViewModel.ToggleFullscreen();
  142. }
  143. }
  144. private void Initialize()
  145. {
  146. _userChannelPersistence = new UserChannelPersistence();
  147. VirtualFileSystem = VirtualFileSystem.CreateInstance();
  148. LibHacHorizonManager = new LibHacHorizonManager();
  149. ContentManager = new ContentManager(VirtualFileSystem);
  150. LibHacHorizonManager.InitializeFsServer(VirtualFileSystem);
  151. LibHacHorizonManager.InitializeArpServer();
  152. LibHacHorizonManager.InitializeBcatServer();
  153. LibHacHorizonManager.InitializeSystemClients();
  154. ApplicationLibrary = new ApplicationLibrary(VirtualFileSystem);
  155. // Save data created before we supported extra data in directory save data will not work properly if
  156. // given empty extra data. Luckily some of that extra data can be created using the data from the
  157. // save data indexer, which should be enough to check access permissions for user saves.
  158. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  159. // Consider removing this at some point in the future when we don't need to worry about old saves.
  160. VirtualFileSystem.FixExtraData(LibHacHorizonManager.RyujinxClient);
  161. AccountManager = new AccountManager(LibHacHorizonManager.RyujinxClient, CommandLineState.Profile);
  162. VirtualFileSystem.ReloadKeySet();
  163. ApplicationHelper.Initialize(VirtualFileSystem, AccountManager, LibHacHorizonManager.RyujinxClient);
  164. }
  165. [SupportedOSPlatform("linux")]
  166. private static async Task ShowVmMaxMapCountWarning()
  167. {
  168. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.LinuxVmMaxMapCountWarningTextSecondary,
  169. LinuxHelper.VmMaxMapCount, LinuxHelper.RecommendedVmMaxMapCount);
  170. await ContentDialogHelper.CreateWarningDialog(
  171. LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountWarningTextPrimary],
  172. LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountWarningTextSecondary]
  173. );
  174. }
  175. [SupportedOSPlatform("linux")]
  176. private static async Task ShowVmMaxMapCountDialog()
  177. {
  178. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.LinuxVmMaxMapCountDialogTextPrimary,
  179. LinuxHelper.RecommendedVmMaxMapCount);
  180. UserResult response = await ContentDialogHelper.ShowTextDialog(
  181. $"Ryujinx - {LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountDialogTitle]}",
  182. LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountDialogTextPrimary],
  183. LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountDialogTextSecondary],
  184. LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountDialogButtonUntilRestart],
  185. LocaleManager.Instance[LocaleKeys.LinuxVmMaxMapCountDialogButtonPersistent],
  186. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  187. (int)Symbol.Help
  188. );
  189. int rc;
  190. switch (response)
  191. {
  192. case UserResult.Ok:
  193. rc = LinuxHelper.RunPkExec($"echo {LinuxHelper.RecommendedVmMaxMapCount} > {LinuxHelper.VmMaxMapCountPath}");
  194. if (rc == 0)
  195. {
  196. Logger.Info?.Print(LogClass.Application, $"vm.max_map_count set to {LinuxHelper.VmMaxMapCount} until the next restart.");
  197. }
  198. else
  199. {
  200. Logger.Error?.Print(LogClass.Application, $"Unable to change vm.max_map_count. Process exited with code: {rc}");
  201. }
  202. break;
  203. case UserResult.No:
  204. rc = LinuxHelper.RunPkExec($"echo \"vm.max_map_count = {LinuxHelper.RecommendedVmMaxMapCount}\" > {LinuxHelper.SysCtlConfigPath} && sysctl -p {LinuxHelper.SysCtlConfigPath}");
  205. if (rc == 0)
  206. {
  207. Logger.Info?.Print(LogClass.Application, $"vm.max_map_count set to {LinuxHelper.VmMaxMapCount}. Written to config: {LinuxHelper.SysCtlConfigPath}");
  208. }
  209. else
  210. {
  211. Logger.Error?.Print(LogClass.Application, $"Unable to write new value for vm.max_map_count to config. Process exited with code: {rc}");
  212. }
  213. break;
  214. }
  215. }
  216. private async Task CheckLaunchState()
  217. {
  218. if (OperatingSystem.IsLinux() && LinuxHelper.VmMaxMapCount < LinuxHelper.RecommendedVmMaxMapCount)
  219. {
  220. Logger.Warning?.Print(LogClass.Application, $"The value of vm.max_map_count is lower than {LinuxHelper.RecommendedVmMaxMapCount}. ({LinuxHelper.VmMaxMapCount})");
  221. if (LinuxHelper.PkExecPath is not null)
  222. {
  223. await Dispatcher.UIThread.InvokeAsync(ShowVmMaxMapCountDialog);
  224. }
  225. else
  226. {
  227. await Dispatcher.UIThread.InvokeAsync(ShowVmMaxMapCountWarning);
  228. }
  229. }
  230. if (!ShowKeyErrorOnLoad)
  231. {
  232. if (_deferLoad)
  233. {
  234. _deferLoad = false;
  235. ViewModel.LoadApplication(_launchPath, _startFullscreen).Wait();
  236. }
  237. }
  238. else
  239. {
  240. ShowKeyErrorOnLoad = false;
  241. await Dispatcher.UIThread.InvokeAsync(async () => await UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys));
  242. }
  243. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
  244. {
  245. await Updater.BeginParse(this, false).ContinueWith(task =>
  246. {
  247. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  248. }, TaskContinuationOptions.OnlyOnFaulted);
  249. }
  250. }
  251. private void Load()
  252. {
  253. StatusBarView.VolumeStatus.Click += VolumeStatus_CheckedChanged;
  254. ApplicationGrid.ApplicationOpened += Application_Opened;
  255. ApplicationGrid.DataContext = ViewModel;
  256. ApplicationList.ApplicationOpened += Application_Opened;
  257. ApplicationList.DataContext = ViewModel;
  258. }
  259. private void SetWindowSizePosition()
  260. {
  261. PixelPoint savedPoint = new(ConfigurationState.Instance.UI.WindowStartup.WindowPositionX,
  262. ConfigurationState.Instance.UI.WindowStartup.WindowPositionY);
  263. ViewModel.WindowHeight = ConfigurationState.Instance.UI.WindowStartup.WindowSizeHeight * Program.WindowScaleFactor;
  264. ViewModel.WindowWidth = ConfigurationState.Instance.UI.WindowStartup.WindowSizeWidth * Program.WindowScaleFactor;
  265. ViewModel.WindowState = ConfigurationState.Instance.UI.WindowStartup.WindowMaximized.Value ? WindowState.Maximized : WindowState.Normal;
  266. if (CheckScreenBounds(savedPoint))
  267. {
  268. Position = savedPoint;
  269. }
  270. else
  271. {
  272. WindowStartupLocation = WindowStartupLocation.CenterScreen;
  273. }
  274. }
  275. private bool CheckScreenBounds(PixelPoint configPoint)
  276. {
  277. for (int i = 0; i < Screens.ScreenCount; i++)
  278. {
  279. if (Screens.All[i].Bounds.Contains(configPoint))
  280. {
  281. return true;
  282. }
  283. }
  284. Logger.Warning?.Print(LogClass.Application, "Failed to find valid start-up coordinates. Defaulting to primary monitor center.");
  285. return false;
  286. }
  287. private void SaveWindowSizePosition()
  288. {
  289. ConfigurationState.Instance.UI.WindowStartup.WindowSizeHeight.Value = (int)Height;
  290. ConfigurationState.Instance.UI.WindowStartup.WindowSizeWidth.Value = (int)Width;
  291. ConfigurationState.Instance.UI.WindowStartup.WindowPositionX.Value = Position.X;
  292. ConfigurationState.Instance.UI.WindowStartup.WindowPositionY.Value = Position.Y;
  293. ConfigurationState.Instance.UI.WindowStartup.WindowMaximized.Value = WindowState == WindowState.Maximized;
  294. MainWindowViewModel.SaveConfig();
  295. }
  296. protected override void OnOpened(EventArgs e)
  297. {
  298. base.OnOpened(e);
  299. Initialize();
  300. ViewModel.Initialize(
  301. ContentManager,
  302. StorageProvider,
  303. ApplicationLibrary,
  304. VirtualFileSystem,
  305. AccountManager,
  306. InputManager,
  307. _userChannelPersistence,
  308. LibHacHorizonManager,
  309. UiHandler,
  310. ShowLoading,
  311. SwitchToGameControl,
  312. SetMainContent,
  313. this);
  314. ApplicationLibrary.ApplicationCountUpdated += ApplicationLibrary_ApplicationCountUpdated;
  315. ApplicationLibrary.ApplicationAdded += ApplicationLibrary_ApplicationAdded;
  316. ViewModel.RefreshFirmwareStatus();
  317. LoadApplications();
  318. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  319. CheckLaunchState();
  320. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  321. }
  322. private void SetMainContent(Control content = null)
  323. {
  324. content ??= GameLibrary;
  325. if (MainContent.Content != content)
  326. {
  327. MainContent.Content = content;
  328. }
  329. }
  330. public static void UpdateGraphicsConfig()
  331. {
  332. #pragma warning disable IDE0055 // Disable formatting
  333. GraphicsConfig.ResScale = ConfigurationState.Instance.Graphics.ResScale == -1 ? ConfigurationState.Instance.Graphics.ResScaleCustom : ConfigurationState.Instance.Graphics.ResScale;
  334. GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  335. GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  336. GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  337. GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression;
  338. GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE;
  339. #pragma warning restore IDE0055
  340. }
  341. private void VolumeStatus_CheckedChanged(object sender, RoutedEventArgs e)
  342. {
  343. var volumeSplitButton = sender as ToggleSplitButton;
  344. if (ViewModel.IsGameRunning)
  345. {
  346. if (!volumeSplitButton.IsChecked)
  347. {
  348. ViewModel.AppHost.Device.SetVolume(ViewModel.VolumeBeforeMute);
  349. }
  350. else
  351. {
  352. ViewModel.VolumeBeforeMute = ViewModel.AppHost.Device.GetVolume();
  353. ViewModel.AppHost.Device.SetVolume(0);
  354. }
  355. ViewModel.Volume = ViewModel.AppHost.Device.GetVolume();
  356. }
  357. }
  358. protected override void OnClosing(WindowClosingEventArgs e)
  359. {
  360. if (!ViewModel.IsClosing && ViewModel.AppHost != null && ConfigurationState.Instance.ShowConfirmExit)
  361. {
  362. e.Cancel = true;
  363. ConfirmExit();
  364. return;
  365. }
  366. ViewModel.IsClosing = true;
  367. if (ViewModel.AppHost != null)
  368. {
  369. ViewModel.AppHost.AppExit -= ViewModel.AppHost_AppExit;
  370. ViewModel.AppHost.AppExit += (sender, e) =>
  371. {
  372. ViewModel.AppHost = null;
  373. Dispatcher.UIThread.Post(() =>
  374. {
  375. MainContent = null;
  376. Close();
  377. });
  378. };
  379. ViewModel.AppHost?.Stop();
  380. e.Cancel = true;
  381. return;
  382. }
  383. SaveWindowSizePosition();
  384. ApplicationLibrary.CancelLoading();
  385. InputManager.Dispose();
  386. Program.Exit();
  387. base.OnClosing(e);
  388. }
  389. private void ConfirmExit()
  390. {
  391. Dispatcher.UIThread.InvokeAsync(async () =>
  392. {
  393. ViewModel.IsClosing = await ContentDialogHelper.CreateExitDialog();
  394. if (ViewModel.IsClosing)
  395. {
  396. Close();
  397. }
  398. });
  399. }
  400. public void LoadApplications()
  401. {
  402. ViewModel.Applications.Clear();
  403. StatusBarView.LoadProgressBar.IsVisible = true;
  404. ViewModel.StatusBarProgressMaximum = 0;
  405. ViewModel.StatusBarProgressValue = 0;
  406. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarGamesLoaded, 0, 0);
  407. ReloadGameList();
  408. }
  409. public void ToggleFileType(string fileType)
  410. {
  411. _ = fileType switch
  412. {
  413. #pragma warning disable IDE0055 // Disable formatting
  414. "NSP" => ConfigurationState.Instance.UI.ShownFileTypes.NSP.Value = !ConfigurationState.Instance.UI.ShownFileTypes.NSP,
  415. "PFS0" => ConfigurationState.Instance.UI.ShownFileTypes.PFS0.Value = !ConfigurationState.Instance.UI.ShownFileTypes.PFS0,
  416. "XCI" => ConfigurationState.Instance.UI.ShownFileTypes.XCI.Value = !ConfigurationState.Instance.UI.ShownFileTypes.XCI,
  417. "NCA" => ConfigurationState.Instance.UI.ShownFileTypes.NCA.Value = !ConfigurationState.Instance.UI.ShownFileTypes.NCA,
  418. "NRO" => ConfigurationState.Instance.UI.ShownFileTypes.NRO.Value = !ConfigurationState.Instance.UI.ShownFileTypes.NRO,
  419. "NSO" => ConfigurationState.Instance.UI.ShownFileTypes.NSO.Value = !ConfigurationState.Instance.UI.ShownFileTypes.NSO,
  420. _ => throw new ArgumentOutOfRangeException(fileType),
  421. #pragma warning restore IDE0055
  422. };
  423. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  424. LoadApplications();
  425. }
  426. private void ReloadGameList()
  427. {
  428. if (_isLoading)
  429. {
  430. return;
  431. }
  432. _isLoading = true;
  433. Thread applicationLibraryThread = new(() =>
  434. {
  435. ApplicationLibrary.LoadApplications(ConfigurationState.Instance.UI.GameDirs, ConfigurationState.Instance.System.Language);
  436. _isLoading = false;
  437. })
  438. {
  439. Name = "GUI.ApplicationLibraryThread",
  440. IsBackground = true,
  441. };
  442. applicationLibraryThread.Start();
  443. }
  444. }
  445. }