# 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: lists, updates, cosmetic engine, conversion to WebKit content filters webext/ web process extension (cdylib): headers, stand-ins, blocked counts (D-036) 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` (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 (D-008): per window one `WindowRenderingContext` (surfman) and one `OffscreenRenderingContext` made from it (`BrowserWindow::page_context`), shared by all the window's tabs, so Servo makes one painter (WebRender instance) per window. Only the active tab's web view is shown; `painted_tab` records whose page is in the framebuffer, so a tab switch forces a repaint. While no tab shows a page (internal page, PiP placeholder) `paint_unshown` still paints, because Servo keeps reporting the frame until it is painted. egui (egui_glow on the window context's glow API) draws the chrome and a paint callback blits the page framebuffer into the page rectangle (`render_to_parent_callback`). glow is 0.17 on both sides. Why not one painter per tab: each painter is a full WebRender instance (~56 MB and ~6 threads; 15 tabs took 1128 MB vs 341 MB shared, same frame time; S005). Servo 0.7 draws a painter's visible web views at the origin at full size, so one shared painter rules out split view. Picture in picture: `pip.take` pauses the tab's video and returns its time; a second web view (`Tab::pip`) with a context and painter of its own loads the same URL at the PiP window's size, `pip.start` seeks and plays it once loaded, and its frames are read back (`read_to_image`) into the PiP window. On exit `pip.state` hands the time back to the tab (`pip.resume`). The page is reloaded, so its state (logins aside) is lost. Servo 0.7 freezes a playing video that is seeked and then `play()`ed: pause before seeking. - 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 ``; `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).build() servo.spin_event_loop(); servo.set_delegate(Rc); 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 (clear_cache, cache_entries) WindowRenderingContext::new(display_handle, window_handle, PhysicalSize) -> Result<_, surfman::Error> Rc::offscreen_context(size) -> OffscreenRenderingContext offscreen.render_to_parent_callback() -> Option) + Send + Sync>> RenderingContext: make_current, prepare_for_rendering, present, resize(PhysicalSize), size, glow_gl_api, read_to_image WebViewBuilder::new(&servo, Rc).url(Url).hidpi_scale_factor(Scale::new(f32)) .delegate(Rc).user_content_manager(Rc).build() WebView: id, url, page_title, favicon -> Option>, load_status, cursor, load(Url), load_request(UrlRequest), reload, can_go_back, go_back(1), can_go_forward, go_forward(1), resize(PhysicalSize), 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|), take_screenshot(Option, |Result|), notify_theme_change(Theme), notify_media_session_action_event(MediaSessionActionType), set_hidpi_scale_factor, clear_session_history UserContentManager::new(&servo); add_script(Rc); remove_script; add_stylesheet(Rc) (changes apply after reload; UserScript::new(String, Option), 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) 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), 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. ``` egui 0.37 deprecates `Ui::id` (now `Ui::scope_id`) and `Id::new` (now `Id::unique` / `IdSalt::new`); the code still uses the old names, which build with warnings. The Servo 0.7 API above matched the crate: the first build had no Servo signature errors. 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) - Picture in picture reloads the page in its own web view (one painter per window, D-008): page state is lost and the video restarts loading before it jumps to the same time. - 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. - Inline `` is painted from its own markup, so `currentColor` misses the CSS colour; `SVG_COLOR_JS` (`inject.rs`) copies each icon's computed colour into its `color` attribute (hover colours not followed). - Fingerprinting: Servo has no IndexedDB, plugins list, WebRTC or DynamicsCompressorNode, and its user agent is a rare Firefox version, so Cover Your Tracks still finds Nacre unique with privacy mode on (bits per metric in `docs/engine/privacy-mode.md`). `document.fonts.check()` and a pass-through compressor are Nacre's own layer (`FONTS_CHECK_JS`, `COMPRESSOR_JS` in `inject.rs`); the screen size comes from `Hub::screen_geometry`. - CSS `mask-image` icons (e.g. Wikipedia's) paint as solid squares. HTTP/2 header limit: see D-012. ## Vendored servo-net patches `vendor/servo-net` is servo-net 0.7.0 through `[patch.crates-io]` (D-012). Every Nacre change is marked `Nacre patch` in the code; a Servo upgrade re-applies the ones upstream still needs, then re-runs the smoke scripts named. | File, function | What and why | Re-check | |---|---|---| | `connector.rs` `create_http_client` | `http2_max_header_list_size(256 KiB)`: hyper's 16 KiB default refuses YouTube's response headers (D-012) | `heavy-web.txt` | | `fetch/methods.rs` `main_fetch` (scheme fetch) | lets the certificate warning's `chrome:allowcert` request through; it ended as UnsupportedScheme (D-014) | `net-privacy.txt` | | `http_cache.rs` `flush_to_disk`, `resource_thread.rs` Exit | writes the memory HTTP cache to the disk cache at quit (D-014) | `cache.txt`, `cache-restart.txt` | | `nacre.rs` (new module, `pub mod nacre` in `lib.rs`) | embedder-set state the patches below read: extra request headers, the third-party cookie switch, the top-level site per webview, site matching (S023) | `privacy-net.txt` | | `http_loader.rs` `http_network_or_cache_fetch` (step 8.15) | appends the embedder's extra headers (`DNT`, `Sec-GPC`, `Save-Data`) unless the request already has them; records a `Document` request's site as its webview's top-level site; skips the `Cookie` header for a third-party request (S023) | `privacy-net.txt` | | `http_loader.rs` `http_network_fetch` (step 15) | doesn't store `Set-Cookie` from a third-party response (S023) | `privacy-net.txt` | | `websocket_loader.rs` `create_handshake_request`, `process_ws_response` | the same third-party rule for WebSocket handshakes (S023) | unit tests only | | `resource_thread.rs` `create_http_states`, Exit; `nacre.rs` `set_cookie_persistence`, `cookie_jar_snapshot`; `Cargo.toml` (+ `serde_json`) | the public cookie jar comes from and goes to the embedder instead of plain `cookie_jar.json`: Nacre's initial jar at start, a JSON copy on demand, the final jar at Exit (S025, D-019) | `cookies.txt` + `cookies-restart.txt` + `cookies-cleared.txt` | | `fetch/methods.rs` `main_fetch` (step 12) | privacy mode's Firefox-style Accept-Language ("en-US,en;q=0.5", `nacre::append_accept_language`) replaces Servo's single locale; a page's own value stays (S024) | `privacy-net.txt` | ## Vendored servo-script patches `vendor/servo-script` is servo-script 0.7.0 through `[patch.crates-io]` (S031), same rules as servo-net above. | File, function | What and why | Re-check | |---|---|---| | `event_loop/timers.rs` `OneshotTimers::fire_timer`, `JsTimerTask::invoke` | due timers wait in a `RootedTraceableBox` instead of a plain `Vec`, and the running timer's callback is rooted: a GC inside one callback swept the functions of the timers still waiting (SIGSEGV in `GlobalScope::from_object`, R5-01) | `crash-adblock.txt` | | `dom/media/`, `dom/html/embedded_content/htmlmediaelement.rs`, `dom/globalscope`, `dom/url` and more | Media Source Extensions (S022-S028), see "Media and Media Source Extensions" below; `grep -rn "Nacre" vendor/servo-script` lists them | `mse.txt`, `mse-player.txt` | Third-party rule (S023): a request is third-party when its host's site (registrable domain, eTLD+1; an IP address or a single-label host stands for itself) differs from the top-level site of its webview. Scheme and port don't count, so `a.example.com` on `example.com` stays first-party. The top-level site comes from the last `Document` request of that webview (net sees it before any subresource) and from the hub's `notify_url_changed` (history navigations without a request, downloads that didn't replace the page); `notify_closed` forgets it. Requests with no webview or no known top-level site are never blocked. `Document` requests are never blocked; `IFrame` documents are checked like any subresource. `document.cookie` and the Cookie Store API in a third-party frame go to net with no webview id (servo-script isn't vendored); Nacre's `FRAME_COOKIE_JS` (`inject.rs`, S024) empties them in a frame whose top page is another site. ## Media and Media Source Extensions (S022-S028) Plain `