MainWindow.axaml.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. CanUpdate = false;
  216. ViewModel.LoadHeading = string.IsNullOrWhiteSpace(titleName) ? string.Format(LocaleManager.Instance["LoadingHeading"], AppHost.Device.Application.TitleName) : titleName;
  217. ViewModel.TitleName = string.IsNullOrWhiteSpace(titleName) ? AppHost.Device.Application.TitleName : titleName;
  218. SwitchToGameControl(startFullscreen);
  219. _currentEmulatedGamePath = path;
  220. Thread gameThread = new(InitializeGame)
  221. {
  222. Name = "GUI.WindowThread"
  223. };
  224. gameThread.Start();
  225. });
  226. }
  227. private void InitializeGame()
  228. {
  229. RendererControl.RendererInitialized += 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.ShowLoadProgress = false;
  256. ViewModel.ShowContent = true;
  257. ViewModel.IsLoadingIndeterminate = false;
  258. Dispatcher.UIThread.InvokeAsync(() =>
  259. {
  260. MainContent.Content = RendererControl;
  261. if (startFullscreen && WindowState != WindowState.FullScreen)
  262. {
  263. ViewModel.ToggleFullscreen();
  264. }
  265. RendererControl.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. ViewModel.ShowMenuAndStatusBar = true;
  296. ViewModel.ShowContent = true;
  297. ViewModel.ShowLoadProgress = false;
  298. ViewModel.IsLoadingIndeterminate = false;
  299. CanUpdate = true;
  300. Cursor = Cursor.Default;
  301. if (MainContent.Content != _mainViewContent)
  302. {
  303. MainContent.Content = _mainViewContent;
  304. }
  305. AppHost = null;
  306. HandleRelaunch();
  307. });
  308. RendererControl.RendererInitialized -= GlRenderer_Created;
  309. RendererControl = null;
  310. ViewModel.SelectedIcon = null;
  311. Dispatcher.UIThread.InvokeAsync(() =>
  312. {
  313. Title = $"Ryujinx {Program.Version}";
  314. });
  315. }
  316. public void Sort_Checked(object sender, RoutedEventArgs args)
  317. {
  318. if (sender is RadioButton button)
  319. {
  320. var sort = Enum.Parse<ApplicationSort>(button.Tag.ToString());
  321. ViewModel.Sort(sort);
  322. }
  323. }
  324. protected override void HandleWindowStateChanged(WindowState state)
  325. {
  326. WindowState = state;
  327. if (state != WindowState.Minimized)
  328. {
  329. Renderer.Start();
  330. }
  331. }
  332. public void Order_Checked(object sender, RoutedEventArgs args)
  333. {
  334. if (sender is RadioButton button)
  335. {
  336. var tag = button.Tag.ToString();
  337. ViewModel.Sort(tag != "Descending");
  338. }
  339. }
  340. private void Initialize()
  341. {
  342. _userChannelPersistence = new UserChannelPersistence();
  343. VirtualFileSystem = VirtualFileSystem.CreateInstance();
  344. LibHacHorizonManager = new LibHacHorizonManager();
  345. ContentManager = new ContentManager(VirtualFileSystem);
  346. LibHacHorizonManager.InitializeFsServer(VirtualFileSystem);
  347. LibHacHorizonManager.InitializeArpServer();
  348. LibHacHorizonManager.InitializeBcatServer();
  349. LibHacHorizonManager.InitializeSystemClients();
  350. ApplicationLibrary = new ApplicationLibrary(VirtualFileSystem);
  351. // Save data created before we supported extra data in directory save data will not work properly if
  352. // given empty extra data. Luckily some of that extra data can be created using the data from the
  353. // save data indexer, which should be enough to check access permissions for user saves.
  354. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  355. // Consider removing this at some point in the future when we don't need to worry about old saves.
  356. VirtualFileSystem.FixExtraData(LibHacHorizonManager.RyujinxClient);
  357. AccountManager = new AccountManager(LibHacHorizonManager.RyujinxClient, CommandLineState.Profile);
  358. VirtualFileSystem.ReloadKeySet();
  359. ApplicationHelper.Initialize(VirtualFileSystem, AccountManager, LibHacHorizonManager.RyujinxClient, this);
  360. RefreshFirmwareStatus();
  361. }
  362. protected void CheckLaunchState()
  363. {
  364. if (ShowKeyErrorOnLoad)
  365. {
  366. ShowKeyErrorOnLoad = false;
  367. Dispatcher.UIThread.Post(async () => await
  368. UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys, this));
  369. }
  370. if (_deferLoad)
  371. {
  372. _deferLoad = false;
  373. LoadApplication(_launchPath, _startFullscreen);
  374. }
  375. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false, this))
  376. {
  377. Updater.BeginParse(this, false).ContinueWith(task =>
  378. {
  379. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  380. }, TaskContinuationOptions.OnlyOnFaulted);
  381. }
  382. }
  383. public void RefreshFirmwareStatus()
  384. {
  385. SystemVersion version = null;
  386. try
  387. {
  388. version = ContentManager.GetCurrentFirmwareVersion();
  389. }
  390. catch (Exception) { }
  391. bool hasApplet = false;
  392. if (version != null)
  393. {
  394. LocaleManager.Instance.UpdateDynamicValue("StatusBarSystemVersion",
  395. version.VersionString);
  396. hasApplet = version.Major > 3;
  397. }
  398. else
  399. {
  400. LocaleManager.Instance.UpdateDynamicValue("StatusBarSystemVersion", "0.0");
  401. }
  402. ViewModel.IsAppletMenuActive = hasApplet;
  403. }
  404. private void Load()
  405. {
  406. VolumeStatus.Click += VolumeStatus_CheckedChanged;
  407. GameGrid.ApplicationOpened += Application_Opened;
  408. GameGrid.DataContext = ViewModel;
  409. GameList.ApplicationOpened += Application_Opened;
  410. GameList.DataContext = ViewModel;
  411. LoadHotKeys();
  412. }
  413. protected override void OnOpened(EventArgs e)
  414. {
  415. base.OnOpened(e);
  416. CheckLaunchState();
  417. }
  418. public static void UpdateGraphicsConfig()
  419. {
  420. GraphicsConfig.ResScale = ConfigurationState.Instance.Graphics.ResScale == -1 ? ConfigurationState.Instance.Graphics.ResScaleCustom : ConfigurationState.Instance.Graphics.ResScale;
  421. GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  422. GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  423. GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  424. GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression;
  425. GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE;
  426. }
  427. public void LoadHotKeys()
  428. {
  429. HotKeyManager.SetHotKey(FullscreenHotKey, new KeyGesture(Key.Enter, KeyModifiers.Alt));
  430. HotKeyManager.SetHotKey(FullscreenHotKey2, new KeyGesture(Key.F11));
  431. HotKeyManager.SetHotKey(DockToggleHotKey, new KeyGesture(Key.F9));
  432. HotKeyManager.SetHotKey(ExitHotKey, new KeyGesture(Key.Escape));
  433. }
  434. public static void SaveConfig()
  435. {
  436. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  437. }
  438. public void UpdateGameMetadata(string titleId)
  439. {
  440. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  441. {
  442. if (DateTime.TryParse(appMetadata.LastPlayed, out DateTime lastPlayedDateTime))
  443. {
  444. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  445. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  446. }
  447. });
  448. }
  449. private void PrepareLoadScreen()
  450. {
  451. using MemoryStream stream = new MemoryStream(ViewModel.SelectedIcon);
  452. using var gameIconBmp = SixLabors.ImageSharp.Image.Load<Bgra32>(stream);
  453. var dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp).ToPixel<Bgra32>();
  454. const int ColorDivisor = 4;
  455. Color progressFgColor = Color.FromRgb(dominantColor.R, dominantColor.G, dominantColor.B);
  456. Color progressBgColor = Color.FromRgb(
  457. (byte)(dominantColor.R / ColorDivisor),
  458. (byte)(dominantColor.G / ColorDivisor),
  459. (byte)(dominantColor.B / ColorDivisor));
  460. ViewModel.ProgressBarForegroundColor = new SolidColorBrush(progressFgColor);
  461. ViewModel.ProgressBarBackgroundColor = new SolidColorBrush(progressBgColor);
  462. }
  463. private void SearchBox_OnKeyUp(object sender, KeyEventArgs e)
  464. {
  465. ViewModel.SearchText = SearchBox.Text;
  466. }
  467. private async void StopEmulation_Click(object sender, RoutedEventArgs e)
  468. {
  469. if (AppHost != null)
  470. {
  471. await AppHost.ShowExitPrompt();
  472. }
  473. }
  474. private async void PauseEmulation_Click(object sender, RoutedEventArgs e)
  475. {
  476. await Task.Run(() =>
  477. {
  478. AppHost?.Pause();
  479. });
  480. }
  481. private async void ResumeEmulation_Click(object sender, RoutedEventArgs e)
  482. {
  483. await Task.Run(() =>
  484. {
  485. AppHost?.Resume();
  486. });
  487. }
  488. private void ScanAmiiboMenuItem_AttachedToVisualTree(object sender, VisualTreeAttachmentEventArgs e)
  489. {
  490. if (sender is MenuItem)
  491. {
  492. ViewModel.IsAmiiboRequested = AppHost.Device.System.SearchingForAmiibo(out _);
  493. }
  494. }
  495. private void VsyncStatus_PointerReleased(object sender, PointerReleasedEventArgs e)
  496. {
  497. AppHost.Device.EnableDeviceVsync = !AppHost.Device.EnableDeviceVsync;
  498. Logger.Info?.Print(LogClass.Application, $"VSync toggled to: {AppHost.Device.EnableDeviceVsync}");
  499. }
  500. private void DockedStatus_PointerReleased(object sender, PointerReleasedEventArgs e)
  501. {
  502. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  503. }
  504. private void AspectRatioStatus_PointerReleased(object sender, PointerReleasedEventArgs e)
  505. {
  506. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  507. ConfigurationState.Instance.Graphics.AspectRatio.Value = (int)aspectRatio + 1 > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  508. }
  509. private void VolumeStatus_CheckedChanged(object sender, SplitButtonClickEventArgs e)
  510. {
  511. var volumeSplitButton = sender as ToggleSplitButton;
  512. if (ViewModel.IsGameRunning)
  513. {
  514. if (!volumeSplitButton.IsChecked)
  515. {
  516. AppHost.Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  517. }
  518. else
  519. {
  520. AppHost.Device.SetVolume(0);
  521. }
  522. ViewModel.Volume = AppHost.Device.GetVolume();
  523. }
  524. }
  525. protected override void OnClosing(CancelEventArgs e)
  526. {
  527. if (!_isClosing && AppHost != null && ConfigurationState.Instance.ShowConfirmExit)
  528. {
  529. e.Cancel = true;
  530. ConfirmExit();
  531. return;
  532. }
  533. _isClosing = true;
  534. if (AppHost != null)
  535. {
  536. AppHost.AppExit -= AppHost_AppExit;
  537. AppHost.AppExit += (sender, e) =>
  538. {
  539. AppHost = null;
  540. Dispatcher.UIThread.Post(() =>
  541. {
  542. MainContent = null;
  543. Close();
  544. });
  545. };
  546. AppHost?.Stop();
  547. e.Cancel = true;
  548. return;
  549. }
  550. ApplicationLibrary.CancelLoading();
  551. InputManager.Dispose();
  552. Program.Exit();
  553. base.OnClosing(e);
  554. }
  555. private void ConfirmExit()
  556. {
  557. Dispatcher.UIThread.InvokeAsync(async () =>
  558. {
  559. _isClosing = await ContentDialogHelper.CreateExitDialog();
  560. if (_isClosing)
  561. {
  562. Close();
  563. }
  564. });
  565. }
  566. }
  567. }