MainWindow.axaml.cs 20 KB

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