MainWindow.axaml.cs 23 KB

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