MainWindow.axaml.cs 23 KB

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