Update the browser, editor, settings, and installer
This commit is contained in:
+100
-6
@@ -10,6 +10,13 @@ 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; }
|
||||
@@ -31,7 +38,7 @@ mod native {
|
||||
enabled: bool, checked: bool, children: Vec<Item>,
|
||||
}
|
||||
#[derive(Clone, Serialize)]
|
||||
struct Menu { request: String, items: Vec<Item> }
|
||||
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))
|
||||
}
|
||||
@@ -53,6 +60,32 @@ mod native {
|
||||
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)?;
|
||||
@@ -87,15 +120,17 @@ mod native {
|
||||
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(args.MenuItems()?, &mut commands, true)?;
|
||||
// WebView2 can omit spelling labels and reject their command IDs.
|
||||
// Its native menu still owns the suggestion text and correction.
|
||||
if requires_native(&entries) { return Ok(()); }
|
||||
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 };
|
||||
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);
|
||||
@@ -182,11 +217,70 @@ pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), Strin
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct Suggestions { language: String, words: Vec<String>, misspelled: bool }
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions, String> {
|
||||
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 || -> Result<Suggestions, String> {
|
||||
use windows::{core::{HSTRING, PWSTR}, Win32::{Globalization::{ISpellCheckerFactory, SpellCheckerFactory}, System::Com::{CoInitializeEx, CoUninitialize, CoCreateInstance, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}}};
|
||||
unsafe {
|
||||
CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(|error| error.to_string())?;
|
||||
struct Apartment;
|
||||
impl Drop for Apartment { fn drop(&mut self) { unsafe { CoUninitialize(); } } }
|
||||
let _apartment = Apartment;
|
||||
let factory: ISpellCheckerFactory = CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string())?;
|
||||
for language in languages {
|
||||
if language.len() > 85 || language.contains('\0') { continue; }
|
||||
let tag = HSTRING::from(&language);
|
||||
if !factory.IsSupported(&tag).map_err(|error| error.to_string())?.as_bool() { continue; }
|
||||
let checker = factory.CreateSpellChecker(&tag).map_err(|error| error.to_string())?;
|
||||
let value = HSTRING::from(&word);
|
||||
if add.unwrap_or(false) {
|
||||
checker.Add(&value).map_err(|error| error.to_string())?;
|
||||
return Ok(Suggestions { language, words: Vec::new(), misspelled: false });
|
||||
}
|
||||
let errors = checker.Check(&value).map_err(|error| error.to_string())?;
|
||||
let mut error = None;
|
||||
errors.Next(&mut error).ok().map_err(|error| error.to_string())?;
|
||||
if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); }
|
||||
let suggestions = checker.Suggest(&value).map_err(|error| error.to_string())?;
|
||||
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().map_err(|error| error.to_string())?;
|
||||
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())
|
||||
}
|
||||
}).await.map_err(|error| error.to_string())?
|
||||
}
|
||||
#[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[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)] {
|
||||
|
||||
Reference in New Issue
Block a user