Skip to main content

Crate egui_macview

Crate egui_macview 

Source
Expand description

§egui-macview

Deterministic macOS AppKit Layout Engines, Authentic Control Primitive Suite, and CoreAnimation Physics Runtime for egui on Windows, macOS, Linux, and Web.

Crates.io Documentation License Tests


§1. Architectural Overview

Standard egui relies on content-driven streaming flow: widgets dynamically compute their own margins and sequentially advance the cursor. While convenient for rapid prototyping, streaming flow poses challenges when building pixel-exact desktop application suites (like Xcode, Final Cut Pro, or macOS System Settings) that require:

  1. Mathematical Layout Determinism: Subpixel-snapped boundaries, zero-margin outer containers, and formal layout contracts that mathematically prevent clipping and content overlap.
  2. AppKit Control Parity: Authentic macOS design language—including focused control rings, segmented pill buttons with animated selection thumbs, cyclic Tab-chain FSMs, and discrete stepper steppers with unit suffixes.
  3. CoreAnimation Physics: Frame-rate independent damped harmonic oscillator spring motion (CASpring), producing exact Apple perceptual micro-interactions across 60Hz, 120Hz ProMotion, and 144Hz displays.

egui-macview solves this by introducing retained NIB-style layout framing, an authentic AppKit control suite, and a high-assurance physics engine built directly on top of egui 0.37.0.


The crate includes an interactive capability showcase demonstrating all primitives working together in a production-grade multi-window environment.

cargo run --example macview_gallery

§The 6 Master-Detail Capability Screens

Clicking the Screens group in the left sidebar switches the central work area across 6 specialized AppKit capability screens:

┌─────────────────┬──────────────────────────────────────────┬──────────────────┐
│ Left Sidebar    │ Center Work Area (Master-Detail)         │ Right Inspector  │
│                 │                                          │                  │
│ • Screens       │ 1. Interactive Canvas & Physics          │ • Presets        │
│   ├─ 1. Canvas  │    - 2D Affine Matrix live transforms    │   ├─ Default NIB │
│   ├─ 2. Vectors │    - Damped CASpring pulse on clicks     │   ├─ Compact HUD │
│   ├─ 3. Tokens  │ 2. Vector Assets Gallery                 │   └─ Expanded    │
│   ├─ 4. Finder  │    - 14 Cupertino true-vector glyphs     │ • Dimensions     │
│   ├─ 5. AVKit   │    - Live search filter (⌘K / Ctrl+K)    │ • Layout & Mask  │
│   └─ 6. Controls│ 3. W3C Design Tokens & WCAG Engine       │   [L][ C ][R][F] │
│                 │    - Token catalogue (colors/metrics)    │ • 2x2 Matrix     │
│ • Presets       │    - Real-time WCAG AA contrast tester   │ • Live Swatches  │
│   ├─ Default    │ 4. Finder & Publishing Data Browser      │                  │
│   ├─ Compact    │    - NSPathControl breadcrumbs & table   │                  │
│   └─ Expanded   │ 5. AVKit Media & Timeline Studio         │                  │
│                 │    - Waveform scrubber & VU meters       │                  │
│                 │ 6. Advanced Controls (SPEC-012)          │                  │
│                 │    - Combo, Date, Tab, Grid, Player, Box │                  │
└─────────────────┴──────────────────────────────────────────┴──────────────────┘
  1. Screen 1: Interactive Canvas & Physics
    • 2D Affine Matrix Manipulation: Live rotation ($\theta$), scaling ($25%\dots200%$), skew, and translation.
    • CASpring Harmonic Oscillator: Analytical spring pulse triggered by canvas clicks or inspector actions.
    • Layout & Alignment Mask Integration: Segmented [Left] [Center] [Right] [Fill] control in the inspector dynamically updates the card’s anchor position or expands it to full container width with zero clipping.
  2. Screen 2: Vector Assets Gallery
    • 14 Authentic Cupertino Symbols: 100% vector TrueType glyphs (MacSymbol::Search, ChevronDown, Gear, Checkmark, etc.) with zero emoji-bleed on Windows or Linux.
    • Instant Search Filtering: Host-adaptive search shortcut ([🔍 ⌘K] on macOS, [🔍 Ctrl+K] on Windows/Linux) with live fuzzy substring matching and metadata inspection cards.
  3. Screen 3: W3C Design Tokens & WCAG Contrast Engine
    • DTCG Token Catalogue: Direct visualization of tokenized colors, elevations, corner radii, and optical typography.
    • Dynamic Contrast Engine: Real-time evaluation of relative luminance ($L \le 0.179$) and contrast ratios against WCAG AA standards with pass/fail badges.
  4. Screen 4: Finder & Publishing Data Browser
    • MacPathControl: Interactive file system breadcrumb path bar with vector folder icons.
    • MacTableView: Multi-column data table with alternating rows, keyboard navigation, and sort chevrons.
    • MacTokenField: Capsule tagging pill input with comma/Enter commit and Backspace removal.
  5. Screen 5: AVKit Media & Timeline Studio
    • MacTrimScrubber: QuickTime/AVKit media timeline trim bar with waveform bars, In/Out trim handles, and floating timecode badge.
    • MacCircularSlider & MacLevelIndicator: Authentic continuous rotary dial and stereo VU meters with peak hold.
    • MacRatingIndicator: 5-star rating control with half-star precision and precomputed geometry.
  6. Screen 6: Advanced Media, Scheduling & Grid Controls (SPEC-012)
    • MacPlayerView: AVKit playback presentation layer with QuickTime floating HUD pod, inline transport, and auto-hide timing.
    • MacDatePicker: Dual date/time picker with integrated stepper, 12-hour analog clock face, and calendar matrix grid.
    • MacComboBox: Hybrid text input with trailing dropdown trigger and viewport-clamped filterable popover list.
    • MacTabView: Flipped-coordinate tab container with bezel bordered tabs and borderless switching.
    • MacDisclosureGroup: Collapsible container with triangular chevron, CASpring rotation, and pill buttons.
    • MacCollectionView: High-performance 2D grid layout with viewport culling and spatial keyboard navigation.
    • MacBox: Container grouping with title badge, rounded corners, and standardized AppKit insets.

§3. Core Component Suite & API Reference

§3.1 Layout Engines

ComponentAppKit EquivalentDescription
MacSplitViewNSSplitViewDual hairline draggable divider with min/max constraint protection and cursor styling.
MacFixedViewRetained NIB FrameExact coordinate subview placement guaranteeing zero margin bleed and exact pixel alignment.
MacRowFlexible Cell RowAuto-budgeting horizontal cell layout with analytical $O(n)$ space distribution.
MacScrollViewNSScrollViewFloating overlay scrollbars with zero gutter reservation and smooth auto-fade timers.
MacStackViewNSStackViewAuto-layout linear stacking container with token-governed spacing and section separators.
MacBoxNSBoxPrimary container grouping with title badge, rounded corners, and standardized content insets.

§3.2 Authentic Control Primitives

ComponentAppKit EquivalentKey Features
MacInputCellNSTextFieldCompact text input with external focus ring, cyclic Tab-chain FSM, and transactional buffer commit.
MacSegmentedControlNSSegmentedControlApple segmented pill with smooth animated sliding selection indicator and dark-mode contrast.
MacOutlineViewNSOutlineViewHierarchical outline view with disclosure triangles, indentation steps, and custom accessory buttons.
MacToggleNSSwitchNative macOS toggle switch with system green active fill and smooth spring thumb transitions.
MacSliderNSSliderContinuous tracking slider with tick marks, keyboard arrow nudging, and token-driven dimensions.
MacStepperNSStepperDiscrete scalar increment/decrement buttons with float epsilon wrapping protection and unit suffix formatting.
MacPopUpButtonNSPopUpButtonTrailing double chevrons with dropdown selection overlay and auto-clamping viewport positioning.
MacSearchFieldNSSearchFieldMagnifying glass glyph, instant clear (×) button, and keyboard escape handling.
MacColorWellNSColorWellColor swatch preview with translucent alpha checkerboard underlay and popover picker.
MacProgressIndicatorNSProgressIndicatorDeterminate/indeterminate horizontal progress bar (6.0 pt / 4.0 pt) and 12-spoke stepped circular activity spinner (Regular, Small, Mini).
MacTableViewNSTableView + NSTableHeaderViewMulti-column data table with 24.0 pt sortable column headers, alternating row backgrounds, single/Shift/Cmd row selection, and keyboard navigation.
MacTokenFieldNSTokenFieldInteractive capsule tag/pill input with comma/Enter commit, per-pill × removal, Backspace pop, flow wrapping, and optional character counter.
MacLevelIndicatorNSLevelIndicatorContinuous and discrete segmented capacity/audio level meter (horizontal or vertical) with green/yellow/red thresholds and peak-hold marker.
MacTrimScrubberAVPlayerView Trim BarQuickTime / AVKit media timeline trim bar with waveform bars, named zones, yellow selection handles, dimmed outside regions, and draggable playhead with MM:SS.d badge.
MacPathControlNSPathControlInteractive file/folder breadcrumb bar with vector icons, chevron separators, clickable segments, and optional trailing Choose... button.
MacMenuBarNSMenu / App MenuAuthentic menu bar with cascading submenus, global keyboard shortcuts, and dynamic width auto-calculation guaranteeing $\ge 24,\text{pt}$ clearance between titles and accelerators.
MacCommandPaletteSpotlight / Quick OpenFloating modal command runner with fuzzy subsequence scoring, category badges, and keyboard navigation.
MacPlayerViewAVPlayerViewAVKit media presentation layer with QuickTime floating HUD pod, inline transport bar, and circular transport controls.
MacDatePickerNSDatePickerDate/time scheduling control with stepper field, 12-hour analog clock face, and calendar matrix grid.
MacComboBoxNSComboBoxHybrid text input with integrated dropdown button and viewport-clamped filterable popover list.
MacTabViewNSTabViewFlipped-coordinate segmented tab container supporting bezel bordered tabs and borderless card switching.
MacDisclosureGroupNSButton DisclosureCollapsible container with triangular disclosure chevron, CASpring rotation, and pill buttons.
MacCollectionViewNSCollectionViewHigh-performance 2D grid layout engine with 2D viewport culling and spatial keyboard navigation.

§3.3 CoreAnimation Physics (CASpring)

CASpring provides the closed-form analytical solution to the damped harmonic oscillator:

$$m \ddot{x} + c \dot{x} + k x = 0$$

  • Response ($T_0$) & Damping Ratio ($\zeta$): Configured via Apple design tokens (macview.motion.spring.default).
  • Analytically Exact: Evaluates position and velocity at any arbitrary time $t$ in microseconds with zero numerical drift or Euler integration lag.
  • Display Agnostic: Delivers mathematically identical motion at 60 FPS, 120 FPS ProMotion, or 240 FPS.

§4. Developer Quick Start

§Add Dependency

Add egui-macview to your Cargo.toml:

[dependencies]
egui = "0.37.0"
egui-macview = "0.6.0"

§Complete Code Example

use egui_macview::{
    MacAppearance, MacInputCell, MacSegmentedControl, MacStepper, MacTheme, MacToggle,
};

pub struct MySettingsView {
    theme: MacTheme,
    selected_tab: usize,
    username: String,
    notifications_enabled: bool,
    zoom_level: f64,
}

impl MySettingsView {
    pub fn new() -> Self {
        Self {
            theme: MacTheme::new(MacAppearance::DarkAqua),
            selected_tab: 0,
            username: "developer@apple.internal".to_string(),
            notifications_enabled: true,
            zoom_level: 100.0,
        }
    }

    pub fn ui(&mut self, ui: &mut egui::Ui) {
        // 1. Apple Segmented Tab Selector
        MacSegmentedControl::new(&["General", "Appearance", "Advanced"], self.selected_tab)
            .theme(&self.theme)
            .show(ui, |new_idx| {
                self.selected_tab = new_idx;
            });

        ui.add_space(12.0);

        // 2. Compact Input with Cyclic Tab Chain
        MacInputCell::new("input_user", &mut self.username)
            .theme(&self.theme)
            .width(220.0)
            .show(ui);

        ui.add_space(8.0);

        // 3. Native Switch Toggle
        ui.horizontal(|h_ui| {
            h_ui.label("Enable Push Notifications:");
            h_ui.add(MacToggle::new(&mut self.notifications_enabled).theme(&self.theme));
        });

        ui.add_space(8.0);

        // 4. Stepper with Unit Formatting
        ui.horizontal(|h_ui| {
            h_ui.label("Display Scale:");
            MacStepper::new(&mut self.zoom_level, 25.0..=200.0, 5.0)
                .theme(&self.theme)
                .show(h_ui);
            h_ui.label(format!("{:.0} %", self.zoom_level));
        });
    }
}

§5. Quality Assurance & Standards (GL-1015 Compliance)

All code adheres strictly to GL-1015 (De Verankeringswet & Software Engineering Standards):

  • 100% Red-Green Test Anchoring: Every requirement, glitch fix, and layout invariant is anchored by failing red COTS tests prior to implementation.
  • Zero Host OS Emoji Bleed: Guaranteed 100% monochrome vector rendering via MacSymbol TrueType glyphs.
  • Zero Dead Controls: Every UI control bidirectionally mutates state and updates visual geometry in real time.
  • Test Suite Pass Rate: 142 passed, 0 failed, 1 ignored (physical Mac SSH differential test runner).
    • appkit_primitives_tests (35 tests)
    • architecture_guard_tests (7 tests)
    • cots_red_baseline_tests (7 tests)
    • high_assurance_invariants_tests (4 tests)
    • macbook_parity_differential_tests (6 tests + 1 live SSH test)
    • menu_and_palette_tests (20 tests)
    • micro_animations_and_hud_tests (7 tests)
    • studio_controls_v05_tests (6 tests)
    • symbol_tests (6 tests)
    • undo_and_feedback_tests (10 tests)
    • wcag_contrast_and_visuals_tests (8 tests)
    • zero_hardcoding_and_primitive_tests (4 tests)
    • Documentation tests (20+ tests)

§6. License

Dual-licensed under either of:

at your option.

Grounded in Apple AppKit, macOS Human Interface Guidelines (HIG), and W3C DTCG Design Tokens.

§Architecture & Highlights

§Quick Start Example

use egui_macview::{
    CASpring, MacAppearance, MacSlider, MacStackView, MacTheme, MacToggle,
};

// 1. Initialize macOS dynamic theme (Aqua or DarkAqua)
let theme = MacTheme::new(MacAppearance::DarkAqua);

// 2. Assemble controls inside an NSStackView linear layout
let mut enabled = true;
let mut volume = 75.0f32;

MacStackView::vertical()
    .theme(&theme)
    .show_separators(true)
    .show(ui, |stack| {
        stack.add(|ui| {
            ui.add(MacToggle::new(&mut enabled).theme(&theme));
        });
        stack.add(|ui| {
            MacSlider::new(&mut volume, 0.0..=100.0)
                .theme(&theme)
                .ticks(5, true)
                .show(ui);
        });
    });

// 3. Analytical spring physics evaluation
let spring = CASpring::new(0.35, 0.85);
let displacement = spring.evaluate(0.15); // t = 150ms

Re-exports§

pub use symbols::setup_symbols_font;
pub use symbols::MacSymbol;
pub use symbols::CUPERTINO_ICONS_FONT_BYTES;
pub use symbols::CUPERTINO_ICONS_FONT_NAME;
pub use theme::contrast_ratio;
pub use theme::relative_luminance;
pub use theme::MacAppearance;
pub use theme::MacBackgroundStyle;
pub use theme::MacTheme;
pub use theme::WindowControlsStyle;
pub use controls::calculate_pan_weights;
pub use controls::MacBox;
pub use controls::MacButtonCell;
pub use controls::MacCircularSlider;
pub use controls::MacCollectionView;
pub use controls::MacCollectionViewFlowLayout;
pub use controls::MacColorWell;
pub use controls::MacComboBox;
pub use controls::MacControlSize;
pub use controls::MacDate;
pub use controls::MacDatePicker;
pub use controls::MacDatePickerElementFlags;
pub use controls::MacDatePickerStyle;
pub use controls::MacDisclosureButton;
pub use controls::MacDisclosureGroup;
pub use controls::MacInputCell;
pub use controls::MacLevelIndicator;
pub use controls::MacLevelIndicatorStyle;
pub use controls::MacLevelOrientation;
pub use controls::MacOutlineRow;
pub use controls::MacOutlineRowResponse;
pub use controls::MacOutlineTree;
pub use controls::MacOutlineView;
pub use controls::MacPathComponent;
pub use controls::MacPathControl;
pub use controls::MacPathControlResponse;
pub use controls::MacPlayerControlsStyle;
pub use controls::MacPlayerView;
pub use controls::MacPopUpButton;
pub use controls::MacProgressControlSize;
pub use controls::MacProgressIndicator;
pub use controls::MacProgressStyle;
pub use controls::MacRatingIndicator;
pub use controls::MacSearchField;
pub use controls::MacSegmentedControl;
pub use controls::MacSlider;
pub use controls::MacSortDirection;
pub use controls::MacStepper;
pub use controls::MacTabItem;
pub use controls::MacTabStyle;
pub use controls::MacTabView;
pub use controls::MacTableColumn;
pub use controls::MacTableView;
pub use controls::MacTableViewOutput;
pub use controls::MacTableViewResponse;
pub use controls::MacThumbnailCell;
pub use controls::MacTimelineZone;
pub use controls::MacToggle;
pub use controls::MacTokenField;
pub use controls::MacTrimScrubber;
pub use controls::MacTrimScrubberResponse;
pub use controls::UNIT_STAR;
pub use controls::MacInsets;
pub use feedback::clamp_menu_rect;
pub use feedback::MacContextMenu;
pub use feedback::MacToast;
pub use feedback::MacToastManager;
pub use feedback::ToastLevel;
pub use layout::is_window_active;
pub use layout::subpixel_snap;
pub use layout::subpixel_snap_pos;
pub use layout::subpixel_snap_rect;
pub use layout::MacFixedView;
pub use layout::MacForm;
pub use layout::MacFormUi;
pub use layout::MacFrame;
pub use layout::MacRow;
pub use layout::MacScrollView;
pub use layout::MacScrollViewOutput;
pub use layout::MacSplitOrientation;
pub use layout::MacSplitView;
pub use layout::MacStackAlignment;
pub use layout::MacStackOrientation;
pub use layout::MacStackUi;
pub use layout::MacStackView;
pub use layout::MacStackViewOutput;
pub use motion::CASpring;
pub use navigation::CommandPaletteItem;
pub use navigation::MacCanvasFooter;
pub use navigation::MacCanvasFooterAction;
pub use navigation::MacCommandPalette;
pub use navigation::MacKeyboardShortcut;
pub use navigation::MacMenuBar;
pub use navigation::MacMenuItemKind;
pub use navigation::MacToolbar;
pub use navigation::MacToolbarResponse;
pub use navigation::NSMenu;
pub use navigation::NSMenuItem;
pub use navigation::COMMAND_PALETTE_HEIGHT;
pub use navigation::COMMAND_PALETTE_WIDTH;
pub use state::NSUndoManager;
pub use state::DEFAULT_UNDO_CAPACITY;
pub use surfaces::MacCard;
pub use surfaces::MacFloatingInfoBox;
pub use surfaces::MacPanel;
pub use surfaces::MacPopover;
pub use surfaces::MacPopoverArrowEdge;
pub use tokens::sf_pro_tracking;
pub use tokens::ColorWellMetrics;
pub use tokens::LayoutMetrics;
pub use tokens::LevelIndicatorMetrics;
pub use tokens::MacColorTokens;
pub use tokens::MacControlMetrics;
pub use tokens::MacDesignTokens;
pub use tokens::MacMotionTokens;
pub use tokens::MacTypographyTokens;
pub use tokens::OutlineViewMetrics;
pub use tokens::PathControlMetrics;
pub use tokens::PopUpButtonMetrics;
pub use tokens::ProgressIndicatorMetrics;
pub use tokens::ProgressSizeMetrics;
pub use tokens::ScrollViewMetrics;
pub use tokens::SearchFieldMetrics;
pub use tokens::SliderMetrics;
pub use tokens::SplitViewMetrics;
pub use tokens::StackViewMetrics;
pub use tokens::StepperMetrics;
pub use tokens::TableViewMetrics;
pub use tokens::ThumbnailCellMetrics;
pub use tokens::ToggleMetrics;
pub use tokens::TokenFieldMetrics;
pub use tokens::TrimScrubberMetrics;

Modules§

controls
macOS AppKit Authentic Controls Suite for egui.
feedback
State feedback surfaces: Context Menus and Animated Toast Notifications.
layout
Layout engines: MacFixedView (absolute pt), MacSplitView (NSSplitView), MacScrollView (NSScrollView), MacStackView (NSStackView), and MacForm (NSForm).
motion
macOS CoreAnimation Spring Physics Engine.
navigation
Desktop Navigation, Canvas Footer, and Spotlight Command Palette Suite.
state
State integrity, transaction management, and snapshot history.
surfaces
macOS AppKit Panel, Popover & Card Surfaces.
symbols
AppKit Vector Symbols, Iconography & CupertinoIcons Engine (SPEC-008).
theme
macOS AppKit Dynamic Theming System.
tokens
Typed W3C DTCG-compliant Design Token models for egui-macview.

Constants§

VERSION
Crate release version string extracted from Cargo.toml.