Nacre on Servo: first complete, reviewed, not yet built version

Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess):
tabs and windows, address bar with suggestions, history, bookmarks and
reading list, downloads with resume and external download managers,
encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists),
VPN through Tor or a proxy and secure DNS via a local bridge proxy,
picture in picture, Discord Rich Presence, media player and visualizer,
spell check, site apps, user scripts and styles, import from other
browsers, gamepads, Web Bluetooth, and every setting of the original Nacre
in a plain egui interface.

Not compiled yet; docs/HANDOFF.md has the first build checklist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-11 06:08:36 -06:00
commit e8167c3f4a
4 changed files with 265927 additions and 0 deletions

134
docs/DESIGN.md Normal file
View file

@ -0,0 +1,134 @@
# Nacre (Rust) — design notes
Working notes for whoever continues this code. Keep it current.
## Ground rules (from the user, 2026-11-10)
- Everything in Rust; engine is Servo 0.7 from crates.io, trimmed (no WebXR, WebGPU, multiprocess). Gamepad and Web Bluetooth stay in (user, 2026-11-10).
- Function first. The UI is plain egui for now; the designed UI comes after everything works.
- Written from scratch. The older `astar76/Nacre-rust` repo is not a source.
- No builds until the code has been reviewed and declared "first build worthy". Then one build:
`nice cargo build --release -j 2`. Never run tests alongside a release build.
- Feature spec: the settings screenshot plus the original Python Nacre (`~/Documents/Apps/Nacre/nacre`,
`config.py` DEFAULTS is the list of settings). Nothing in there is to be dropped silently; things Servo cannot do
are listed under "Engine limits" and shown as unavailable in the UI.
- Never connect to Tor or proxies in tests.
## Layout
```
src/main.rs args, single instance, starts the event loop
src/app.rs App: winit ApplicationHandler, owns Servo, windows, timers, background jobs
src/window.rs BrowserWindow: winit window + GL contexts + egui; forwards input; paints
src/hub.rs Servo delegates; everything Servo tells us becomes an Event in a queue
src/tabs.rs Tab (one WebView or an internal page), per-window tab list
src/keys.rs winit -> Servo key conversion, shortcut table (rebindable)
src/inject.rs JavaScript injected into pages (bridge, autofill, find, media, PiP, cosmetic filters)
src/adblock.rs adblock-rust engine, lists, updates, counters
src/discord.rs Discord Rich Presence over the local IPC socket
src/media.rs media state gathered from pages; feeds the media button, Discord, MPRIS later
src/importer.rs import from Chromium- and Firefox-family browsers
src/spell.rs spell check (spellbook + hunspell dictionaries)
src/perf.rs memory use, low-memory mode, energy saver, tab freezing and unloading
src/updates.rs update check against the Forgejo releases API
src/paths.rs config / data / cache dirs, profiles
src/tabs.rs Tab, internal pages (Page), prompts and dialogs per tab
src/theme.rs palette and egui visuals from the Appearance settings
src/resources.rs Servo's resource files and Nacre's error/certificate/crash pages
src/instance.rs single instance per profile (links go to the running browser)
src/pdf.rs one-page PDF for "save as PDF"
src/actions.rs Command enum and everything the browser does when asked
src/util.rs small helpers (time, url fixing, json files, random)
src/store/ settings, history, bookmarks, downloads, vault, permissions, session, apps, scripts
src/net/ bridge (local CONNECT proxy: direct / SOCKS5 / HTTP upstream, DoH), fetch (ureq), tor, dlm
src/ui/ egui: chrome (tab strip, toolbar, omnibox, bookmarks bar), menus, dialogs, pages/*
```
## How the pieces fit
- One process, many windows. `App` holds `Rc<Shared>` (Servo, stores, ad blocker, bridge handle) and a map of
`BrowserWindow`s. Window kinds: Normal, App (site installed as app: no toolbar), Pip (always on top, one video).
- Incognito is a second process (`nacre --incognito`) with a temporary profile that is deleted on exit, because
Servo 0.7 has no per-WebView private mode.
- Rendering: per window one `WindowRenderingContext` (surfman). Each tab gets its own
`OffscreenRenderingContext` made from it, so Servo gives each tab its own painter (WebRender instance).
egui (egui_glow on the window context's glow API) draws the chrome and a paint callback blits the tab's
framebuffer into the page rectangle (`render_to_parent_callback`). glow is 0.17 on both sides.
Why per tab and not per window like servoshell: Servo 0.7 always draws a painter's visible webviews at the
origin at full size, so only separate painters allow picture-in-picture (the PiP tab's context is resized to
the PiP window, read back with `read_to_image` and shown as a texture in the PiP window) and split view.
Cost: a WebRender instance per tab. Kept in check by `thread_pool_webrender_workers_max = 2` and by unloading
idle tabs (perf settings). If shared-GL painters misbehave at first build, fall back to one per window and
drop split view; PiP then becomes "reopen the video in the PiP window at the same time".
- Servo callbacks arrive on the main thread inside `servo.spin_event_loop()`. The delegate (`hub::Hub`) answers the
synchronous ones right there (resource loads -> ad blocker, navigation requests -> HTTPS-only / downloads /
external schemes) and queues the rest as `Event`s that `App` drains after each spin.
- Page -> browser messages: the bridge user script keeps a private reference to `console.log` and sends
`<token><json>`; `show_console_message` picks those out. The token is random per run and never exposed to pages.
Browser -> page: `WebView::evaluate_javascript`.
- Network: Servo reads its proxy prefs once at start, so it is always pointed at `net::bridge`, a local CONNECT
proxy. The bridge decides per connection: direct (optionally resolving through DoH), or through the VPN upstream
(SOCKS5 with remote DNS for Tor, or an HTTP proxy). Switching VPN or DNS needs no restart. Nacre's own requests
(downloads, filter lists, updates) go through the bridge too. `NACRE_NO_BRIDGE=1` turns it off for debugging.
- Settings pages, history, bookmarks, downloads, passwords, apps and so on are egui views shown in a tab
("internal tab", `nacre://settings` etc.), not web pages.
## Servo 0.7 embedding cheat sheet (checked against the crate source)
```
servo = { version = "=0.7.0", default-features = false,
features = ["bundled", "clipboard", "js_jit", "media-gstreamer", "webgl", "webcrypto",
"brotli-compression-stream", "gamepad", "bluetooth", "native-bluetooth"] }
Gamepads: gilrs events -> InputEvent::Gamepad(GamepadEvent::{Connected, Disconnected, Updated}); rumble via GamepadDelegate.
Bluetooth: pref dom_bluetooth_enabled=true; WebViewDelegate::show_bluetooth_device_dialog -> device picker dialog.
rustls::crypto::aws_lc_rs::default_provider().install_default() // before ServoBuilder
ServoBuilder::default().opts(Opts).preferences(Preferences).event_loop_waker(Box<dyn EventLoopWaker>).build()
servo.spin_event_loop(); servo.set_delegate(Rc<dyn ServoDelegate>); servo.set_preference(name, PrefValue)
servo.site_data_manager() -> &SiteDataManager (site_data, clear_site_data, clear_cookies, cookies_for_url, set_cookie_for_url)
servo.network_manager() -> Ref<NetworkManager> (clear_cache, cache_entries)
WindowRenderingContext::new(display_handle, window_handle, PhysicalSize<u32>) -> Result<_, surfman::Error>
Rc<WindowRenderingContext>::offscreen_context(size) -> OffscreenRenderingContext
offscreen.render_to_parent_callback() -> Option<Box<dyn Fn(&glow::Context, euclid::default::Rect<i32>) + Send + Sync>>
RenderingContext: make_current, prepare_for_rendering, present, resize(PhysicalSize<u32>), size, glow_gl_api, read_to_image
WebViewBuilder::new(&servo, Rc<dyn RenderingContext>).url(Url).hidpi_scale_factor(Scale::new(f32))
.delegate(Rc<dyn WebViewDelegate>).user_content_manager(Rc<UserContentManager>).build()
WebView: id, url, page_title, favicon -> Option<Ref<Image>>, load_status, cursor, load(Url), load_request(UrlRequest),
reload, can_go_back, go_back(1), can_go_forward, go_forward(1), resize(PhysicalSize<u32>), show, hide,
set_focused(bool), focused, paint, notify_input_event(InputEvent), notify_scroll_event(Scroll, WebViewPoint),
set_page_zoom(f32), page_zoom, exit_fullscreen, evaluate_javascript(script, |Result<JSValue, _>|),
take_screenshot(Option<WebViewRect>, |Result<RgbaImage, _>|), notify_theme_change(Theme),
notify_media_session_action_event(MediaSessionActionType), set_hidpi_scale_factor, clear_session_history
UserContentManager::new(&servo); add_script(Rc<UserScript>); remove_script; add_stylesheet(Rc<UserStyleSheet>)
(changes apply after reload; UserScript::new(String, Option<PathBuf>), UserStyleSheet::new(String, Url))
InputEvent::{Keyboard(KeyboardEvent::new(keyboard_types::KeyboardEvent)), MouseButton(MouseButtonEvent::new(action, button, point)),
MouseMove(MouseMoveEvent::new(point)), MouseLeftViewport(MouseLeftViewportEvent{focus_moving_to_another_iframe}),
Wheel(WheelEvent::new(WheelDelta{x,y,z,mode}, point)), EditingAction(ClipboardAction), Ime(ImeEvent), Touch(..)}
point: WebViewPoint::Device(DevicePoint) (From<DevicePoint>)
WebResourceLoad: .request {method, headers, url, destination (content_security_policy::Destination), referrer_url,
is_for_main_frame, is_redirect}; .intercept(WebResourceResponse::new(url)) -> InterceptedWebResourceLoad
{send_body_data(Vec<u8>), finish(), cancel()}. Dropping the load un-intercepted lets it through.
NavigationRequest {url}; allow()/deny(); dropped = allowed.
PermissionRequest: feature() -> PermissionFeature; allow()/deny().
EmbedderControl::{SelectElement, ColorPicker, FilePicker, InputMethod, SimpleDialog(Alert|Confirm|Prompt), ContextMenu}
ContextMenu: items(), element_info() {flags, link_url, image_url}, select(ContextMenuAction), dismiss()
CreateNewWebViewRequest::builder(rendering_context) -> WebViewBuilder (window.open / target=_blank)
MediaSessionEvent::{SetMetadata{title,artist,album}, PlaybackStateChange, SetPositionState{duration,playback_rate,position}}
Prefs worth knowing: user_agent, network_http_proxy_uri, network_https_proxy_uri, network_http_no_proxy,
network_enforce_tls_enabled (HTTPS-only), devtools_server_enabled, devtools_server_listen_address,
dom_*_enabled switches, shell_background_color_rgba, session_history_max_length, js_mem_max.
Opts: config_dir (profile storage: cookies, local storage), temporary_storage, ignore_certificate_errors, multiprocess.
```
Not in Servo 0.7, so Nacre does it itself: downloads, find in page, private mode, SOCKS proxies, spell check,
picture-in-picture, extensions, password capture, printing.
## Engine limits (shown as unavailable, not hidden)
- Widevine / DRM video: Servo has no EME. The setting stays, marked "not available with this engine".
- Chrome extensions: not possible. Replaced by user scripts and user styles (Apps -> Scripts).
- Hardware acceleration switch: Servo needs GL; "Off" selects software GL (LIBGL_ALWAYS_SOFTWARE) on next start.
- Printing: "Save page as PDF/PNG" through a full-page screenshot.
## Feature checklist
See `docs/FEATURES.md`; every row names the file that implements it and its review state.

114
docs/FEATURES.md Normal file
View file

@ -0,0 +1,114 @@
# Feature checklist
Every item of the settings screenshot and of the original Nacre's `config.py`, where it lives, and its state.
"Partial" and "engine limit" items say why in the UI too.
## Browser basics
| Feature | Where | State |
|---|---|---|
| Tabs: open, close, reorder by drag, pin, mute, duplicate, move to new window, close others/right | `actions.rs`, `ui/chrome.rs` | written |
| Reopen closed tabs, recently closed list | `store/session.rs`, `actions.rs` | written |
| Windows, incognito (separate process, temporary profile) | `main.rs`, `paths.rs` | written |
| Address bar: URL or search, suggestions (history, bookmarks, tabs, pages, engine), Alt+Enter new tab | `ui/chrome.rs`, `util::address_to_url` | written |
| Back/forward (with history list), reload, hard reload, home | `actions.rs` | written; "stop" has no Servo API |
| Find in page (count, next/previous, match case) | `inject.rs` FIND_JS, `ui/dialogs.rs` | written |
| Zoom per site, Ctrl+wheel | `actions.rs`, settings `web.zoom_sites` | written |
| Full screen (F11 and page fullscreen) | `app.rs` | written |
| Context menu (links, images, media, selection, spelling, page) | `ui/menus.rs` | written |
| Page dialogs: alert/confirm/prompt, HTTP sign-in, select, colour, file picker, leave page | `ui/dialogs.rs`, `app.rs` | written |
| Pop-ups / target=_blank as tabs, pop-up permission | `app.rs on_create_new` | written |
| Single instance (links go to the running browser) | `instance.rs` | written |
| Session restore, crash recovery offer | `app.rs`, `store/session.rs` | written |
| Error pages (network, certificate, crash) | `assets/servo/*.html`, `resources.rs` | written |
| Developer tools: console + eval, network log, source; Firefox remote debugging | `ui/pages/devtools.rs` | written |
| View source, save page, save as PDF/PNG (no printing in Servo) | `actions.rs`, `pdf.rs` | written |
| QR code for page | `ui/menus.rs` | written |
| Task manager, free up memory | `ui/pages/misc.rs` | written |
| Keyboard shortcuts, rebindable | `keys.rs`, settings | written |
| Gamepads (W3C standard mapping), Web Bluetooth device picker | `app.rs poll_gamepads`, `ui/dialogs.rs` | written; rumble reports unsupported |
| Notifications (notify-send or in-app) | `app.rs` | written |
## General (screenshot)
| Setting | State |
|---|---|
| Setup (first-run wizard, rerun) | written (`ui/pages/misc.rs welcome`) |
| On startup: New tab / Restore / Home page | written |
| Home page | written |
| Search engine (+ custom engines, suggestions) | written |
| Profiles (list, add, delete, open) | written |
| Spell check (languages, dictionaries downloaded, suggestions, add word) | written (`spell.rs`, SPELL_JS) |
| Keyboard shortcuts | written |
| Import from another browser (Chromium/Firefox families; bookmarks file; passwords CSV) | written (`importer.rs`) |
| New tab shortcuts and page elements, backgrounds, weather, notes | written (`ui/pages/newtab.rs`) |
| Custom title bar | written (restart) |
| Floating content card | written |
## Appearance
Colour source (website/system/palette/custom), fallback, palette swatches, mode, scheme style and contrast, motion,
roundness, websites light/dark, force dark, interface size: written (`theme.rs`, settings page). The Material You look
itself is for the UI pass.
## Toolbar
Navigation / Your Nacre / Tools and actions buttons toggles, bookmarks bar always/new tab/never, bookmark manager:
written.
## Performance
| Setting | State |
|---|---|
| Memory (use, threads, free up) | written (Linux numbers) |
| Low-memory mode auto/on/off | written |
| Energy saver off/battery/always | written |
| Memory saver (unload after) | written |
| Freeze background tabs | partial: stops drawing; Servo can't pause scripts |
| Always keep these sites active | written |
| Load restored tabs when opened | written |
| Preload pages | written (DNS warm-up) |
| Smooth scrolling | written (CSS) |
| Still new tab background | written |
| Save data | partial: JS hint, no request header |
| Hardware acceleration | written (software GL, restart) |
## Privacy
| Setting | State |
|---|---|
| VPN: Tor (system, Tor Browser, or started) or custom SOCKS5/HTTP, kill switch while connecting | written (`net/bridge.rs`, `net/tor.rs`) |
| Privacy mode (+ in incognito) | written (PRIVACY_JS) |
| Secure DNS (Cloudflare, Quad9, Google, Mullvad, AdGuard, custom) | written (`net/dns.rs`) |
| HTTPS-only mode with fallback prompt and exceptions | written |
| Site settings (defaults and per-site) | written |
| Delete browsing data (+ on exit) | written |
| Send Do Not Track and GPC | partial: JS only (no headers in Servo 0.7) |
| Remove tracking parameters | written |
| Block third-party cookies | engine limit, shown as unavailable |
| Google sign-in quirk | written (UA switch + JS) |
| Sites where ad blocking is paused | written |
| Remote debugging, user agent | written |
## Ad blocker
Block ads and trackers, filter engine status + update now, 22 filter lists in groups, your lists, own rules, hide
leftovers (cosmetic incl. generic hiding), animate removal, block YouTube ads, update automatically: written
(`adblock.rs`, `hub.rs`, COSMETIC_JS). Seed lists ship in `assets/filters`.
## Downloads
Save to, ask where, show when they start, pause/resume (Range), retry, cancel, open/show in folder, external download
managers (AB Download Manager, aria2/Motrix, JDownloader 2, FDM, IDM) with ping status and fallback: written
(`net/download.rs`, `net/dlm.rs`). Downloads are detected by URL type, a header probe, and `<a download>`.
## Media
Media button (when playing/always/never), player flyout (art, seek, controls, mute tab/site, PiP), visualizer
(cava / simulated / off), spin artwork, Discord Rich Presence (arRPC/Discord, per-site app IDs, browsing activity,
buttons, paused state), picture in picture (own always-on-top window): written. Protected content (Widevine): engine
limit, shown as unavailable.
## Passwords and autofill
Encrypted vault (device key or master password, auto-lock, re-ask before showing), save prompt, autofill, strong
password suggestion, addresses and cards, CSV import/export, generator, weak/reused check: written
(`store/vault.rs`, AUTOFILL_JS, `ui/pages/passwords.rs`).
## Apps
Install site as app (own window, launcher entry), desktop shortcut, user scripts and styles (stand-in for extensions):
written.
## About
Version, engine, colour, profile paths, update repository, automatic and manual update check: written
(`updates.rs`).

29
docs/HANDOFF.md Normal file
View file

@ -0,0 +1,29 @@
# Handoff: where the from-scratch Nacre stands
Read `docs/DESIGN.md` first (rules, layout, the Servo 0.7 API cheat sheet), then `docs/FEATURES.md` (every feature
and where it lives) and `docs/REVIEW.md` (known gaps and things to check at the first build).
User rules: Servo engine, all Rust, plain UI for now, nothing from the original dropped (gamepad and Web Bluetooth
stay in), no builds until the code was reviewed. Build with `nice cargo build --release -j 2`, never together with
the test suite.
## State (2026-11-11)
- All modules written (~19k lines): storage, networking (bridge proxy for VPN/secure DNS, Tor, downloads, download
managers), ad blocker, Discord, media, spell check, importer, updates, keys, Servo glue (`hub.rs`, `window.rs`,
`app.rs`, `actions.rs`) and the plain egui UI (chrome, menus, dialogs, every nacre:// page).
- Review passes done without compiling: API signatures checked against the crate sources in ~/.cargo/registry,
names cross-checked between modules (commands, UI state, shared fields, crate:: paths), every setting checked
to be read by the code. Bugs found and fixed are in git history.
- Never compiled. Expect a round of compile errors at the first build (type inference, borrow checker, small
API mismatches); fix them in place, don't restructure.
## First build checklist
1. `nice cargo build --release -j 2` (first build takes hours: Servo, SpiderMonkey, WebRender).
2. Fix compile errors.
3. Run `cargo test` separately (unit tests in util, settings, history, bookmarks, permissions, vault, dns,
bridge (loopback only), download, adblock, keys, scripts, updates, inject, hub, theme).
4. Smoke test offscreen (see the user's CLAUDE.md): page renders, tabs switch, settings open.
5. Go through docs/REVIEW.md, especially "several painters on one GL context".
## Not included (candidates after the first build)
Reader mode, translate, split view (the per-tab painters make it possible), MPRIS media keys, real gamepad rumble.

21
docs/REVIEW.md Normal file
View file

@ -0,0 +1,21 @@
# Review notes
Things to check or fix in the review passes before the first build. Remove an item when it is done.
- discord.rs on Windows: named-pipe reads block (no read timeout on `File`). Read only during the handshake
there, or use a reader thread.
- Servo can't add request headers or strip cookies per request, so "Send Do Not Track & GPC" only sets
`navigator.globalPrivacyControl`/`doNotTrack` in pages, and "Block third-party cookies" is not possible.
Settings must say so (shown as "partial" / "not available with this engine").
- Servo's request interceptor holds a global lock while the embedder answers: `load_web_resource` must answer
synchronously, never keep a `WebResourceLoad` waiting.
- Intercepted responses skip redirect handling, so HTTPS-only and tracking-parameter stripping serve a tiny page
that calls `location.replace()` instead of a 30x.
- Google sign-in quirk: the user agent is a global pref; switching it for accounts.google.com affects requests of
other tabs made at that moment.
- First build: check that several painters on one GL context (one per tab) render correctly and don't fight over
GL state. Fallback plan is in DESIGN.md.
- Settings → Downloads "Save to" and the new tab image picker open rfd dialogs on the main thread, which stalls
page rendering while they are open. Move them to `App::spawn` like the other file dialogs.
- Autofill fills logins with `evaluate_javascript`, which runs in the top document only: login forms inside
iframes are captured (their own script reports them) but can't be filled yet.