Glossary of Rust & egui Terms

Canonical definitions used across all lessons and reference sheets. Designed for quick screen lookup and clean printing.

Canonical Glossary

Term & Syntax Definition Avoid / CAD Context
Immediate-Mode GUI (IMGUI) A UI paradigm where widgets are not persistent objects in memory; instead, your application state lives in a plain Rust struct and every frame you call functions like ui.checkbox(...) or ui.button(...) that simultaneously query input and emit draw commands (docs.rs/egui). Analogy: redrawing the active copper and silkscreen layers directly from the board data model on every display refresh. Avoid: "stateless UI" (your Rust struct holds persistent state across frames; only the widget tree is transient).
Retained-Mode GUI A traditional UI paradigm (DOM, Qt, Flutter widget trees) where the framework stores a persistent graph of widget objects with their own internal state that must be synchronised with application state via callbacks or listeners. Avoid: "stateful UI" (both immediate-mode and retained-mode UIs manage state; they differ in whether widgets retain a separate copy of it).
Manifest (Cargo.toml) The configuration file for a Rust package defining its metadata, external dependencies (like eframe), and compiler optimisation profiles (Cargo Book). Avoid: "package.json" or "build script" (Cargo.toml is declarative metadata; build.rs is a build script).
Struct (struct) A composite Rust data type that groups named fields together into a single unit of ownership (Rust Book §5.1), such as struct PcbReviewerApp. Avoid: "class" or "object" (Rust structs have no inheritance hierarchy and separate data layout from impl behaviour blocks).
Default Trait (Default) A standard library trait granting a type a canonical parameterless constructor (T::default()) for initial values (std::default::Default). Avoid: "default constructor" (Rust has no implicit constructors; Default::default() is an explicit trait method).
Heap Box (Box<T>) A smart pointer that allocates a value of type T on the heap and owns it through a fixed-size pointer on the stack (Rust Book §15.1), used to hand Box<dyn eframe::App> to eframe::run_native. Avoid: "raw pointer" (Box<T> uniquely owns its heap allocation and drops it deterministically when it goes out of scope).
Shared Borrow (&T) An immutable, read-only reference to a value of type T; multiple &T references can coexist simultaneously, but the target cannot be mutated while borrowed (Rust Book §4.2). Avoid: "pointer" or "copy" (a shared borrow is a compile-time lifetime-checked non-owning reference).
Mutable Borrow (&mut T) An exclusive, read-write reference to a value of type T that allows a called function (such as ui.checkbox(&mut self.show_top_copper, "Top Cu")) to read and modify a value in place without taking ownership (Rust Book §4.2). Avoid: "mutable pointer" or "pass by reference" (emphasise exclusivity: no other &T or &mut T to the same data may overlap).
Closure (|ui| { ... }) An anonymous inline function that can capture variables (like self) from its surrounding scope, with parameters written between vertical pipes |...| (Rust Book §13.1). Avoid: "callback" (in egui, panel closures execute synchronously right now during the current frame, not asynchronously later).
Copy Semantics (Copy) A marker trait for small stack-only values (Pos2, Vec2, Rect, Color32, Stroke, PcbLayer) that duplicate trivially by copying bits on assignment or function call without moving ownership (Rust Book §4.1). Avoid: "deep clone" (Copy is an implicit bitwise stack copy; heap-allocating duplicates use explicit .clone()).
Enum & Exhaustive match An algebraic data type enumerating a closed set of variants (PcbLayer, Option<NetId>, ActiveTool) where match forces every variant to be handled at compile time (Rust Book §6). Avoid: "integer constants" (Rust enums are strongly typed sum types and can carry per-variant data).
Optional Value (Option<T>) Rust's null-free enum representing a value that is either present (Some(T)) or absent (None), used for hover and selection state (Option<NetId>). Avoid: "null" or "nullable pointer" (Rust references are never null; absence is always explicit in the type signature).
String Slice vs. Owned String (&'static str vs. String) &'static str is a zero-allocation borrowed view into UTF-8 text baked into the compiled binary, whereas String is a heap-allocated, growable UTF-8 buffer constructed dynamically with format!(...) or mutated by TextEdit::singleline (Rust Book §8.2). Avoid: calling both "strings" without distinguishing borrowed slices (&str) from owned buffers (String).
Disjoint Struct Field Borrowing Rust's borrow checker tracks borrows per struct field when fields are accessed directly, allowing a shared borrow (&self.board) and a mutable borrow (&mut self.view) to coexist in the same scope (Rustonomicon). Avoid: "borrowing self twice" (borrowing distinct fields &self.board and &mut self.view works precisely because whole-struct &mut self is split across disjoint fields).
Data-Carrying Enum (Tagged Union) A Rust enum whose variants store variant-specific payload fields directly inside the variant (such as ActiveTool::Measuring { start_mm: Pos2, end_mm: Pos2 }), making invalid state combinations unrepresentable (Rust Book §6.1). Avoid: "boolean flag + optional fields" (which permit contradictory states like is_measuring = true with start_mm = None).
eframe::App The root application trait in eframe whose core method, fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame), is invoked on every repaint (docs.rs/eframe). Avoid: "window controller" (eframe::App describes per-frame UI state transitions and rendering).
egui::Context (ctx) The top-level handle to egui for the entire window (accessible via ui.ctx()): manages input state, fonts, style, widget ID memory, and floating windows (docs.rs/egui). Avoid: confusing ctx: &egui::Context (whole-window coordinator) with ui: &mut egui::Ui (a bounded region or root panel container).
egui::Ui (ui) A bounded rectangular region (passed directly to eframe::App::ui, Panel::show, or CentralPanel::show) with an automatic layout cursor on which you invoke widget methods (ui.heading, ui.checkbox, ui.button, ui.allocate_painter) (docs.rs/egui). Avoid: storing Ui across frames (Ui is a short-lived per-frame layout builder).
egui::Response The immediate return value of every widget call (e.g., ui.button("Reset").clicked() or .hovered()) reporting how the user interacted with that widget during the current frame (docs.rs/egui). Avoid: "event listener" (Response is a plain value inspected synchronously inside ui).
egui::Painter The 2D vector drawing API returned by ui.allocate_painter(size, sense) that emits clipped shapes (rect_filled, line_segment, circle_filled, text) in back-to-front painter's algorithm order (docs.rs/egui). Avoid: "GPU shader" (Painter tessellates 2D vector primitives into vertex/index meshes for eframe to render).
egui::emath::TSTransform A 2D translation plus uniform scaling transform (scaling * pt + translation) with .inverse() for mapping between physical board millimetres (world space) and window points (screen space) (docs.rs/emath). Avoid: manually mixing unscaled millimetres and screen pixels without a typed coordinate transform.
Mutation Testing (cargo-mutants) A verification technique that injects small deliberate faults (mutants, such as flipping true to false, replacing + with -, or emptying a method body) and verifies that cargo test fails for every injected fault (mutants.rs). Avoid: equating "100% line coverage" with verified behaviour (line coverage only proves code ran, whereas caught mutants prove assertions fail when logic breaks).
Headless UI Harness (egui_kittest) The official testing library for egui that drives an app or widget closure without opening an OS window, supporting semantic AccessKit widget queries (get_by_label), simulated clicks/key presses, and offscreen visual snapshots (docs.rs/egui_kittest). Avoid: skipping eframe::App::ui forever once headless UI testing is available in Act II+.
Hash Map & Entry API (HashMap<K, V>) A hash-table collection mapping unique keys K: Eq + Hash to values V, whose .entry(key) method returns Entry::Vacant or Entry::Occupied for in-place inspection or insertion without double lookups or silent overwrites (std::collections::HashMap). Avoid: relying on HashMap iteration order in immediate-mode UIs (sort keys first so widget order is deterministic).
Floating Window & Widget Identity (egui::Window, egui::Id) egui::Window renders a floating, draggable overlay layer above panels, keyed by a deterministic egui::Id::unique(...) hash so egui remembers window state without collisions (docs.rs/egui). Avoid: creating multiple windows or grids with identical titles and no disambiguating .id(...).
Struct Lifetime ('a) & egui::Widget A generic lifetime annotation <'a> on a builder struct (such as LayerSwatch<'a>) proving that the struct cannot outlive the &'a mut state fields it borrows while impl<'a> egui::Widget for LayerSwatch<'a> consumes self inside ui.add(...) (Rust Book §10.3). Avoid: thinking lifetimes change runtime performance ('a is purely a compile-time borrow check erased before code generation).
Engine-First Crate Layering (L0–L7) A multi-crate Cargo [workspace] architecture that isolates pure domain state (crates/pcb-doc at L1, depending only on L0 emath) from UI rendering (pcb-reviewer at L6/L7), enforced by Tier 1 manifest gates (validate_l1_manifest_no_ui_deps) so domain tests and cargo-mutants run in milliseconds without linking eframe (Cargo Book §3.3). Avoid: importing egui::Color32 or eframe inside L1 domain crates (expose UI-agnostic RGB tuples or geometry primitives in L1 and bridge them in L6).
Versioned Envelope Serialization (serde, thiserror) Wrapping a serialized domain model in an explicit envelope struct (ReviewSessionEnvelope { schema_version, board_id, board }) and returning typed Result<T, SessionIoError> values derived via thiserror::Error so malformed JSON or incompatible schema versions surface as non-destructive UI banners rather than panics (serde.rs). Avoid: calling .unwrap() on serde_json::from_str or using .. when destructuring persisted envelopes.
Copy-on-Write (Arc::make_mut, Arc::ptr_eq) Wrapping document collections in std::sync::Arc<...> so cloning a BoardModel snapshot copies only four 8-byte pointers (O(1)), while mutating a collection via Arc::make_mut clones the inner buffer only when strong_count > 1 and leaves untouched buffers pointer-shared (Arc::ptr_eq == true) (std::sync::Arc). Avoid: deep-cloning Vec<TraceSegment> or HashMap<PinId, ReviewNote> on every edit or snapshot.
Undo/Redo Ring Buffer & Drag Coalescing (VecDeque, coalesce_key) A bounded history stack (VecDeque<HistoryEntry>) that evicts oldest snapshots via pop_front(), swaps snapshots in O(1) via std::mem::replace, and merges consecutive 60-FPS egui::Slider drag frames sharing Some(coalesce_key) into a single undo entry until Response::drag_stopped() calls commit_coalesce() (std::collections::VecDeque). Avoid: pushing a new undo entry on every slider_resp.changed() frame without a coalesce_key.
Command Registry & panic_hunt Fuzzer (CommandSpec) A static slice (COMMAND_SPECS: &[CommandSpec]) pairing canonical command IDs ("review.addPin", "session.inspect") with an EnabledFn precondition guard (fn(&BoardModel, &BoardHistory) -> Result<(), String>) and a RunFn execution pointer, verified by a Tier 5 panic_hunt fuzzer that feeds adversarial JSON payloads into execute_command. Avoid: scattering untyped state mutations across ad-hoc button callbacks without parameter bounds checks.
Viewport Frustum Culling (Rect::intersects) Testing each pad's or stroke-expanded trace's axis-aligned bounding box (bounds_mm().intersects(viewport_mm)) before submitting geometry to egui::Painter, skipping off-screen primitives in O(N) bounds checks rather than tessellating invisible meshes (docs.rs/emath). Avoid: computing trace bounding boxes from centreline endpoints alone without expanding by width_mm * 0.5.
Non-Blocking Background Channel (std::sync::mpsc::try_recv) Offloading file parsing onto a worker thread (std::thread::spawn) that streams ImportJobMessage progress updates over an mpsc::channel, while eframe::App::ui drains ready messages via rx.try_recv() and calls ctx.request_repaint() while ImportJobState::Running is active (std::sync::mpsc). Avoid: calling blocking rx.recv() inside eframe::App::ui (which freezes the UI thread).
Process-Wide GPU Lock & Frame Snapshot Digest (gpu_lock, FrameSnapshotDigest) A OnceLock<Mutex<()>> guard (let _gpu = gpu_lock(); using PoisonError::into_inner) acquired on the first line of GPU/snapshot tests to serialize concurrent driver access, paired with a deterministic 64-bit FNV-1a FrameSnapshotDigest over visible layer masks, culled geometry counts, and DRC markers. Avoid: running multiple concurrent wgpu or snapshot harnesses across threads without acquiring gpu_lock().
Zero-Copy S-Expression Parser Combinators (nom::IResult, SexprNode) Functional parser combinators (delimited, many0, alt, take_while1) from nom that thread an unconsumed &str slice through IResult<&str, SexprNode> in a standalone L0 crate (crates/kicad-sexpr) enforced by validate_l0_standalone_manifest (docs.rs/nom). Avoid: writing ad-hoc regexes or byte-index loops that panic on unclosed parentheses or unterminated string literals.
Pinned KiCad Corpus Oracle & Ratchet Floors (CORPUS_PASS_FLOOR, CORPUS_ROUNDTRIP_FLOOR) A Tier 4 verification harness (run_pinned_kicad_corpus) that lowers real-structure .kicad_pcb S-expression fixtures into BoardModel, re-exports them (to_kicad_pcb_sexpr), and asserts non-decreasing pass and round-trip floor constants (reloaded == board). Avoid: testing a CAD parser on a single synthetic toy string without lossless round-trip oracles.
Embedded SQL AST Validation & Foreign-Key Store (turso_parser, TursoReviewStore) Validating SQLite/Turso DDL and DML statements (Stmt::CreateTable, Stmt::Insert, Stmt::Select, Stmt::Begin, Stmt::Commit, Stmt::Rollback) with turso_parser::parser::Parser before executing idempotent schema migrations and foreign-key-checked SqlReviewRecord queries in TursoReviewStore. Avoid: concatenating unvalidated raw SQL strings or inserting review threads for unregistered board_id keys.
Atomic SQL Transactions, Audit Hash Chain & Local-First Replica Sync (AuditLogEntry, verify_audit_chain) Executing multi-pin status sign-offs on a staged transaction snapshot that commits or rolls back atomically (execute_atomic_signoff_batch), chaining each AuditLogEntry via compute_audit_entry_hash(seq, pin_id, from_status, to_status, prev_hash), and merging remote replica rows when remote.revision > local.revision (sync_with_remote_replica). Avoid: partially applying a failed sign-off batch or overwriting newer local edits with stale remote revisions.
LLM-Native Spatial & Electrical Queries (schemars::JsonSchema, SpatialNeighborhoodReport, NetTopologyReport) Deriving JSON Schema Draft 2020-12 definitions from Rust structs (#[derive(JsonSchema)]) and projecting dense CAD geometry into bounded, token-efficient spatial neighborhood (query_spatial_neighborhood), net connectivity (query_net_topology), and custom DRC (run_custom_drc) reports with max_items truncation caps. Avoid: dumping raw multi-megabyte .kicad_pcb S-expressions into an LLM context window.
Headless Model Context Protocol Server & In-Memory Duplex Client (rmcp, #[tool_router], tokio::io::duplex) Exposing BoardModel queries and review actions over the official Rust MCP SDK (rmcp::ServerHandler, #[tool_router], #[tool], Parameters<T>, Json<T>) together with kicad:// resources and structured prompts, verified deterministically in-memory by connecting PcbMcpServer and MockMcpClient across tokio::io::duplex streams. Avoid: requiring external LLM API keys or network sockets to unit-test MCP tool schemas and handlers.
Constant-Time Bearer Auth & Cropped PNG Region Snapshots (verify_bearer_token, capture_cropped_region_png) Authenticating loopback GUI control commands (LoopbackControlBridge) with a bitwise XOR byte accumulator (verify_bearer_token) that prevents timing side-channel leaks, and rendering bounded PCB regions (width_px * height_px <= 16_384) into PNG_MAGIC_HEADER-verified (\x89PNG\r\n\x1a\n) snapshots (CroppedPngSnapshot). Avoid: using short-circuiting string equality (==) on bearer tokens or returning unbounded 4K screenshots to vision models.
Embedded egui MCP Inspector Workbench & Agent Playbooks (McpInspectorWorkbench, McpTransportMode) An in-app egui protocol inspector that toggles between McpTransportMode::HeadlessDuplex and McpTransportMode::BridgedLoopback, records RpcFrameRecord JSON-RPC 2.0 traffic, and executes deterministic 4-step hardware review playbooks (run_power_integrity_playbook). Avoid: shipping AI-controllable desktop tools without an offline workbench to inspect and replay JSON-RPC tool calls.

Quick Lookup: Key eframe & egui APIs by Lesson