+A framework for desktop apps that run one website (or a web app you would otherwise use through a
+heavy Electron client) in a small native window and extend it in place, the way BetterDiscord
+extends Discord. You get tabs, split panes, several signed-in accounts side by side, themes,
+plugins, a signed store for them, backups and updates. You write a small adapter that says what
+the site is.
-
Make the apps you use way better. A framework for light desktop apps that wrap one
-website and extend it in place, the way BetterDiscord extends Discord.
-GPL-3.0-or-later · npm create waybetter
+The first app built on it is [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x).
+License: GPL-3.0-or-later.
-
+```sh
+npm install waybetter # page runtime, shell, CLI tools
+npm create waybetter # scaffold a plugin, a theme or a whole app
+```
-You bring a site and a small adapter that says what the site is. wayBetter gives you the rest: a
-Tauri 2 window with tabs, split panes and every account signed in side by side; a page runtime with
-a plugin API, a theme engine and string packs; a signed Store with a safe install screen; backups,
-encrypted sync and signed updates; and the tooling to scaffold, sign, scan and release it.
+Links: [source](https://git.crt.fyi/CRT/waybetter) · [npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi)
-| What you get | |
-| --- | --- |
-| **A window around the site** | Tabs in the titlebar, split panes, an address bar per tab, command palette, decks of columns, workspaces. One WebView profile per account, so all of them stay signed in. |
-| **Plugins** | `*.plugin.js` files with a declared `@permissions` line, a themed UI kit (toast, dialog, prompt), commands in the palette, live reload in developer mode. |
-| **Themes** | One JSON document: colours with contrast enforced, fonts per role (Google Fonts downloaded once, after asking), shapes, layout, decoration, icon packs, per-pane and per-account themes, a Theme Builder with a doctor report. |
-| **String packs** | Data that re-words the site's own interface: a language it does not offer, a fix, your own wording. Never code. |
-| **A signed Store** | One Ed25519-signed catalog for every wayBetter app, `waybetter://install` links, drag-and-drop and Open With, all through one install screen that shows the source, SHA-256, permissions and code first. |
-| **Release tooling** | `waybetter store`, `release`, `privacy-scan`, `build-env`, `i18n` and `strings`: sign the catalog, build binaries free of the builder's paths, and refuse to ship a build with a privacy hit. |
-
-## How it fits together
-
-
+## The three layers
A wayBetter app is one Tauri 2 window with several webviews. The framework has one piece for each
layer and does not need to know which site you wrap.
@@ -40,58 +27,9 @@ layer and does not need to know which site you wrap.
| Page runtime | `packages/runtime` (TypeScript, no dependencies) | Injected into tabs that are on the site's exact origin: one DOM hub and one fetch/XHR hub, the plugin API and its themed UI kit, the theme engine, split-view navigation, link routing, account reporting, deck columns, string packs. |
| Shell | `packages/shell` (TypeScript and React) | The local UI around the tabs: `createShell(site)` gives tabs in the titlebar, split panes, address bar, command palette, account switcher, decks and workspaces; `createPanel(site)` gives the app's own settings tab (appearance, theme builder, plugins, store, backup, developer mode). |
-Details of every module are in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
-
-## Quick start
-
-```sh
-npm create waybetter app kickapp -- --site kick.com --name "wayBetter for Kick" --yes
-```
-
-
-
-The same tool starts a plugin or a theme:
-
-```sh
-npm create waybetter plugin -- --name "Hide Trends" # add --ts for TypeScript
-npm create waybetter theme -- --name "Midnight Mint" --accent "#3ddc97"
-```
-
-The app scaffold adds the framework as a git submodule at `waybetter/` by default (`--host-source
-path` and `--host-source git` are the alternatives). After `npm run tauri dev`, replace the
-placeholder selectors in `src/site.ts` and `src-tauri/src/site.rs`. All flags:
-`npm create waybetter -- --help`, and [packages/create-waybetter](packages/create-waybetter/README.md).
-
-Inside an app, plugins and themes are plain files, the docs and examples are built in, and developer
-mode reloads them as you save:
-
-
-
-## Packages
-
-| Package | Where | What it is |
-| --- | --- | --- |
-| [`waybetter`](https://www.npmjs.com/package/waybetter) | `packages/waybetter` | The npm package: the built runtime and shell (plain ESM with `.d.ts`), JSON Schemas for themes, icon packs, catalogs and i18n, the locales, and the `waybetter` command (`dev`, `store`, `release`, `i18n`, `strings`, `privacy-scan`, `build-env`) |
-| `create-waybetter` | `packages/create-waybetter` | `npm create waybetter`: scaffolds a plugin (JS or TypeScript), a theme or a whole app. No dependencies |
-| `@waybetter/runtime` | `packages/runtime` | The page runtime (published inside `waybetter`) |
-| `@waybetter/shell` | `packages/shell` | Shell models, frame, panel and Store screens (published inside `waybetter`) |
-| `waybetter-host` | `crates/waybetter-host` | The Rust host crate (features `tauri`, `net`, `app`), used from source as a git submodule or a path dependency |
-
-## Built with wayBetter
-
-
-
-
-
-
-
-
wayBetter for X (x.com; macOS, Windows, Linux). Tabs, split panes,
-every account side by side, a deck, 14 themes, eight area plugins, string packs, drafts, and fixes
-for X's own bugs. waybetter.fyi/x
-
-
-
-Built something on wayBetter? Add it here with a pull request.
+Both TypeScript packages ship as the npm package `waybetter` (plain ESM with `.d.ts`). The Rust
+crate is used from source, as a git submodule or a path dependency. Details of every module are in
+[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
## A minimal adapter
@@ -154,6 +92,21 @@ The app itself is `waybetter_host::app` configured with an `AppConfig` and a `Si
implementation (what only your site knows: page scripts, legacy domains, link routing). Anything
else the app needs is an ordinary `#[tauri::command]` in your crate.
+## Start a project
+
+```sh
+npm create waybetter plugin -- --name "Hide Trends"
+npm create waybetter theme -- --name "Midnight Mint" --accent "#3ddc97"
+npm create waybetter app kickapp -- --site kick.com --name "wayBetter for Kick" --yes
+```
+
+The app scaffold adds the framework as a git submodule at `waybetter/` by default (`--host-source
+path` and `--host-source git` are the alternatives). Its next steps, as the tool prints them:
+`git init && git submodule add https://git.crt.fyi/CRT/waybetter.git waybetter`, then
+`npm install`, `npm run build`, `npm run tauri dev`, then replace the placeholder selectors in
+`src/site.ts` and `src-tauri/src/site.rs`. Flags: `npm create waybetter -- --help`.
+See [packages/create-waybetter](packages/create-waybetter/README.md).
+
## The dev loop
In a scaffolded app, `npm run dev` runs `waybetter dev --watch "node scripts/build.mjs --watch"`:
@@ -242,19 +195,12 @@ bun run test:create # scaffolds each kind into temp folders and checks them a
`test:create` also runs `cargo check` on a generated app (about a minute cold);
`WAYBETTER_SKIP_CARGO_CHECK=1` skips that step. Requires Bun 1.4.2+, Node 24+ and Rust 1.88+.
-## Docs
-
-- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): every module of the host, runtime and shell
-- [docs/STORE.md](docs/STORE.md): the signed catalog, install links and the install screen
-- [docs/STRING-PACKS.md](docs/STRING-PACKS.md): the string pack format and `waybetter strings check`
-- [packages/waybetter](packages/waybetter/README.md), [packages/create-waybetter](packages/create-waybetter/README.md), [packages/runtime](packages/runtime/README.md), [packages/shell](packages/shell/README.md)
-- A full app on the framework: [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x), whose docs cover themes, plugins, area plugins and translating
-
## Contributing
Issues and pull requests go to [git.crt.fyi/CRT/waybetter](https://git.crt.fyi/CRT/waybetter).
-Keep the split: generic mechanisms belong here, site-specific ones in the app.
+Keep the split: generic mechanisms belong here, site-specific ones in the app. If you built
+something on wayBetter, add it to the list below with a pull request.
-## License
-
-GPL-3.0-or-later. Made by [@CRTkafa](https://x.com/CRTkafa).
+| Project | Target | What it is |
+| --- | --- | --- |
+| [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x) | x.com | Tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. |
diff --git a/assets/readme/architecture.svg b/assets/readme/architecture.svg
deleted file mode 100644
index 5c10979..0000000
--- a/assets/readme/architecture.svg
+++ /dev/null
@@ -1,127 +0,0 @@
-
diff --git a/assets/readme/create-terminal.svg b/assets/readme/create-terminal.svg
deleted file mode 100644
index 1878c88..0000000
--- a/assets/readme/create-terminal.svg
+++ /dev/null
@@ -1,29 +0,0 @@
-
diff --git a/assets/readme/hero.webp b/assets/readme/hero.webp
deleted file mode 100644
index ecb0081..0000000
Binary files a/assets/readme/hero.webp and /dev/null differ
diff --git a/assets/readme/make.mp4 b/assets/readme/make.mp4
deleted file mode 100644
index 1681e1b..0000000
Binary files a/assets/readme/make.mp4 and /dev/null differ
diff --git a/assets/readme/make.webp b/assets/readme/make.webp
deleted file mode 100644
index 313a2b4..0000000
Binary files a/assets/readme/make.webp and /dev/null differ
diff --git a/assets/readme/showcase-panes.webp b/assets/readme/showcase-panes.webp
deleted file mode 100644
index ac4baaa..0000000
Binary files a/assets/readme/showcase-panes.webp and /dev/null differ
diff --git a/assets/readme/showcase-themes.webp b/assets/readme/showcase-themes.webp
deleted file mode 100644
index 7f932c4..0000000
Binary files a/assets/readme/showcase-themes.webp and /dev/null differ
diff --git a/crates/waybetter-host/Cargo.lock b/crates/waybetter-host/Cargo.lock
index f2829c1..e3b77c8 100644
--- a/crates/waybetter-host/Cargo.lock
+++ b/crates/waybetter-host/Cargo.lock
@@ -1207,18 +1207,6 @@ dependencies = [
"pin-project-lite",
]
-[[package]]
-name = "fallible-iterator"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
-
-[[package]]
-name = "fallible-streaming-iterator"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
-
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -1739,30 +1727,12 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
-[[package]]
-name = "hashbrown"
-version = "0.16.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
-dependencies = [
- "foldhash",
-]
-
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
-[[package]]
-name = "hashlink"
-version = "0.11.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f"
-dependencies = [
- "hashbrown 0.16.1",
-]
-
[[package]]
name = "heck"
version = "0.4.1"
@@ -2388,17 +2358,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "libsqlite3-sys"
-version = "0.36.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a"
-dependencies = [
- "cc",
- "pkg-config",
- "vcpkg",
-]
-
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -3465,31 +3424,6 @@ dependencies = [
"windows-sys 0.52.0",
]
-[[package]]
-name = "rsqlite-vfs"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
-dependencies = [
- "hashbrown 0.16.1",
- "thiserror 2.0.21",
-]
-
-[[package]]
-name = "rusqlite"
-version = "0.38.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3"
-dependencies = [
- "bitflags 2.13.2",
- "fallible-iterator",
- "fallible-streaming-iterator",
- "hashlink",
- "libsqlite3-sys",
- "smallvec",
- "sqlite-wasm-rs",
-]
-
[[package]]
name = "rust-ini"
version = "0.21.3"
@@ -4037,18 +3971,6 @@ dependencies = [
"der",
]
-[[package]]
-name = "sqlite-wasm-rs"
-version = "0.5.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
-dependencies = [
- "cc",
- "js-sys",
- "rsqlite-vfs",
- "wasm-bindgen",
-]
-
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -5146,12 +5068,6 @@ dependencies = [
"wasm-bindgen",
]
-[[package]]
-name = "vcpkg"
-version = "0.2.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
-
[[package]]
name = "version-compare"
version = "0.2.1"
@@ -5304,7 +5220,6 @@ dependencies = [
"minisign-verify",
"objc2-app-kit",
"reqwest",
- "rusqlite",
"rustls",
"serde",
"serde_json",
diff --git a/crates/waybetter-host/Cargo.toml b/crates/waybetter-host/Cargo.toml
index 7158692..f203e14 100644
--- a/crates/waybetter-host/Cargo.toml
+++ b/crates/waybetter-host/Cargo.toml
@@ -17,8 +17,6 @@ default = []
tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:tauri-plugin-updater", "dep:tokio", "dep:arboard", "dep:clipboard-win", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"]
# Store downloads (`store::net`): allow-listed https, no redirects or cookies, size caps.
net = ["dep:reqwest", "dep:rustls"]
-# The drafts vault (`vault`): the app's local SQLite store of drafts with CAS revisions.
-vault = ["dep:rusqlite"]
# The whole app (`app::run_app`): window, shell and tab webviews, the generic commands and the
# Tauri plugins every wayBetter app registers.
app = ["tauri", "dep:tauri-plugin-single-instance", "dep:tauri-plugin-deep-link", "dep:tauri-plugin-window-state", "dep:tauri-plugin-opener", "dep:tauri-plugin-process", "dep:tauri-plugin-dialog"]
@@ -62,7 +60,6 @@ tauri-plugin-window-state = { version = "2", optional = true }
tauri-plugin-opener = { version = "2", optional = true }
tauri-plugin-process = { version = "2", optional = true }
tauri-plugin-dialog = { version = "2", optional = true }
-rusqlite = { version = "0.38", features = ["bundled"], optional = true }
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"], optional = true }
rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true }
diff --git a/crates/waybetter-host/src/alerts.rs b/crates/waybetter-host/src/alerts.rs
index 0c040b5..d3a1708 100644
--- a/crates/waybetter-host/src/alerts.rs
+++ b/crates/waybetter-host/src/alerts.rs
@@ -7,16 +7,6 @@ use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Duration, Instant};
-/// What an app declares about its alerts for the host's settings commands
-/// ([`crate::alerts_commands`]): where they are saved and how the page runtime takes the keywords
-/// (`window...set(keywords)`, else parked in `window.`).
-#[derive(Clone, Copy, Debug)]
-pub struct AlertsConfig {
- pub file: &'static str,
- pub member: &'static str,
- pub queue: &'static str,
-}
-
pub const MAX_KEYWORDS: usize = 32;
pub const MIN_KEYWORD_CHARS: usize = 2;
pub const MAX_KEYWORD_CHARS: usize = 64;
diff --git a/crates/waybetter-host/src/alerts_commands.rs b/crates/waybetter-host/src/alerts_commands.rs
deleted file mode 100644
index b26fc62..0000000
--- a/crates/waybetter-host/src/alerts_commands.rs
+++ /dev/null
@@ -1,78 +0,0 @@
-//! Keyword alert settings, native side, for every app that sets [`crate::app::AppConfig::alerts`]:
-//! the shell-only `alerts_get` / `alerts_set` ([`crate::commands::ALERTS`]) over the owner's
-//! [`AlertSettings`] (saved in app data, validated by [`crate::alerts`]). Site tabs gain no command
-//! here: native code hands the page runtime the keywords to watch ([`script`]) at every page load
-//! and whenever they change. What a match looks like and the notification are the app's.
-
-use crate::alerts::AlertSettings;
-use crate::app::config;
-use crate::host::{eval_in_site_tabs, read_json, shell_only, write_json};
-use crate::tabs::deliver_script;
-use std::sync::{Mutex, MutexGuard};
-use tauri::{AppHandle, Manager, Webview};
-
-pub use crate::alerts::AlertsConfig;
-
-struct AlertState(Mutex);
-
-/// Loads the saved settings. Does nothing unless the app set [`crate::app::AppConfig::alerts`].
-pub(crate) fn init(app: &AppHandle) {
- let Some(alerts) = config(app).alerts else { return };
- let settings = read_json::(app, alerts.file).and_then(|settings| settings.validated().ok()).unwrap_or_default();
- app.manage(AlertState(Mutex::new(settings)));
-}
-
-fn state(app: &AppHandle) -> Result, String> {
- app.try_state::()
- .ok_or("DATABASE: alert state unavailable; restart safely")?
- .inner()
- .0
- .lock()
- .map_err(|_| "DATABASE: alert state unavailable; restart safely".into())
-}
-
-/// The owner's alert settings.
-pub fn settings(app: &AppHandle) -> Result {
- Ok(state(app)?.clone())
-}
-
-/// The script that hands the page runtime the keywords to watch (empty = alerts off).
-pub fn script(app: &AppHandle) -> String {
- let (Some(alerts), Ok(settings)) = (config(app).alerts, settings(app)) else { return String::new() };
- script_for(app, alerts, &settings)
-}
-
-fn script_for(app: &AppHandle, alerts: &AlertsConfig, settings: &AlertSettings) -> String {
- let keywords = serde_json::to_string(settings.active_keywords()).unwrap_or_else(|_| "[]".into());
- deliver_script(config(app).site.runtime_global, alerts.member, "set", alerts.queue, &keywords)
-}
-
-/// Validates, saves and keeps the settings, and does not touch the tabs: for the app's own
-/// writers (a backup import), which then evaluate [`script`] themselves.
-pub fn store(app: &AppHandle, settings: AlertSettings) -> Result {
- let alerts = config(app).alerts.ok_or_else(|| "UNAVAILABLE: this app has no alerts".to_owned())?;
- let settings = settings.validated()?;
- // The lock is held across the write so concurrent saves cannot leave disk and memory disagreeing.
- let mut current = state(app)?;
- write_json(app, alerts.file, &settings)?;
- *current = settings.clone();
- Ok(settings)
-}
-
-#[tauri::command]
-pub(crate) async fn alerts_get(webview: Webview, app: AppHandle) -> Result {
- shell_only(&webview)?;
- settings(&app)
-}
-
-#[tauri::command]
-pub(crate) async fn alerts_set(webview: Webview, app: AppHandle, settings: AlertSettings) -> Result {
- shell_only(&webview)?;
- let settings = store(&app, settings)?;
- eval_in_site_tabs(&app, config(&app).site, &script(&app));
- Ok(settings)
-}
-
-pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
- tauri::generate_handler![alerts_get, alerts_set]
-}
diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs
index 3a4249d..8e1b1e5 100644
--- a/crates/waybetter-host/src/app.rs
+++ b/crates/waybetter-host/src/app.rs
@@ -96,16 +96,6 @@ pub struct AppConfig {
/// [`commands::DEV`] and runs the watcher while it is on; the theme file is the app's
/// ([`SiteHooks::dev_theme_apply`]).
pub dev: bool,
- /// Site themes (the owner's theme, account and pane themes, the live preview): serves
- /// [`commands::THEME`]; the app names its built-in themes and the files they are saved in.
- pub themes: Option<&'static crate::theme_commands::ThemeConfig>,
- /// Keyword alert settings (saved in app data, handed to the page runtime): serves
- /// [`commands::ALERTS`]; the match and the notification are the app's.
- pub alerts: Option<&'static crate::alerts_commands::AlertsConfig>,
- /// The drafts vault (a SQLite database in app data with CAS revisions): serves
- /// [`commands::VAULT`]; the rules (kinds, limits, capture ownership) are the app's.
- #[cfg(feature = "vault")]
- pub vault: Option<&'static crate::vault_commands::VaultConfig>,
/// Native updates and the hotfix channel: serves [`commands::UPDATE`] and runs the update loop.
/// Needs `updater` (the plugin) and the `net` feature.
#[cfg(feature = "net")]
@@ -136,10 +126,6 @@ impl AppConfig {
fonts: false,
sync: false,
dev: false,
- themes: None,
- alerts: None,
- #[cfg(feature = "vault")]
- vault: None,
#[cfg(feature = "net")]
updates: None,
}
@@ -158,25 +144,6 @@ impl AppConfig {
self
}
- /// Serves the theme commands ([`commands::THEME`]) with these built-in themes.
- pub const fn with_themes(mut self, themes: &'static crate::theme_commands::ThemeConfig) -> Self {
- self.themes = Some(themes);
- self
- }
-
- /// Serves the alert settings commands ([`commands::ALERTS`]).
- pub const fn with_alerts(mut self, alerts: &'static crate::alerts_commands::AlertsConfig) -> Self {
- self.alerts = Some(alerts);
- self
- }
-
- /// Serves the drafts vault commands ([`commands::VAULT`]) over this database and rules.
- #[cfg(feature = "vault")]
- pub const fn with_vault(mut self, vault: &'static crate::vault_commands::VaultConfig) -> Self {
- self.vault = Some(vault);
- self
- }
-
/// Serves the sync commands ([`commands::SYNC`]).
pub const fn with_sync(mut self) -> Self {
self.sync = true;
@@ -279,8 +246,8 @@ pub trait SiteHooks: Send + Sync + 'static {
/// A tab webview was created.
fn tab_created(&self, _app: &AppHandle) {}
- /// A Google font was installed or removed ([`commands::GFONTS`]); the host has already given the
- /// site tabs their theme, and the font bytes, again ([`crate::theme_commands::apply`]).
+ /// A Google font was installed or removed ([`commands::GFONTS`]): give the site tabs their
+ /// theme, and the font bytes, again.
fn fonts_changed(&self, _app: &AppHandle) {}
/// The app's native settings as backup sections (themes, plugins, tweaks, ... keyed by section
@@ -722,31 +689,13 @@ async fn tab_zoom(webview: Webview, app: AppHandle, id: String, factor: Option) -> Result<(), String> {
shell_only(&webview)?;
host::tab_find(&app, &id, &action, query.as_deref())
}
-/// Sets the native menu bar (macOS) from the shell's description ([`crate::menu`]); other platforms keep the
-/// in-app menu and answer false. Choosing an item sends its id to the shell (`native-menu`).
-#[tauri::command]
-async fn menu_set(webview: Webview, app: AppHandle, spec: serde_json::Value) -> Result {
- shell_only(&webview)?;
- let spec = crate::menu::parse(spec)?;
- #[cfg(target_os = "macos")]
- {
- crate::menu::set(&app, &spec)?;
- Ok(true)
- }
- #[cfg(not(target_os = "macos"))]
- {
- let _ = (app, spec);
- Ok(false)
- }
-}
-
/// Whether safe mode is on ([`crate::safe`]): the shell shows it in the titlebar and drops its chrome theme.
#[tauri::command]
async fn safe_mode_get(webview: Webview) -> Result {
@@ -971,14 +920,6 @@ async fn features_set(webview: Webview, app: AppHandle, features: serde_json::Ma
set_features(&app, features)
}
-/// Runs a plugin's palette command in tab `id`: only a command that tab reported, only while it is
-/// on the site. The command's code runs in the page; the tab gets keyboard focus for what it opens.
-#[tauri::command]
-async fn tab_run_command(webview: Webview, app: AppHandle, id: String, command: String) -> Result<(), String> {
- shell_only(&webview)?;
- crate::tab_commands::run(&app, &id, &command)
-}
-
/// The onboarding mode: what was chosen, whether the first-run screen was answered, and whether
/// this app was set up before modes existed.
#[tauri::command]
@@ -1165,7 +1106,6 @@ fn tab_builder(app: &AppHandle, hooks: &Arc, tab: &NewTab, url: U
}
let finished = matches!(payload.event(), PageLoadEvent::Finished);
if !finished {
- crate::tab_commands::cleared(app, tab.label());
load_hooks.page_started(app, &tab);
// An engine that resets page zoom on navigation still shows this tab's.
host::restore_tab_zoom(app, &tab);
@@ -1254,7 +1194,6 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's
tab_action,
tab_zoom,
tab_find,
- menu_set,
safe_mode_get,
safe_mode_set,
diag_get,
@@ -1280,7 +1219,6 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's
mode_set,
settings_get,
settings_set,
- tab_run_command,
tab_shortcut,
tab_link_drag,
open_panel
@@ -1308,24 +1246,6 @@ fn dev_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'st
crate::dev_commands::handler()
}
-/// The alert settings commands ([`commands::ALERTS`]).
-fn alerts_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
- crate::alerts_commands::handler()
-}
-
-/// The drafts vault commands ([`commands::VAULT`]); without the `vault` feature none are served.
-fn vault_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
- #[cfg(feature = "vault")]
- return crate::vault_commands::handler();
- #[cfg(not(feature = "vault"))]
- |_: tauri::ipc::Invoke| false
-}
-
-/// The theme commands ([`commands::THEME`]).
-fn theme_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
- crate::theme_commands::handler()
-}
-
/// The workspaces and sync commands ([`commands::WORKSPACES`], [`commands::SYNC`]).
fn sync_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
crate::sync_commands::handler()
@@ -1394,31 +1314,16 @@ impl App {
let update_handler = update_handler();
let sync_handler = sync_handler();
let dev_handler = dev_handler();
- let theme_handler = theme_handler();
- let alerts_handler = alerts_handler();
- let vault_handler = vault_handler();
let backup_handler = backup_handler();
let builder = tauri::Builder::::default()
- // The native menu bar's choices go to the shell, which runs them ([`crate::menu`]).
- .on_menu_event(|app, event| {
- #[cfg(target_os = "macos")]
- if let Some(id) = crate::menu::chosen(event.id().as_ref()) {
- emit_shell(app, crate::menu::EVENT_NATIVE_MENU, id.to_owned());
- }
- #[cfg(not(target_os = "macos"))]
- let _ = (app, event);
- })
// Must be first: a second launch focuses the running window instead of fighting over
// the app's data and WebView profile (and hands over its link).
- .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
+ .plugin(tauri_plugin_single_instance::init(|app, _, _| {
if let Some(window) = app.get_window(policy::MAIN_LABEL) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
- // A double-click or "Open with" on a file while the app runs: its path arrives here.
- #[cfg(feature = "net")]
- crate::store_commands::opened_args(app, &_args, &_cwd);
}));
// Install links (after single-instance, which forwards a second launch's link).
let builder = if config.deep_link { builder.plugin(tauri_plugin_deep_link::init()) } else { builder };
@@ -1492,10 +1397,6 @@ impl App {
crate::media_commands::init(&handle);
crate::sync_commands::init(&handle);
crate::dev_commands::init(&handle);
- crate::theme_commands::init(&handle);
- crate::alerts_commands::init(&handle);
- #[cfg(feature = "vault")]
- crate::vault_commands::init(&handle)?;
#[cfg(feature = "net")]
crate::fonts_commands::init(&handle);
#[cfg(feature = "net")]
@@ -1528,57 +1429,14 @@ impl App {
dev_handler(invoke)
} else if commands::BACKUP.contains(&invoke.message.command()) {
backup_handler(invoke)
- } else if commands::THEME.contains(&invoke.message.command()) {
- theme_handler(invoke)
- } else if commands::ALERTS.contains(&invoke.message.command()) {
- alerts_handler(invoke)
- } else if commands::VAULT.contains(&invoke.message.command()) {
- vault_handler(invoke)
} else if commands::is_host(invoke.message.command()) {
host_handler(invoke)
} else {
handler(invoke)
}
})
- .build(context)
- .unwrap_or_else(|error| panic!("Failed to launch {}: {error}", config.title))
- .run(|app, event| on_run_event(app, &event));
- }
-}
-
-/// Run-loop events: the macOS close-hides rule, and why the app is going away for `--diag` ([`crate::diag`]): an exit request with its code (None is a
-/// polite quit from outside: Cmd+Q, the Dock, or another app such as an auto-quitter closing the last
-/// window), window close/destroy events and the final exit. Nothing is written without diagnostics.
-fn on_run_event(app: &AppHandle, event: &tauri::RunEvent) {
- // macOS: the red close button sends the main window to the Dock (minimized, not hidden: an auto-quitter
- // such as Swift Quit terminates an app whose window list goes empty, but not one with a minimized window)
- // and the app keeps running; a Dock click shows it
- // again; Cmd+Q still quits (an exit request, not a window close).
- #[cfg(target_os = "macos")]
- match event {
- tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::CloseRequested { api, .. }, .. } if label == policy::MAIN_LABEL => {
- api.prevent_close();
- if let Some(window) = app.get_window(policy::MAIN_LABEL) {
- let _ = window.minimize();
- }
- }
- tauri::RunEvent::Reopen { .. } => {
- if let Some(window) = app.get_window(policy::MAIN_LABEL) {
- let _ = window.unminimize();
- let _ = window.show();
- let _ = window.set_focus();
- }
- }
- _ => {}
- }
- #[cfg(not(target_os = "macos"))]
- let _ = app;
- match event {
- tauri::RunEvent::ExitRequested { code, .. } => crate::diag::log("host", &format!("exit requested code={code:?}")),
- tauri::RunEvent::Exit => crate::diag::log("host", "exit"),
- tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::CloseRequested { .. }, .. } => crate::diag::log("host", &format!("window {label} close requested")),
- tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } => crate::diag::log("host", &format!("window {label} destroyed")),
- _ => {}
+ .run(context)
+ .unwrap_or_else(|error| panic!("Failed to launch {}: {error}", config.title));
}
}
diff --git a/crates/waybetter-host/src/commands.rs b/crates/waybetter-host/src/commands.rs
index 5b4e541..b3927d2 100644
--- a/crates/waybetter-host/src/commands.rs
+++ b/crates/waybetter-host/src/commands.rs
@@ -13,7 +13,6 @@ pub const SHELL: &[&str] = &[
"tab_action",
"tab_zoom",
"tab_find",
- "menu_set",
"safe_mode_get",
"safe_mode_set",
"diag_get",
@@ -39,7 +38,6 @@ pub const SHELL: &[&str] = &[
"mode_set",
"settings_get",
"settings_set",
- "tab_run_command",
];
/// Tab-only: any tab webview, speaking only about itself.
@@ -56,7 +54,6 @@ pub const STORE: &[&str] = &[
"install_pending",
"install_stage_link",
"install_stage_file",
- "install_stage_opened",
"install_cancel",
"install_commit",
"plugin_remove",
@@ -121,24 +118,9 @@ pub const DEV: &[&str] = &["dev_get", "dev_set", "dev_pick_theme", "dev_clear_th
/// (`SiteHooks::backup_sections`, `backup_drafts`, `backup_apply`).
pub const BACKUP: &[&str] = &["backup_collect", "backup_export_file", "backup_open_file", "backup_apply"];
-/// Shell-only, optional: site themes (the owner's theme, account and pane themes, the Theme
-/// Builder's live preview), served when the app sets `AppConfig::themes`. An app that uses them
-/// grants these to the shell (`testkit::Capabilities::assert_shell_only_group`).
-pub const THEME: &[&str] = &["theme_get", "theme_set", "theme_preview", "theme_scopes_get", "theme_scopes_set"];
-
-/// Shell-only, optional: the keyword alert settings (`alerts_get`, `alerts_set`), served when the app
-/// sets `AppConfig::alerts`. An app that uses them grants these to the shell
-/// (`testkit::Capabilities::assert_shell_only_group`).
-pub const ALERTS: &[&str] = &["alerts_get", "alerts_set"];
-
-/// Shell-only, optional: the drafts vault (list, save with a revision check, revisions, archive and
-/// restore, observations, one consistent export), served when the app sets `AppConfig::vault`. An app
-/// that uses them grants these to the shell (`testkit::Capabilities::assert_shell_only_group`).
-pub const VAULT: &[&str] = &["draft_list", "draft_save", "draft_revisions", "draft_status", "observation_list", "data_export"];
-
/// Whether `command` is one of the host's (dispatched to the host, never to the app's handler).
pub fn is_host(command: &str) -> bool {
- SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command) || STORE.contains(&command) || MEDIA.contains(&command) || GFONTS.contains(&command) || UPDATE.contains(&command) || WORKSPACES.contains(&command) || SYNC.contains(&command) || DEV.contains(&command) || BACKUP.contains(&command) || THEME.contains(&command) || ALERTS.contains(&command) || VAULT.contains(&command)
+ SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command) || STORE.contains(&command) || MEDIA.contains(&command) || GFONTS.contains(&command) || UPDATE.contains(&command) || WORKSPACES.contains(&command) || SYNC.contains(&command) || DEV.contains(&command) || BACKUP.contains(&command)
}
/// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`).
@@ -150,11 +132,11 @@ pub fn permission(command: &str) -> String {
/// once). Leaked on purpose: tauri-build wants `&'static` and a build script runs once.
///
/// ```ignore
-/// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["capture_draft"]))
+/// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"]))
/// ```
pub fn manifest(app: &[&'static str]) -> &'static [&'static str] {
- let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len() + STORE.len() + MEDIA.len() + GFONTS.len() + UPDATE.len() + WORKSPACES.len() + SYNC.len() + DEV.len() + BACKUP.len() + THEME.len() + ALERTS.len() + VAULT.len());
- for command in app.iter().chain(SHELL).chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP).chain(THEME).chain(ALERTS).chain(VAULT) {
+ let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len() + STORE.len() + MEDIA.len() + GFONTS.len() + UPDATE.len() + WORKSPACES.len() + SYNC.len() + DEV.len() + BACKUP.len());
+ for command in app.iter().chain(SHELL).chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP) {
if !all.contains(command) {
all.push(command);
}
@@ -168,20 +150,20 @@ mod tests {
#[test]
fn manifest_adds_the_host_commands_once() {
- let all = manifest(&["capture_draft", "tabs_sync"]);
- assert_eq!(all[0], "capture_draft");
+ let all = manifest(&["draft_list", "tabs_sync"]);
+ assert_eq!(all[0], "draft_list");
assert_eq!(all.iter().filter(|c| **c == "tabs_sync").count(), 1);
- for command in SHELL.iter().chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP).chain(THEME).chain(ALERTS).chain(VAULT) {
+ for command in SHELL.iter().chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP) {
assert!(all.contains(command), "{command}");
assert!(is_host(command));
}
- assert!(!is_host("capture_draft"));
+ assert!(!is_host("draft_list"));
assert_eq!(permission("tab_link_drag"), "allow-tab-link-drag");
}
#[test]
fn shell_and_tab_commands_do_not_overlap() {
- assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command) || STORE.contains(command) || MEDIA.contains(command) || GFONTS.contains(command) || UPDATE.contains(command) || WORKSPACES.contains(command) || SYNC.contains(command) || DEV.contains(command) || BACKUP.contains(command) || THEME.contains(command) || ALERTS.contains(command)));
+ assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command) || STORE.contains(command) || MEDIA.contains(command) || GFONTS.contains(command) || UPDATE.contains(command) || WORKSPACES.contains(command) || SYNC.contains(command) || DEV.contains(command) || BACKUP.contains(command)));
assert!(!TAB.iter().any(|command| SITE.contains(command)));
}
}
diff --git a/crates/waybetter-host/src/diag.rs b/crates/waybetter-host/src/diag.rs
index e7bcb18..642ecc5 100644
--- a/crates/waybetter-host/src/diag.rs
+++ b/crates/waybetter-host/src/diag.rs
@@ -4,7 +4,7 @@
//! overlays and `shell_raise` calls with their results, native focus calls, and the shell document's
//! focus, blur and visibility changes. A line is an event name and a few words: never a URL, a
//! query, page text or anything about an account ([`clean`] keeps plain printable ASCII only and
-//! caps the length). Each launch with diagnostics on starts a new file; the one before it is kept as `diag.prev.log`.
+//! caps the length). The file is truncated at each launch with diagnostics on.
use std::io::Write;
use std::path::PathBuf;
@@ -15,7 +15,6 @@ use std::time::Instant;
pub const ARG: &str = "--diag";
pub const ENV: &str = "WAYBETTER_DIAG";
pub const FILE: &str = "diag.log";
-pub const PREVIOUS: &str = "diag.prev.log";
const MAX_LINE: usize = 300;
static ON: AtomicBool = AtomicBool::new(false);
@@ -35,13 +34,10 @@ pub fn clean(line: &str) -> String {
line.chars().take(MAX_LINE).map(|ch| if (' '..='~').contains(&ch) { ch } else { '?' }).collect()
}
-/// Starts writing to `dir/diag.log` (created, truncated); the previous run's log is kept as `diag.prev.log`.
-/// Nothing happens without a folder.
+/// Starts writing to `dir/diag.log` (created, truncated). Nothing happens without a folder.
pub fn start(dir: Option) {
let Some(dir) = dir else { return };
let _ = std::fs::create_dir_all(&dir);
- // A run that went wrong is usually relaunched at once: keep its log.
- let _ = std::fs::rename(dir.join(FILE), dir.join(PREVIOUS));
if let Ok(file) = std::fs::File::create(dir.join(FILE)) {
if let Ok(mut sink) = SINK.lock() {
*sink = Some((file, Instant::now()));
diff --git a/crates/waybetter-host/src/find.rs b/crates/waybetter-host/src/find.rs
index fa37a90..9c648eb 100644
--- a/crates/waybetter-host/src/find.rs
+++ b/crates/waybetter-host/src/find.rs
@@ -6,7 +6,7 @@
//! (Windows, WebView2 Runtime with `ICoreWebView2_28`; its own find bar suppressed), which also
//! reports the match count and the active match (`tab-find` events to the shell). Everywhere else
//! (macOS, Linux, an older WebView2 Runtime) native code evaluates [`fallback_script`] in the tab:
-//! the page's matches drawn with the CSS Custom Highlight API (see [`fallback_script`]), which counts nothing.
+//! the engine's `window.find`, which selects the next match and scrolls to it but counts nothing.
//!
//! The query is data: it goes from the shell to the engine and is kept nowhere (no file, no log,
//! no state in this crate). Tabs gain no command; a tab may only forward the key name `find`
@@ -86,79 +86,23 @@ pub fn request(action: &str, query: Option<&str>) -> Result
Ok(FindRequest { action, query: if action == FindAction::Stop { None } else { query } })
}
-/// The script native code evaluates where the engine's find cannot be driven natively (macOS,
-/// Linux, an old WebView2): the page's matches drawn with the CSS Custom Highlight API (every match
-/// tinted, the active one stronger and scrolled into view; independent of window focus, which the
-/// engine's selection-based `window.find` is not: it shows nothing while the page is not the key
-/// view), or `window.find` where an engine lacks that API. `stop` removes the highlights.
-/// The query appears only as a JSON string literal; nothing is sent anywhere or stored: the
-/// matches live in the page's highlight registry until `stop`, the query nowhere.
+/// The script native code evaluates where the engine's find cannot be driven natively: the
+/// engine's `window.find` (case-insensitive, wrapping), or clearing the selection for `stop`.
+/// The query appears only as a JSON string literal; nothing is sent anywhere or stored in the page.
pub fn fallback_script(request: &FindRequest) -> String {
- let action = match request.action {
- FindAction::Start => "start",
- FindAction::Next => "next",
- FindAction::Previous => "previous",
- FindAction::Stop => "stop",
- };
- let query = request.query.as_ref().map_or_else(|| "null".to_owned(), |query| serde_json::to_string(query).unwrap_or_else(|_| "null".into()));
- HIGHLIGHT_SCRIPT.replace("__ACTION__", action).replace("__QUERY__", &query)
-}
-
-const HIGHLIGHT_SCRIPT: &str = r#"(()=>{try{
-const action="__ACTION__",query=__QUERY__;
-const H=window.CSS&&CSS.highlights,ALL="wb-find",ACT="wb-find-active";
-const sheets=()=>document.adoptedStyleSheets||[];
-const stop=()=>{if(H){H.delete(ALL);H.delete(ACT);}try{document.adoptedStyleSheets=sheets().filter(s=>!s.__wbFind);}catch(e){}};
-if(action==="stop"||(action==="start"&&query===null)){stop();return;}
-if(!H||typeof Highlight!=="function"){
- if(query!==null&&typeof window.find==="function"){if(action==="start"){const s=getSelection();if(s)s.removeAllRanges();}window.find(query,false,action==="previous",true,false,false,false);}
- return;
-}
-const live=r=>r.startContainer.isConnected&&r.endContainer.isConnected;
-const collect=q=>{
- const needle=q.toLowerCase(),out=[];
- if(!needle||needle.length!==q.length)return out;
- const walker=document.createTreeWalker(document.body||document.documentElement,NodeFilter.SHOW_TEXT,{acceptNode:n=>{const p=n.parentElement;return !p||/^(SCRIPT|STYLE|NOSCRIPT|TEXTAREA)$/.test(p.tagName)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});
- for(let n;(n=walker.nextNode())&&out.length<2000;){
- const t=n.nodeValue;
- if(t.length=0&&out.length<2000;i=hay.indexOf(needle,i+needle.length)){
- const r=document.createRange();r.setStart(n,i);r.setEnd(n,i+needle.length);out.push(r);
+ match (&request.action, &request.query) {
+ (FindAction::Stop, _) | (_, None) => {
+ "(()=>{try{const s=getSelection();if(s)s.removeAllRanges();}catch(e){}})();".to_owned()
+ }
+ (action, Some(query)) => {
+ let text = serde_json::to_string(query).unwrap_or_else(|_| "\"\"".into());
+ // A new query starts from the top of the page; next/previous continue from the selection.
+ let restart = if *action == FindAction::Start { "const s=getSelection();if(s)s.removeAllRanges();" } else { "" };
+ let backwards = *action == FindAction::Previous;
+ format!("(()=>{{try{{{restart}if(typeof window.find==='function')window.find({text},false,{backwards},true,false,false,false);}}catch(e){{}}}})();")
+ }
}
- }
- return out;
-};
-const active=H.get(ACT);
-const current=active?[...active][0]:null;
-let all,idx;
-if(action==="start"){
- all=collect(query);
- idx=all.findIndex(r=>r.getBoundingClientRect().bottom>0);
- if(idx<0)idx=0;
-}else{
- all=[...(H.get(ALL)||[])].filter(live);
- if(!all.length&&query!==null)all=collect(query);
- const at=current?all.indexOf(current):-1;
- idx=!all.length?-1:action==="previous"?(at<=0?all.length-1:at-1):(at+1)%all.length;
}
-H.set(ALL,new Highlight(...all));
-if(idx<0||!all.length){H.delete(ACT);}
-else{
- const mark=new Highlight(all[idx]);mark.priority=1;H.set(ACT,mark);
- const box=all[idx].getBoundingClientRect();
- if(box.top<0||box.bottom>innerHeight){const el=all[idx].startContainer.parentElement;if(el)el.scrollIntoView({block:"center",inline:"nearest"});}
-}
-if(!sheets().some(s=>s.__wbFind)){
- const sheet=new CSSStyleSheet();
- sheet.replaceSync("::highlight(wb-find){background-color:rgba(255,213,74,.55);color:inherit}::highlight(wb-find-active){background-color:#ff9632;color:#000}");
- sheet.__wbFind=true;
- document.adoptedStyleSheets=[...sheets(),sheet];
-}
-}catch(e){}})();"#;
#[cfg(test)]
mod tests {
@@ -183,16 +127,19 @@ mod tests {
#[test]
fn the_fallback_script_carries_the_query_only_as_a_string_literal() {
let script = fallback_script(&request("start", Some("it's \"quoted\" \\ ${x} `y`")).unwrap());
- assert!(script.contains(r#"const action="start",query="it's \"quoted\" \\ ${x} `y`";"#), "{script}");
+ assert!(script.contains(r#"window.find("it's \"quoted\" \\ ${x} `y`",false,false,true"#), "{script}");
+ assert!(script.contains("removeAllRanges"), "a new query starts from the top");
let next = fallback_script(&request("next", Some("a")).unwrap());
- assert!(next.contains(r#"const action="next",query="a";"#));
- assert!(fallback_script(&request("previous", Some("a")).unwrap()).contains(r#"action="previous""#));
- // Stop and a step without a query carry no query: stop clears the highlights, a step uses the page's matches.
- assert!(fallback_script(&request("stop", None).unwrap()).contains(r#"action="stop",query=null;"#));
- assert!(fallback_script(&request("next", None).unwrap()).contains("query=null;"));
- // Nothing leaves the page or stays in it: no network, storage, invoke or markup writes.
+ assert!(next.contains(r#"window.find("a",false,false,true"#) && !next.contains("removeAllRanges"));
+ assert!(fallback_script(&request("previous", Some("a")).unwrap()).contains(r#"window.find("a",false,true,true"#));
+ // Stop (and a step without a query) only clears the selection.
+ for request in [request("stop", None).unwrap(), request("next", None).unwrap()] {
+ let script = fallback_script(&request);
+ assert!(script.contains("removeAllRanges") && !script.contains("window.find"), "{script}");
+ }
+ // Nothing leaves the page or stays in it: no network, storage, invoke or DOM writes.
for script in [script, next] {
- for forbidden in ["fetch", "XMLHttpRequest", "localStorage", "sessionStorage", "invoke", "postMessage", "innerHTML", "document.cookie", "eval(", "__ACTION__", "__QUERY__"] {
+ for forbidden in ["fetch", "XMLHttpRequest", "localStorage", "sessionStorage", "invoke", "postMessage", "innerHTML", "document.cookie", "eval("] {
assert!(!script.contains(forbidden), "{forbidden} in {script}");
}
}
diff --git a/crates/waybetter-host/src/fonts_commands.rs b/crates/waybetter-host/src/fonts_commands.rs
index bd005de..c1423db 100644
--- a/crates/waybetter-host/src/fonts_commands.rs
+++ b/crates/waybetter-host/src/fonts_commands.rs
@@ -23,7 +23,6 @@ pub(crate) fn init(app: &AppHandle) {
}
fn changed(app: &AppHandle) {
- crate::theme_commands::apply(app);
crate::app::hooks(app).fonts_changed(app);
}
diff --git a/crates/waybetter-host/src/host.rs b/crates/waybetter-host/src/host.rs
index 4f63653..489556a 100644
--- a/crates/waybetter-host/src/host.rs
+++ b/crates/waybetter-host/src/host.rs
@@ -166,7 +166,7 @@ pub fn forget_tab_zoom(app: &AppHandle, id: &str) {
/// `tab_find`: searches tab `id`'s page ([`crate::find`]). The engine's own find where this build
/// can drive it (WebView2's `ICoreWebView2Find`, which reports counts through `tab-find` events);
-/// otherwise the evaluated Custom Highlight fallback ([`crate::find::fallback_script`]). The query is kept nowhere.
+/// otherwise the evaluated `window.find` fallback. The query is kept nowhere.
pub fn tab_find(app: &AppHandle, id: &str, action: &str, query: Option<&str>) -> Result<(), String> {
if !policy::valid_tab_id(id) {
return Err("VALIDATION: invalid tab id".into());
@@ -451,20 +451,10 @@ pub fn place_child(webview: &Webview, x: f64, y: f64, width: f64,
// One native move+resize: separate set_position/set_size calls were two WebView2 `SetBounds`
// (the page re-laid out at the old size, then at the new one) and two main-thread messages.
#[cfg(not(target_os = "linux"))]
- {
- let _ = webview.set_bounds(tauri::Rect {
- position: tauri::LogicalPosition::new(x, y).into(),
- size: tauri::LogicalSize::new(width, height).into(),
- });
- #[cfg(target_os = "macos")]
- if crate::diag::active() {
- let actual = webview.bounds().map(|b| {
- let (p, s) = (b.position.to_logical::(1.0), b.size.to_logical::(1.0));
- format!("{},{} {}x{}", p.x, p.y, s.width, s.height)
- });
- crate::diag::log("host", &format!("place {} asked {x},{y} {width}x{height} now {actual:?}", webview.label()));
- }
- }
+ let _ = webview.set_bounds(tauri::Rect {
+ position: tauri::LogicalPosition::new(x, y).into(),
+ size: tauri::LogicalSize::new(width, height).into(),
+ });
}
/// Linux: the shell webview becomes the base layer of a GtkOverlay filling the window, which
@@ -919,49 +909,17 @@ pub fn place_tab(webview: &Webview, rect: crate::layout::Rect, vi
let was_visible = placed.was_visible(webview.label());
(placed.place(webview.label(), rect, visible), was_visible)
};
- // macOS: a pane that comes back from hidden (parked at 1x1) and is resized while still hidden keeps
- // the page's old viewport (X drew an empty timeline until the next real resize). Show it first, then
- // size it, then tell the page its window changed.
- #[cfg(target_os = "macos")]
- let reveal = changed.visible && visible;
- #[cfg(not(target_os = "macos"))]
- let reveal = false;
- if reveal {
- set_tab_visible(webview, visible, parked, was_visible);
- }
- // macOS: the cached placement says nothing moved, but AppKit (window animations, a monitor change, a
- // restore from the Dock) can move or resize a child behind our back; the pane then shows the shell's
- // black ground until relaunch. A visible pane whose real frame differs is placed again.
- #[cfg(target_os = "macos")]
- let drifted = visible && !changed.bounds && !reveal && native_frame_differs(webview, rect);
- #[cfg(not(target_os = "macos"))]
- let drifted = false;
- if changed.bounds || drifted {
+ if changed.bounds {
let (x, y, width, height) = rect;
place_child(webview, x, y, width, height);
}
- if reveal {
- let _ = webview.eval("window.dispatchEvent(new Event('resize'));");
- } else if changed.visible {
+ if changed.visible {
set_tab_visible(webview, visible, parked, was_visible);
} else {
set_memory_target(webview, visible, parked);
}
}
-/// macOS: whether a child webview's real frame is off the rectangle last asked for (more than 1.5 px).
-#[cfg(target_os = "macos")]
-fn native_frame_differs(webview: &Webview, rect: crate::layout::Rect) -> bool {
- let Ok(actual) = webview.bounds() else { return false };
- let (position, size) = (actual.position.to_logical::(1.0), actual.size.to_logical::(1.0));
- let (x, y, width, height) = rect;
- let off = (position.x - x).abs() > 1.5 || (position.y - y).abs() > 1.5 || (size.width - width).abs() > 1.5 || (size.height - height).abs() > 1.5;
- if off {
- crate::diag::log("host", &format!("pane {} drifted to {},{} {}x{}, placing it again", webview.label(), position.x, position.y, size.width, size.height));
- }
- off
-}
-
/// A tab webview was closed: a new one with the same label is placed from scratch.
pub fn forget_tab(app: &AppHandle, label: &str) {
#[cfg(windows)]
diff --git a/crates/waybetter-host/src/lib.rs b/crates/waybetter-host/src/lib.rs
index a492583..b61a5c0 100644
--- a/crates/waybetter-host/src/lib.rs
+++ b/crates/waybetter-host/src/lib.rs
@@ -63,10 +63,8 @@ pub mod hotfix;
pub mod i18n;
pub mod layout;
pub mod media;
-pub mod menu;
pub mod modes;
pub mod plugins;
-pub mod popover;
pub mod policy;
pub mod profiles;
pub mod safe;
@@ -78,8 +76,6 @@ pub mod tabs;
pub mod testkit;
pub mod theme;
pub mod update;
-#[cfg(feature = "vault")]
-pub mod vault;
pub mod window_fit;
pub mod workspaces;
pub mod zoom;
@@ -95,14 +91,6 @@ mod sync_commands;
#[cfg(feature = "app")]
mod dev_commands;
#[cfg(feature = "app")]
-pub mod theme_commands;
-#[cfg(feature = "app")]
-pub mod tab_commands;
-#[cfg(feature = "app")]
-pub mod alerts_commands;
-#[cfg(all(feature = "app", feature = "vault"))]
-pub mod vault_commands;
-#[cfg(feature = "app")]
mod backup_commands;
#[cfg(all(feature = "app", feature = "net"))]
mod fonts_commands;
@@ -112,8 +100,6 @@ mod update_commands;
pub mod devloop;
#[cfg(feature = "tauri")]
pub mod host;
-#[cfg(feature = "tauri")]
-pub mod popover_host;
#[cfg(all(feature = "tauri", feature = "net"))]
pub mod updater;
diff --git a/crates/waybetter-host/src/menu.rs b/crates/waybetter-host/src/menu.rs
deleted file mode 100644
index a517982..0000000
--- a/crates/waybetter-host/src/menu.rs
+++ /dev/null
@@ -1,255 +0,0 @@
-//! The native menu bar (macOS): the shell describes the whole bar (`menu_set`, shell-only) and
-//! native code builds it; choosing an item sends its id back to the shell (`native-menu` event),
-//! which runs the same actions the in-app menu does. Nothing here performs an action itself, and
-//! tabs gain no command: the bar is the shell's alone.
-//!
-//! The description is data and is validated before anything is built: bounded depth and size,
-//! one-line labels, ids of a fixed alphabet, accelerators of a fixed alphabet, and system items
-//! (Services, Hide, Quit, Edit's Cut/Copy/Paste, Window's Minimize/Zoom) only by name from a fixed
-//! list. Other platforms keep the in-app menu: `menu_set` does nothing there.
-
-use serde::Deserialize;
-
-/// The shell event carrying the id of the chosen item.
-pub const EVENT_NATIVE_MENU: &str = "native-menu";
-
-const MAX_NODES: usize = 400;
-const MAX_DEPTH: usize = 4;
-const MAX_LABEL: usize = 120;
-const MAX_ID: usize = 96;
-const MAX_ACCELERATOR: usize = 32;
-
-/// System items the shell may ask for by name.
-pub const ROLES: &[&str] = &[
- "services", "hide", "hide_others", "show_all", "quit", "undo", "redo", "cut", "copy", "paste", "select_all", "minimize", "maximize", "fullscreen",
-];
-
-/// A submenu the system treats specially (macOS lists the open windows in the Window menu, adds the
-/// search field to Help).
-pub const SUBMENU_ROLES: &[&str] = &["window", "help"];
-
-#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
-#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
-pub enum Node {
- /// An item the shell handles: its id comes back when it is chosen. `checked` makes it a check item.
- #[serde(rename_all = "camelCase")]
- Item { id: String, label: String, #[serde(default)] accelerator: Option, #[serde(default)] checked: Option, #[serde(default = "yes")] enabled: bool },
- Separator,
- #[serde(rename_all = "camelCase")]
- Submenu { label: String, items: Vec, #[serde(default = "yes")] enabled: bool, #[serde(default)] role: Option },
- /// A system item by name ([`ROLES`]); `label` overrides its title.
- #[serde(rename_all = "camelCase")]
- Predefined { role: String, #[serde(default)] label: Option },
-}
-
-fn yes() -> bool {
- true
-}
-
-/// The whole bar: top-level submenus only.
-#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct MenuSpec {
- pub menus: Vec,
-}
-
-fn valid_label(text: &str) -> bool {
- let count = text.chars().count();
- count > 0 && count <= MAX_LABEL && !text.chars().any(char::is_control)
-}
-
-/// Ids are ASCII words (`theme:midnight`, `plugin.chat`, `file/new-tab`).
-pub fn valid_id(id: &str) -> bool {
- !id.is_empty() && id.len() <= MAX_ID && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-' | '/'))
-}
-
-/// Accelerators like `CmdOrCtrl+Shift+G`: words, `+` and one key (a letter, digit or punctuation mark).
-fn valid_accelerator(text: &str) -> bool {
- !text.is_empty() && text.len() <= MAX_ACCELERATOR && text.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '\\' | '[' | ']' | ',' | '.' | ';' | '\'' | '=' | '-' | '`' | '/'))
-}
-
-/// Validates a description before anything is built.
-pub fn validate(spec: &MenuSpec) -> Result<(), String> {
- fn walk(nodes: &[Node], depth: usize, count: &mut usize) -> Result<(), String> {
- if depth > MAX_DEPTH {
- return Err("VALIDATION: menu too deep".into());
- }
- for node in nodes {
- *count += 1;
- if *count > MAX_NODES {
- return Err("VALIDATION: menu too large".into());
- }
- match node {
- Node::Item { id, label, accelerator, .. } => {
- if !valid_id(id) || !valid_label(label) || accelerator.as_deref().is_some_and(|text| !valid_accelerator(text)) {
- return Err("VALIDATION: invalid menu item".into());
- }
- }
- Node::Separator => {}
- Node::Submenu { label, items, role, .. } => {
- if !valid_label(label) || role.as_deref().is_some_and(|role| !SUBMENU_ROLES.contains(&role)) {
- return Err("VALIDATION: invalid submenu".into());
- }
- walk(items, depth + 1, count)?;
- }
- Node::Predefined { role, label } => {
- if !ROLES.contains(&role.as_str()) || label.as_deref().is_some_and(|text| !valid_label(text)) {
- return Err("VALIDATION: invalid system item".into());
- }
- }
- }
- }
- Ok(())
- }
- if spec.menus.is_empty() || spec.menus.iter().any(|node| !matches!(node, Node::Submenu { .. })) {
- return Err("VALIDATION: the bar is a list of menus".into());
- }
- walk(&spec.menus, 0, &mut 0)
-}
-
-/// Parses and validates the shell's JSON description.
-pub fn parse(value: serde_json::Value) -> Result {
- let spec: MenuSpec = serde_json::from_value(value).map_err(|_| "VALIDATION: invalid menu".to_string())?;
- validate(&spec)?;
- Ok(spec)
-}
-
-#[cfg(all(feature = "tauri", target_os = "macos"))]
-pub use build::set;
-
-#[cfg(all(feature = "tauri", target_os = "macos"))]
-mod build {
- use super::{valid_id, Node};
- use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
- use tauri::{AppHandle, Runtime};
-
- fn append(app: &AppHandle, menu: &Submenu, nodes: &[Node]) -> tauri::Result<()> {
- for node in nodes {
- let item: Box> = match node {
- Node::Item { id, label, accelerator, checked, enabled } => {
- // An accelerator the platform cannot parse leaves the item without a key, not without an item.
- let key = accelerator.as_deref();
- match checked {
- Some(state) => Box::new(CheckMenuItem::with_id(app, id.as_str(), label, *enabled, *state, key).or_else(|_| CheckMenuItem::with_id(app, id.as_str(), label, *enabled, *state, None::<&str>))?),
- None => Box::new(MenuItem::with_id(app, id.as_str(), label, *enabled, key).or_else(|_| MenuItem::with_id(app, id.as_str(), label, *enabled, None::<&str>))?),
- }
- }
- Node::Separator => Box::new(PredefinedMenuItem::separator(app)?),
- Node::Submenu { label, items, enabled, role } => {
- let sub = Submenu::new(app, label, *enabled)?;
- append(app, &sub, items)?;
- match role.as_deref() {
- Some("window") => sub.set_as_windows_menu_for_nsapp()?,
- Some("help") => sub.set_as_help_menu_for_nsapp()?,
- _ => {}
- }
- Box::new(sub)
- }
- Node::Predefined { role, label } => {
- let text = label.as_deref();
- Box::new(match role.as_str() {
- "services" => PredefinedMenuItem::services(app, text)?,
- "hide" => PredefinedMenuItem::hide(app, text)?,
- "hide_others" => PredefinedMenuItem::hide_others(app, text)?,
- "show_all" => PredefinedMenuItem::show_all(app, text)?,
- "quit" => PredefinedMenuItem::quit(app, text)?,
- "undo" => PredefinedMenuItem::undo(app, text)?,
- "redo" => PredefinedMenuItem::redo(app, text)?,
- "cut" => PredefinedMenuItem::cut(app, text)?,
- "copy" => PredefinedMenuItem::copy(app, text)?,
- "paste" => PredefinedMenuItem::paste(app, text)?,
- "select_all" => PredefinedMenuItem::select_all(app, text)?,
- "minimize" => PredefinedMenuItem::minimize(app, text)?,
- "maximize" => PredefinedMenuItem::maximize(app, text)?,
- _ => PredefinedMenuItem::fullscreen(app, text)?,
- })
- }
- };
- menu.append(item.as_ref())?;
- }
- Ok(())
- }
-
- /// Builds the bar and makes it the application's menu (on the main thread).
- pub fn set(app: &AppHandle, spec: &super::MenuSpec) -> Result<(), String> {
- let spec = spec.clone();
- let handle = app.clone();
- app.run_on_main_thread(move || {
- let build = || -> tauri::Result