Repository navigation
Expand file tree
/
Copy pathWebView2.cpp
More file actions
2735 lines (2377 loc) · 104 KB
/
Copy pathWebView2.cpp
File metadata and controls
2735 lines (2377 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include "common.h"
#include <wil/cppwinrt_helpers.h> // For wil::resume_foreground (marshals coroutine continuation to the UI DispatcherQueue)
#include <corewindow.h>
#include "InvokableCallbackHelper.h"
#include "winrt\Microsoft.UI.Input.DragDrop.h"
#include "shobjidl_core.h"
#include "math.h"
#include "Microsoft.UI.Xaml.xamlroot.h"
#include "ResourceAccessor.h"
#include "RuntimeProfiler.h"
#include "UIAutomationCore.h"
#include "UIAutomationCoreApi.h"
#include "WebView2.h"
#include "WebView2AutomationPeer.h"
#include <WebView2Interop.h>
#include "WebView2Utility.h"
#include "Windows.Globalization.h"
#include <wrl\event.h>
#include "MuxcTraceLogging.h"
#include <shellapi.h> // For DragQueryFile, CF_HDROP
#include <appmodel.h>
using namespace Microsoft::WRL;
static constexpr wstring_view s_error_wv2_closed{ L"Cannot create CoreWebView2 for Closed WebView2 element."sv };
static constexpr wstring_view s_error_cwv2_not_present{ L"Failed because a valid CoreWebView2 is not present. Make sure one was created, for example by calling EnsureCoreWebView2Async() API."sv };
// Drag content type flags - each bit represents a clipboard format present in the data object.
// Multiple bits can be set when the data object contains multiple formats.
static constexpr DWORD DRAG_CONTENT_NONE = 0x0000;
static constexpr DWORD DRAG_CONTENT_FILES = 0x0001; // CF_HDROP
static constexpr DWORD DRAG_CONTENT_HTML = 0x0002; // "HTML Format"
static constexpr DWORD DRAG_CONTENT_URL = 0x0004; // "UniformResourceLocatorW"
static constexpr DWORD DRAG_CONTENT_TEXT = 0x0008; // CF_UNICODETEXT
static constexpr DWORD DRAG_CONTENT_BITMAP = 0x0010; // CF_BITMAP
static constexpr DWORD DRAG_CONTENT_IMAGE = 0x0020; // CF_DIB
// White matches CoreWebView2Controller.DefaultBackgroundColor
const winrt::Color WebView2::sc_controllerDefaultBackgroundColor{ 255, 255, 255, 255 };
// When the Xaml window is closed (eg by user clicking 'x'), CoreWebView2
// (associated with child "Input HWND") is notified ahead of Xaml WebView2
// resulting in a window of time when calls into the CoreWebView2 APIs
// fail with ERROR_INVALID_STATE. The helper functions below are available
// to detect and gracefully handle this situation.
// Checks CoreWebView2Controller status, use at start of simple/short functions
bool WebView2::CoreWebView2HasInvalidState()
{
if (m_coreWebViewController)
{
try { bool isVisible = m_coreWebViewController.IsVisible(); }
catch (winrt::hresult_error e)
{
if (e.code().value == HRESULT_FROM_WIN32(ERROR_INVALID_STATE))
{
return true;
}
}
}
return false;
}
// Wraps calls to Core Objects and swallows ERROR_INVALID_STATE, use around synchronous CWV2 API calls made frequently
// (Note: for async CWV2 calls needing the check, use below code directly for simplicity)
template <typename Delegate>
void WebView2::CoreWebView2RunIgnoreInvalidStateSync(Delegate delegate)
{
try
{
delegate();
}
catch (winrt::hresult_error e)
{
if (e.code().value != HRESULT_FROM_WIN32(ERROR_INVALID_STATE))
{
throw;
}
}
}
WebView2::WebView2()
{
__RP_Marker_ClassById(RuntimeProfiler::ProfId_WebView2);
m_loadedRevoker = Loaded(winrt::auto_revoke, { this, &WebView2::OnLoaded });
m_unloadedRevoker = Unloaded(winrt::auto_revoke, { this, &WebView2::OnUnloaded });
// Turn off DirectManipulation for this element so that all scrolling and gesture
// inside the WebView element will be handled by Anaheim.
this->ManipulationMode(winrt::ManipulationModes::None);
// Set the default FlowDirection to LeftToRight to prevent page inversion
// when parent element's FlowDirection is RightToLeft
this->FlowDirection(winrt::FlowDirection::LeftToRight);
// TODO_WebView2: These can be deferred to CreateCoreObjects
m_manipulationModeChangedToken.value = RegisterPropertyChangedCallback(winrt::UIElement::ManipulationModeProperty(),
{ this, &WebView2::OnManipulationModePropertyChanged });
m_visibilityChangedToken.value = RegisterPropertyChangedCallback(winrt::UIElement::VisibilityProperty(),
{ this, &WebView2::OnVisibilityPropertyChanged });
OnVisibilityPropertyChanged(nullptr, nullptr);
// IsTabStop is false by default for UIElement
IsTabStop(true);
// Set the background for WebView2 to ensure it will be visible to hit-testing.
Background(winrt::SolidColorBrush(winrt::Colors::Transparent()));
}
void WebView2::OnManipulationModePropertyChanged(const winrt::DependencyObject& /*sender*/, const winrt::DependencyProperty& /*args*/)
{
MUX_FAIL_FAST_MSG("WebView2.ManipulationMode cannot be set to anything other than \"None\".");
}
void WebView2::OnVisibilityPropertyChanged(const winrt::DependencyObject& /*sender*/, const winrt::DependencyProperty& /*args*/)
{
UpdateRenderedSubscriptionAndVisibility();
}
// Public Close() API
void WebView2::Close()
{
CloseInternal(false /* inShutdownPath */);
}
// Close Implementation (notice this does not implement IClosable). Also called implicitly as part of destruction.
void WebView2::CloseInternal(bool inShutdownPath)
{
DisconnectFromRootVisualTarget();
UnregisterCoreEventHandlers();
m_xamlRootChangedRevoker.revoke();
m_renderedRevoker.revoke();
if (m_tempHostHwnd && !winrt::CoreWindow::GetForCurrentThread())
{
DestroyWindow(m_tempHostHwnd);
m_tempHostHwnd = nullptr;
}
if (m_manipulationModeChangedToken.value != 0)
{
UnregisterPropertyChangedCallback(winrt::UIElement::ManipulationModeProperty(), m_manipulationModeChangedToken.value);
m_manipulationModeChangedToken.value = 0;
}
if (m_visibilityChangedToken.value != 0)
{
UnregisterPropertyChangedCallback(winrt::UIElement::VisibilityProperty(), m_visibilityChangedToken.value);
m_visibilityChangedToken.value = 0;
}
if (m_coreWebView)
{
m_coreWebView = nullptr;
}
if (m_coreWebViewController)
{
m_coreWebViewController.Close();
m_coreWebViewController = nullptr;
}
if (m_coreWebViewCompositionController)
{
m_coreWebViewCompositionController = nullptr;
}
UnregisterXamlEventHandlers();
// If called from destructor, skip ResetProperties() as property values no longer matter.
// (Otherwise, Xaml Core will assert on failure to resurrect WV2's DXaml Peer)
if (!inShutdownPath)
{
ResetProperties();
}
m_isClosed = true;
}
WebView2::~WebView2()
{
CloseInternal(true /* inShutdownPath */);
}
void WebView2::OnPropertyChanged(winrt::DependencyPropertyChangedEventArgs const& args)
{
winrt::IDependencyProperty property = args.Property();
if (property == s_SourceProperty)
{
const auto newValueUri = unbox_value<winrt::Uri>(args.NewValue());
if (ShouldNavigate(newValueUri))
{
if (!m_isClosed)
{
OnSourceChanged(newValueUri);
}
else
{
throw winrt::hresult_error(RO_E_CLOSED, s_error_wv2_closed);
}
}
}
else if ((property == s_CanGoBackProperty || property == s_CanGoForwardProperty) && !m_canGoPropSetInternally)
{
throw winrt::hresult_invalid_argument();
}
else if (property == s_DefaultBackgroundColorProperty)
{
SetControllerDefaultBackgroundColor();
}
}
void WebView2::HandlePointerPressed(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
// Chromium handles WM_MOUSEXXX for mouse, WM_POINTERXXX for touch
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
winrt::Microsoft::UI::Input::PointerPoint pointerPoint{ args.GetCurrentPoint(*this) };
UINT message = 0x0;
if (deviceType == winrt::PointerDeviceType::Mouse)
{
// WebView takes mouse capture to avoid missing pointer released events that occur outside of the element that
// end pointer pressed state inside the webview. Example, scrollbar is being used and mouse is moved out
// of webview bounds before being released, the webview will miss the released event and upon reentry into
// the webview, the mouse will still cause the scrollbar to move as if selected.
m_hasMouseCapture = this->CapturePointer(args.Pointer());
winrt::PointerPointProperties properties{ pointerPoint.Properties() };
if (properties.IsLeftButtonPressed())
{
// Double Click is working as well with this code, presumably by being recognized on browser side from WM_LBUTTONDOWN/ WM_LBUTTONUP
message = WM_LBUTTONDOWN;
m_isLeftMouseButtonPressed = true;
}
else if (properties.IsMiddleButtonPressed())
{
message = WM_MBUTTONDOWN;
m_isMiddleMouseButtonPressed = true;
}
else if (properties.IsRightButtonPressed())
{
message = WM_RBUTTONDOWN;
m_isRightMouseButtonPressed = true;
}
else if (properties.IsXButton1Pressed())
{
message = WM_XBUTTONDOWN;
m_isXButton1Pressed = true;
}
else if (properties.IsXButton2Pressed())
{
message = WM_XBUTTONDOWN;
m_isXButton2Pressed = true;
}
else
{
MUX_ASSERT(false);
}
}
else if (deviceType == winrt::PointerDeviceType::Touch)
{
message = WM_POINTERDOWN;
int32_t id = pointerPoint.PointerId();
m_hasTouchCapture.insert(std::pair<int32_t, bool>(id, this->CapturePointer(args.Pointer())));
}
else if (deviceType == winrt::PointerDeviceType::Pen)
{
message = WM_POINTERDOWN;
m_hasPenCapture = this->CapturePointer(args.Pointer());
}
// Since OnXamlPointerMessage() will mark the args handled, Xaml FocusManager will ignore
// this Pressed event when it bubbles up to the XamlRoot, not setting focus as expected.
// Thus, we need to manually set Xaml Focus (Pointer) on WebView2 here.
// TODO_WebView2: Update this to UIElement::Focus [sync version], when it becomes available.
if (IsTabStop() == true)
{
winrt::FocusManager::TryFocusAsync(*this, winrt::FocusState::Pointer);
}
OnXamlPointerMessage(message, args);
}
void WebView2::HandlePointerReleased(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
// Chromium handles WM_MOUSEXXX for mouse, WM_POINTERXXX for touch
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
winrt::PointerPoint pointerPoint{ args.GetCurrentPoint(*this) };
winrt::PointerPointProperties properties{ pointerPoint.Properties() };
UINT message = 0x0;
// Get pointer id for handling multi-touch capture
int32_t id = pointerPoint.PointerId();
if (deviceType == winrt::PointerDeviceType::Mouse)
{
if (m_isLeftMouseButtonPressed)
{
message = WM_LBUTTONUP;
m_isLeftMouseButtonPressed = false;
}
else if (m_isMiddleMouseButtonPressed)
{
message = WM_MBUTTONUP;
m_isMiddleMouseButtonPressed = false;
}
else if (m_isRightMouseButtonPressed)
{
message = WM_RBUTTONUP;
m_isRightMouseButtonPressed = false;
}
else if (m_isXButton1Pressed)
{
message = WM_XBUTTONUP;
m_isXButton1Pressed = false;
}
else if (m_isXButton2Pressed)
{
message = WM_XBUTTONUP;
m_isXButton2Pressed = false;
}
else
{
// It is not guaranteed that we will get a PointerPressed before PointerReleased.
// For example, the mouse can be pressed in the space next to a webview, dragged
// into the webview, and then released. This is a valid case and should not crash.
// Because we can't always know what button was pressed before a release, we can't
// forward this message on to CoreWebView2.
return;
}
if (m_hasMouseCapture)
{
this->ReleasePointerCapture(args.Pointer());
m_hasMouseCapture = false;
}
}
else
{
if (m_hasTouchCapture.count(id) > 0)
{
this->ReleasePointerCapture(args.Pointer());
m_hasTouchCapture.erase(id);
}
if (m_hasPenCapture)
{
this->ReleasePointerCapture(args.Pointer());
m_hasPenCapture = false;
}
message = WM_POINTERUP;
}
OnXamlPointerMessage(message, args);
}
void WebView2::HandlePointerMoved(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
// Capture pointer point to be used in StartAsync later
m_lastPointerPoint = args.GetCurrentPoint(*this);
// Chromium handles WM_MOUSEXXX for mouse, WM_POINTERXXX for touch
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
UINT message = deviceType == winrt::PointerDeviceType::Mouse ? WM_MOUSEMOVE : WM_POINTERUPDATE;
OnXamlPointerMessage(message, args);
}
void WebView2::HandlePointerWheelChanged(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
// Chromium handles WM_MOUSEXXX for mouse, WM_POINTERXXX for touch
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
winrt::PointerPoint pointerPoint{ args.GetCurrentPoint(*this) };
winrt::PointerPointProperties properties{ pointerPoint.Properties() };
UINT message;
if (deviceType == winrt::PointerDeviceType::Mouse)
{
message = properties.IsHorizontalMouseWheel() ? WM_MOUSEHWHEEL : WM_MOUSEWHEEL;
}
else
{
message = WM_POINTERWHEEL;
}
OnXamlPointerMessage(message, args);
}
void WebView2::HandlePointerExited(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
UINT message;
if (deviceType == winrt::PointerDeviceType::Mouse)
{
if (m_hasMouseCapture)
{
// WM_MOUSELEAVE should not fire while we have capture, since doing so
// will cancel capture in the WebView.
m_isMouseLeaveNeeded = true;
return;
}
message = WM_MOUSELEAVE;
ResetMouseInputState();
}
else
{
message = WM_POINTERLEAVE;
}
OnXamlPointerMessage(message, args);
}
void WebView2::HandlePointerEntered(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
if (deviceType != winrt::PointerDeviceType::Mouse) //mouse does not have an equivalent pointer_entered event, so only handling pen/touch
{
OnXamlPointerMessage(WM_POINTERENTER, args);
}
else
{
MUX_ASSERT(deviceType == winrt::PointerDeviceType::Mouse);
// If there was a queued MouseLeave, clear it now that the mouse has re-entered.
m_isMouseLeaveNeeded = false;
}
}
void WebView2::HandlePointerCanceled(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
ResetPointerHelper(args);
}
void WebView2::HandlePointerCaptureLost(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args)
{
ResetPointerHelper(args);
}
void WebView2::ResetPointerHelper(const winrt::PointerRoutedEventArgs& args)
{
winrt::PointerDeviceType deviceType{ args.Pointer().PointerDeviceType() };
if (deviceType == winrt::PointerDeviceType::Mouse)
{
m_hasMouseCapture = false;
ResetMouseInputState();
if (m_isMouseLeaveNeeded)
{
m_isMouseLeaveNeeded = false;
SendMouseLeave();
}
}
else if (deviceType == winrt::PointerDeviceType::Touch)
{
// Get pointer id for handling multi-touch capture
winrt::Microsoft::UI::Input::PointerPoint logicalPointerPoint{ args.GetCurrentPoint(*this) };
int32_t id = logicalPointerPoint.PointerId();
if (m_hasTouchCapture.count(id) > 0)
{
m_hasTouchCapture.erase(id);
}
}
else if (deviceType == winrt::PointerDeviceType::Pen)
{
m_hasPenCapture = false;
}
}
void WebView2::SendMouseLeave()
{
if (!m_coreWebView || !m_coreWebViewCompositionController || CoreWebView2HasInvalidState())
{
// nothing to forward input to
return;
}
m_coreWebViewCompositionController.SendMouseInput(
winrt::CoreWebView2MouseEventKind{ static_cast<winrt::CoreWebView2MouseEventKind>(WM_MOUSELEAVE) },
winrt::CoreWebView2MouseEventVirtualKeys{ static_cast<winrt::CoreWebView2MouseEventVirtualKeys>(0) },
0,
winrt::Point{ 0, 0 });
}
bool WebView2::ShouldNavigate(const winrt::Uri& uri)
{
return uri != nullptr && uri.RawUri() != m_stopNavigateOnUriChanged;
}
winrt::IAsyncAction WebView2::OnSourceChanged(winrt::Uri providedUri)
{
auto strongThis = get_strong(); // ensure object lifetime during coroutines
// Trigger / wait for CWV2 creation if one isn't yet ready
if (!m_coreWebView)
{
// Creation request when one is already in flight (either explicit or implicit)
if (m_creationInProgressAsync)
{
MUX_ASSERT(m_isExplicitCreationInProgress || m_isImplicitCreationInProgress);
// If the in-flight creation is explicit (EnsureCWV2*Async()), navigate to new source when that ends
// Otherwise it's implicit (another Source set), we are done; first Source will use updated Source value
if (m_isExplicitCreationInProgress)
{
// Capture the DispatcherQueue now, while we are guaranteed to be on the UI thread
// (before any suspension). After a co_await we may resume on a background thread, where
// reading DispatcherQueue() could race with core/thread shutdown and return null, which
// would AV inside wil::resume_foreground.
auto dispatcherQueue = DispatcherQueue();
// If EnsureCWV2*Async() call is in flight, wait for it to complete then set Source
co_await *m_creationInProgressAsync;
// The await above may resume on a background thread (e.g. when the caller did not
// await EnsureCoreWebView2Async before setting Source). Marshal back to the UI thread
// before touching UI-affine WebView2/CoreWebView2 objects below, otherwise navigation
// fails with RO_E_WRONG_THREAD (0x8001010E). Guard against a null DispatcherQueue from a
// shutdown race so we never enqueue on a null queue.
if (dispatcherQueue)
{
co_await wil::resume_foreground(dispatcherQueue);
}
}
else if (m_isImplicitCreationInProgress)
{
// If Set Source is in flight, nothing to do - it will apply latest source when it completes
co_return;
}
}
// First-time creation request
else
{
m_isImplicitCreationInProgress = true;
co_await CreateCoreObjects();
}
}
if (m_coreWebView)
{
// TODO_WebView2: Should we use RawUri() instead of AbsoluteUri()?
// Try to apply latest source (could have changed during the co_await's above)
const auto updatedUri = this->Source();
if (!updatedUri.Equals(providedUri) && ShouldNavigate(updatedUri))
{
m_coreWebView.Navigate(updatedUri.AbsoluteUri());
}
else
{
m_coreWebView.Navigate(providedUri.AbsoluteUri());
}
}
co_return;
}
HWND WebView2::GetHostHwnd() noexcept
{
if (!m_xamlHostHwnd)
{
auto xamlRoot = this->XamlRoot();
if (xamlRoot)
{
com_ptr<IXamlRootNative> xamlRootNative = xamlRoot.as<IXamlRootNative>();
winrt::check_hresult(xamlRootNative->get_HostWindow(&m_xamlHostHwnd));
}
}
return m_xamlHostHwnd;
}
void WebView2::RegisterCoreEventHandlers()
{
// Previously we used get_weak() here, but we found the potential to hit a
// refcounting problem where in some scenarios the outer object gets
// an extra Release() in this process.
auto weakThis {winrt::make_weak(static_cast<winrt::WebView2>(*this))};
m_coreNavigationStartingRevoker = m_coreWebView.NavigationStarting(winrt::auto_revoke, {
[weakThis](auto const&, winrt::CoreWebView2NavigationStartingEventArgs const& args)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
// Update Uri without navigation
rawThis->UpdateSourceInternal();
rawThis->FireNavigationStarting(args);
}
} });
m_coreSourceChangedRevoker = m_coreWebView.SourceChanged(winrt::auto_revoke, {
[weakThis](auto const&, winrt::CoreWebView2SourceChangedEventArgs const& args)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
rawThis->UpdateSourceInternal();
}
} });
m_coreNavigationCompletedRevoker = m_coreWebView.NavigationCompleted(winrt::auto_revoke, {
[weakThis](auto const&, winrt::CoreWebView2NavigationCompletedEventArgs const& args)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
rawThis->FireNavigationCompleted(args);
}
} });
m_coreWebMessageReceivedRevoker = m_coreWebView.WebMessageReceived(winrt::auto_revoke, {
[weakThis](auto const&, winrt::CoreWebView2WebMessageReceivedEventArgs const& args)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
rawThis->FireWebMessageReceived(args);
}
} });
m_coreMoveFocusRequestedRevoker = m_coreWebViewController.MoveFocusRequested(winrt::auto_revoke, {
[weakThis](auto const&, const winrt::CoreWebView2MoveFocusRequestedEventArgs& args)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
winrt::CoreWebView2MoveFocusReason moveFocusRequestedReason{ args.Reason() };
if (moveFocusRequestedReason == winrt::CoreWebView2MoveFocusReason::Next ||
moveFocusRequestedReason == winrt::CoreWebView2MoveFocusReason::Previous)
{
winrt::XamlRoot xamlRoot = rawThis->XamlRoot();
if (xamlRoot)
{
winrt::FocusNavigationDirection xamlDirection = moveFocusRequestedReason == winrt::CoreWebView2MoveFocusReason::Next
? winrt::FocusNavigationDirection::Next
: winrt::FocusNavigationDirection::Previous;
winrt::FindNextElementOptions findNextElementOptions;
findNextElementOptions.SearchRoot(xamlRoot.Content());
winrt::DependencyObject nextElement = winrt::FocusManager::FindNextElement(xamlDirection, findNextElementOptions);
winrt::DependencyObject focusedElement = winrt::FocusManager::GetFocusedElement(xamlRoot).try_as<winrt::DependencyObject>();
if (nextElement && nextElement != focusedElement)
{
// TODO_WebView2: We should check TryMoveFocusAsync() result before returning since FindNextElement()
// only finds the next focusable element, but does not guarantee that we can
// actually focus on it (eg it could be empty/in the process of loading).
// Waiting on this result via winrt/cpp coroutine results in the WINRT_ASSERT
// warning about a blocking wait on UI Thread.
//
// We will address this scenario properly as part of:
// Task 23157748: WebView2 should implement IInternalCoreWindowFocus (use Xaml's unified focus model)
//
// For now, we'll assign the return value of TryMoveFocusAsync() to a dummy variable
// in order to avoid the code analysis error C26444:
//
// https://docs.microsoft.com/en-us/cpp/code-quality/c26444?view=vs-2019
// If core webview is also losing focus via something other than TAB (web LostFocus event fired)
// and the TAB handling is arriving later (eg due to longer MOJO delay), skip manually moving Xaml Focus to next element.
winrt::DependencyObject thisElement = rawThis->try_as<winrt::DependencyObject>();
if (thisElement == focusedElement)
{
// Move focus to the next XAML element
const auto _ = winrt::FocusManager::TryMoveFocusAsync(xamlDirection, findNextElementOptions);
}
}
else
{
// Handle the case where there is no "next" focusable XAML element (WebView2 is first/last/only element),
// which we are in if FindNextElement() returns either null or the (already focused) WebView2. The appropriate
// behavior here is to cycle focus inside the webview, "wrapping around" to the other end (regardless of
// WebView2.KeyboardNavigationMode).To achieve this, manually Call MoveFocus() in the specified direction.
rawThis->MoveFocusIntoCoreWebView2(moveFocusRequestedReason);
}
}
}
// Always mark the args handled to prevent CoreWebView2Controller's "default behavior" which breaks XAML focus expectations (by explicitly changing HWND focus)
// More info: https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2movefocusrequestedeventargs?view=webview2-winrt-1.0.2535.41#handled
args.Handled(TRUE);
}
} });
m_coreProcessFailedRevoker = m_coreWebView.ProcessFailed(winrt::auto_revoke, {
[weakThis](auto const&, const winrt::CoreWebView2ProcessFailedEventArgs& args)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
// Moving focus out of WebView2
winrt::FocusNavigationDirection xamlDirection{ winrt::FocusNavigationDirection::Next };
winrt::FindNextElementOptions findNextElementOptions;
winrt::XamlRoot xamlRoot = rawThis->XamlRoot();
if (xamlRoot)
{
findNextElementOptions.SearchRoot(xamlRoot.Content());
winrt::DependencyObject nextElement = winrt::FocusManager::FindNextElement(xamlDirection, findNextElementOptions);
if (nextElement)
{
const auto _ = winrt::FocusManager::TryMoveFocusAsync(xamlDirection, findNextElementOptions);
}
}
winrt::CoreWebView2ProcessFailedKind coreProcessFailedKind{ args.ProcessFailedKind() };
if (coreProcessFailedKind == winrt::CoreWebView2ProcessFailedKind::BrowserProcessExited)
{
rawThis->m_isCoreFailure_BrowserExited_State = true;
// CoreWebView2 takes care of clearing the event handlers when closing the host,
// but we still need to reset the event tokens
rawThis->UnregisterCoreEventHandlers();
// Null these out so we can't try to use them anymore
rawThis->m_coreWebViewCompositionController = nullptr;
rawThis->m_coreWebViewController = nullptr;
rawThis->m_coreWebView = nullptr;
rawThis->ResetProperties();
}
rawThis->FireCoreProcessFailedEvent(args);
}
} });
m_cursorChangedRevoker = m_coreWebViewCompositionController.CursorChanged(winrt::auto_revoke, {
[weakThis](auto const& controller, auto const& obj)
{
if (auto strongThis = weakThis.get())
{
WebView2* rawThis = winrt::get_self<WebView2>(strongThis);
winrt::CoreCursor coreCursor = controller.Cursor();
winrt::IInputSystemCursor inputSystemCursor;
switch (coreCursor.Type())
{
default:
case winrt::CoreCursorType::Arrow:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Arrow);
break;
case winrt::CoreCursorType::Cross:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Cross);
break;
case winrt::CoreCursorType::Hand:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Hand);
break;
case winrt::CoreCursorType::Help:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Help);
break;
case winrt::CoreCursorType::IBeam:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::IBeam);
break;
case winrt::CoreCursorType::Person:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Person);
break;
case winrt::CoreCursorType::Pin:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Pin);
break;
case winrt::CoreCursorType::SizeAll:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::SizeAll);
break;
case winrt::CoreCursorType::SizeNortheastSouthwest:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::SizeNortheastSouthwest);
break;
case winrt::CoreCursorType::SizeNorthwestSoutheast:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::SizeNorthwestSoutheast);
break;
case winrt::CoreCursorType::SizeNorthSouth:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::SizeNorthSouth);
break;
case winrt::CoreCursorType::SizeWestEast:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::SizeWestEast);
break;
case winrt::CoreCursorType::UniversalNo:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::UniversalNo);
break;
case winrt::CoreCursorType::Wait:
inputSystemCursor = winrt::InputSystemCursor::Create(winrt::InputSystemCursorShape::Wait);
break;
}
winrt::InputCursor inputCursorToSet = inputSystemCursor.as<winrt::InputCursor>();
rawThis->ProtectedCursor(inputCursorToSet);
}
} });
RegisterDragStartingHandler();
}
void WebView2::UnregisterCoreEventHandlers()
{
if (m_coreWebView)
{
m_coreNavigationStartingRevoker.revoke();
m_coreSourceChangedRevoker.revoke();
m_coreNavigationCompletedRevoker.revoke();
m_coreWebMessageReceivedRevoker.revoke();
m_coreProcessFailedRevoker.revoke();
}
if (m_coreWebViewController)
{
m_coreMoveFocusRequestedRevoker.revoke();
}
if (m_coreWebViewCompositionController)
{
m_cursorChangedRevoker.revoke();
UnRegisterDragStartingHandler();
}
}
winrt::IAsyncAction WebView2::CreateCoreObjects(winrt::CoreWebView2Environment environment, winrt::CoreWebView2ControllerOptions controllerOptions)
{
MUX_ASSERT((m_isImplicitCreationInProgress && !m_isExplicitCreationInProgress) ||
(!m_isImplicitCreationInProgress && m_isExplicitCreationInProgress));
auto strongThis = get_strong(); // ensure object lifetime during coroutines
if (m_isClosed)
{
throw winrt::hresult_error(RO_E_CLOSED, s_error_wv2_closed);
}
else
{
XamlTelemetry::WebView2_CreateCoreObjects(true, reinterpret_cast<uint64_t>(this));
m_creationInProgressAsync = std::make_unique<AsyncWebViewOperations>();
RegisterXamlEventHandlers();
// We are about to attempt re-creation of the environment,
// so clear any previous 'Missing Anaheim Warning'
Children().Clear();
// Normally we always need a new environment, the exception being when Anaheim process failed and we get to reuse the existing one
if (!m_isCoreFailure_BrowserExited_State)
{
m_coreWebViewEnvironment = environment ? environment : co_await CreateDefaultCoreEnvironment();
}
if (m_coreWebViewEnvironment)
{
co_await CreateCoreWebViewFromEnvironment(GetHostHwnd(), controllerOptions);
// Do initialization including rendering setup.
// Try this now but defer to Loaded event if it hasn't fired yet.
TryCompleteInitialization();
}
else if (m_shouldShowMissingAnaheimWarning)
{
CreateMissingAnaheimWarning();
}
XamlTelemetry::WebView2_CreateCoreObjects(false, reinterpret_cast<uint64_t>(this));
}
co_return;
}
winrt::IAsyncOperation<winrt::CoreWebView2Environment> WebView2::CreateDefaultCoreEnvironment() noexcept
{
hstring browserInstall;
hstring userDataFolder;
winrt::CoreWebView2Environment returnedValue = nullptr;
auto strongThis = get_strong(); // ensure object lifetime during coroutines
// NOTE: To enable Anaheim logging, add: environmentOptions.AdditionalBrowserArguments(L"--enable-logging=stderr --v=1");
winrt::CoreWebView2EnvironmentOptions environmentOptions = winrt::CoreWebView2EnvironmentOptions();
auto applicationLanguagesList = winrt::ApplicationLanguages::Languages();
if (applicationLanguagesList.Size() > 0)
{
environmentOptions.Language(applicationLanguagesList.GetAt(0));
}
try
{
returnedValue = co_await winrt::CoreWebView2Environment::CreateWithOptionsAsync(browserInstall, userDataFolder, environmentOptions);
}
catch (winrt::hresult_error e)
{
winrt::hresult hr = e.code().value;
m_shouldShowMissingAnaheimWarning = hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
FireCoreWebView2Initialized(hr);
}
co_return returnedValue;
}
winrt::IAsyncAction WebView2::CreateCoreWebViewFromEnvironment(HWND hwndParent, winrt::CoreWebView2ControllerOptions controllerOptions)
{
auto strongThis = get_strong(); // ensure object lifetime during coroutines
if (!hwndParent)
{
hwndParent = EnsureTemporaryHostHwnd();
}
try
{
auto windowRef = winrt::CoreWebView2ControllerWindowReference::CreateFromWindowHandle(reinterpret_cast<UINT64>(hwndParent));
// CreateCoreWebView2CompositionController(Async) creates a CompositionController and is in visual hosting mode.
// Calling CreateCoreWebView2Controller would create a Controller and would be in windowed mode.
if (!controllerOptions)
{
m_coreWebViewCompositionController = co_await m_coreWebViewEnvironment.CreateCoreWebView2CompositionControllerAsync(windowRef);
}
else
{
m_customCoreWebViewControllerOptions = controllerOptions;
m_coreWebViewCompositionController = co_await m_coreWebViewEnvironment.CreateCoreWebView2CompositionControllerAsync(windowRef, controllerOptions);
}
m_coreWebViewController = m_coreWebViewCompositionController.as<winrt::CoreWebView2Controller>();
m_coreWebViewController.DefaultBackgroundColor(this->DefaultBackgroundColor());
m_coreWebViewController.ShouldDetectMonitorScaleChanges(false);
m_coreWebView = m_coreWebViewController.CoreWebView2();
RegisterCoreEventHandlers();
// Creation is considered complete at this point, however rendering and accessibility
// hookup will only run after we get Loaded event (see TryCompleteInitialization())
FireCoreWebView2Initialized(winrt::hresult(S_OK));
}
catch (winrt::hresult_error e)
{
winrt::hresult hr = e.code().value;
FireCoreWebView2Initialized(hr);
}
m_isImplicitCreationInProgress = false;
m_isExplicitCreationInProgress = false;
m_creationInProgressAsync->StopWaiting();
m_creationInProgressAsync.reset();
co_return;
}
// Get a theme-appropriate Background color to use as BG for SystemVisualBridge.
// This helps avoid flicker when CoreWebView2 is intializing or shutting down.
winrt::Color WebView2::GetThemeBackgroundColor()
{
bool isHighContrast = GetAccessibilitySettings().HighContrast();
std::wstring helperBrushName = isHighContrast ? L"BrushForThemeBackgroundColor_HC" : L"BrushForThemeBackgroundColor";
// Ensure helper SCB referencing appropriate color as a ThemeResource is added to WV2.Resources.
// This is needed since programatic lookup of theme resources themselves does not account for active theme.
if (!this->Resources().HasKey(box_value(helperBrushName)))
{
std::wstring resourceName = isHighContrast ? L"SystemColorWindowColor" : L"SolidBackgroundFillColorBase";
winrt::SolidColorBrush helperBrush = winrt::XamlReader::Load(
L"<SolidColorBrush xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' "
L"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' "
L"x:Name='" + helperBrushName + L"' "
L"Color='{ThemeResource " + resourceName + L"}'/>"
).as<winrt::SolidColorBrush>();
this->Resources().Insert(box_value(helperBrushName), helperBrush);
}
// Read off the theme-appropriate BG color from helper brush resource
return (this->Resources().Lookup(box_value(helperBrushName)).as<winrt::SolidColorBrush>()).Color();
}
void WebView2::UpdateDefaultVisualBackgroundColor()
{
if (m_systemVisualBridge) { m_systemVisualBridge.BackgroundColor(GetThemeBackgroundColor()); }
}
HWND WebView2::EnsureTemporaryHostHwnd()
{
// If we don't know the parent yet, either use the CoreWindow as the parent,
// or if we don't have one, create a dummy hwnd to be the temporary parent.
// Using a dummy parent all the time won't work, since we can't reparent the
// browser from a Non-ShellManaged Hwnd (dummy) to a ShellManaged one (CoreWindow).
winrt::CoreWindow coreWindow = winrt::CoreWindow::GetForCurrentThread();
if (coreWindow)
{
auto coreWindowInterop = coreWindow.as<ICoreWindowInterop>();
winrt::check_hresult(coreWindowInterop->get_WindowHandle(&m_tempHostHwnd));
}
else
{
// Register the window class.
const wchar_t CLASS_NAME[] = L"WEBVIEW2_TEMP_PARENT";
HINSTANCE hInstance = ::GetModuleHandleW(NULL);