Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 159 additions & 13 deletions SampleApps/WebView2APISample/SettingsComponent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,11 @@ bool SettingsComponent::HandleWindowMessage(
wil::com_ptr<ICoreWebView2ContextMenuTarget> target;
CHECK_FAILURE(args->get_ContextMenuTarget(&target));

if (TryShowSpellCheckContextMenu(args, items, target))
{
return S_OK;
}

COREWEBVIEW2_CONTEXT_MENU_TARGET_KIND targetKind;
CHECK_FAILURE(target->get_Kind(&targetKind));
// Custom UI Context Menu rendered if invoked on selected text
Expand All @@ -610,29 +615,30 @@ bool SettingsComponent::HandleWindowMessage(
auto showMenu = [this, args, itemsCount, items, target]
{
CHECK_FAILURE(args->put_Handled(true));
HMENU hPopupMenu = CreatePopupMenu();
AddMenuItems(hPopupMenu, items);
wil::unique_hmenu hPopupMenu(CreatePopupMenu());
AddMenuItems(hPopupMenu.get(), items);
HWND hWnd;
m_controller->get_ParentWindow(&hWnd);
CHECK_FAILURE(m_controller->get_ParentWindow(&hWnd));
SetForegroundWindow(hWnd);
RECT rct;
GetClientRect(hWnd, &rct);
POINT topLeft;
topLeft.x = rct.left;
topLeft.y = rct.top;
POINT topLeft = {rct.left, rct.top};
ClientToScreen(hWnd, &topLeft);
POINT p;
CHECK_FAILURE(args->get_Location(&p));
POINT location;
CHECK_FAILURE(args->get_Location(&location));
RECT bounds;
CHECK_FAILURE(m_controller->get_Bounds(&bounds));
double scale;
m_controller3->get_RasterizationScale(&scale);
CHECK_FAILURE(
m_controller3->get_RasterizationScale(&scale));
INT32 selectedCommandId = TrackPopupMenu(
hPopupMenu,
hPopupMenu.get(),
TPM_TOPALIGN | TPM_LEFTALIGN | TPM_RETURNCMD,
bounds.left + topLeft.x + ((int)(p.x * scale)),
bounds.top + topLeft.y + ((int)(p.y * scale)), 0, hWnd,
NULL);
bounds.left + topLeft.x +
static_cast<int>(location.x * scale),
bounds.top + topLeft.y +
static_cast<int>(location.y * scale),
0, hWnd, nullptr);
CHECK_FAILURE(
args->put_SelectedCommandId(selectedCommandId));
};
Expand Down Expand Up @@ -1882,6 +1888,146 @@ void SettingsComponent::SetEnhancedSecurityModeState(
}
//! [SetEnhancedSecurityModeState]

//! [SpellCheckSuggestions]
bool SettingsComponent::TryShowSpellCheckContextMenu(
wil::com_ptr<ICoreWebView2ContextMenuRequestedEventArgs> args,
wil::com_ptr<ICoreWebView2ContextMenuItemCollection> items,
wil::com_ptr<ICoreWebView2ContextMenuTarget> target)
{
auto spellCheckTarget = target.try_query<ICoreWebView2ExperimentalContextMenuTarget2>();
if (!spellCheckTarget)
{
return false;
}
BOOL hasSpellingError = FALSE;
CHECK_FAILURE(spellCheckTarget->get_HasSpellingError(&hasSpellingError));
if (!hasSpellingError)
{
return false;
}

wil::com_ptr<ICoreWebView2Deferral> deferral;
CHECK_FAILURE(args->GetDeferral(&deferral));
CHECK_FAILURE(args->put_Handled(TRUE));
CHECK_FAILURE(spellCheckTarget->GetSpellCheckSuggestions(
Callback<ICoreWebView2ExperimentalGetSpellCheckSuggestionsCompletedHandler>(
[appWindow = m_appWindow, webView = m_webView, args, items, deferral](
HRESULT errorCode,
ICoreWebView2ExperimentalSpellCheckSuggestionCollectionView* suggestions)
-> HRESULT
{
if (FAILED(errorCode))
{
CHECK_FAILURE(deferral->Complete());
if (errorCode != E_ABORT)
{
CHECK_FAILURE(errorCode);
}
return S_OK;
}
wil::com_ptr<ICoreWebView2ExperimentalSpellCheckSuggestionCollectionView>
suggestionItems = suggestions;
appWindow->RunAsync(
[appWindow, webView, args, items, suggestionItems, deferral]()
{
auto completeDeferral = wil::scope_exit(
[deferral]() { CHECK_FAILURE(deferral->Complete()); });
auto settings = appWindow->GetComponent<SettingsComponent>();
if (!settings || settings->m_webView.get() != webView.get())
{
return;
}
wil::unique_hmenu hPopupMenu(CreatePopupMenu());

UINT32 suggestionCount = 0;
if (suggestionItems)
{
CHECK_FAILURE(suggestionItems->get_Count(&suggestionCount));
}
for (UINT32 i = 0; i < suggestionCount; i++)
{
wil::com_ptr<ICoreWebView2ExperimentalSpellCheckSuggestion>
suggestion;
CHECK_FAILURE(suggestionItems->GetValueAtIndex(i, &suggestion));
wil::unique_cotaskmem_string label;
CHECK_FAILURE(suggestion->get_SuggestionText(&label));
INT32 commandId = 0;
CHECK_FAILURE(suggestion->get_CommandId(&commandId));
AppendMenu(
hPopupMenu.get(), MF_STRING, static_cast<UINT_PTR>(commandId),
label.get());
}
if (suggestionCount > 0)
{
AppendMenu(hPopupMenu.get(), MF_SEPARATOR, 0, nullptr);
}

UINT32 defaultItemsCount = 0;
CHECK_FAILURE(items->get_Count(&defaultItemsCount));
for (UINT32 i = defaultItemsCount; i > 0; --i)
{
wil::com_ptr<ICoreWebView2ContextMenuItem> item;
CHECK_FAILURE(items->GetValueAtIndex(i - 1, &item));
wil::unique_cotaskmem_string name;
CHECK_FAILURE(item->get_Name(&name));
if (wcscmp(name.get(), L"spellcheck") == 0)
{
CHECK_FAILURE(items->RemoveValueAtIndex(i - 1));
--defaultItemsCount;
}
}
while (defaultItemsCount > 0)
{
wil::com_ptr<ICoreWebView2ContextMenuItem> item;
CHECK_FAILURE(items->GetValueAtIndex(0, &item));
COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND kind;
CHECK_FAILURE(item->get_Kind(&kind));
if (kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR)
{
break;
}
CHECK_FAILURE(items->RemoveValueAtIndex(0));
--defaultItemsCount;
}
settings->AddMenuItems(hPopupMenu.get(), items);

INT32 selectedCommandId =
settings->ShowCustomContextMenu(hPopupMenu.get(), args);
if (selectedCommandId != 0)
{
CHECK_FAILURE(args->put_SelectedCommandId(selectedCommandId));
}
});
return S_OK;
})
.Get()));
return true;
}

//! [SpellCheckSuggestions]

INT32 SettingsComponent::ShowCustomContextMenu(
HMENU hPopupMenu, wil::com_ptr<ICoreWebView2ContextMenuRequestedEventArgs> args)
{
HWND hWnd;
CHECK_FAILURE(m_controller->get_ParentWindow(&hWnd));
SetForegroundWindow(hWnd);
RECT rct;
GetClientRect(hWnd, &rct);
POINT topLeft = {rct.left, rct.top};
ClientToScreen(hWnd, &topLeft);
POINT location;
CHECK_FAILURE(args->get_Location(&location));
RECT bounds;
CHECK_FAILURE(m_controller->get_Bounds(&bounds));
double scale;
CHECK_FAILURE(m_controller3->get_RasterizationScale(&scale));
return TrackPopupMenu(
hPopupMenu, TPM_TOPALIGN | TPM_LEFTALIGN | TPM_RETURNCMD,
bounds.left + topLeft.x + static_cast<int>(location.x * scale),
bounds.top + topLeft.y + static_cast<int>(location.y * scale), 0, hWnd, nullptr);
}

SettingsComponent::~SettingsComponent()
{
m_webView->remove_NavigationStarting(m_navigationStartingToken);
Expand Down
7 changes: 7 additions & 0 deletions SampleApps/WebView2APISample/SettingsComponent.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ class SettingsComponent : public ComponentBase
~SettingsComponent() override;

private:
bool TryShowSpellCheckContextMenu(
wil::com_ptr<ICoreWebView2ContextMenuRequestedEventArgs> args,
wil::com_ptr<ICoreWebView2ContextMenuItemCollection> items,
wil::com_ptr<ICoreWebView2ContextMenuTarget> target);
INT32 ShowCustomContextMenu(
HMENU hPopupMenu, wil::com_ptr<ICoreWebView2ContextMenuRequestedEventArgs> args);

HRESULT OnPermissionRequested(
ICoreWebView2* sender, ICoreWebView2PermissionRequestedEventArgs* args);
AppWindow* m_appWindow = nullptr;
Expand Down
4 changes: 2 additions & 2 deletions SampleApps/WebView2APISample/WebView2APISample.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -540,13 +540,13 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220201.1\build\native\Microsoft.Windows.ImplementationLibrary.targets" Condition="Exists('..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220201.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" />
<Import Project="..\packages\Microsoft.Web.WebView2.1.0.4312-prerelease\build\native\Microsoft.Web.WebView2.targets" Condition="Exists('..\packages\Microsoft.Web.WebView2.1.0.4312-prerelease\build\native\Microsoft.Web.WebView2.targets')" />
<Import Project="..\packages\Microsoft.Web.WebView2.1.0.4365-prerelease\build\native\Microsoft.Web.WebView2.targets" Condition="Exists('..\packages\Microsoft.Web.WebView2.1.0.4365-prerelease\build\native\Microsoft.Web.WebView2.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220201.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220201.1\build\native\Microsoft.Windows.ImplementationLibrary.targets'))" />
<Error Condition="!Exists('..\packages\Microsoft.Web.WebView2.1.0.4312-prerelease\build\native\Microsoft.Web.WebView2.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Web.WebView2.1.0.4312-prerelease\build\native\Microsoft.Web.WebView2.targets'))" />
<Error Condition="!Exists('..\packages\Microsoft.Web.WebView2.1.0.4365-prerelease\build\native\Microsoft.Web.WebView2.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Web.WebView2.1.0.4365-prerelease\build\native\Microsoft.Web.WebView2.targets'))" />
</Target>
</Project>
2 changes: 1 addition & 1 deletion SampleApps/WebView2APISample/packages.config
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Web.WebView2" version="1.0.4312-prerelease" targetFramework="native" />
<package id="Microsoft.Web.WebView2" version="1.0.4365-prerelease" targetFramework="native" />
<package id="Microsoft.Windows.ImplementationLibrary" version="1.0.220201.1" targetFramework="native" />
</packages>
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4312-prerelease" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4365-prerelease" />
</ItemGroup>
<ItemGroup>
<Folder Include="assets\" />
Expand Down
93 changes: 93 additions & 0 deletions SampleApps/WebView2WpfBrowser/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,11 @@ void WebView_ContextMenuRequested(
CoreWebView2ContextMenuRequestedEventArgs args)
{
IList<CoreWebView2ContextMenuItem> menuList = args.MenuItems;
if (TryShowSpellCheckContextMenu(args, menuList))
{
return;
}

CoreWebView2ContextMenuTargetKind context = args.ContextMenuTarget.Kind;
// Using custom context menu UI
if (context == CoreWebView2ContextMenuTargetKind.SelectedText)
Expand Down Expand Up @@ -1444,6 +1449,94 @@ void WebView_ContextMenuRequested(
}
// </CustomContextMenu>

bool TryShowSpellCheckContextMenu(
CoreWebView2ContextMenuRequestedEventArgs args,
IList<CoreWebView2ContextMenuItem> menuList)
{
#if USE_WEBVIEW2_EXPERIMENTAL
if (args.ContextMenuTarget.HasSpellingError)
{
async void ShowMenuAsync()
{
await ShowSpellCheckContextMenuAsync(args, menuList);
}

ShowMenuAsync();
return true;
}
#endif
return false;
}

#if USE_WEBVIEW2_EXPERIMENTAL
// <SpellCheckSuggestions>
async Task ShowSpellCheckContextMenuAsync(
CoreWebView2ContextMenuRequestedEventArgs args,
IList<CoreWebView2ContextMenuItem> menuList)
{
CoreWebView2Deferral deferral = args.GetDeferral();
args.Handled = true;

bool menuOpened = false;
try
{
IReadOnlyList<CoreWebView2SpellCheckSuggestion> suggestions =
await args.ContextMenuTarget.GetSpellCheckSuggestionsAsync();

ContextMenu cm = new ContextMenu();
foreach (CoreWebView2SpellCheckSuggestion suggestion in suggestions)
{
MenuItem suggestionItem = new MenuItem();
suggestionItem.Header = suggestion.SuggestionText;
int commandId = suggestion.CommandId;
suggestionItem.Click +=
(s, ex) => { args.SelectedCommandId = commandId; };
cm.Items.Add(suggestionItem);
}

for (int i = menuList.Count - 1; i >= 0; i--)
{
if (menuList[i].Name == "spellcheck")
{
menuList.RemoveAt(i);
}
}
while (menuList.Count > 0 &&
menuList[0].Kind == CoreWebView2ContextMenuItemKind.Separator)
{
menuList.RemoveAt(0);
}
if (suggestions.Count > 0 && menuList.Count > 0)
{
cm.Items.Add(new Separator());
}

PopulateContextMenu(args, menuList, cm);
cm.Closed += (s, ex) => deferral.Complete();
cm.IsOpen = true;
menuOpened = true;
}
catch (COMException exception) when (
exception.HResult == unchecked((int)0x80004004)) // E_ABORT
{
// The context-menu request was superseded or its WebView was closed.
return;
}
catch (COMException exception)
{
MessageBox.Show(exception.Message, "Custom context menus");
}
finally
{
if (!menuOpened)
{
deferral.Complete();
}
}
}
// </SpellCheckSuggestions>
#endif

void PopulateContextMenu(CoreWebView2ContextMenuRequestedEventArgs args,
IList<CoreWebView2ContextMenuItem> menuList,
ItemsControl cm)
Expand Down
2 changes: 1 addition & 1 deletion SampleApps/WebView2WpfBrowser/WebView2WpfBrowser.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4312-prerelease" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4365-prerelease" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup>
</Project>
Loading