From c1973023d072f54c0cabb74d655ec426098e20ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Kaan=20K=C3=B6se?= Date: Fri, 23 Aug 2024 03:00:22 +0200 Subject: [PATCH] Fix for webview2 not focusing properly issue. --- Wino.Mail/Views/ComposePage.xaml.cs | 32 +++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/Wino.Mail/Views/ComposePage.xaml.cs b/Wino.Mail/Views/ComposePage.xaml.cs index 0e5d591b..5b3338a0 100644 --- a/Wino.Mail/Views/ComposePage.xaml.cs +++ b/Wino.Mail/Views/ComposePage.xaml.cs @@ -21,6 +21,7 @@ using Windows.Storage.Pickers; using Windows.UI.ViewManagement.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using Wino.Core.Domain; @@ -62,6 +63,19 @@ namespace Wino.Views Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--enable-features=OverlayScrollbar,msOverlayScrollbarWinStyle,msOverlayScrollbarWinStyleAnimation"); } + private async void GlobalFocusManagerGotFocus(object sender, FocusManagerGotFocusEventArgs e) + { + // In order to delegate cursor to the inner editor for WebView2. + // When the control got focus, we invoke script to focus the editor. + // This is not done on the WebView2 handlers, because somehow it is + // repeatedly focusing itself, even though when it has the focus already. + + if (e.NewFocusedElement == Chromium) + { + await FocusEditorAsync(false); + } + } + private static async void OnIsComposerDarkModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { if (obj is ComposePage page) @@ -356,19 +370,26 @@ namespace Wino.Views await InvokeScriptSafeAsync("imageInput.click();"); } - private async Task FocusEditorAsync() + /// + /// Places the cursor in the composer. + /// + /// Whether control itself should be focused as well or not. + private async Task FocusEditorAsync(bool focusControlAsWell) { await InvokeScriptSafeAsync("editor.selection.focus();"); - Chromium.Focus(FocusState.Keyboard); - Chromium.Focus(FocusState.Programmatic); + if (focusControlAsWell) + { + Chromium.Focus(FocusState.Keyboard); + Chromium.Focus(FocusState.Programmatic); + } } private async void EmojiButtonClicked(object sender, RoutedEventArgs e) { CoreInputView.GetForCurrentView().TryShow(CoreInputViewKind.Emoji); - await FocusEditorAsync(); + await FocusEditorAsync(focusControlAsWell: true); } public async Task UpdateEditorThemeAsync() @@ -440,6 +461,8 @@ namespace Wino.Views { base.OnNavigatedTo(e); + FocusManager.GotFocus += GlobalFocusManagerGotFocus; + var anim = ConnectedAnimationService.GetForCurrentView().GetAnimation("WebViewConnectedAnimation"); anim?.TryStart(Chromium); @@ -694,6 +717,7 @@ namespace Wino.Views { base.OnNavigatingFrom(e); + FocusManager.GotFocus -= GlobalFocusManagerGotFocus; await ViewModel.UpdateMimeChangesAsync(); DisposeDisposables();