Update editor, workspace, Git services, appearance, and project guides
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
//! Display WebView2 spelling commands through the shared frontend menu.
|
||||
//! Keep COM event arguments on the WebView thread until selection or cancellation.
|
||||
|
||||
#[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 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> }
|
||||
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 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) -> Result<(), String> {
|
||||
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().map_err(|e| e.to_string())?.cast().map_err(|e| e.to_string())?;
|
||||
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)?;
|
||||
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 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 };
|
||||
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).map_err(|e| e.to_string())?;
|
||||
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<(), String> {
|
||||
#[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())); }).map_err(|e| e.to_string())?;
|
||||
tauri::async_runtime::spawn_blocking(move || receive.recv().map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())?
|
||||
}
|
||||
#[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<(), String> {
|
||||
#[cfg(windows)] {
|
||||
let label = window.label().to_owned();
|
||||
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false))).map_err(|e| e.to_string())?;
|
||||
}
|
||||
#[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<(), String> {
|
||||
#[cfg(windows)] {
|
||||
let label = window.label().to_owned();
|
||||
window.with_webview(move |_| native::close(&label)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
#[cfg(not(windows))] { let _ = window; }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user