MainWindow.axaml.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Input;
  4. using Avalonia.Interactivity;
  5. using Avalonia.Markup.Xaml;
  6. using Avalonia.Media;
  7. using Avalonia.Threading;
  8. using Avalonia.Win32;
  9. using FluentAvalonia.UI.Controls;
  10. using Ryujinx.Ava.Common;
  11. using Ryujinx.Ava.Common.Locale;
  12. using Ryujinx.Ava.Input;
  13. using Ryujinx.Ava.Ui.Applet;
  14. using Ryujinx.Ava.Ui.Controls;
  15. using Ryujinx.Ava.Ui.Models;
  16. using Ryujinx.Ava.Ui.ViewModels;
  17. using Ryujinx.Common.Configuration;
  18. using Ryujinx.Common.Logging;
  19. using Ryujinx.Graphics.Gpu;
  20. using Ryujinx.HLE.FileSystem;
  21. using Ryujinx.HLE.HOS;
  22. using Ryujinx.HLE.HOS.Services.Account.Acc;
  23. using Ryujinx.Input.SDL2;
  24. using Ryujinx.Modules;
  25. using Ryujinx.Ui.App.Common;
  26. using Ryujinx.Ui.Common;
  27. using Ryujinx.Ui.Common.Configuration;
  28. using SixLabors.ImageSharp.PixelFormats;
  29. using System;
  30. using System.ComponentModel;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Threading;
  34. using System.Threading.Tasks;
  35. using InputManager = Ryujinx.Input.HLE.InputManager;
  36. using ProgressBar = Avalonia.Controls.ProgressBar;
  37. namespace Ryujinx.Ava.Ui.Windows
  38. {
  39. public class MainWindow : StyleableWindow
  40. {
  41. private bool _canUpdate;
  42. private bool _isClosing;
  43. private bool _isLoading;
  44. private Control _mainViewContent;
  45. private UserChannelPersistence _userChannelPersistence;
  46. private static bool _deferLoad;
  47. private static string _launchPath;
  48. private static bool _startFullscreen;
  49. private string _currentEmulatedGamePath;
  50. internal readonly AvaHostUiHandler UiHandler;
  51. private AutoResetEvent _rendererWaitEvent;
  52. public VirtualFileSystem VirtualFileSystem { get; private set; }
  53. public ContentManager ContentManager { get; private set; }
  54. public AccountManager AccountManager { get; private set; }
  55. public LibHacHorizonManager LibHacHorizonManager { get; private set; }
  56. internal AppHost AppHost { get; private set; }
  57. public InputManager InputManager { get; private set; }
  58. internal RendererControl GlRenderer { get; private set; }
  59. public ContentControl ContentFrame { get; private set; }
  60. public TextBlock LoadStatus { get; private set; }
  61. public TextBlock FirmwareStatus { get; private set; }
  62. public TextBox SearchBox { get; private set; }
  63. public ProgressBar LoadProgressBar { get; private set; }
  64. public Menu Menu { get; private set; }
  65. public MenuItem UpdateMenuItem { get; private set; }
  66. public MenuItem ActionsMenuItem { get; private set; }
  67. public GameGridView GameGrid { get; private set; }
  68. public GameListView GameList { get; private set; }
  69. public OffscreenTextBox HiddenTextBox { get; private set; }
  70. public HotKeyControl FullscreenHotKey { get; private set; }
  71. public HotKeyControl FullscreenHotKey2 { get; private set; }
  72. public HotKeyControl DockToggleHotKey { get; private set; }
  73. public HotKeyControl ExitHotKey { get; private set; }
  74. public ToggleSplitButton VolumeStatus { get; set; }
  75. internal MainWindowViewModel ViewModel { get; private set; }
  76. public SettingsWindow SettingsWindow { get; set; }
  77. public bool CanUpdate
  78. {
  79. get => _canUpdate;
  80. set
  81. {
  82. _canUpdate = value;
  83. Dispatcher.UIThread.InvokeAsync(() => UpdateMenuItem.IsEnabled = _canUpdate);
  84. }
  85. }
  86. public static bool ShowKeyErrorOnLoad { get; set; }
  87. public ApplicationLibrary ApplicationLibrary { get; set; }
  88. public MainWindow()
  89. {
  90. ViewModel = new MainWindowViewModel(this);
  91. DataContext = ViewModel;
  92. InitializeComponent();
  93. AttachDebugDevTools();
  94. UiHandler = new AvaHostUiHandler(this);
  95. Title = $"Ryujinx {Program.Version}";
  96. Height = Height / Program.WindowScaleFactor;
  97. Width = Width / Program.WindowScaleFactor;
  98. if (Program.PreviewerDetached)
  99. {
  100. Initialize();
  101. ViewModel.Initialize();
  102. InputManager = new InputManager(new AvaloniaKeyboardDriver(this), new SDL2GamepadDriver());
  103. LoadGameList();
  104. }
  105. _rendererWaitEvent = new AutoResetEvent(false);
  106. }
  107. [Conditional("DEBUG")]
  108. private void AttachDebugDevTools()
  109. {
  110. this.AttachDevTools();
  111. }
  112. public void LoadGameList()
  113. {
  114. if (_isLoading)
  115. {
  116. return;
  117. }
  118. _isLoading = true;
  119. ViewModel.LoadApplications();
  120. _isLoading = false;
  121. }
  122. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  123. {
  124. if (ViewModel.ShowMenuAndStatusBar && !ViewModel.ShowLoadProgress)
  125. {
  126. Dispatcher.UIThread.InvokeAsync(() =>
  127. {
  128. if (args.VSyncEnabled)
  129. {
  130. ViewModel.VsyncColor = new SolidColorBrush(Color.Parse("#ff2eeac9"));
  131. }
  132. else
  133. {
  134. ViewModel.VsyncColor = new SolidColorBrush(Color.Parse("#ffff4554"));
  135. }
  136. ViewModel.DockedStatusText = args.DockedMode;
  137. ViewModel.AspectRatioStatusText = args.AspectRatio;
  138. ViewModel.GameStatusText = args.GameStatus;
  139. ViewModel.FifoStatusText = args.FifoStatus;
  140. ViewModel.GpuStatusText = args.GpuName;
  141. ViewModel.ShowStatusSeparator = true;
  142. });
  143. }
  144. }
  145. public void Application_Opened(object sender, ApplicationOpenedEventArgs args)
  146. {
  147. if (args.Application != null)
  148. {
  149. ViewModel.SelectedIcon = args.Application.Icon;
  150. string path = new FileInfo(args.Application.Path).FullName;
  151. LoadApplication(path);
  152. }
  153. args.Handled = true;
  154. }
  155. public async Task PerformanceCheck()
  156. {
  157. if (ConfigurationState.Instance.Logger.EnableTrace.Value)
  158. {
  159. string mainMessage = LocaleManager.Instance["DialogPerformanceCheckLoggingEnabledMessage"];
  160. string secondaryMessage = LocaleManager.Instance["DialogPerformanceCheckLoggingEnabledConfirmMessage"];
  161. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(this, mainMessage, secondaryMessage, LocaleManager.Instance["InputDialogYes"], LocaleManager.Instance["InputDialogNo"], LocaleManager.Instance["RyujinxConfirm"]);
  162. if (result != UserResult.Yes)
  163. {
  164. ConfigurationState.Instance.Logger.EnableTrace.Value = false;
  165. SaveConfig();
  166. }
  167. }
  168. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  169. {
  170. string mainMessage = LocaleManager.Instance["DialogPerformanceCheckShaderDumpEnabledMessage"];
  171. string secondaryMessage = LocaleManager.Instance["DialogPerformanceCheckShaderDumpEnabledConfirmMessage"];
  172. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(this, mainMessage, secondaryMessage, LocaleManager.Instance["InputDialogYes"], LocaleManager.Instance["InputDialogNo"], LocaleManager.Instance["RyujinxConfirm"]);
  173. if (result != UserResult.Yes)
  174. {
  175. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  176. SaveConfig();
  177. }
  178. }
  179. }
  180. internal static void DeferLoadApplication(string launchPathArg, bool startFullscreenArg)
  181. {
  182. _deferLoad = true;
  183. _launchPath = launchPathArg;
  184. _startFullscreen = startFullscreenArg;
  185. }
  186. #pragma warning disable CS1998
  187. public async void LoadApplication(string path, bool startFullscreen = false, string titleName = "")
  188. #pragma warning restore CS1998
  189. {
  190. if (AppHost != null)
  191. {
  192. await ContentDialogHelper.CreateInfoDialog(this,
  193. LocaleManager.Instance["DialogLoadAppGameAlreadyLoadedMessage"],
  194. LocaleManager.Instance["DialogLoadAppGameAlreadyLoadedSubMessage"],
  195. LocaleManager.Instance["InputDialogOk"],
  196. "",
  197. LocaleManager.Instance["RyujinxInfo"]);
  198. return;
  199. }
  200. #if RELEASE
  201. await PerformanceCheck();
  202. #endif
  203. Logger.RestartTime();
  204. if (ViewModel.SelectedIcon == null)
  205. {
  206. ViewModel.SelectedIcon = ApplicationLibrary.GetApplicationIcon(path);
  207. }
  208. PrepareLoadScreen();
  209. _mainViewContent = ContentFrame.Content as Control;
  210. GlRenderer = new RendererControl(3, 3, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  211. AppHost = new AppHost(GlRenderer, InputManager, path, VirtualFileSystem, ContentManager, AccountManager, _userChannelPersistence, this);
  212. if (!AppHost.LoadGuestApplication().Result)
  213. {
  214. AppHost.DisposeContext();
  215. return;
  216. }
  217. ViewModel.LoadHeading = string.IsNullOrWhiteSpace(titleName) ? string.Format(LocaleManager.Instance["LoadingHeading"], AppHost.Device.Application.TitleName) : titleName;
  218. ViewModel.TitleName = string.IsNullOrWhiteSpace(titleName) ? AppHost.Device.Application.TitleName : titleName;
  219. SwitchToGameControl(startFullscreen);
  220. _currentEmulatedGamePath = path;
  221. Thread gameThread = new Thread(InitializeGame)
  222. {
  223. Name = "GUI.WindowThread"
  224. };
  225. gameThread.Start();
  226. }
  227. private void InitializeGame()
  228. {
  229. GlRenderer.GlInitialized += GlRenderer_Created;
  230. AppHost.StatusUpdatedEvent += Update_StatusBar;
  231. AppHost.AppExit += AppHost_AppExit;
  232. _rendererWaitEvent.WaitOne();
  233. AppHost?.Start();
  234. AppHost.DisposeContext();
  235. }
  236. private void HandleRelaunch()
  237. {
  238. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  239. {
  240. _userChannelPersistence.ShouldRestart = false;
  241. Dispatcher.UIThread.Post(() =>
  242. {
  243. LoadApplication(_currentEmulatedGamePath);
  244. });
  245. }
  246. else
  247. {
  248. // otherwise, clear state.
  249. _userChannelPersistence = new UserChannelPersistence();
  250. _currentEmulatedGamePath = null;
  251. }
  252. }
  253. public void SwitchToGameControl(bool startFullscreen = false)
  254. {
  255. ViewModel.ShowContent = true;
  256. ViewModel.ShowLoadProgress = false;
  257. ViewModel.IsLoadingIndeterminate = false;
  258. Dispatcher.UIThread.InvokeAsync(() =>
  259. {
  260. ContentFrame.Content = GlRenderer;
  261. if (startFullscreen && WindowState != WindowState.FullScreen)
  262. {
  263. ViewModel.ToggleFullscreen();
  264. }
  265. GlRenderer.Focus();
  266. });
  267. }
  268. public void ShowLoading(bool startFullscreen = false)
  269. {
  270. ViewModel.ShowContent = false;
  271. ViewModel.ShowLoadProgress = true;
  272. ViewModel.IsLoadingIndeterminate = true;
  273. Dispatcher.UIThread.InvokeAsync(() =>
  274. {
  275. if (startFullscreen && WindowState != WindowState.FullScreen)
  276. {
  277. ViewModel.ToggleFullscreen();
  278. }
  279. });
  280. }
  281. private void GlRenderer_Created(object sender, EventArgs e)
  282. {
  283. ShowLoading();
  284. _rendererWaitEvent.Set();
  285. }
  286. private void AppHost_AppExit(object sender, EventArgs e)
  287. {
  288. if (_isClosing)
  289. {
  290. return;
  291. }
  292. ViewModel.IsGameRunning = false;
  293. Dispatcher.UIThread.InvokeAsync(() =>
  294. {
  295. if (ContentFrame.Content != _mainViewContent)
  296. {
  297. ContentFrame.Content = _mainViewContent;
  298. }
  299. ViewModel.ShowMenuAndStatusBar = true;
  300. ViewModel.ShowContent = true;
  301. ViewModel.ShowLoadProgress = false;
  302. ViewModel.IsLoadingIndeterminate = false;
  303. Cursor = Cursor.Default;
  304. AppHost = null;
  305. HandleRelaunch();
  306. });
  307. GlRenderer.GlInitialized -= GlRenderer_Created;
  308. GlRenderer = null;
  309. ViewModel.SelectedIcon = null;
  310. Dispatcher.UIThread.InvokeAsync(() =>
  311. {
  312. Title = $"Ryujinx {Program.Version}";
  313. });
  314. }
  315. public void Sort_Checked(object sender, RoutedEventArgs args)
  316. {
  317. if (sender is RadioButton button)
  318. {
  319. var sort = Enum.Parse<ApplicationSort>(button.Tag.ToString());
  320. ViewModel.Sort(sort);
  321. }
  322. }
  323. protected override void HandleWindowStateChanged(WindowState state)
  324. {
  325. WindowState = state;
  326. if (state != WindowState.Minimized)
  327. {
  328. Renderer.Start();
  329. }
  330. }
  331. public void Order_Checked(object sender, RoutedEventArgs args)
  332. {
  333. if (sender is RadioButton button)
  334. {
  335. var tag = button.Tag.ToString();
  336. ViewModel.Sort(tag != "Descending");
  337. }
  338. }
  339. private void Initialize()
  340. {
  341. _userChannelPersistence = new UserChannelPersistence();
  342. VirtualFileSystem = VirtualFileSystem.CreateInstance();
  343. LibHacHorizonManager = new LibHacHorizonManager();
  344. ContentManager = new ContentManager(VirtualFileSystem);
  345. LibHacHorizonManager.InitializeFsServer(VirtualFileSystem);
  346. LibHacHorizonManager.InitializeArpServer();
  347. LibHacHorizonManager.InitializeBcatServer();
  348. LibHacHorizonManager.InitializeSystemClients();
  349. ApplicationLibrary = new ApplicationLibrary(VirtualFileSystem);
  350. // Save data created before we supported extra data in directory save data will not work properly if
  351. // given empty extra data. Luckily some of that extra data can be created using the data from the
  352. // save data indexer, which should be enough to check access permissions for user saves.
  353. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  354. // Consider removing this at some point in the future when we don't need to worry about old saves.
  355. VirtualFileSystem.FixExtraData(LibHacHorizonManager.RyujinxClient);
  356. AccountManager = new AccountManager(LibHacHorizonManager.RyujinxClient, Program.CommandLineProfile);
  357. VirtualFileSystem.ReloadKeySet();
  358. ApplicationHelper.Initialize(VirtualFileSystem, AccountManager, LibHacHorizonManager.RyujinxClient, this);
  359. RefreshFirmwareStatus();
  360. }
  361. protected void CheckLaunchState()
  362. {
  363. if (ShowKeyErrorOnLoad)
  364. {
  365. ShowKeyErrorOnLoad = false;
  366. Dispatcher.UIThread.Post(async () => await
  367. UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys, this));
  368. }
  369. if (_deferLoad)
  370. {
  371. _deferLoad = false;
  372. LoadApplication(_launchPath, _startFullscreen);
  373. }
  374. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false, this))
  375. {
  376. Updater.BeginParse(this, false).ContinueWith(task =>
  377. {
  378. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  379. }, TaskContinuationOptions.OnlyOnFaulted);
  380. }
  381. }
  382. public void RefreshFirmwareStatus()
  383. {
  384. SystemVersion version = null;
  385. try
  386. {
  387. version = ContentManager.GetCurrentFirmwareVersion();
  388. }
  389. catch (Exception) { }
  390. bool hasApplet = false;
  391. if (version != null)
  392. {
  393. LocaleManager.Instance.UpdateDynamicValue("StatusBarSystemVersion",
  394. version.VersionString);
  395. hasApplet = version.Major > 3;
  396. }
  397. else
  398. {
  399. LocaleManager.Instance.UpdateDynamicValue("StatusBarSystemVersion", "0.0");
  400. }
  401. ViewModel.IsAppletMenuActive = hasApplet;
  402. }
  403. private void InitializeComponent()
  404. {
  405. AvaloniaXamlLoader.Load(this);
  406. ContentFrame = this.FindControl<ContentControl>("Content");
  407. GameList = this.FindControl<GameListView>("GameList");
  408. LoadStatus = this.FindControl<TextBlock>("LoadStatus");
  409. FirmwareStatus = this.FindControl<TextBlock>("FirmwareStatus");
  410. LoadProgressBar = this.FindControl<ProgressBar>("LoadProgressBar");
  411. SearchBox = this.FindControl<TextBox>("SearchBox");
  412. Menu = this.FindControl<Menu>("Menu");
  413. UpdateMenuItem = this.FindControl<MenuItem>("UpdateMenuItem");
  414. GameGrid = this.FindControl<GameGridView>("GameGrid");
  415. HiddenTextBox = this.FindControl<OffscreenTextBox>("HiddenTextBox");
  416. FullscreenHotKey = this.FindControl<HotKeyControl>("FullscreenHotKey");
  417. FullscreenHotKey2 = this.FindControl<HotKeyControl>("FullscreenHotKey2");
  418. DockToggleHotKey = this.FindControl<HotKeyControl>("DockToggleHotKey");
  419. ExitHotKey = this.FindControl<HotKeyControl>("ExitHotKey");
  420. VolumeStatus = this.FindControl<ToggleSplitButton>("VolumeStatus");
  421. ActionsMenuItem = this.FindControl<MenuItem>("ActionsMenuItem");
  422. VolumeStatus.Click += VolumeStatus_CheckedChanged;
  423. GameGrid.ApplicationOpened += Application_Opened;
  424. GameGrid.DataContext = ViewModel;
  425. GameList.ApplicationOpened += Application_Opened;
  426. GameList.DataContext = ViewModel;
  427. LoadHotKeys();
  428. }
  429. protected override void OnOpened(EventArgs e)
  430. {
  431. base.OnOpened(e);
  432. CheckLaunchState();
  433. }
  434. public static void UpdateGraphicsConfig()
  435. {
  436. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  437. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  438. GraphicsConfig.ResScale = resScale == -1 ? resScaleCustom : resScale;
  439. GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  440. GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  441. GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  442. }
  443. public void LoadHotKeys()
  444. {
  445. HotKeyManager.SetHotKey(FullscreenHotKey, new KeyGesture(Key.Enter, KeyModifiers.Alt));
  446. HotKeyManager.SetHotKey(FullscreenHotKey2, new KeyGesture(Key.F11));
  447. HotKeyManager.SetHotKey(DockToggleHotKey, new KeyGesture(Key.F9));
  448. HotKeyManager.SetHotKey(ExitHotKey, new KeyGesture(Key.Escape));
  449. }
  450. public static void SaveConfig()
  451. {
  452. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  453. }
  454. public void UpdateGameMetadata(string titleId)
  455. {
  456. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  457. {
  458. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  459. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  460. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  461. });
  462. }
  463. private void PrepareLoadScreen()
  464. {
  465. using MemoryStream stream = new MemoryStream(ViewModel.SelectedIcon);
  466. using var gameIconBmp = SixLabors.ImageSharp.Image.Load<Bgra32>(stream);
  467. var dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp).ToPixel<Bgra32>();
  468. const int ColorDivisor = 4;
  469. Color progressFgColor = Color.FromRgb(dominantColor.R, dominantColor.G, dominantColor.B);
  470. Color progressBgColor = Color.FromRgb(
  471. (byte)(dominantColor.R / ColorDivisor),
  472. (byte)(dominantColor.G / ColorDivisor),
  473. (byte)(dominantColor.B / ColorDivisor));
  474. ViewModel.ProgressBarForegroundColor = new SolidColorBrush(progressFgColor);
  475. ViewModel.ProgressBarBackgroundColor = new SolidColorBrush(progressBgColor);
  476. }
  477. private void SearchBox_OnKeyUp(object sender, KeyEventArgs e)
  478. {
  479. ViewModel.SearchText = SearchBox.Text;
  480. }
  481. private async void StopEmulation_Click(object sender, RoutedEventArgs e)
  482. {
  483. if (AppHost != null)
  484. {
  485. await AppHost.ShowExitPrompt();
  486. }
  487. }
  488. private async void PauseEmulation_Click(object sender, RoutedEventArgs e)
  489. {
  490. await Task.Run(() =>
  491. {
  492. AppHost?.Pause();
  493. });
  494. }
  495. private async void ResumeEmulation_Click(object sender, RoutedEventArgs e)
  496. {
  497. await Task.Run(() =>
  498. {
  499. AppHost?.Resume();
  500. });
  501. }
  502. private void ScanAmiiboMenuItem_AttachedToVisualTree(object sender, VisualTreeAttachmentEventArgs e)
  503. {
  504. if (sender is MenuItem)
  505. {
  506. ViewModel.IsAmiiboRequested = AppHost.Device.System.SearchingForAmiibo(out _);
  507. }
  508. }
  509. private void VsyncStatus_PointerReleased(object sender, PointerReleasedEventArgs e)
  510. {
  511. AppHost.Device.EnableDeviceVsync = !AppHost.Device.EnableDeviceVsync;
  512. Logger.Info?.Print(LogClass.Application, $"VSync toggled to: {AppHost.Device.EnableDeviceVsync}");
  513. }
  514. private void DockedStatus_PointerReleased(object sender, PointerReleasedEventArgs e)
  515. {
  516. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  517. }
  518. private void AspectRatioStatus_PointerReleased(object sender, PointerReleasedEventArgs e)
  519. {
  520. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  521. ConfigurationState.Instance.Graphics.AspectRatio.Value = (int)aspectRatio + 1 > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  522. }
  523. private void VolumeStatus_CheckedChanged(object sender, SplitButtonClickEventArgs e)
  524. {
  525. var volumeSplitButton = sender as ToggleSplitButton;
  526. if (ViewModel.IsGameRunning)
  527. {
  528. if (!volumeSplitButton.IsChecked)
  529. {
  530. AppHost.Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  531. }
  532. else
  533. {
  534. AppHost.Device.SetVolume(0);
  535. }
  536. ViewModel.Volume = AppHost.Device.GetVolume();
  537. }
  538. }
  539. protected override void OnClosing(CancelEventArgs e)
  540. {
  541. if (!_isClosing && AppHost != null && ConfigurationState.Instance.ShowConfirmExit)
  542. {
  543. e.Cancel = true;
  544. ConfirmExit();
  545. return;
  546. }
  547. _isClosing = true;
  548. if (AppHost != null)
  549. {
  550. AppHost.AppExit -= AppHost_AppExit;
  551. AppHost.AppExit += (sender, e) =>
  552. {
  553. AppHost = null;
  554. Dispatcher.UIThread.Post(Close);
  555. };
  556. AppHost?.Stop();
  557. e.Cancel = true;
  558. return;
  559. }
  560. ApplicationLibrary.CancelLoading();
  561. InputManager.Dispose();
  562. Program.Exit();
  563. base.OnClosing(e);
  564. }
  565. private void ConfirmExit()
  566. {
  567. Dispatcher.UIThread.InvokeAsync(async () =>
  568. {
  569. _isClosing = await ContentDialogHelper.CreateExitDialog(this);
  570. if (_isClosing)
  571. {
  572. Close();
  573. }
  574. });
  575. }
  576. }
  577. }