Add a shared error type and shared file helpers to the Rust host

Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
This commit is contained in:
Knotty Wyvern
2026-10-27 22:41:11 -07:00
parent 69f90df571
commit bd46f3a189
18 changed files with 1103 additions and 882 deletions
+26 -23
View File
@@ -1,6 +1,8 @@
//! 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) }
@@ -109,13 +111,13 @@ mod native {
Ok(result)
}
pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> Result<(), String> {
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().map_err(|e| e.to_string())?.cast().map_err(|e| e.to_string())?;
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);
@@ -143,7 +145,7 @@ mod native {
Ok(())
}));
let mut token = 0;
core.add_ContextMenuRequested(&handler, &mut token).map_err(|e| e.to_string())?;
core.add_ContextMenuRequested(&handler, &mut token)?;
INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); });
}
Ok(())
@@ -179,21 +181,21 @@ mod native {
}
#[tauri::command]
pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<(), String> {
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())); }).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())?
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<(), String> {
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))).map_err(|e| e.to_string())?;
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false)))?;
}
#[cfg(not(windows))] { let _ = (window, request, command, fallback); }
Ok(())
@@ -208,10 +210,10 @@ pub fn close_window(app: &tauri::AppHandle, label: &str) {
}
#[tauri::command]
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), String> {
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<()> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::close(&label)).map_err(|e| e.to_string())?;
window.with_webview(move |_| native::close(&label))?;
}
#[cfg(not(windows))] { let _ = window; }
Ok(())
@@ -223,9 +225,10 @@ 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, String>;
type Reply = Result<Suggestions>;
type Request = (String, Vec<String>, bool, mpsc::SyncSender<Reply>);
static WORKER: OnceLock<mpsc::Sender<Request>> = OnceLock::new();
@@ -233,9 +236,9 @@ mod suggestions_worker {
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| error.to_string());
let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(Error::from);
let apartment_initialized = initialized.is_ok();
let factory: Result<ISpellCheckerFactory, String> = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string()));
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 {
@@ -244,26 +247,26 @@ mod suggestions_worker {
if language.len() > 85 || language.contains('\0') { continue; }
if !checkers.contains_key(&language) {
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())?;
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).map_err(|error| error.to_string())?;
checker.Add(&value)?;
return Ok(Suggestions { language, words: Vec::new(), misspelled: false });
}
let errors = checker.Check(&value).map_err(|error| error.to_string())?;
let errors = checker.Check(&value)?;
let mut error = None;
errors.Next(&mut error).ok().map_err(|error| error.to_string())?;
errors.Next(&mut error).ok()?;
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 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().map_err(|error| error.to_string())?;
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); }
@@ -287,12 +290,12 @@ mod suggestions_worker {
}
#[tauri::command]
pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions, String> {
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.map_err(|error| error.to_string())?
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()) }
}
@@ -309,7 +312,7 @@ mod tests {
let first = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false);
let cold = start.elapsed();
if let Err(error) = &first {
if error.contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; }
if error.to_string().contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; }
}
let first = first.unwrap();
assert!(first.misspelled);