MainWindow.axaml.cs 24 KB

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