364 lines
18 KiB
Rust
364 lines
18 KiB
Rust
//! Display WebView2 spelling commands through the shared frontend menu.
|
|
//! Keep COM event arguments on the WebView thread until selection or cancellation.
|
|
|
|
use crate::error::Result;
|
|
|
|
#[cfg(any(windows, test))]
|
|
#[derive(Debug, PartialEq)]
|
|
enum Selection { Stale, Cancel, Native, Command(i32) }
|
|
|
|
#[cfg(any(windows, test))]
|
|
fn requires_native_label(kind: i32, label: &str) -> bool {
|
|
kind != 3 && label.trim().is_empty()
|
|
}
|
|
|
|
#[cfg(any(windows, test))]
|
|
fn excluded_command(name: &str, editable: bool) -> bool {
|
|
// WebView2 names unsupported OS tools "other", including direction and dictation.
|
|
// Keep recognized editor commands without matching localized labels or runtime IDs.
|
|
matches!(name, "share" | "writingDirection" | "voiceTyping") || (editable && name == "other")
|
|
}
|
|
|
|
#[cfg(any(windows, test))]
|
|
fn selection(current: &str, request: &str, command: Option<i32>, fallback: bool, enabled: &std::collections::HashSet<i32>) -> Selection {
|
|
if current != request { return Selection::Stale; }
|
|
if fallback { return Selection::Native; }
|
|
command.filter(|id| enabled.contains(id)).map(Selection::Command).unwrap_or(Selection::Cancel)
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
mod native {
|
|
use std::{cell::RefCell, collections::{HashMap, HashSet}};
|
|
use serde::Serialize;
|
|
use tauri::{Emitter, Manager};
|
|
use webview2_com::{take_pwstr, ContextMenuRequestedEventHandler, Microsoft::Web::WebView2::Win32::*};
|
|
use windows::core::{Interface, PWSTR, BOOL};
|
|
|
|
#[derive(Clone, Serialize)]
|
|
pub struct Item {
|
|
id: i32, name: String, label: String, shortcut: String, kind: i32,
|
|
enabled: bool, checked: bool, children: Vec<Item>,
|
|
}
|
|
#[derive(Clone, Serialize)]
|
|
struct Menu { request: String, items: Vec<Item>, fallback_spelling: bool }
|
|
fn requires_native(items: &[Item]) -> bool {
|
|
items.iter().any(|item| super::requires_native_label(item.kind, &item.label) || requires_native(&item.children))
|
|
}
|
|
struct Pending {
|
|
request: String, args: ICoreWebView2ContextMenuRequestedEventArgs,
|
|
deferral: ICoreWebView2Deferral, commands: HashSet<i32>,
|
|
}
|
|
impl Drop for Pending {
|
|
fn drop(&mut self) { unsafe { let _ = self.deferral.Complete(); } }
|
|
}
|
|
thread_local! {
|
|
static PENDING: RefCell<HashMap<String, Pending>> = RefCell::new(HashMap::new());
|
|
static INSTALLED: RefCell<HashMap<String, (ICoreWebView2_11, i64)>> = RefCell::new(HashMap::new());
|
|
}
|
|
|
|
unsafe fn text(read: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
|
|
let mut value = PWSTR::null();
|
|
let result = read(&mut value);
|
|
let text = take_pwstr(value);
|
|
result.map(|_| text)
|
|
}
|
|
unsafe fn trim_menu(collection: &ICoreWebView2ContextMenuItemCollection, editable: bool) -> windows::core::Result<u32> {
|
|
let mut count = 0;
|
|
collection.Count(&mut count)?;
|
|
let mut index = 0;
|
|
let mut separator = true;
|
|
while index < count {
|
|
let item = collection.GetValueAtIndex(index)?;
|
|
let mut kind = COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND;
|
|
item.Kind(&mut kind)?;
|
|
let name = text(|value| item.Name(value))?;
|
|
let empty_submenu = kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU && trim_menu(&item.Children()?, editable)? == 0;
|
|
let is_separator = kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR;
|
|
if (!is_separator && super::excluded_command(&name, editable)) || empty_submenu || (is_separator && separator) {
|
|
collection.RemoveValueAtIndex(index)?;
|
|
count -= 1;
|
|
} else {
|
|
separator = is_separator;
|
|
index += 1;
|
|
}
|
|
}
|
|
if separator && count > 0 {
|
|
collection.RemoveValueAtIndex(count - 1)?;
|
|
count -= 1;
|
|
}
|
|
Ok(count)
|
|
}
|
|
unsafe fn items(collection: ICoreWebView2ContextMenuItemCollection, commands: &mut HashSet<i32>, parent_enabled: bool) -> windows::core::Result<Vec<Item>> {
|
|
let mut count = 0;
|
|
collection.Count(&mut count)?;
|
|
let mut result = Vec::new();
|
|
for index in 0..count {
|
|
let item = collection.GetValueAtIndex(index)?;
|
|
let (mut id, mut kind, mut enabled, mut checked) = (0, COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND, BOOL(0), BOOL(0));
|
|
item.CommandId(&mut id)?;
|
|
item.Kind(&mut kind)?;
|
|
item.IsEnabled(&mut enabled)?;
|
|
item.IsChecked(&mut checked)?;
|
|
let enabled = parent_enabled && enabled.as_bool();
|
|
let children = if kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { items(item.Children()?, commands, enabled)? } else { Vec::new() };
|
|
if enabled && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { commands.insert(id); }
|
|
result.push(Item {
|
|
id, name: text(|value| item.Name(value))?, label: text(|value| item.Label(value))?,
|
|
shortcut: text(|value| item.ShortcutKeyDescription(value))?, kind: kind.0,
|
|
enabled, checked: checked.as_bool(), children,
|
|
});
|
|
}
|
|
Ok(result)
|
|
}
|
|
|
|
pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> crate::error::Result<()> {
|
|
let label = window.label().to_owned();
|
|
if INSTALLED.with(|installed| installed.borrow().contains_key(&label)) { return Ok(()); }
|
|
let app = window.app_handle().clone();
|
|
let owner = label.clone();
|
|
unsafe {
|
|
let core: ICoreWebView2_11 = controller.CoreWebView2()?.cast()?;
|
|
let handler = ContextMenuRequestedEventHandler::create(Box::new(move |_, args| {
|
|
let Some(args) = args else { return Ok(()); };
|
|
let mut editable = BOOL(0);
|
|
args.ContextMenuTarget()?.IsEditable(&mut editable)?;
|
|
// Filter the original collection so native fallback uses the same commands.
|
|
let collection = args.MenuItems()?;
|
|
trim_menu(&collection, editable.as_bool())?;
|
|
if !editable.as_bool() { return Ok(()); }
|
|
let mut commands = HashSet::new();
|
|
let entries = items(collection, &mut commands, true)?;
|
|
// Windows supplies suggestions when WebView2 omits their labels.
|
|
let fallback_spelling = requires_native(&entries) || !entries.iter().any(|item| item.name == "spellCheck" && !item.label.trim().is_empty());
|
|
let Some(window) = app.get_webview_window(&owner) else { return Ok(()); };
|
|
let pending = Pending { request: uuid::Uuid::new_v4().to_string(), args: args.clone(), deferral: args.GetDeferral()?, commands };
|
|
let menu = Menu { request: pending.request.clone(), items: entries, fallback_spelling };
|
|
args.SetHandled(true)?;
|
|
let previous = PENDING.with(|state| state.borrow_mut().insert(owner.clone(), pending));
|
|
drop(previous);
|
|
if window.emit("spelling-menu", menu).is_err() {
|
|
// Restore the native menu if the frontend cannot receive the request.
|
|
let _ = args.SetHandled(false);
|
|
let pending = PENDING.with(|state| state.borrow_mut().remove(&owner));
|
|
drop(pending);
|
|
}
|
|
Ok(())
|
|
}));
|
|
let mut token = 0;
|
|
core.add_ContextMenuRequested(&handler, &mut token)?;
|
|
INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); });
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn select(label: &str, request: &str, command: Option<i32>, fallback: bool) {
|
|
let result = PENDING.with(|state| {
|
|
let mut state = state.borrow_mut();
|
|
let pending = state.get(label)?;
|
|
let choice = super::selection(&pending.request, request, command, fallback, &pending.commands);
|
|
if choice == super::Selection::Stale { return None; }
|
|
Some((state.remove(label)?, choice))
|
|
});
|
|
if let Some((pending, choice)) = result {
|
|
unsafe {
|
|
match choice {
|
|
super::Selection::Command(id) => { let _ = pending.args.SetSelectedCommandId(id); }
|
|
super::Selection::Native => { let _ = pending.args.SetHandled(false); }
|
|
_ => {}
|
|
}
|
|
}
|
|
// Drop completes the deferral after the selected command is set.
|
|
}
|
|
}
|
|
|
|
pub fn close(label: &str) {
|
|
let pending = PENDING.with(|state| state.borrow_mut().remove(label));
|
|
drop(pending);
|
|
if let Some((core, token)) = INSTALLED.with(|installed| installed.borrow_mut().remove(label)) {
|
|
unsafe { let _ = core.remove_ContextMenuRequested(token); }
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<()> {
|
|
#[cfg(windows)] {
|
|
let (send, receive) = std::sync::mpsc::channel();
|
|
let owner = window.clone();
|
|
window.with_webview(move |webview| { let _ = send.send(native::install(&owner, webview.controller())); })?;
|
|
tauri::async_runtime::spawn_blocking(move || receive.recv()?).await?
|
|
}
|
|
#[cfg(not(windows))] { let _ = window; Ok(()) }
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn spelling_menu_select(window: tauri::WebviewWindow, request: String, command: Option<i32>, fallback: Option<bool>) -> Result<()> {
|
|
#[cfg(windows)] {
|
|
let label = window.label().to_owned();
|
|
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false)))?;
|
|
}
|
|
#[cfg(not(windows))] { let _ = (window, request, command, fallback); }
|
|
Ok(())
|
|
}
|
|
|
|
pub fn close_window(app: &tauri::AppHandle, label: &str) {
|
|
#[cfg(windows)] {
|
|
let label = label.to_owned();
|
|
let _ = app.run_on_main_thread(move || native::close(&label));
|
|
}
|
|
#[cfg(not(windows))] { let _ = (app, label); }
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<()> {
|
|
#[cfg(windows)] {
|
|
let label = window.label().to_owned();
|
|
window.with_webview(move |_| native::close(&label))?;
|
|
}
|
|
#[cfg(not(windows))] { let _ = window; }
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(serde::Serialize)]
|
|
pub struct Suggestions { language: String, words: Vec<String>, misspelled: bool }
|
|
|
|
#[cfg(windows)]
|
|
mod suggestions_worker {
|
|
use super::Suggestions;
|
|
use crate::error::{Error, Result};
|
|
use std::{collections::HashMap, sync::{mpsc, OnceLock}};
|
|
use windows::{core::{HSTRING, PWSTR}, Win32::{Globalization::{ISpellChecker, ISpellCheckerFactory, SpellCheckerFactory}, System::Com::{CoInitializeEx, CoUninitialize, CoCreateInstance, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}}};
|
|
type Reply = Result<Suggestions>;
|
|
type Request = (String, Vec<String>, bool, mpsc::SyncSender<Reply>);
|
|
static WORKER: OnceLock<mpsc::Sender<Request>> = OnceLock::new();
|
|
|
|
pub fn request(word: String, languages: Vec<String>, add: bool) -> Reply {
|
|
let worker = WORKER.get_or_init(|| {
|
|
let (send, receive) = mpsc::channel::<Request>();
|
|
std::thread::spawn(move || unsafe {
|
|
let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(Error::from);
|
|
let apartment_initialized = initialized.is_ok();
|
|
let factory: Result<ISpellCheckerFactory> = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(Error::from));
|
|
let mut checkers = HashMap::<String, ISpellChecker>::new();
|
|
for (word, languages, add, reply) in receive {
|
|
let result = (|| -> Reply {
|
|
let factory = factory.as_ref().map_err(Clone::clone)?;
|
|
for language in languages {
|
|
if language.len() > 85 || language.contains('\0') { continue; }
|
|
if !checkers.contains_key(&language) {
|
|
let tag = HSTRING::from(&language);
|
|
if !factory.IsSupported(&tag)?.as_bool() { continue; }
|
|
let checker = factory.CreateSpellChecker(&tag)?;
|
|
checkers.insert(language.clone(), checker);
|
|
}
|
|
let checker = &checkers[&language];
|
|
let value = HSTRING::from(&word);
|
|
if add {
|
|
checker.Add(&value)?;
|
|
return Ok(Suggestions { language, words: Vec::new(), misspelled: false });
|
|
}
|
|
let errors = checker.Check(&value)?;
|
|
let mut error = None;
|
|
errors.Next(&mut error).ok()?;
|
|
if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); }
|
|
let suggestions = checker.Suggest(&value)?;
|
|
let mut words = Vec::new();
|
|
for _ in 0..8 {
|
|
let mut values = [PWSTR::null()];
|
|
let mut count = 0;
|
|
suggestions.Next(&mut values, Some(&mut count)).ok()?;
|
|
if count == 0 { break; }
|
|
let suggestion = webview2_com::take_pwstr(values[0]);
|
|
if !suggestion.is_empty() && suggestion != word { words.push(suggestion); }
|
|
}
|
|
return Ok(Suggestions { language, words, misspelled: true });
|
|
}
|
|
Err("No spelling dictionary is installed for this language.".into())
|
|
})();
|
|
let _ = reply.send(result);
|
|
}
|
|
drop(checkers);
|
|
drop(factory);
|
|
if apartment_initialized { CoUninitialize(); }
|
|
});
|
|
send
|
|
});
|
|
let (reply, receive) = mpsc::sync_channel(1);
|
|
worker.send((word, languages, add, reply)).map_err(|_| "The spelling service stopped.".to_owned())?;
|
|
receive.recv().map_err(|_| "The spelling service stopped.".to_owned())?
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions> {
|
|
if word.is_empty() || word.len() > 256 || word.contains('\0') || languages.len() > 20 {
|
|
return Err("Invalid spelling request.".into());
|
|
}
|
|
#[cfg(windows)] {
|
|
tauri::async_runtime::spawn_blocking(move || suggestions_worker::request(word, languages, add.unwrap_or(false))).await?
|
|
}
|
|
#[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) }
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::collections::HashSet;
|
|
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn spelling_worker_reuses_the_dictionary_for_repeated_requests() {
|
|
let start = std::time::Instant::now();
|
|
let first = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false);
|
|
let cold = start.elapsed();
|
|
if let Err(error) = &first {
|
|
if error.to_string().contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; }
|
|
}
|
|
let first = first.unwrap();
|
|
assert!(first.misspelled);
|
|
assert!(first.words.iter().any(|word| word == "received"));
|
|
let start = std::time::Instant::now();
|
|
for _ in 0..10 {
|
|
let next = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false).unwrap();
|
|
assert_eq!(first.words, next.words);
|
|
}
|
|
eprintln!("Spelling service: cold {cold:?}, average warm {:?}", start.elapsed() / 10);
|
|
}
|
|
|
|
#[test]
|
|
fn unrelated_browser_tools_are_removed_without_changing_editor_commands() {
|
|
for name in ["share", "writingDirection", "voiceTyping", "other"] { assert!(excluded_command(name, true)); }
|
|
assert!(!excluded_command("other", false), "Keep unrelated non-editable native actions");
|
|
for name in ["cut", "copy", "paste", "pasteAndMatchStyle", "undo", "redo", "selectAll", "spellCheck", "addToDictionary", "emoji", "copyLink", "custom"] {
|
|
assert!(!excluded_command(name, true), "Keep {name}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn stale_requests_cannot_select_or_cancel_a_new_menu() {
|
|
for command in [None, Some(42)] {
|
|
assert_eq!(selection("new", "old", command, false, &HashSet::from([42])), Selection::Stale);
|
|
assert_eq!(selection("new", "old", command, true, &HashSet::from([42])), Selection::Stale);
|
|
}
|
|
}
|
|
#[test]
|
|
fn only_enabled_commands_from_the_current_request_can_run() {
|
|
let enabled = HashSet::from([42]);
|
|
assert_eq!(selection("a", "a", Some(42), false, &enabled), Selection::Command(42));
|
|
assert_eq!(selection("a", "a", Some(43), false, &enabled), Selection::Cancel);
|
|
assert_eq!(selection("a", "a", None, false, &enabled), Selection::Cancel);
|
|
}
|
|
#[test]
|
|
fn unmatched_editable_target_keeps_the_native_menu() {
|
|
assert_eq!(selection("a", "a", None, true, &HashSet::new()), Selection::Native);
|
|
}
|
|
#[test]
|
|
fn blank_commands_keep_native_suggestions_but_separators_do_not() {
|
|
assert!(requires_native_label(0, ""));
|
|
assert!(requires_native_label(0, " "));
|
|
assert!(requires_native_label(4, ""));
|
|
assert!(!requires_native_label(3, ""));
|
|
assert!(!requires_native_label(0, "received"));
|
|
}
|
|
}
|