MainWindow.axaml.cs 24 KB

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