Update the browser, editor, settings, and installer

This commit is contained in:
Knotty Wyvern
2026-10-12 14:46:21 -07:00
parent 909894b9c8
commit f6eaa52949
163 changed files with 146260 additions and 534 deletions
+15 -11
View File
@@ -30,6 +30,10 @@ const COMMANDS: &[&str] = &[
"resize",
"visible",
"input",
"insertText",
"edit",
"contextAction",
"frameAck",
"createProfile",
"renameProfile",
"duplicateProfile",
@@ -109,15 +113,6 @@ fn executable(app: &AppHandle) -> Result<PathBuf> {
} else {
"RuneStone-Browser"
};
let packaged = app
.path()
.resource_dir()
.map_err(fail)?
.join("browser-engine")
.join(name);
if packaged.is_file() {
return Ok(packaged);
}
#[cfg(debug_assertions)]
{
let development = Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -127,6 +122,15 @@ fn executable(app: &AppHandle) -> Result<PathBuf> {
return Ok(development);
}
}
let packaged = app
.path()
.resource_dir()
.map_err(fail)?
.join("browser-engine")
.join(name);
if packaged.is_file() {
return Ok(packaged);
}
Err("The browser runtime is missing. Build RuneStone with its browser runtime.".into())
}
@@ -224,7 +228,7 @@ impl Worker {
}
}
}
Some("state") | Some("error") => {
Some("state") | Some("error") | Some("context-menu") | Some("open-link") => {
if let Ok(routes) = routes.lock() {
for target in &routes.windows {
if let Some(id) = value["tabId"].as_str() {
@@ -410,7 +414,7 @@ impl BrowserState {
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock().map_err(fail)?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "input", "bookmark", "agentSnapshot"].contains(&command) {
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock().map_err(fail)?.owners.get(id) {
Some(window) if window == owner => {},
+3
View File
@@ -7,6 +7,7 @@ mod git;
mod completion;
mod settings;
mod spelling;
mod theme;
use pty::PtyState;
use tauri::Manager;
@@ -24,7 +25,9 @@ pub fn run() {
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.invoke_handler(tauri::generate_handler![
theme::theme_export,
spelling::spelling_menu_install,
spelling::spelling_suggestions,
spelling::spelling_menu_select,
spelling::spelling_menu_uninstall,
settings::settings_open_window,
+39 -8
View File
@@ -269,6 +269,16 @@ fn directory_files(path: &Path) -> Result<BTreeMap<String, Vec<u8>>> {
fn tree_hash(path: &Path) -> Result<String> {
Ok(fingerprint(&directory_files(path)?))
}
fn valid_version(version: &str) -> bool {
let parts: Vec<_> = version.split('.').collect();
if parts.len() != 3 || parts[..2].iter().any(|part| {
part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit())
}) {
return false;
}
let digits = parts[2].bytes().take_while(|byte| byte.is_ascii_digit()).count();
digits > 0 && parts[2][digits..].bytes().all(|byte| byte.is_ascii_lowercase())
}
fn package(source: &Path) -> Result<Package> {
let mut files = BTreeMap::new();
let mut names = BTreeSet::new();
@@ -340,13 +350,8 @@ fn package(source: &Path) -> Result<Package> {
{
return Err("The manifest needs a name, author, description, and version.".into());
}
if manifest.version.split('.').count() != 3
|| !manifest
.version
.split('.')
.all(|n| !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit()))
{
return Err("Use a plugin version such as 1.0.0.".into());
if !valid_version(&manifest.version) {
return Err("Use a plugin version such as 1.0.0 or 1.0.0a.".into());
}
relative(&manifest.entry)?;
if !manifest.entry.ends_with(".js") && !manifest.entry.ends_with(".mjs") {
@@ -1460,6 +1465,9 @@ mod tests {
#[test]
fn author_packager_produces_an_installable_repeatable_zip() {
let mut f = Fixture::new();
let manifest = fs::read_to_string(f.source.join("plugin.json"))
.unwrap().replace("1.0.0", "1.0.0a");
fs::write(f.source.join("plugin.json"), manifest).unwrap();
fs::create_dir(f.source.join("assets")).unwrap();
fs::write(f.source.join("assets/style.css"), "body { color: red; }").unwrap();
let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../scripts/packagePlugin.mjs");
@@ -1478,7 +1486,7 @@ mod tests {
);
};
build();
let path = output.join("org.test.demo-1.0.0.zip");
let path = output.join("org.test.demo-1.0.0a.zip");
let first = fs::read(&path).unwrap();
build();
assert_eq!(first, fs::read(&path).unwrap());
@@ -1490,6 +1498,7 @@ mod tests {
assert!(row.error.is_none(), "{:?}", row.error);
f.service.install("main", &row.token, false).unwrap();
let installed = f.service.row("org.test.demo").unwrap();
assert_eq!(installed.manifest.version, "1.0.0a");
assert!(!installed.enabled);
assert_eq!(
fs::read(Path::new(&installed.path).join("assets/style.css")).unwrap(),
@@ -1550,6 +1559,28 @@ mod tests {
.is_none());
}
#[test]
fn hotfix_versions_validate_and_survive_zip_install() {
for version in ["0.2.28", "0.2.28a", "0.2.28b", "0.2.28aa", "1.0.1000z"] {
assert!(valid_version(version), "{version}");
}
for version in ["", "1.0", "1.0.0.0", "1.0.a", "1.0.0A", "1.0.0a1", "1.0.0-beta", "1.0.0+build", "1.0.0é"] {
assert!(!valid_version(version), "{version}");
}
let mut f = Fixture::new();
let manifest = fs::read_to_string(f.source.join("plugin.json"))
.unwrap().replace("1.0.0", "0.2.28a");
let path = f.root.join("hotfix.zip");
archive(&path, &[("plugin.json", manifest.as_bytes()), ("main.js", b"export function activate() {}")]);
assert_eq!(package(&path).unwrap().manifest.version, "0.2.28a");
let row = f.service.inspect("main", path);
assert!(row.error.is_none());
f.service.install("main", &row.token, true).unwrap();
let mut reopened = Service::open(f.root.join("app")).unwrap();
let snapshot = reopened.snapshot().unwrap();
assert_eq!(snapshot.plugins[0].manifest.version, "0.2.28a");
assert!(snapshot.plugins[0].enabled);
}
#[test]
fn validates_paths_ids_limits_and_versions() {
for name in [
"../file",
+100 -6
View File
@@ -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)] {
+14
View File
@@ -0,0 +1,14 @@
use tauri_plugin_dialog::DialogExt;
#[tauri::command]
pub async fn theme_export(app: tauri::AppHandle, contents: String, default_name: String) -> Result<Option<String>, String> {
if contents.len() > 1_048_576 { return Err("The theme exceeds the 1 MB limit.".into()); }
serde_json::from_str::<serde_json::Value>(&contents).map_err(|_| "The theme contains invalid JSON.".to_string())?;
let name = std::path::Path::new(&default_name).file_name().and_then(|name| name.to_str()).unwrap_or("theme.json").to_string();
tauri::async_runtime::spawn_blocking(move || {
let Some(file) = app.dialog().file().set_title("Export theme").add_filter("Theme JSON", &["json"]).set_file_name(name).blocking_save_file() else { return Ok(None); };
let path = file.into_path().map_err(|error| error.to_string())?;
std::fs::write(&path, contents).map_err(|error| format!("Could not export the theme: {error}"))?;
Ok(Some(path.to_string_lossy().into_owned()))
}).await.map_err(|error| error.to_string())?
}
+1 -1
View File
@@ -404,7 +404,7 @@ fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: Path
config.title = format!("{} — RuneStone", workspace_info(&root).name);
if let Some(token) = transfer {
let id = uuid::Uuid::parse_str(&token).map_err(|_| err("Invalid tab transfer."))?;
config.url = tauri::WebviewUrl::App(format!("index.html?tabTransfer={id}").into());
config.url = tauri::WebviewUrl::App(format!("?tabTransfer={id}").into());
}
// Bind before building: the new frontend asks for its own root on startup.
state.inner.lock().map_err(|_| err("workspace lock"))?.insert(label.clone(), OpenWorkspace {