MainWindow.axaml.cs 24 KB

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