Nacre/docs/DESIGN.md
astar76 6ee1409c9a S016: chrome and menus redesign: pill tabs on springs, address pill, toolbar badges, page card, floating flyouts
Tabs slide to their slots with a sliding selection pill and drag under the
pointer; the address field is a pill with a site chip, host emphasis and a
star that fills; flyouts and menus share one floating surface that springs
open and fades closed. Web page corners are masked over the GL blit.
tests/smoke/chrome.txt shoots the chrome and every flyout dark and light.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:11:33 -06:00

20 KiB

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 BrowserWindows. 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 Events 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.

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.

UI system (S015)

Everything the interface draws takes its colours, radii, sizes and springs from src/theme.rs; widgets live in src/ui/widgets.rs, Expressive shapes in src/ui/paint.rs, icons in src/ui/icons.rs. nacre://gallery (src/ui/pages/gallery.rs, not linked from the UI) shows all of it; SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt shoots it dark and light. Rules: the app-taste skill. No one-off colour, radius or duration.

Tokens reach widgets through the egui context. theme::apply(ctx, &palette, &settings) (called by App::style_window whenever the theme, seed or settings change) stores theme::Tokens { palette, roundness, motion } and sets egui visuals, text styles and spacing. From any Ui: theme::palette(ui.ctx()), theme::radius(ui.ctx(), theme::L), theme::spring(...). Fonts are set once per window: ui::fonts() in window.rs.

Colour (theme::Palette, from the material-colors crate, D-009). Palette::new(seed, dark, variant, contrast) builds the M3 scheme; variant is a theme::VARIANTS key (tonal_spot default), contrast -1..1. Seeds: theme::seed (website colour if chroma ≥ 12 and tone 8..95, else fallback; system accent; preset; custom).

  • M3 roles: primary, on_primary, primary_container, on_primary_container, inverse_primary, secondary*, tertiary* (same four each), error, on_error, error_container, on_error_container, surface, surface_dim, surface_bright, surface_container_lowest, surface_container_low, surface_container, surface_container_high, surface_container_highest, on_surface, on_surface_variant, outline, outline_variant, inverse_surface, inverse_on_surface, scrim, shadow.
  • Extra: warning, success (fixed hues at primary's tones).
  • Old names kept as aliases for existing code: accent = primary, on_accent = on_primary, accent_soft = secondary_container, surface_high = surface_container_high, surface_low = surface_container_lowest (the page background), text = on_surface, text_weak = on_surface_variant. New code uses the M3 names.
  • Usage: page background surface_container_lowest; cards surface_container; floating surfaces surface_container_high; fields surface_container_highest; hairlines outline_variant; selection secondary_container + on_secondary_container; main action primary.
  • State layers: theme::layer(base, over, amount) mixes opaque; constants HOVER 0.08, FOCUS 0.10, PRESS 0.10, DRAG 0.16, DISABLED_CONTENT 0.38, DISABLED_CONTAINER 0.12 (content colour over the container).

Shape and space. Radii XS 4, S 8, M 12, L 16, XL 28, FULL (pill); always read through theme::radius(ctx, token) (Roundness setting: Subtle ×0.5, Default ×1, Round ×1.4) and convert with theme::corner_radius(f32). Spacing GAP_XS 4, GAP_S 8, GAP_M 12, GAP_L 16, GAP_XL 24. Heights CONTROL_SMALL 32 (icon buttons), CONTROL 40 (buttons, segmented), ROW 56 (list rows). Cards use L, chrome pills FULL, small egui widgets S (theme::corner).

Type. Outfit (OFL, assets/fonts/Outfit[wght].ttf, one variable font) at theme::Weight Thin 200, Light 300, Regular 400 (egui's Proportional), Medium 500, SemiBold 600; theme::font(size, weight). Sizes SMALL 12, BODY 14, TITLE 18, HEADLINE 24, DISPLAY 64 (clock: Thin, primary). egui text styles: Small/Body/Button/Heading(24 Medium)/Monospace 13. Outfit is Latin only: every family falls back to Material Symbols, then egui's Ubuntu-Light (Cyrillic, Greek). No CJK font is bundled.

Icons. Material Symbols Outlined (Apache 2.0), cut to tools/icons.txt by tools/icons.py into assets/fonts/MaterialSymbolsOutlined-Nacre.ttf (FILL and wght axes kept). Use the constants icons::HOME etc. (icons::ALL lists them). To add one: add its name (fonts.google.com/icons) to tools/icons.txt, run python tools/icons.py. Draw with widgets::icon(ui, center, glyph, size, filled, colour) or theme::icon_font(size, filled); filled (FILL 1) is for selected states. Icons also work inside text (format!("{} Open folder", icons::FOLDER_OPEN)) through the fallback. Sizes ICON 20, ICON_LARGE 32. Never emoji.

Motion. theme::spring(ctx, id, target, spring) -> f32: per-id state in egui memory, retargets keeping velocity, starts at the target on first use, repaints only while moving, returns the target at once with Motion off. theme::effect(ctx, id, on) -> 0..1 is the colour/opacity spring. Presets (stiffness/damping ratio): FAST 1400/0.62 (press, small controls), DEFAULT 700/0.68 (panels, movement), SLOW 300/0.74 (big transitions), EFFECT 900/1.0 (colour, opacity; never overshoots). Motion setting = time factor (Off 0, Fast 0.6, Normal 1, Slow 1.8; stiffness ÷ factor²); theme::animation_time drives egui's own animations (0.1 s × factor).

Widgets (ui::widgets; all have hover state layer, press squeeze, focus ring in secondary, disabled 38 %):

  • button(ui, ButtonKind::{Filled, Tonal, Outlined, Text}, Option<icon>, label) -> Response: 40 px pill, press morphs to radius S.
  • icon_button(ui, icon, tooltip), icon_toggle(ui, icon, tooltip, on): 32 px circle, press squashes to a squircle; selected = secondary_container fill and filled icon.
  • switch(ui, &mut bool) -> changed: M3 switch, handle travels (FAST) and grows with a check when on, hover halo.
  • segmented(ui, &mut T, &[(T, label)]) -> changed: equal-width segments, selected = tonal fill + check that slides in.
  • card(ui, |ui| ...): surface_container, radius L; rows inside get hairlines between them (not above the first).
  • row(ui, title, description, |ui| control), switch_row, link_row(ui, title, description) -> clicked (whole row is the button, chevron at the end), section(ui, title) (group title in primary, above a card).
  • text_field, number, page_column, glyph(toolbar key) -> icon.

Shapes (ui::paint): cookie(painter, center, radius, lobes, rotation, fill, stroke), cookie_image(painter, texture, center, radius, lobes, rotation) (artwork in a cookie), cookie_points, wavy_line(painter, x0, x1, y, amplitude, wavelength, phase, stroke), wavy_progress(painter, rect, fraction, amplitude, phase, &palette) (amplitude 0 = flat, animate it with a spring when playing/paused; advance phase only while something plays), shadow(painter, rect, radius, dark) (one soft shadow for floating surfaces; egui's window_shadow/popup_shadow are set to match).

What egui can't do here: no text blur or text shadows; no per-glyph variable axes inside one label (a weight is a font family); shadows are tessellator-blurred rectangles only (not arbitrary shapes); Ui::id/Id::new are deprecated in 0.37 but still used across the code.

Chrome (S016, src/ui/chrome.rs). Everything behind the chrome and around the page is chrome::chrome_fill (surface_container); the page is a card with margin GAP_S (sides and bottom) and radius L. Web pages are blitted as rectangles, so ui::card_corners paints a ring in the chrome colour over the corners (works over the GL blit). Heights: tab strip 44 (tab pills 34, gap 4, width 76..240, pinned 44, +24 with an audio button), toolbar 52 (address pill 40), bookmarks bar 36 (chips 28), title bar 36, app bar 44; buttons inside tabs and the address field are 24. Tabs slide to their slots with DEFAULT springs, the selection pill (secondary_container) slides between them, a dragged tab stays under the pointer (theme::spring_jump) and the others make room (drag_layout); a window resize jumps instead of sliding. Toolbar order: back, forward, reload, home, incognito | address | passwords, history, bookmarks, downloads, qr, apps, devtools, pip, screenshot, adblock, media, vpn, profile, menu (each shown per the toolbar setting). Status on buttons: badges (blocked count, running downloads), a progress ring round downloads, a coloured dot on the VPN, a slash through the shield when off. All icons are Material Symbols (D-009).

Floating surfaces (src/ui/menus.rs). menus::floating(ctx, id, pos, pivot, open, |ui| ..) draws a menus::surface (surface_container_high, radius L, popup shadow) that grows from its pivot corner (scale 0.9 to 1, DEFAULT) and fades in (EFFECT); with open false it shrinks and fades without input, then returns None. Flyouts keep the last one drawn so it animates out; switching flyouts closes one while the other opens. Rows: menu_item(ui, icon, label, trailing, selected) (34 high, icon column, label cut with an ellipsis, shortcut or detail on the right), divider, empty, one_line (text cut to a width). egui popups (Popup::menu, submenus) use the same surface frame. Areas need default_size set or egui caps them at 600×400.

Feature checklist

See docs/FEATURES.md; every row names the file that implements it and its review state.