Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ferrokit: native Mac apps in Rust

Ferrokit is a native macOS GUI framework for Rust. It puts a real Mac app on top of your Rust code: every view is a real AppKit control (an actual NSTableView, NSOutlineView, NSTextView, NSSplitView), built once and updated in place by fine-grained signals.

  • Your Rust code, a real Mac app on top. The UI calls your crates directly, in one language and one cargo build: no Swift layer, no FFI bridge, no types written twice, no Xcode project.
  • The real controls, without the ceremony. Not a web view, and not a GPU renderer imitating AppKit, so scrolling, keyboard navigation, VoiceOver, spell check, input methods and Dark Mode are Apple’s own. You declare views and signals; Ferrokit writes the data sources and delegates.
  • Apps that check themselves. An app can run its own checks through its real controls, unattended, and every project ships an AGENTS.md, so you or your AI assistant can build a change and know it works.

Built with it: Rowboat, a SQLite editor in the Mac App Store, about 17,000 lines of Rust (how it’s made).

It’s Mac only, on purpose, and needs macOS 15 or later. If you need Windows or Linux too, read the comparison first: other toolkits fit that better.

Try it in one command

git clone https://github.com/lhassa8/ferrokit && cd ferrokit && cargo run --release -p ferrokit --example sql_browser

That’s a SQLite browser over a generated sample of a million orders: click orders, fling the table, sort by total, type a query (⌘R runs it), switch to Dark Mode.

Or start your own app:

cargo install cargo-ferrokit && cargo ferrokit new my-app && cd my-app && cargo ferrokit run

What the code looks like

Views are built once. When a signal changes, only the views that read it update, in place: no virtual DOM, no diffing.

use ferrokit::*;

fn main() {
    let count = Signal::new(0);
    App::new("Counter")
        .window(Window::new("Counter").size(320.0, 140.0).view(
            vstack((
                text(move || format!("Clicked {} times", count.get())),
                button("Click me", move || count.update(|n| *n += 1)),
            ))
            .padding(20.0),
        ))
        .run();
}

What you get without writing it

Because each view is the real AppKit control:

  • VoiceOver reads AppKit’s own accessibility tree; testing::ax_audit finds controls you forgot to name.
  • Text is Apple’s text system: spell check, dictation, Japanese, Chinese and Korean input, the emoji picker, Find (⌘F), undo per window.
  • Tables and outlines are NSTableView and NSOutlineView: a million rows, sorting, arrow keys, ⌘C as tab-separated text, drag to the Finder.
  • The look follows the system: Dark Mode, accent colours, sidebar materials, Liquid Glass on macOS 26.
  • The system’s services: the Share menu, Quick Look, printing, notifications, menu-bar extras.

From idea to a shipped app

cargo ferrokit makes, runs, checks, bundles, notarises and packages for the Mac App Store, with Sparkle updates and crash reports for apps you ship yourself. See shipping to the Mac App Store.

Where things stand

Ferrokit is an alpha (0.15): the API still changes between minor versions, and it’s young (started October 2026), made by one person with an AI coding assistant, and has no outside users yet. About 580 self-checks across 18 example apps and cargo ferrokit’s templates run the real apps on macOS 15, 26 and the newest beta. Rowboat, a SQLite editor built with it, is in the Mac App Store.

If you build something with it, even a weekend toy, say so in an issue: what people build decides what comes next.

Ferrokit FAQ: native Mac apps in Rust

Short answers, each with a link to the longer one.

What is Ferrokit?

A native macOS GUI framework for Rust. Every view is a real AppKit control (an actual NSTableView, NSOutlineView, NSTextView, NSSplitView), built once and updated in place by fine-grained signals. The crate is ferrokit, with cargo-ferrokit to create, run, check, bundle and ship apps. It’s unrelated to other projects called Ferrokit.

Does Ferrokit draw its own widgets or use AppKit?

It uses AppKit’s own controls; it draws nothing of its own except where you ask it to (a canvas, charts). So scrolling, keyboard navigation, VoiceOver, spell check, input methods and Dark Mode behave exactly as in any other Mac app, because they are Apple’s code.

Does it run on Windows, Linux, iOS or the web?

No. It’s Mac only, on purpose, and needs macOS 15 or later. If your app must run elsewhere too, egui, Iced, Slint, Tauri, GPUI or NSH fit better: see the comparison. Windows is a possible second platform later, not planned for now.

Is Ferrokit ready for production?

It’s an alpha (0.15, November 2026): the API still changes between minor versions, it’s made by one person with an AI coding assistant, and it has no outside users yet. Against that: about 580 self-checks across 18 example apps and cargo ferrokit’s templates run the real apps on every change, on macOS 15 and 26, and Rowboat, a SQLite editor built with it, is in the Mac App Store. Pin the version and read the changelog before upgrading; Stability and support says what’s promised, and the migration guide covers the API changes before 1.0.

How does Ferrokit compare with egui, Iced, Slint, Tauri and GPUI?

They’re cross-platform and draw their own controls (Tauri uses a web view); Ferrokit is Mac only and uses AppKit’s. Pick one of them if the app must run on Windows or Linux, or is a tool, a game or a debug UI. Pick Ferrokit when it’s a Mac app that should behave exactly like one. The comparison page has the details, with links to each project’s docs. If you know egui, Iced or Slint already, Coming from egui, Iced or Slint maps their ideas onto Ferrokit’s, with the same app written in each.

Why not write the Mac app in Swift?

Because your code is in Rust. A Swift app on top of a Rust core needs a bridge: an FFI layer generated with uniffi or swift-bridge and kept in sync, the same types on both sides, async carried across the boundary, and an Xcode project beside your Cargo.toml. With Ferrokit the UI calls your crates directly, in one cargo build.

You also get AppKit’s own controls with a declarative API. Mac apps with big tables or serious text editing still use NSTableView and NSTextView, which from Swift means writing data sources and delegates; in Ferrokit you declare the views and signals. And the app can check itself through its real controls, which helps when an AI assistant writes the code.

Pick Swift instead if you have no Rust code to reuse, if you want iOS as well, or if you want Apple’s own tools, documentation and a stable API: Ferrokit is an alpha with one maintainer. It’s built on objc2, the standard Rust bindings to Apple’s frameworks, so the two can meet: an NSView from anywhere goes into a Ferrokit window with native(..), and SwiftUI views go in with ferrokit-build.

Can I add a GUI to my existing Rust CLI or library?

Yes: as a second binary in the same package, behind a feature, so the CLI’s build doesn’t change. A native Mac GUI for an existing Rust CLI shows the Cargo.toml, what to do with #[tokio::main], and how the window follows a data file the CLI changes.

Does Ferrokit work with async code, tokio and reqwest?

Yes. spawn_local runs a future on the main thread, where it can set signals between .awaits; background runs blocking work on another thread. Alerts, the Open and Save panels and sheets can be awaited (alert_async, save_panel_async…). For tokio libraries, keep a tokio runtime in the app and await work on it with on_runtime (the tokio feature), which is aborted when the task is. See Async code in a native Mac app.

Can I use SwiftUI views, like Swift Charts?

Yes. Write the view in Swift, compile it from build.rs with ferrokit-build, and wrap its NSHostingView with native(..). See SwiftUI views in a Rust Mac app. Any other NSView (MapKit, PDFKit, your own) wraps the same way: Wrapping any NSView.

Is a Ferrokit app accessible with VoiceOver?

Yes, through AppKit’s own accessibility tree. You name controls that have no visible label with .accessibility_label(..), and testing::ax_audit finds the ones you forgot. See VoiceOver, spell check and input methods in a Rust GUI.

Can I ship a Ferrokit app on the Mac App Store, or notarise it?

Yes. cargo ferrokit bundle makes a signed .app, cargo ferrokit notarize notarises it for direct download, cargo ferrokit appcast publishes Sparkle updates, and cargo ferrokit bundle --app-store makes the sandboxed, universal installer package the store takes. See Shipping a Rust app to the Mac App Store.

How big is a Ferrokit app?

A release build of the app cargo ferrokit new makes is about 5 MB as a bundled .app. There’s no runtime to ship: AppKit and the Swift runtime come with macOS.

Do I need unsafe code?

Not for apps built from Ferrokit’s own views: the app cargo ferrokit new makes has none. You need it only to call AppKit directly, such as wrapping a view Ferrokit doesn’t have.

Does Ferrokit work with AI coding agents like Claude Code, Codex or Cursor?

Yes; it’s written to. The crate ships an AGENTS.md with the rules, recipes that compile and known limits, plus API.md with every public item; cargo ferrokit agents puts the first into your project. Agents can verify their own work with cargo ferrokit check, which runs the app’s self-checks. In our latest trial (November 2026), a fresh agent that found Ferrokit through crates.io alone added a working GUI to an existing tokio CLI in under six minutes, with 14 passing self-checks. See For AI coding agents and llms.txt.

What licence is Ferrokit under?

MIT or Apache-2.0, at your option, like most Rust crates.

How do I start?

cargo install cargo-ferrokit && cargo ferrokit new my-app && cd my-app && cargo ferrokit run

Then the guide. If you build something with it, say so in an issue.

Built with Ferrokit: Rowboat, a SQLite editor in the Mac App Store

Rowboat is a free SQLite editor for the Mac, written entirely in Rust with Ferrokit. It’s the answer to “has anyone shipped a real app with this?”: it’s in the Mac App Store, in 174 countries, in English and German, for macOS 15 or later.

In numbers

Codeabout 17,000 lines of Rust, plus rusqlite with SQLite bundled
Started6 November 2026, from Ferrokit’s sql_browser example
1.0 in the store18 November 2026 (submitted 8 November)
1.1, the first update25 November 2026
Store package8.7 MB, universal (Apple silicon and Intel), sandboxed
Self-checksabout 118, run through the real app’s controls (CHECK=all)
A million rowson screen in about a fifth of a second, and they scroll smoothly

What it’s made of

Apart from the schema diagram, every part of the window is an AppKit control that Ferrokit creates once and updates in place:

  • The data: table(..), an NSTableView that asks only for the rows on screen, which is why a million rows cost nothing to show. Edits are staged in Rust and written when you commit, with undo through undo(..).
  • The SQL editor: text_editor(..), an NSTextView, with highlighting, completion and a formatter written in Rust on top. Input methods, spell check and VoiceOver are the system’s.
  • The sidebar: outline(..) in a sidebar(..): tables, views, indexes, triggers and saved snippets.
  • The schema diagram: a canvas(..), the one place Rowboat draws for itself.
  • Database Health: Ferrokit’s charts (a donut of space per table and index) above a table of every object.
  • The rest of the Mac: a toolbar, menus, sheets, popovers, an inspector, the Open and Save panels, the pasteboard, Quick Look for images and PDFs in cells, and drag to the Finder.

How it got into the store

cargo ferrokit bundle --app-store built the sandboxed, universal installer package the store takes; Shipping a Rust app to the Mac App Store walks through the same steps. Rowboat has no network access and its privacy label is “Data Not Collected”: a sandboxed Rust app needed nothing special to get there.

Updates go through the store. For apps you ship yourself, cargo ferrokit appcast publishes Sparkle updates instead (see Testing and shipping).

What it taught Ferrokit

Rowboat is the framework’s daily-use test, and building it changed Ferrokit. Tables gained cell focus (a focused column, as in a spreadsheet), styled cells, animated rows and links dropped from a browser. Text and search fields gained on_arrows, for lists filtered as you type, the way Open Quickly works. And it found bugs that every app would have hit: a canvas that was never drawn at its minimum size, views showing through a hidden parent, and empty editable cells with no name for VoiceOver. The changelog says which changes came from Rowboat.

Try it, or build your own

  • Get Rowboat from the Mac App Store (free, no account).
  • Its starting point is in Ferrokit’s repository: cargo run --release -p ferrokit --example sql_browser.
  • Start your own: cargo install cargo-ferrokit && cargo ferrokit new my-app, then the guide.

If you’ve built something with Ferrokit, tell us in an issue and it can be listed here too.

A native Mac app in Rust, step by step

This page goes from an empty folder to a signed, notarised .app you can send to someone, with Ferrokit. The app’s UI is real AppKit: the same NSWindow, NSTableView and NSTextField a Swift app would use, driven from Rust. No Xcode project, no Swift, no web view.

You need macOS 15 or later and stable Rust.

1. Make the app

cargo install cargo-ferrokit
cargo ferrokit new my-app && cd my-app

That’s a small to-do app: a text field, a table of tasks with checkboxes, a menu command with a shortcut, and self-checks. It also has an AGENTS.md, so Claude Code, Codex or Cursor know how a Ferrokit app is written.

2. Run it as a real app

cargo ferrokit run

run builds a .app bundle, so the app has its name in the menu bar, its icon in the Dock and its own identity, and runs it with its output in the terminal. While you work:

cargo ferrokit preview

rebuilds and restarts it every time you save, with its windows where you left them.

3. Write the UI

A Ferrokit app is views over signals. A view is built once; when a signal it reads changes, that one native view updates in place.

use ferrokit::*;

fn main() {
    let count = Signal::new(0);
    App::new("Counter")
        .window(Window::new("Counter").size(320.0, 140.0).view(
            vstack((
                text(move || format!("Clicked {} times", count.get())),
                button("Click me", move || count.update(|n| *n += 1)),
            ))
            .padding(20.0),
        ))
        .run();
}

The guide goes on from here: state, layout, controls and forms, tables and editors, and menus, toolbars, sheets and documents.

4. Check it

cargo ferrokit check

Clippy (warnings are errors), your tests, a bundle, then the app’s own self-checks: the app runs with CHECK=all, drives its own UI (clicks, typing, menu commands) and reports what AppKit did. See Testing and shipping.

5. Ship it

Settings live in Cargo.toml:

[package.metadata.ferrokit]
name = "My App"
id = "com.example.myapp"
icon = "icon.png"
cargo ferrokit bundle --universal --zip

makes a signed My App.app with the hardened runtime for Apple silicon and Intel. With a Developer ID certificate, cargo ferrokit notarize signs it, sends it to Apple’s notary service, staples the ticket and zips it for sending. For updates, cargo ferrokit appcast and Sparkle; for the store, the Mac App Store page.

A real NSTableView from Rust: a million rows

You can drive AppKit’s NSTableView from Rust directly with the objc2-app-kit bindings: implement NSTableViewDataSource and NSTableViewDelegate with define_class!, make cell views, keep the delegate alive, and handle sorting and selection yourself. That works, and it’s the right choice for one table in an otherwise non-AppKit app.

Ferrokit does that part for you. Its table is a real NSTableView, virtualised (only the rows on screen have views), fed from a model of your own Rust rows:

use std::rc::Rc;
use ferrokit::*;

#[derive(Clone)]
struct Order {
    id: u32,
    customer: String,
    total: f64,
    paid: bool,
}

fn sample(n: u32) -> Vec<Order> {
    let names = ["Ada", "Grace", "Linus", "Margaret", "Ken"];
    (1..=n)
        .map(|id| Order {
            id,
            customer: names[id as usize % names.len()].to_string(),
            total: f64::from(id % 9_973) / 10.0,
            paid: id % 3 != 0,
        })
        .collect()
}

fn main() {
    let all = Rc::new(sample(1_000_000));
    let query = Signal::new(String::new());

    // Created once; the columns read from your own row type.
    let model = Rc::new(TableModel::new(
        vec![
            Column::number("id", "Order", |o: &Order| f64::from(o.id)).decimals(0),
            Column::text("customer", "Customer", |o: &Order| o.customer.clone()).width(200.0),
            Column::number("total", "Total", |o: &Order| o.total).decimals(2),
            Column::check("paid", "Paid", |o: &Order| o.paid),
        ],
    ));
    let m = model.clone();

    App::new("Orders")
        .window(Window::new("Orders").size(640.0, 480.0).view(
            vstack((
                search_field(&query).accessibility_label("Search customers"),
                table(&model)
                    // Row numbers are positions in what you gave set_rows,
                    // whatever the user sorted by.
                    .on_activate(|row| println!("opened model row {row}"))
                    .accessibility_label("Orders"),
                // Runs again whenever `query` changes and updates the
                // table in place.
                watch(move || {
                    let q = query.get().to_lowercase();
                    let rows = all
                        .iter()
                        .filter(|o| q.is_empty() || o.customer.to_lowercase().contains(&q))
                        .cloned()
                        .collect();
                    m.set_rows(rows);
                }),
            ))
            .padding(12.0),
        ))
        .run();
}

What you get without writing it:

  • Scrolling and keyboard are the table’s own: arrow keys, Page Up and Down, type-to-select, ⌘A, ⌘-click and ⇧-click.
  • Sorting: clicking a header sorts by that column (numbers as numbers, dates as dates). Row numbers in every event stay model indices, positions in what you gave set_rows, whatever the sort.
  • A million rows: only the rows on screen have views; 200,000 rows load in about 5 ms. set_rows replaces the rows in place; update_row, push, insert and remove change single rows.
  • Copy and drag: ⌘C copies the selected rows as tab-separated text that Numbers and Excel paste as cells; .row_drag() drags rows out.
  • VoiceOver reads it as a table, row by row and cell by cell.

More: editable cells, date and progress columns, icons, grouped rows with floating headers, a focused cell as in a spreadsheet, row menus, drag to reorder, and files dropped from the Finder. All in Tables, outlines and editors, with NSOutlineView for trees and NSBrowser for column views.

To see a million rows for yourself:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit && cargo run --release -p ferrokit --example sql_browser

When to use objc2 directly instead

  • Your app’s UI is drawn by something else (egui, Iced, a game engine) and you need one AppKit view inside it: Ferrokit runs the whole window, so it doesn’t fit there.
  • You need an NSTableView feature Ferrokit doesn’t expose. Then you can still use Ferrokit and reach for the bindings for that one part: native(..) wraps any NSView.

VoiceOver, spell check and input methods in a Rust GUI

Most Rust GUI toolkits draw their own widgets, so they have to rebuild what the Mac already does: a text field that works with the Japanese input method’s candidate window, spell checking with the red underline and the right-click suggestions, an accessibility tree VoiceOver can walk. Several are doing that work (egui and Slint support screen readers through AccessKit, and Iced’s support is in progress), and how far each has got is on the comparison page.

Ferrokit takes the other route: its views are the system’s controls. A text_field is an NSTextField, a text_editor is an NSTextView, a table is an NSTableView. So these come from macOS itself:

  • Input methods: Japanese, Chinese and Korean composition with the candidate window at the caret; the emoji picker (⌃⌘Space); dictation.
  • Spelling and grammar: the underline, suggestions on right-click, Edit ▸ Spelling and Grammar.
  • Text editing: every Mac shortcut (⌥← by word, ⌘← to the line start, ⌃K and the other Emacs keys), Find and Replace (⌘F), undo per window, the Services menu, Look Up, Writing Tools where the Mac offers them.
  • VoiceOver: AppKit’s own accessibility tree: tables read by row and cell, sliders with their values, buttons with their titles. Full Keyboard Access and Tab order follow.
  • Right-to-left layout for Arabic and Hebrew, and the user’s own date and number formats.

The one thing you do: name your controls

VoiceOver reads a control’s name. A button is named by its title, but a text field after a text("Title:") label has no name of its own: the label is a separate view. Give it one with .accessibility_label(..), and let a self-check catch the ones you forget:

use ferrokit::*;

fn main() {
    let title = Signal::new(String::new());
    let notes = TextModel::new("Spell-checked, with input methods, dictation and Find.\n");
    let checks = std::env::var("CHECK").is_ok_and(|v| v == "all");

    App::new("Notes")
        .window(Window::new("Notes").size(520.0, 400.0).view(
            vstack((
                hstack((
                    text("Title:"),
                    // The text beside it is a separate view, so name the field.
                    text_field(&title).accessibility_label("Title"),
                )),
                // A real NSTextView: spell check, Japanese and Chinese input,
                // the emoji picker, undo, Edit ▸ Find, the Services menu.
                text_editor(&notes).accessibility_label("Notes"),
            ))
            .padding(12.0),
        ))
        .on_launch(move || {
            if checks {
                // What VoiceOver users would miss: unnamed controls.
                let problems = testing::ax_audit(&windows()[0]);
                testing::check("accessibility", problems.is_empty(), format!("{problems:?}"));
                testing::finish();
            }
        })
        .run();
}

testing::ax_audit(&window) lists the controls VoiceOver couldn’t name; cargo ferrokit check runs it with the rest of your self-checks. Controls and forms has the rules, and Testing and shipping the checks.

What it costs

The same choice that gives you the Mac’s own behaviour makes Ferrokit Mac only. If your app must also run on Windows and Linux, a cross-platform toolkit is the better fit, and you’ll be testing its IME and screen-reader support on each platform. See the comparison.

Shipping a Rust app to the Mac App Store

The Mac App Store takes an installer package (.pkg) of a sandboxed app, built for Apple silicon and Intel, signed with your App Store certificates and carrying a provisioning profile. With Ferrokit, cargo ferrokit bundle --app-store makes that package from your Cargo project. This is the path Rowboat, a SQLite editor built with Ferrokit, took into the Mac App Store.

What you need from Apple

From your Apple Developer account:

  • an Apple Distribution certificate (signs the app) and a Mac Installer Distribution certificate (signs the package; Keychain Access shows it as “3rd Party Mac Developer Installer”), both in your keychain;
  • a Mac App Store provisioning profile for the app’s bundle id (developer.apple.com ▸ Profiles), saved next to the app;
  • the app in App Store Connect, with the same bundle id.

The settings

[package.metadata.ferrokit]
name = "My App"
id = "com.example.myapp"
icon = "icon.png"
sandbox = true
category = "public.app-category.productivity"
app-store-sign = "Apple Distribution: Your Name (TEAMID)"
installer-sign = "3rd Party Mac Developer Installer: Your Name (TEAMID)"
provisioning-profile = "MyApp.provisionprofile"

Build the package

cargo ferrokit bundle --app-store --build 42

It builds a universal app, embeds the profile, signs the app with its sandbox entitlements and the profile’s app and team ids (a profile for another app, or for iOS, is refused with the reason), and writes My App.pkg. --build is the build number (CFBundleVersion); each upload needs a higher one. --dry-run does all of it without your identities, then prints the signing commands it would run.

Upload the package with Apple’s Transporter app.

Before you submit: run it sandboxed

App Review checks that the app works inside the App Sandbox, where files outside the app’s container are reachable only through the open and save panels, drops, and the security-scoped bookmarks Ferrokit keeps for Open Recent. Run the sandboxed build yourself first:

cargo ferrokit run

with sandbox = true in Cargo.toml. Ferrokit’s own example apps run their self-checks in the sandbox too.

Outside the store

For apps you distribute yourself: cargo ferrokit notarize (Developer ID signing, Apple’s notary service, stapling), Sparkle updates with cargo ferrokit appcast, and crash reports with App::crash_reports. All in Testing and shipping.

Wrapping any NSView in a Rust UI

Ferrokit wraps a lot of AppKit, but not every view, and not the frameworks beside it: MapKit’s map, SceneKit, PDFKit’s thumbnails, a third-party view, or a view your app draws itself. native(..) takes any NSView you make with the objc2 bindings and makes it a Ferrokit view: it’s laid out with the others, updates from signals, takes part in focus and VoiceOver, and is torn down with its window.

use ferrokit::*;
use objc2_app_kit::NSLevelIndicator;

fn main() {
    let level = Signal::new(3.0);
    App::new("Meter")
        .window(Window::new("Meter").size(320.0, 120.0).view(
            vstack((
                // Any NSView, made once when the window is built…
                native(|mtm| {
                    let meter = NSLevelIndicator::new(mtm);
                    meter.setMaxValue(5.0);
                    meter
                })
                // …and changed in place whenever a signal it reads changes.
                .update(move |meter| meter.setDoubleValue(level.get()))
                .measure(|_| Size { w: 120.0, h: 18.0 })
                .flexible(false, false)
                .accessibility_label("Signal strength"),
                slider(&level, 0.0, 5.0).accessibility_label("Level"),
            ))
            .padding(20.0),
        ))
        .run();
}

The objc2 crates go in your Cargo.toml, with the features for the classes you call:

[dependencies]
ferrokit = "0.15"
objc2-app-kit = { version = "0.3", features = ["NSResponder", "NSView", "NSControl", "NSLevelIndicator"] }
  • native(make) calls make(mtm) once, on the main thread, when the window is built.
  • .update(f) runs f as an effect: now, and again whenever a signal it read changes. Give unrelated properties their own updates.
  • .measure(..) and .flexible(..) size it; .keep(delegate) keeps a delegate alive (AppKit holds delegates weakly); .on_remove(..) cleans up.
  • A wrapped view is a leaf: Ferrokit views can’t go inside it.

The native_views example wraps MKMapView and a clock face the app draws itself:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit && cargo run -p ferrokit --example native_views

Custom native views has delegates, drawing, focus and accessibility. For a SwiftUI view (Swift Charts, MapKit’s Map), see SwiftUI views in a Rust Mac app.

A native Mac GUI for an existing Rust CLI

Short answer: add the app as a second binary in the same package, behind a gui feature, so the command-line tool’s build doesn’t change. The app’s main belongs to AppKit, so it’s a plain fn main, not #[tokio::main]. Async functions from your library run on a tokio runtime the app keeps. cargo ferrokit builds, checks and bundles that binary with its feature on.

This page uses a small time tracker, tally, as the example: a library with async load and save, and a CLI with start, stop and report.

Where does the GUI go?

In the same package, as a second binary that only builds with the gui feature:

[dependencies]
# …the CLI's own dependencies…
ferrokit = { version = "0.15", optional = true }

[features]
gui = ["dep:ferrokit"]

[[bin]]
name = "tally"
path = "src/main.rs"

[[bin]]
name = "tally-gui"
path = "src/bin/tally-gui.rs"
required-features = ["gui"]

[package.metadata.ferrokit]
bin = "tally-gui"
name = "Tally"
id = "com.example.tally"
  • cargo build and cargo install tally build the CLI alone, as before. Nobody who only wants the CLI downloads Ferrokit.
  • bin = "tally-gui" tells cargo ferrokit which binary is the app. cargo ferrokit run, check and bundle then build it with the gui feature turned on, and check lints and tests with it too. (This needs cargo-ferrokit 0.10 or later.)
  • In a workspace, a new member package that depends on your library works as well. Run cargo ferrokit in its folder.

What happens to #[tokio::main]?

The CLI keeps it. The app can’t have it (it needs tokio’s rt-multi-thread feature for Runtime::new()): AppKit needs the main thread for as long as the app runs, and App::run doesn’t return until the app quits. So the app keeps a tokio runtime of its own and calls the library from it:

  • Before the app starts, runtime().block_on(tally::load()) is fine: nothing is on screen yet.
  • While it runs, never block the main thread. Run the library’s async code on another thread with background(|| runtime().block_on(…)) inside a spawn_local task, or with spawn(work, done).

Here is the whole app half, with a stand-in for the library so it compiles on its own:

// The app half of "A native Mac GUI for an existing Rust CLI". In a real
// project, `tally` is the crate's own library; here it's a stand-in module.
mod tally {
    #[derive(Clone, PartialEq)]
    pub struct Entry {
        pub project: String,
        pub minutes: u32,
    }

    pub fn path() -> std::path::PathBuf {
        std::env::var_os("TALLY_FILE").map(Into::into).unwrap_or_else(|| "entries.txt".into())
    }

    /// The library's own async loader, as the CLI calls it.
    pub async fn load() -> std::io::Result<Vec<Entry>> {
        let text = match tokio::fs::read_to_string(path()).await {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
            Err(e) => return Err(e),
        };
        Ok(text
            .lines()
            .filter_map(|l| l.split_once(','))
            .map(|(p, m)| Entry { project: p.to_string(), minutes: m.trim().parse().unwrap_or(0) })
            .collect())
    }
}

use std::rc::Rc;
use std::sync::OnceLock;
use std::time::{Duration, SystemTime};
use ferrokit::*;

/// The tokio runtime the library's async functions run on. `main` belongs
/// to AppKit, so it can't be `#[tokio::main]`.
fn runtime() -> &'static tokio::runtime::Runtime {
    static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
    RT.get_or_init(|| tokio::runtime::Runtime::new().expect("a tokio runtime"))
}

fn modified() -> Option<SystemTime> {
    std::fs::metadata(tally::path()).and_then(|m| m.modified()).ok()
}

fn main() {
    // Before the app starts, blocking on the library is fine.
    let entries = Signal::new(runtime().block_on(tally::load()).unwrap_or_default());

    let model = Rc::new(TableModel::new(
        vec![
            Column::text("project", "Project", |e: &tally::Entry| e.project.clone()).width(240.0),
            Column::number("minutes", "Minutes", |e: &tally::Entry| f64::from(e.minutes)),
        ],
    ));
    let m = model.clone();

    App::new("Tally")
        .window(Window::new("Tally").size(420.0, 360.0).view(
            vstack((
                text(move || format!("{} entries", entries.with(Vec::len))).font(Font::headline()),
                table(&model).accessibility_label("Entries"),
                watch(move || m.set_rows(entries.get())),
            ))
            .padding(12.0),
        ))
        .on_launch(move || {
            // The CLI may change the file while the window is open: look
            // once a second, read it off the main thread, and set the
            // signal only when the entries differ (set_rows clears the
            // table's selection).
            spawn_local(async move {
                let mut seen = modified();
                loop {
                    sleep(Duration::from_secs(1)).await;
                    if modified() == seen {
                        continue;
                    }
                    seen = modified();
                    if let Ok(fresh) = background(|| runtime().block_on(tally::load())).await
                        && fresh != entries.get_untracked()
                    {
                        entries.set(fresh);
                    }
                }
            })
            .detach();
        })
        .run();
}

What if the CLI changes the data while the window is open?

Both read and write the same file, so the window should follow. The example looks at the file’s modification time once a second, in a spawn_local loop that sleeps on the main run loop, reads the file on another thread, and sets the signal only when the entries changed. That last part matters: TableModel::set_rows clears the table’s selection, so reloading identical data every second would keep clearing what the user selected.

Save through the library’s own save from the app too, so both write the same format.

How do I check it?

cargo ferrokit check runs clippy, the tests, a bundle, and then the app with CHECK=all, where the app clicks through its own window and prints [check] name PASS|FAIL lines. The example above has no self-checks, to stay short, so check would wait for them and fail: copy the pattern from the src/main.rs that cargo ferrokit new makes (its self_checks), or see Testing and shipping. Point those checks at a temporary data file (an environment variable your library already reads, like TALLY_FILE here), never the user’s own. They only run under CHECK=all, so they can stay in the release build.

Does an AI coding agent get this right?

We tested exactly this on 2026-11-15: a fresh coding agent, given a tokio CLI like this one and asked for “a native Mac GUI for it, with the ferrokit crate”, built a working app in about ten minutes with no compile errors and six passing self-checks. It chose the layout above by itself. The rough edges it hit (choosing the binary, live combo box suggestions, a word in an empty date cell) are fixed in 0.10, and AGENTS.md, which agents read first, now has a section on exactly this case. A second trial on 0.10.0 (2026-11-19), with an agent that found Ferrokit’s docs through cargo info alone, followed that section exactly: a working app in under six minutes, with 14 passing self-checks. What it missed in the testing helpers (waiting for a save, answering an alert) is in 0.10.1. Run cargo ferrokit agents in your project to put that file where your agent will find it.

See also

Async code in a native Mac app (tokio, reqwest)

AppKit runs on the main thread, and so does every Ferrokit view. Async code fits in without a second UI thread: spawn_local runs a future on the main thread, so between its .awaits it can read and set signals like any button action. The future doesn’t have to be Send.

use ferrokit::*;
use std::time::Duration;

fn is_prime(n: u32) -> bool {
    n >= 2 && (2..).take_while(|d| d * d <= n).all(|d| !n.is_multiple_of(d))
}

fn main() {
    let status = Signal::new(String::from("Ready"));
    let running: Signal<Option<Task>> = Signal::new(None);

    let start = button("Count primes", move || {
        // A second click starts over: the count already running stops.
        if let Some(task) = running.get_untracked() {
            task.cancel();
        }
        let task = spawn_local(async move {
            status.set("Counting…".into());
            // Blocking work runs on another thread; the window stays responsive.
            let n = background(|| (2..5_000_000u32).filter(|&k| is_prime(k)).count()).await;
            running.set(None);
            status.set(format!("{n} primes below five million"));
            // A timer on the main run loop: nothing is blocked while it waits.
            sleep(Duration::from_secs(5)).await;
            status.set("Ready".into());
        });
        running.set(Some(task));
    });
    let cancel = button("Cancel", move || {
        if let Some(task) = running.get() {
            task.cancel();
            running.set(None);
            status.set("Cancelled".into());
        }
    });

    App::new("Primes")
        .window(Window::new("Primes").size(360.0, 140.0).view(
            vstack((text(move || status.get()), hstack((start, cancel)))).padding(20.0),
        ))
        .run();
}

Inside a task:

  • background(|| …).await runs blocking work (a big computation, a file read, a synchronous database call) on another thread and gives the result back to the task.
  • sleep(duration).await waits on a timer in the main run loop, without blocking anything.
  • Each poll is a batch: views that read several signals the task sets update once.

A task stops with its window

A task belongs to the window or view that was current when it started. Close the window, or remove the view, and the future is dropped: the task stops at the .await it was waiting at, so a closed window never gets a late update. spawn_local returns a Task handle:

  • task.cancel() stops it now (a Cancel button). Work a background call already started on its thread runs to the end, and its result is dropped.
  • task.detach() keeps it running after its owner goes (an upload that should finish when its window is closed).

Tasks keep running while a menu is open or a window is being resized. A panic inside a task, or in the background work it awaits, is reported through App::on_error and ends only that task.

Awaiting alerts, panels and sheets

The dialogs that take a callback have awaitable versions, so a flow of questions reads top to bottom:

spawn_local(async move {
    let Some(path) = save_panel_async(&window, "export.csv", None).await else { return };
    let ask = Alert::new("Export 10,000 rows?", "This takes a moment.").button("Export").button("Cancel");
    if alert_async(&window, ask).await != Some(0) {
        return;
    }
    background(move || write_csv(&path)).await;
});

alert_async gives the button’s index, open_panel_async and save_panel_async the paths (None for Cancel), and sheet_async shows your own sheet and gives what its buttons send. If the task is cancelled while it waits, the sheet closes.

tokio, reqwest and sqlx

Ferrokit has no I/O runtime of its own, and doesn’t depend on one. reqwest, sqlx and most of tokio’s I/O need tokio’s reactor, so keep a tokio runtime in your app and run the I/O there. With Ferrokit’s tokio feature, on_runtime awaits work on it:

ferrokit = { version = "0.15", features = ["tokio"] }
// Needs tokio (rt-multi-thread) and reqwest in Cargo.toml; not compiled on this site.
let rt = tokio::runtime::Runtime::new()?; // kept for the app's lifetime
let handle = rt.handle().clone();

let page = Signal::new(String::new());
let error = Signal::new(None::<String>);
let fetch = button("Fetch", move || {
    let handle = handle.clone();
    spawn_local(async move {
        let url = "https://example.com";
        match on_runtime(&handle, async move { reqwest::get(url).await?.text().await }).await {
            Ok(body) => page.set(body),
            Err(e) => error.set(Some(e.to_string())),
        }
    });
});

The request runs on tokio’s threads; the result comes back to the main thread, where the task sets the signals. If the window closes first, the task is dropped and the request is aborted on tokio too. A panic on the runtime is reported through App::on_error and ends the task, so there’s no JoinError to unwrap.

Without the feature, handle.spawn(…).await works as well (a JoinHandle is an ordinary future), but it isn’t aborted with the task and gives a Result<_, JoinError>.

Async loading

Resource::new_async reloads a value when the signals it reads change, with an async load: the newest load wins, and an older one is dropped at its .await. A sleep at the start of the load debounces search-as-you-type.

An app in the App Sandbox needs network = true under [package.metadata.ferrokit] to make outgoing connections.

What not to do

  • Don’t block inside a task: each poll runs on the main thread, and the UI waits for it. Blocking work goes in background.
  • Don’t call block_on on the main thread: it freezes the UI.

More in the guide: Async tasks, and Loading data for Resource. The design is in issue #2.

Open your Mac app from a link (myapp://)

A Mac app can have its own kind of link, myapp://…, that opens it from a web page, an email, another app or open in Terminal. Sign-in callbacks (OAuth redirects) and “open this item” links work this way. In Ferrokit it takes two pieces.

1. Declare the scheme in Cargo.toml:

[package.metadata.ferrokit]
url-schemes = ["notes"]

cargo ferrokit bundle (and cargo ferrokit run, which builds a bundle too) writes it into the app’s Info.plist (CFBundleURLTypes). macOS learns which app opens notes:// links the first time the bundled app runs; after that, a link starts the app if it isn’t running. A misspelt scheme, such as "notes://" or one with a space, stops the build and says what’s wrong.

2. Handle the links with App::on_open_url:

use ferrokit::*;

fn main() {
    let opened = Signal::new(String::from("No link yet"));
    App::new("Notes")
        // Every notes://… link, whether it launched the app or came while it ran.
        .on_open_url(move |url| match url.strip_prefix("notes://open/") {
            Some(id) if !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()) => {
                opened.set(format!("Opening note {id}"));
            }
            // Anyone can send the app a link: ignore what you don't recognise.
            _ => opened.set(format!("Ignored {url}")),
        })
        .window(Window::new("Notes").size(360.0, 120.0).view(text(move || opened.get()).padding(20.0)))
        .run();
}

on_open_url gets every link, whether it launched the app or arrived while the app was running, after the windows are up.

Try it:

cargo ferrokit run
open "notes://open/42"

Things to know

  • Only a bundled app that has run once gets links. A bundle that’s built but never run isn’t known to macOS yet (open says no application can open the link), and a bare cargo run never gets links. Use cargo ferrokit run.
  • Several copies, one winner. When more than one copy of the app declares the scheme (an old build, a copy in /Applications), macOS picks one of them, not necessarily the one you just built.
  • Links arrive percent-encoded, as macOS gives them (notes://open/my%20note). Decode them with a crate such as url if you need to.
  • Treat a link as untrusted input. Any web page or app can send your app one. Check it before acting on it, and ask before doing anything destructive.

The guide has it too: Links into the app, with all of the [package.metadata.ferrokit] settings in cargo ferrokit’s README.

SwiftUI views in a Rust Mac app (Swift Charts)

Some of Apple’s views exist only in SwiftUI: Swift Charts, Gauge’s styles, MapKit’s SwiftUI Map, and many third-party packages. A Ferrokit app can still show them. SwiftUI’s NSHostingView is an NSView, so native(..) wraps it like any other. You write the SwiftUI view in Swift, and the ferrokit-build crate compiles it into your app from build.rs.

1. Add the build helper and the objc2 crates to Cargo.toml:

[dependencies]
ferrokit = "0.15"
objc2 = "0.6"
objc2-app-kit = { version = "0.3", features = ["NSResponder", "NSView"] }

[build-dependencies]
ferrokit-build = "0.15"
// build.rs
fn main() {
    ferrokit_build::swift("swift").compile();
}

Every .swift file under swift/ becomes one Swift module, linked into the app. The Swift runtime and the frameworks your Swift imports (SwiftUI, Charts…) come with macOS, so nothing is copied into the app.

2. Write the view in Swift, and export C functions: one that returns the hosting view, retained, and one per value the app sets.

// swift/Sales.swift
import Charts
import SwiftUI

final class SalesModel: ObservableObject {
    @Published var values: [Double] = []
}

struct SalesChart: View {
    @ObservedObject var model: SalesModel
    var body: some View {
        Chart(Array(model.values.enumerated()), id: \.offset) {
            BarMark(x: .value("Month", $0.offset), y: .value("Sales", $0.element))
        }
        .padding()
    }
}

@MainActor @_cdecl("sales_chart_new")
public func salesChartNew() -> UnsafeMutableRawPointer {
    let view = NSHostingView(rootView: SalesChart(model: SalesModel()))
    return Unmanaged.passRetained(view).toOpaque()
}

@MainActor @_cdecl("sales_chart_set")
public func salesChartSet(_ view: UnsafeMutableRawPointer, _ values: UnsafePointer<Double>, _ count: Int) {
    let host = Unmanaged<NSHostingView<SalesChart>>.fromOpaque(view).takeUnretainedValue()
    host.rootView.model.values = Array(UnsafeBufferPointer(start: values, count: count))
}

3. Wrap it in Rust and set its values from a signal:

// Not compiled on this site: it needs the Swift file above to link.
use ferrokit::*;
use objc2::rc::Retained;
use objc2_app_kit::NSView;
use std::ffi::c_void;

unsafe extern "C" {
    fn sales_chart_new() -> *mut c_void;
    fn sales_chart_set(view: *mut c_void, values: *const f64, count: isize);
}

let sales = Signal::new(vec![12.0, 30.0, 22.0, 48.0]);
let chart = native(|_| {
    // SAFETY: a +1 NSHostingView, owned from here on.
    unsafe { Retained::from_raw(sales_chart_new().cast::<NSView>()) }.expect("a view")
})
.update(move |view| {
    let v: *mut c_void = (view as *const NSView).cast_mut().cast();
    // SAFETY: the chart's own view; a buffer of `len` values.
    sales.with(|s| unsafe { sales_chart_set(v, s.as_ptr(), s.len() as isize) })
});

When sales changes, the update runs again and Swift Charts redraws. The chart is laid out with the rest of the window, and SwiftUI’s view is released when the Ferrokit view leaves the tree.

For values coming back from SwiftUI, such as a slider, pass a C callback and a context pointer (a boxed signal, freed in .on_remove) to the Swift function.

Things to know

  • Toolchain: swiftc comes with the Command Line Tools (xcode-select --install), and that’s enough for Swift like the example above. Since the macOS 27 SDK, SwiftUI’s @State, @Entry and #Preview are macros, and only Xcode has the plugin that expands them. When an Xcode is in /Applications, ferrokit-build uses it for them automatically, with a warning; without one, it stops the build and says to install Xcode. No Xcode project is needed either way.
  • Builds: ferrokit-build follows the target architecture (Apple silicon, Intel and universal builds), the Cargo profile, and MACOSX_DEPLOYMENT_TARGET (15.0 by default).
  • Accessibility: SwiftUI’s views are in the window’s accessibility tree, for VoiceOver and for Ferrokit’s testing::ax_elements and ax_audit, which find a SwiftUI control without a name as they do Ferrokit’s own.
  • Size: the view’s ideal size is the hosting view’s fittingSize, which native already uses; by default it fills the room it gets.
  • The glue is by hand for now. A smaller bridge, with SwiftUI views registered by name and .prop, .binding and .on on the Rust side, is being designed in issue #7: say there what you’d use it for.

More in the guide: SwiftUI views, and ferrokit-build’s options (module name, minimum macOS, Swift 6 mode) in its README.

Ferrokit vs Swift, egui, Iced, Slint, Tauri, GPUI, NSH, cacao and objc2 on the Mac

Which Rust GUI should you use for a Mac app? It depends mostly on one question: does the app have to run anywhere else?

  • Also Windows, Linux, mobile or the web: use a cross-platform toolkit: egui, Iced, Slint, Tauri, GPUI or NSH. Ferrokit is Mac only.
  • Mac only, and it should look and behave like a Mac app: that’s what Ferrokit is for, especially when the app’s core is Rust. NSH and raw objc2 are the other ways to get AppKit views from Rust, and Swift itself is the other way to a Mac app (Or just Swift?).

Ferrokit is written by the same person as this page, so read it with that in mind. Facts about the other projects come from their own repositories and docs, checked 2026-11-11 (GPUI 2026-11-16), with links. If something here is wrong or out of date, please open an issue.

At a glance

How it draws on the MacPlatformsMaturity (2026-11-11)
FerrokitStock AppKit controls (NSTableView, NSTextView…)macOS 15+0.15, alpha; started Oct 2026; one maintainer; no outside users yet
eguiIts own renderer (immediate mode, wgpu/OpenGL)Mac, Windows, Linux, web, Android0.37 (Oct 2026); ~32k stars; very active
IcedIts own renderer (wgpu or CPU)Mac, Windows, Linux, web0.14 (Dec 2025); ~32k stars; active; calls itself experimental
SlintIts own renderer; the cupertino style imitates macOSDesktop, mobile, web, embedded1.18 (Sep 2026); ~25k stars; active; commercial company behind it
TauriThe system web view (WKWebView); UI in HTML, CSS, JSMac, Windows, Linux, iOS, Android2.12 (Oct 2026), 3.0 in alpha; ~113k stars; very active
GPUI with GPUI ComponentIts own GPU renderer (Metal on the Mac); controls “inspired by macOS and Windows”Mac, Windows, Linux (GPUI Kit also WebAssembly)GPUI 0.2.2, pre-1.0, “often breaking changes” (Zed’s editor is built on it); GPUI Component 0.10 (Nov 2026), ~21k stars, very active (Longbridge)
NSHAppKit views and Core Animation, styled by the appMac, iOS, Android, Windows, Linux, web0.5 (Nov 2026); ~2.5k stars; very active (Longbridge)
cacaoAppKit controls through safe bindingsMac (iOS in alpha)0.4.0-beta2 (Aug 2023); ~2.1k stars; no commits since Dec 2024
objc2Whatever AppKit you call yourself: bindings, no widget layerApple platformsobjc2 0.6.5, objc2-app-kit 0.3.2; the bindings Ferrokit itself uses

What the Mac gives you, and who gets it

VoiceOverInput methods (Japanese, Chinese…)System spell checkA table with a million rows
FerrokitAppKit’s own treeThe system’s (NSTextView, NSTextField)Yes (the system’s)NSTableView, virtualised
eguiVia AccessKit, on by default; custom widgets describe themselves (docs)Supported, fixes still landing (#8681)Not foundegui_extras::TableBuilder lays out visible rows only
IcedNot in a release yet (#1849)Added in 0.14Not foundtable widget (0.15); virtualisation not found
SlintVia AccessKit, accessible-* propertiesNot confirmed on desktopNot foundStandardTableView, visible rows only (docs)
TauriWhat WebKit and your HTML provideWhat WebKit providesWhat WebKit providesA JavaScript grid library of your choice
GPUI + GPUI ComponentVia AccessKit, built into its interaction layer (README)Not stated in the READMENot statedData table with virtual scrolling, “hundreds of thousands of rows”
NSHThe real view hierarchy, with labels, roles and states (docs)Handled (inputs are NSTextField/NSTextView)Not statedDataTable, cells in view only (docs)
cacaoWhatever the wrapped controls doSameSameListView with cached rows
objc2Whatever you buildSameSameNSTableView, if you write its data source and delegate

“Not found” means we found nothing about it in the project’s own docs or code; tell us if it exists.

Shipping

Bundle and signNotariseMac App StoreUpdates
Ferrokitcargo ferrokit bundlecargo ferrokit notarizebundle --app-store (sandboxed, universal .pkg)Sparkle, cargo ferrokit appcast
TauriTauri’s bundlerYes, with Apple credentials (docs)Documented path (docs)Tauri’s updater plugin
SlintGenerates an Xcode projectDocumentedDocumentedNot covered
NSHnsh package (ad hoc signed .app)By hand, per its docsNot found for macOSNot found
egui, Iced, cacao, objc2Not in the project (community tools such as cargo-bundle)By handBy handBy hand

Or just Swift?

For a Mac-only app, the real alternative to Ferrokit isn’t another Rust toolkit: it’s Swift, with AppKit or SwiftUI.

  • Swift wins when there’s no Rust code to reuse, when the app should also run on iOS, and when you want Apple’s own tools (Xcode, previews), documentation, sample code and a stable API. SwiftUI is the quickest way to a modern Mac UI; AppKit from Swift has everything Ferrokit has, and more.
  • Ferrokit wins when the app’s core is Rust. The Swift route then needs a bridge (uniffi or swift-bridge), types on both sides, async across the boundary and two build systems; with Ferrokit the UI calls your crates directly, in one cargo build. It also gives AppKit’s data-heavy controls (NSTableView, NSOutlineView, NSTextView) a declarative API, where Swift would use data sources and delegates or SwiftUI’s simpler Table and List.
  • Both: an app can be Swift with a Rust core through a bridge, or Ferrokit with a few SwiftUI views compiled in by ferrokit-build.

When to pick which

Pick egui for tools, debug UIs, editors and anything that also runs on Windows, Linux or the web, when a consistent look of its own is fine. It’s the quickest way from nothing to a window, and it’s mature.

Pick Iced for a typed, Elm-style architecture across desktop platforms, if you can wait for its accessibility work.

Pick Slint for a designer-friendly markup language, embedded devices, or one UI on desktop and mobile. Check its licence: royalty-free for desktop, mobile and web apps (not embedded), GPLv3, or commercial.

Pick Tauri if you or your team know web development, or you want one UI on desktop and mobile with the largest ecosystem. The UI is HTML and CSS in WebKit; it can look Mac-like with work, but it’s a web page.

Pick GPUI with GPUI Component for a fast, polished desktop app on Mac, Windows and Linux with a ready-made component set (docks, a code editor, data tables, charts): it’s the toolkit Zed is built on, and the one r/rust named most when asked about native-feeling Rust apps. It draws its own controls on the GPU, styled after macOS and Windows, rather than using AppKit’s, and GPUI itself is pre-1.0 with frequent breaking changes.

Pick NSH for native views on several platforms from one Rust (or TSX) codebase, with your own design system on top. It’s the closest project to Ferrokit in spirit; the difference is that NSH is cross-platform and lets the app own the controls’ look, while Ferrokit is Mac only and uses AppKit’s stock controls as they are.

Use objc2 directly to add one AppKit view or call to an app built with something else, or for complete control. It’s what Ferrokit is built on; Ferrokit’s native(..) lets you mix the two.

cacao pioneered safe AppKit bindings in Rust, but it hasn’t had a release since 2023 or a commit since 2024 and pins an old objc2 beta, so it’s hard to recommend for a new app.

Pick Swift (AppKit or SwiftUI) for a Mac app with no Rust code behind it, or one that should also run on iOS.

Pick Ferrokit when the app is Mac only, its core is (or will be) Rust, should behave exactly like a Mac app (tables, outlines, text, menus, VoiceOver, Dark Mode, Liquid Glass) without you rebuilding any of it, and you’d rather write Rust than Swift. Go in knowing what it is today: an alpha with one maintainer and no outside users yet, whose API will still change. The examples show how far it goes, and the roadmap where it’s heading.

Coming from egui, Iced or Slint

The ideas carry over, with a few differences. Coming from egui, Iced or Slint has them in full, with the same app written in each:

  • Views are built once. Unlike egui, nothing re-runs every frame; unlike Iced, there’s no view function rebuilding a tree after each message. A view reads signals, and when a signal changes only the native views that read it update (State).
  • State is signals, Signal<T>, which are Copy: closures take them with move. It’s closer to Slint’s properties or SolidJS than to Elm’s messages.
  • Deep widgets have models. A table is a TableModel of your own row type, created once and fed with set_rows; a text editor is a TextModel. You don’t re-describe a million rows each frame (Tables, outlines and editors).
  • Menus, shortcuts and the toolbar are the system’s: commands, handled where the focus is (The app shell).
  • Styling is AppKit’s: system colours and fonts, materials, SF Symbols. You style less and get the system look (Styling).
  • Everything runs on the main thread; spawn does background work and hands the result back, and spawn_local runs async code there, awaiting work on other threads or your own tokio runtime (Async code in a native Mac app).

Stability and support

What Ferrokit promises, and what it doesn’t. Ferrokit is made by one person, so this is a policy one person can keep: the times below are what to expect, not a contract.

Versions

Ferrokit follows semantic versioning. Its crates (ferrokit, ferrokit-core, cargo-ferrokit, ferrokit-build) share one version and are released together; ferrokit pins ferrokit-core exactly, so use matching versions.

  • Now (0.x): a minor release (0.15 → 0.16) may change the API; a patch release (0.15.0 → 0.15.1) never does. Every change that breaks code is in the CHANGELOG with what to write instead, and the migration guide collects them.
  • From 1.0: minor releases (1.1, 1.2) add things and never break code that compiles against an earlier 1.x. A change that breaks code waits for 2.0. Where it can, the new form arrives first in a 1.x release with the old one deprecated beside it, so you can move over before 2.0. A major release comes at most once a year, with a migration guide.
  • Renames: a renamed item keeps working, deprecated, for at least one minor release.

What the promise covers

Covered: every public item of ferrokit documented on docs.rs (also listed in API.md), and cargo ferrokit’s commands, flags and [package.metadata.ferrokit] settings.

Not covered:

  • Items that name AppKit or objc2 types, the escape hatches: WindowRef::ns and from_ns, native(..), TableModel::table_view, TextModel::text_view, Color::ns and from_ns, Font::ns, the Stored trait and the view lookups in testing (which return NSViews). They follow objc2’s versions: when Ferrokit moves to a new objc2-app-kit, they may change in a minor release, and the CHANGELOG says so. The everyday API names no AppKit types, so most apps never touch them.
  • testing::probes: Ferrokit’s own counters and switches for its checks.
  • ferrokit-core’s own API. Apps use what ferrokit re-exports.
  • Hidden items (#[doc(hidden)]): they’re public only because Ferrokit’s crates share them.
  • What macOS draws. Controls are AppKit’s, so their look follows the system: a new macOS can change a button’s shape or a table’s spacing, and that isn’t a Ferrokit change.
  • Text that isn’t API: error messages, log lines and cargo ferrokit’s output.

macOS

  • Supported: macOS 15 or later, which today means macOS 15 and 26. At least the current macOS and the one before are always supported.
  • The minimum rises only in a minor release, announced in the CHANGELOG one release ahead, and only past versions Apple no longer updates.
  • New macOS versions: the self-checks run on each beta from the first. What a release breaks (macOS 27 turned column browser cells into text cells, for instance) is fixed in a patch release: before the public release where possible, and within two weeks of it otherwise.
  • Checked on: macOS 15 and the current release in CI on every change, in release and debug builds, and the newest beta locally. Apple Silicon is checked; Intel builds but isn’t run regularly (#6).

Rust

The latest stable Rust is tested. The minimum (rust-version, now 1.88) rises only in a minor release.

Fixes

WhatWhen
A security issueA reply within 3 days, and a patch release within 14 days of confirming it.
Something a new macOS breaksA patch release within 2 weeks of that macOS’s release, sooner for betas where possible.
A regression (worked before, doesn’t now)The next patch release, usually within a week.
Other bugs and requestsAs time allows. Issues that say what you’re building weigh most (ROADMAP).

Fixes go into the latest release only: before 1.0, the newest 0.x; from 1.0, the newest 1.x. After a 2.0, the last 1.x gets security fixes and macOS fixes for six months.

Reporting

  • Bugs and requests: GitHub issues. A small example, the macOS version and the output of cargo ferrokit check help most.
  • Security issues: report them privately, not in a public issue. See SECURITY.md.

Failures

An Objective-C exception or a panic in code AppKit calls is caught where it came in, reported (App::on_error) and survived, never silently dropped. Every change runs the self-checks: about 580 checks across 18 example apps and cargo ferrokit’s templates, through the real controls (scripts/check-all.sh).

Migrating to the 1.0 API

Three releases, 0.13, 0.14 and 0.15 (November 2026), settled the API that 1.0 will promise. This guide takes an app from 0.12 or earlier to 0.15 in one pass. Each release’s CHANGELOG section has the full list; this page orders it by what you’ll meet.

How long it takes: almost all of it is mechanical, and the compiler finds every place. Rowboat, a 17,000-line app, changed 162 lines for 0.13, one for 0.14 and about 290 for 0.15, most of them in its self-checks.

Upgrading

  1. Move every Ferrokit crate to the same version: ferrokit = "0.15" (and ferrokit-build, and cargo install cargo-ferrokit --locked for the tool). The crates are released together and must match.
  2. Run cargo build, then work down the errors with the sections below.
  3. Run cargo ferrokit check: clippy, your tests and the app’s self-checks.

From an older version than 0.12, read the CHANGELOG sections in between first; before 0.4 the crates had other names (see the end of this page).

Windows are WindowRef (0.15)

Every function that returned Retained<NSWindow> returns a WindowRef, and every one that took &NSWindow takes &WindowRef: open, windows, focused_window, the dialogs, the document functions, perform_in, undoable_in, print and testing’s window functions.

Code that only passes a window along doesn’t change:

let w = open(Window::new("Notes").view(editor));
alert(&w, Alert::new("Saved", "The note was saved."), |_| {});

Where you named the type, write WindowRef for Retained<NSWindow> and &WindowRef for &NSWindow:

// Before
fn export(window: &NSWindow, csv: String) { save_panel(window, "export.csv", None, move |path| { /* … */ }); }
// After
fn export(window: &WindowRef, csv: String) { save_panel(window, "export.csv", None, move |path| { /* … */ }); }

WindowRef has the common needs itself: title() (a String), set_title, size, set_size, close, is_open, is_key and bring_to_front. Two handles to the same window are ==, and it’s Hash, so it can be a map key. For anything else, .ns() gives AppKit’s NSWindow:

BeforeAfter
w.title().to_string()w.title()
w.makeKeyAndOrderFront(None)w.bring_to_front()
w.setTitle(&NSString::from_str("x"))w.set_title("x")
w.contentView()w.ns().contentView()
objc2::Message::retain(window) or window.retain()window.clone()
Retained::as_ptr(&a) == Retained::as_ptr(&b)a == b
a window from AppKit (view.window()) passed to FerrokitWindowRef::from_ns(&ns_window)

ferrokit no longer re-exports NSWindow; code that still names it writes objc2_app_kit::NSWindow and adds objc2-app-kit to its Cargo.toml.

Models choose their own ids (0.13)

TableModel and TextModel no longer take a ViewId:

// Before
let model = TableModel::new(ViewId(1), vec![Column::text("name", "Name", |p: &Person| p.name.clone())]);
let text = TextModel::new(ViewId(2), "");
// After
let model = TableModel::new(vec![Column::text("name", "Name", |p: &Person| p.name.clone())]);
let text = TextModel::new("");

ViewId is gone from ferrokit.

Builders instead of struct literals (0.13)

OpenOptions and CellStyle can gain fields now, so they’re built with methods:

// Before
open_panel(&w, OpenOptions { extensions: vec!["csv".into()], multiple: true, directories: false }, |paths| { /* … */ });
CellStyle { color: Some(Color::Secondary), strikethrough: done, ..Default::default() }
// After
open_panel(&w, OpenOptions::new().extensions(&["csv"]).multiple(), |paths| { /* … */ });
CellStyle::new().color(Some(Color::Secondary)).strikethrough(done)

A _ arm in matches on growing enums (0.13)

These enums and structs are #[non_exhaustive], so they can grow without breaking apps: Color, ButtonStyle, ControlSize, SymbolEffect, DragItem, ItemImage, FilterTest, FieldKind, FormStyle, input::Key, and the structs OpenOptions, CellStyle, Failure, CollectionItem, Series, Shadow, FilterField, SentNotification and testing::AxElement. A match on one needs a _ => arm; the structs are made through their constructors and read through their fields.

Smaller changes

BeforeAfterSince
label(f), Labeltext(f), Text0.13
.color_when(f), background_when(f), opacity_when(f).color(f), .background(f), .opacity(f)0.13
MenuItem::enabled_when(f), checked_when(f), title_when(f).disabled(move || !f()), .checked(f), menu_item(f, ..)0.13
Mod::Command (testing::input)Modifier::Command0.13
testing::menu_key("n", NSEventModifierFlags::Command)testing::menu_key("n", &[Modifier::Command])0.14
Collection::on_activate(|item: T| ..)on_activate(|item: &T| ..)0.13
ferrokit::effect_runs() and the other diagnostics in the crate roottesting::live_nodes(), testing::live_signals(); Ferrokit’s own counters in testing::probes0.13, 0.14
ToolbarItem::Button { .. } and the other variantstoolbar_button(..), toolbar_group(..), toolbar_search(..)…0.14
model.drain_events(), set_row_drag(..) and the models’ other plumbingthe Table and TextEditor modifiers (.row_drag(..), .on_select(..)…)0.14
implementing View yourself (build, Cx, Node)compose Ferrokit’s views in a function returning impl View, or wrap an NSView with native(..)0.14

Things that got easier and need no change: .tooltip(..), .accessibility_label(..), progress, gauge, VideoPlayer::muted and MenuBarExtra::title take a plain value or a closure, and a closure follows the signals it reads (0.13); popover_on works on every view (0.13).

Escape hatches

What still names AppKit types after 0.15 (WindowRef::ns, native(..), table_view(), text_view(), Color::ns, Font::ns, Stored, testing’s view lookups) follows objc2’s versions rather than Ferrokit’s: see STABILITY.md. If your app uses them only in its self-checks, as most do, that’s where future objc2 updates will touch it.

From before 0.4

Until 0.4 the crates were called appkit-ui (now ferrokit) and appkit-host (now ferrokit-core). Their last releases only re-export the new crates: change the names in Cargo.toml and the use lines, then follow the CHANGELOG from 0.4 on. iced-appkit (AppKit views inside Iced windows) stopped at 0.2.1.

Help

If something isn’t covered here, or the compiler’s error doesn’t lead anywhere, open an issue: a missing step in this guide is a bug.

Getting started

ferrokit needs macOS 15 or later and a stable Rust toolchain. Nothing else: no Xcode project, no Swift, no build script.

The quickest start is cargo ferrokit, which makes a working app with self-checks, then runs, checks and bundles it:

cargo install cargo-ferrokit
cargo ferrokit new my-app
cd my-app && cargo ferrokit run

While you work on it, cargo ferrokit preview runs it the same way and then rebuilds and restarts it every time you save a file: its windows open where you left them, the app doesn’t take the focus from your editor, and a build that fails leaves the running app as it was. Values kept with stored survive the restart; other state starts afresh.

cargo ferrokit preview

--document makes a document app instead (New, Open…, Save, Recent, one window per file). Testing and shipping covers check, bundle and notarize.

By hand, add ferrokit to a binary crate:

[dependencies]
ferrokit = "0.15"

A first app

use ferrokit::*;

fn main() {
    let count = Signal::new(0);
    App::new("Counter")
        .window(
            Window::new("Counter").size(320.0, 140.0).view(
                vstack((
                    text(move || format!("Clicked {} times", count.get())),
                    button("Click me", move || count.update(|n| *n += 1)),
                ))
                .padding(20.0),
            ),
        )
        .run();
}

What happens here:

  • App::new names the app. It gets the standard menu bar (the app menu, Edit, Window, Help) without asking.
  • Window::new(…).view(…) builds the window’s views once. The text given a closure reads count, so when count changes, that one NSTextField gets its new text. Nothing else is rebuilt. Most things a view shows work this way: a value, or a closure over signals.
  • button takes the action to run on click.
  • run starts AppKit’s run loop and doesn’t return.

Signals are Copy handles: each closure takes its own with move, as above, and nothing needs cloning. A signal is freed with the window, row or document that made it.

Main thread only

AppKit is single-threaded, and so is ferrokit: views and signals live on the main thread. Long work goes to a background thread with spawn, which hands the result back to the main thread (see State).

A GUI for an existing project

A Rust project that already has a library or a command-line tool can add its Mac app as a second binary in the same package. Put it behind a feature, so the tool’s build and cargo install stay as they are:

[dependencies]
ferrokit = { version = "0.15", optional = true }

[features]
gui = ["dep:ferrokit"]

[[bin]]
name = "tally"
path = "src/main.rs"

[[bin]]
name = "tally-gui"
path = "src/bin/tally-gui.rs"
required-features = ["gui"]

[package.metadata.ferrokit]
bin = "tally-gui"
name = "Tally"

With bin set, cargo ferrokit run, check and bundle build tally-gui with the gui feature. (In a workspace, a new member package that depends on the library works as well.)

The app’s main is a plain fn main that ends in App::run: AppKit needs the main thread for as long as the app runs, so it can’t be a #[tokio::main] function. A library with async functions runs them on a tokio runtime the app keeps, from a background thread. (Runtime::new() needs tokio’s rt-multi-thread feature; with only rt, use Builder::new_current_thread().enable_all().build().)

use std::sync::OnceLock;
use ferrokit::*;

fn runtime() -> &'static tokio::runtime::Runtime {
    static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
    RT.get_or_init(|| tokio::runtime::Runtime::new().expect("a tokio runtime"))
}

fn main() {
    // Once, before the app starts: blocking here is fine.
    let entries = Signal::new(runtime().block_on(tally::load()).unwrap_or_default());
    // Later, from a button: the save runs on another thread, and the
    // result comes back on the main thread.
    let save_now = move || {
        let list = entries.get_untracked();
        spawn(move || runtime().block_on(tally::save(list)), |result| {
            if let Err(e) = result {
                eprintln!("not saved: {e}");
            }
        });
    };
    App::new("Tally")
        .window(Window::new("Tally").view(button("Save", save_now)))
        .run();
}

Opening windows later

App::window opens windows at launch. open(Window) opens one while the app runs; closing it (the close button, ⌘W, or close_window) tears its views down and frees it.

use ferrokit::*;

fn about() {
    open(Window::new("About").size(300.0, 120.0).view(text("Made with ferrokit").padding(20.0)));
}
fn main() { about(); }

State

State lives in signals. Views that read a signal while they build subscribe to it, and update in place when it changes.

Signal

use ferrokit::*;

let name = Signal::new(String::from("Ada"));
name.set("Grace".into());                 // notifies readers
name.update(|n| n.push_str(" Hopper"));    // changes in place, notifies
let now = name.get();                      // a copy, subscribing the reader
let len = name.with(|n| n.len());          // read without copying
let quiet = name.get_untracked();          // read without subscribing
let chars = name.with_untracked(|n| n.chars().count()); // the same, without copying
let _ = (now, len, quiet, chars);

set_if_changed skips the notification when the value is equal.

Handles and owners

Signal and Memo are Copy handles: closures capture them as they are, with no cloning. Each belongs to the owner that was current when it was made, and is freed with it:

  • A window’s view tree: signals made while its view builds, by its effects, and by its buttons’ actions (a sheet’s form, say) are freed when the window closes.
  • A dynamic branch or a for_each row: freed when the branch is replaced or the row removed.
  • A document: its content, path and edited state go with it.

Signals made outside any owner, such as app state created in main, live as long as the app. Reading a freed signal panics with a message saying so; setting it does nothing, and try_get and is_alive check first. testing::live_signals() counts the signals in existence, for leak checks.

Values in views: fixed, or from signals

What a view shows takes either a value or a closure that reads signals: text("Total") or text(move || format!("{} left", left.get())), and the same for .color(..), .background(..), .opacity(..), .disabled(..), .hidden(..), a button’s title and symbol, and a menu item’s title. A closure runs again when a signal it read changes, and only that view updates. (These take impl IntoValue<T>.)

use ferrokit::*;

let done = Signal::new(false);
let row = text("Boots")
    .padding(8.0)
    .background(move || if done.get() { Color::Green.opacity(0.18) } else { Color::Clear })
    .opacity(move || if done.get() { 0.5 } else { 1.0 });
let toggle = button(move || if done.get() { "Unpack".to_string() } else { "Pack".to_string() }, move || done.set(!done.get()));
let _ = (row, toggle);

Memo: derived state

A memo recomputes when its inputs change, and notifies its own readers only when its value actually changes.

use ferrokit::*;

let items = Signal::new(vec![3, 1, 4, 1, 5]);
let total = Memo::new(move || items.with(|v| v.iter().sum::<i32>()));
let view = text(move || format!("Total: {}", total.get()));
let _ = view;

Effect: reacting to changes

An effect runs now, then again whenever a signal it read changes. It stops when its handle is dropped, so keep it.

use ferrokit::*;

let theme = Signal::new(Appearance::System);
let _keep = Effect::new(move || set_appearance(theme.get()));

Inside a view tree, watch(…) does the same and lives as long as its place in the tree.

Batching

Event handlers (button actions, field edits, menu items) already run in a batch: effects and layout run once at the end, however many signals changed. Use batch yourself when you change several signals from elsewhere:

use ferrokit::*;

let (first, last) = (Signal::new(String::new()), Signal::new(String::new()));
batch(|| {
    first.set("Ada".into());
    last.set("Lovelace".into());
});

untrack(|| …) reads signals without subscribing the running effect.

Background work

spawn(work, then) runs work on a background thread and then with its result on the main thread, inside a batch.

use ferrokit::*;

let rows = Signal::new(Vec::<String>::new());
spawn(
    || std::fs::read_to_string("/etc/hosts").unwrap_or_default().lines().map(String::from).collect::<Vec<_>>(),
    move |lines| rows.set(lines),
);

later(f) runs f on the next pass of the main run loop.

Async tasks

spawn_local(future) runs a future on the main thread. Between its .awaits it can read and set signals as an action does. Each poll is a batch. Inside a task:

  • background(|| …).await runs blocking work on another thread (it’s spawn as a future);
  • sleep(duration).await pauses without blocking anything;
  • alert_async, open_panel_async, save_panel_async and sheet_async show a sheet and give its answer.
use ferrokit::*;
use std::time::Duration;

let status = Signal::new(String::new());
let save = button("Save", move || {
    spawn_local(async move {
        status.set("Saving…".into());
        let written = background(|| std::fs::write("/tmp/notes.txt", "…")).await;
        status.set(match written {
            Ok(()) => "Saved".into(),
            Err(e) => format!("Couldn't save: {e}"),
        });
        sleep(Duration::from_secs(2)).await;
        status.set(String::new());
    });
});
let _ = save;
  • A task belongs to the owner current when it starts, as a signal does. Closing its window, or removing its view, drops the future: the task stops at the .await it’s waiting at. spawn_local returns a Task: cancel() stops it, detach() keeps it running after its owner goes.
  • Tasks keep running while a menu is open or a window is being resized.
  • A panic in a task, or in background work it awaits, is reported (see App::on_error) and ends that task only.
  • Ferrokit has no I/O runtime. Libraries such as reqwest and sqlx need their own (tokio): see tokio, reqwest and sqlx below.

Awaiting a sheet

The callback-taking dialogs have awaitable versions, so a flow of questions reads top to bottom:

use ferrokit::*;

fn export(window: WindowRef, csv: String, status: Signal<String>) {
    spawn_local(async move {
        let Some(path) = save_panel_async(&window, "export.csv", None).await else { return };
        if path.exists() {
            let ask = Alert::new("Replace “export.csv”?", "A file with that name exists.").button("Replace").button("Cancel");
            if alert_async(&window, ask).await != Some(0) {
                return;
            }
        }
        match background(move || std::fs::write(&path, csv)).await {
            Ok(()) => status.set("Exported".into()),
            Err(e) => status.set(format!("Couldn't export: {e}")),
        }
    });
}
let _ = export;
  • alert_async gives the index of the button chosen, or None if the alert ended without one (its window closed) and it has no Cancel button.
  • open_panel_async and save_panel_async give the paths, or None for Cancel.
  • sheet_async(&window, |reply| Window::new(..).view(..)) shows your own sheet and gives what its buttons send: reply.send(value) closes it with a value, reply.cancel() with None.
  • If the task is cancelled while it waits (its window closed, Task::cancel), the sheet closes.

tokio, reqwest and sqlx

Ferrokit has no I/O runtime and doesn’t depend on one. Keep a tokio runtime in your app for the I/O, and with Ferrokit’s tokio feature (ferrokit = { version = "…", features = ["tokio"] }) await work on it with on_runtime:

let rt = tokio::runtime::Runtime::new()?; // kept for the app's lifetime
let handle = rt.handle().clone();
spawn_local(async move {
    match on_runtime(&handle, async move { reqwest::get(url).await?.text().await }).await {
        Ok(body) => page.set(body),
        Err(e) => error.set(Some(e.to_string())),
    }
});
  • When the task is cancelled (its window closed), the work on the runtime is aborted too.
  • A panic on the runtime is reported like one in the task, and ends the task: there’s no JoinError to unwrap.
  • Without the feature, handle.spawn(…).await works as well: a tokio JoinHandle is a plain future. It isn’t aborted with the task, and its result is a Result<_, JoinError>.

Don’t block inside a task: a poll runs on the main thread, and the UI waits for it.

Loading data: Resource

A resource loads a value on a background thread from the signals it reads, and loads again when they change. It’s made for search-as-you-type:

  • Starting a new load cancels the one running. Its result is dropped, so an older query’s rows never replace a newer one’s.
  • The last value stays readable while the next loads, so a table doesn’t flash empty between keystrokes.
use ferrokit::*;

let query = Signal::new(String::new());
let results = Resource::new(move || query.get(), |q: String, cancel: &Cancel| {
    let mut rows = Vec::new();
    for i in 0..1_000_000u32 {
        if i % 10_000 == 0 && cancel.is_cancelled() {
            break; // the user typed again; this result won't be shown
        }
        if i.to_string().contains(&q) {
            rows.push(i);
        }
    }
    Ok::<_, String>(rows)
});
let view = vstack((
    search_field(&query),
    text(move || match results.state() {
        Load::Loading => "Searching…".into(),
        Load::Ready(rows) => format!("{} matches", rows.len()),
        Load::Failed(error) => format!("Search failed: {error}"),
    }),
));
let _ = view;
  • get() is the latest value (None before the first load); loading() is whether a load is running; error() is the latest failure’s text. state() combines them.
  • An error keeps the last value: get() still returns it.
  • refetch() loads again with the same inputs.
  • A resource is owned like a signal: closing its window cancels its load.

Resource::new_async takes a load that returns a future instead. It runs on the main thread as a task, so it needn’t be Send, and a newer load drops the older one’s future at its .await (no Cancel to check):

use ferrokit::*;
use std::time::Duration;

let query = Signal::new(String::new());
let results = Resource::new_async(move || query.get(), |q: String| async move {
    sleep(Duration::from_millis(200)).await; // typing on drops this load here
    let words = background(|| std::fs::read_to_string("/usr/share/dict/words")).await.map_err(|e| e.to_string())?;
    Ok::<_, String>(words.lines().filter(|w| w.starts_with(&q)).map(String::from).collect::<Vec<_>>())
});
let _ = results;

The sleep at the start debounces: while the user keeps typing, each load is dropped before it reads anything. Await on_runtime in it for network I/O.

Stored settings

stored(key, default) is a signal backed by the user’s defaults: it starts from the saved value and saves every change.

use ferrokit::*;

let sounds = stored("play sounds", true);
let view = checkbox("Play sounds", &sounds);
let _ = view;

Views and layout

A view is a value that builds its native views once, the first time it is shown, and updates them in place after. Make your own views by composing these, or wrap a native view with native(..). Layout is done in Rust: stacks and grids size their children from the controls’ natural sizes, and only the part of the tree that changed is laid out again.

Stacks, spacers and padding

use ferrokit::*;

let toolbar = hstack((
    button("Back", || {}),
    spacer(),                      // takes the free space
    text("Page 1 of 3"),
    spacer(),
    button("Next", || {}),
))
.spacing(8.0);
let page = vstack((toolbar, divider(), text("Content").fill_width())).padding(16.0);
let _ = page;
  • vstack and hstack take a tuple of views (or a Vec<AnyView> for a computed list). .alignment(Align::Center) aligns across the stack; .spacing(points) sets the gap.
  • spacer() takes the space left over. A fixed view keeps its natural size.
  • Modifiers, on any view: .padding(p), .padding_xy(horizontal, vertical), .width(w), .height(h), .frame(w, h), .fill_width(), .fill_height().
  • .min_width(w) and .min_height(h): at least that size, larger if the content is.
  • text(..).truncate(): one line, shortened with “…” when its row is short of room (a long path, a long name), instead of pushing past the row’s edge. A row holding truncating text gives up room before overflowing. Add .min_width(w) to keep it readable: it shrinks to w and no further, and the row’s other truncating text gives up the rest.
  • A stack takes a tuple of up to 16 views, a Vec<AnyView>, or one view alone: vstack(for_each(..)). Past 16, group some in a nested stack or pass a Vec<AnyView>.
  • zstack puts views on top of one another, such as text over a picture (see Materials and windows).

Grids: forms

A grid sizes its columns to their widest cell. align_column right-aligns the labels of a form.

use ferrokit::*;

let (name, email) = (Signal::new(String::new()), Signal::new(String::new()));
let form = grid([
    (text("Name:"), text_field(&name).accessibility_label("Name")),
    (text("Email:"), text_field(&email).accessibility_label("Email")),
])
.align_column(0, Align::End)
.spacing(8.0, 10.0);
let _ = form;

Every row of a grid has the same type. When the rows hold different controls, wrap each cell in AnyView::new (or use form and form_row from Controls and forms, which take any control per row):

use ferrokit::*;

let (name, plan) = (Signal::new(String::new()), Signal::new("free"));
let form = grid([
    (AnyView::new(text("Name:")), AnyView::new(text_field(&name).accessibility_label("Name"))),
    (AnyView::new(text("Plan:")), AnyView::new(picker(&plan, vec![("Free", "free"), ("Plus", "plus")]).accessibility_label("Plan"))),
])
.align_column(0, Align::End);
let _ = form;

Text that changes

text("…") is fixed. text(|| …) re-runs when the signals it reads change, and updates only its own text field.

Lists: for_each and identity

for_each builds a row per item and keeps rows by identity: when the list changes, rows whose id is still there are kept (with their native views and state), new ids are built, and gone ones are torn down.

use ferrokit::*;

#[derive(Clone)]
struct Task {
    id: u32,
    title: String,
}

impl Identifiable for Task {
    type Id = u32;
    fn id(&self) -> u32 {
        self.id
    }
}

let tasks = Signal::new(vec![Task { id: 1, title: "Write docs".into() }]);
let list = scroll(vstack((for_each(move || tasks.get(), |task: Task| text(task.title)),)));
tasks.update(|v| v.push(Task { id: 2, title: "Ship".into() })); // builds one row
let _ = list;

Switching subtrees: dynamic

dynamic(|| …) rebuilds its subtree when the signals it read change. Use it for “show this or that”; use .id(key) on a view to keep it across rebuilds while the key is the same.

use ferrokit::*;

let signed_in = Signal::new(false);
let body = dynamic(move || if signed_in.get() { AnyView::new(text("Welcome back")) } else { AnyView::new(button("Sign in", || {})) });
let _ = body;

To hide a view and keep it, use .hidden(|| …) instead: its native views stay built, with their state (a field’s text, a table’s scroll position), and while hidden it takes no room in its stack. It’s the better fit for a panel shown in one mode only, which a dynamic would rebuild each time.

use ferrokit::*;

let advanced = Signal::new(false);
let form = vstack((
    checkbox("Show advanced options", &advanced),
    vstack((text("Cache size"), text_field(&Signal::new(String::new())))).hidden(move || !advanced.get()),
));
let _ = form;

Scrolling

scroll(view) puts a view in an NSScrollView and lays its content out at the visible width.

Teardown

When a view leaves the tree (a list row removed, a dynamic branch switched, a window closed) its native views are removed, its effects stop and its memory is freed. AppKit itself keeps about 0.6 KB per view ever shown, so prefer updating views over replacing them in hot paths.

Controls and forms

Each control is the AppKit one, bound two ways to a signal: the control shows the signal’s value, and user changes set the signal.

use ferrokit::*;

let name = Signal::new(String::new());
let password = Signal::new(String::new());
let notify = Signal::new(true);
let sounds = Signal::new(false);
let size = Signal::new(2u8);
let volume = Signal::new(0.5);
let days = Signal::new(30.0);

let form = vstack((
    text_field(&name).placeholder("Your name").accessibility_label("Name"),
    secure_field(&password).accessibility_label("Password"),
    toggle("Notifications", &notify),          // an NSSwitch with a title
    checkbox("Play sounds", &sounds),
    picker(&size, vec![("Small", 1u8), ("Medium", 2), ("Large", 3)]).accessibility_label("Size"),
    slider(&volume, 0.0, 1.0).accessibility_label("Volume"),
    stepper(&days, 1.0, 365.0, 1.0).accessibility_label("Keep for"),
    progress(|| Some(0.4)),                     // None: indeterminate
    image("star.fill").description("Favourite"),
));
let _ = form;
ControlAppKit viewValue
text_field, secure_fieldNSTextField, NSSecureTextFieldSignal<String>
toggleNSSwitchSignal<bool>
checkboxNSButton (check box)Signal<bool>
pickerNSPopUpButtonany Signal<T: PartialEq + Clone>
slider, stepperNSSlider, NSStepperSignal<f64>
progressNSProgressIndicatora closure: Some(fraction) or None
imageNSImageView with an SF Symbol–
buttonNSButtonan action
menu_buttonNSPopUpButton, pulling downmenu items
help_buttonNSButton, help bezelan action
date_pickerNSDatePickerSignal<SystemTime>
time_pickerNSDatePicker (hour and minute)Signal<(u32, u32)>
color_wellNSColorWellSignal<Color>
segmentedNSSegmentedControlany Signal<T: PartialEq + Clone>
combo_boxNSComboBoxSignal<String>, with suggestions
search_fieldNSSearchFieldSignal<String>
use std::time::SystemTime;
use ferrokit::*;

#[derive(Clone, PartialEq)]
enum Layout { List, Grid }

let due = Signal::new(SystemTime::now());
let remind_at = Signal::new((8u32, 30u32));
let tint = Signal::new(Color::rgb(0.2, 0.5, 1.0));
let layout = Signal::new(Layout::List);
let city = Signal::new(String::new());
let query = Signal::new(String::new());

let form = vstack((
    date_picker(&due).with_time().accessibility_label("Due"),       // .calendar(), .range(min, max)
    time_picker(&remind_at).accessibility_label("Remind at"),
    color_well(&tint).accessibility_label("Tint"),
    segmented(&layout, vec![("List", Layout::List), ("Grid", Layout::Grid)]).accessibility_label("Layout"),
    combo_box(&city, vec!["Berlin", "Lagos", "Tokyo"]).accessibility_label("City"),
    search_field(&query).placeholder("Search orders").on_submit(|| println!("search")),
));
let _ = form;
  • date_picker holds a std::time::SystemTime; .calendar() shows a month calendar instead of a field with a stepper.
  • time_picker holds a time of day, (hour, minute) with the hour 0–23, shown in the user’s 12- or 24-hour format: for a daily reminder or an opening time, which keep their hour and minute whatever the date.
  • Color is sRGB (Color::rgb(r, g, b), components 0–1); the well opens the system colour picker.
  • segmented reads each segment’s title to VoiceOver; give the control as a whole a name too.
  • combo_box keeps free text: typing sets the signal, and so does picking a suggestion. Its suggestions are a fixed list; combo_box_with(&value, move || names.get()) reads them from signals and updates the list when they change. .placeholder("Project") shows grey text while it’s empty.
  • search_field updates its signal as the user types; the clear button empties it, and Return runs on_submit.

Buttons

use ferrokit::*;

let name = Signal::new(String::new());
let save = button("Save", || println!("saved"))
    .disabled(move || name.with(String::is_empty))  // re-evaluated when `name` changes
    .default_action();                           // Return presses it
let cancel = button("Cancel", || println!("cancelled")).cancel_action(); // Escape presses it
let _ = (save, cancel);

text_field(…).on_submit(f) runs f on Return in that field.

A button’s look and size, a menu of actions, and the help button:

use ferrokit::*;

let bar = hstack((
    button("Unread", || {}).style(ButtonStyle::Recessed),         // a filter bar's look
    button("Delete", || {}).destructive().control_size(ControlSize::Small),
    menu_button("Export", vec![
        menu_item("CSV…", || println!("csv")),
        menu_item("PDF…", || println!("pdf")),
    ]),
    menu_button("", vec![menu_item("Rename", || {})])
        .symbol("ellipsis.circle")
        .style(ButtonStyle::Borderless)
        .accessibility_label("More"),
    help_button(|| println!("help")),
));
let _ = bar;
  • ButtonStyle: Standard, Borderless, Inline (a capsule inside a row), Recessed, Circular (a symbol alone), Toolbar, Glass (Liquid Glass on macOS 26; standard before).
  • ControlSize: Mini, Small (inspectors), Regular, Large.
  • .destructive() marks Delete and Discard: AppKit never presses it for Return, and draws it red where the style does.
  • menu_button items are the menu bar’s: .disabled(..), .checked(..), key equivalents and separators work the same.

Sliders and progress

use ferrokit::*;

let quality = Signal::new(50.0);
let volume = Signal::new(0.5);
let angle = Signal::new(0.0);
let loaded = Signal::new(None::<f64>);

let panel = hstack((
    slider(&quality, 0.0, 100.0).ticks(11).snap_to_ticks(),   // stops at 0, 10, … 100
    slider(&volume, 0.0, 1.0).vertical(),                     // fills the height it's given
    slider(&angle, 0.0, 360.0).circular(),                    // a dial
    progress(move || loaded.get()).spinner().control_size(ControlSize::Small),
));
let _ = panel;

A spinner spins while its closure returns None and fills a circle with Some(fraction); a bar does the same as a stripe.

Forms

form lays out labelled rows in sections, as Mac settings do. Each form_row(label, control) names its control for VoiceOver by the label (unless the control has a name of its own); form_content(view) is a row with no label; .help("…") adds a line of smaller text under a row, and a section’s .footer("…") one under the section.

use ferrokit::*;

let (name, sync, size, beta) = (Signal::new(String::new()), Signal::new(true), Signal::new(12.0), Signal::new(false));
let settings = form(vec![
    section("Account", vec![
        form_row("Name", text_field(&name)),
        form_row("Sync", toggle("", &sync)).help("Keeps your library the same on every Mac."),
    ]),
    section("Appearance", vec![form_row("Text size", slider(&size, 9.0, 24.0))]).footer("Applies to new windows."),
    section("", vec![form_content(checkbox("Try new features", &beta))]),
]);
let _ = settings;

Two styles:

  • FormStyle::Grouped (the default) is System Settings: each section a rounded box, labels on the left, controls on the right, lines between rows.
  • FormStyle::Columns (.style(FormStyle::Columns)) is the classic settings window: labels right-aligned in one column ending in a colon, controls after them, lined up across sections. The settings example uses it.

group_box("Title", content) is a titled box on the fill for grouped content (SwiftUI’s GroupBox). disclosure("Advanced", &open, || content) is a title with a disclosure triangle: clicking either shows the content, built when it’s shown; the signal says whether it’s open, both ways.

toggle("", &value) is the switch alone, for a form row to name.

Tab order, shortcuts, input methods

Tab and Shift-Tab follow the views’ positions, top-left to bottom-right. Text fields get AppKit’s own editing: ⌘A, ⌘C, ⌘V, ⌘Z, spell checking, dictation, and input methods (Japanese, Chinese…) with the candidate window at the caret. You don’t write any of it.

Accessibility: name every control

VoiceOver reads a control’s name. A field after text("Name:") has none of its own: the text is a separate view. Name such controls with .accessibility_label("…"):

  • a text_field, picker, slider or stepper beside a text label (a form row names its control for you)
  • an editor or a table that isn’t otherwise titled
  • an icon-only button

button("Save", …), checkbox("…", …) and toggle("…", …) are named by their titles. image(symbol) is decorative (VoiceOver skips it) unless you give it a .description("…").

testing::ax_audit(&window) lists the controls VoiceOver can’t name; run it in your app’s self-checks (see Testing and shipping).

Tables, outlines and editors

These are the widgets web views and custom-drawn toolkits find hardest, and the reason to use AppKit: a virtualised NSTableView that scrolls millions of rows at display rate, NSOutlineView, and NSTextView with all of the system’s text services.

Tables

A table shows a TableModel: your rows (any type) and columns that read from them. The model is created once and updated in place.

use std::rc::Rc;
use ferrokit::*;

#[derive(Clone)]
struct Order {
    customer: String,
    total: f64,
    paid: bool,
}

let model = Rc::new(TableModel::new(
    vec![
        Column::text("customer", "Customer", |o: &Order| o.customer.clone()).width(200.0),
        Column::number("total", "Total", |o: &Order| o.total),
        Column::check("paid", "Paid", |o: &Order| o.paid),
    ],
));
model.set_rows(vec![Order { customer: "Ada".into(), total: 12.5, paid: true }]);

let m = model.clone();
let view = table(&model)
    .on_select(|rows| println!("selected model rows {rows:?}"))
    .on_activate(move |row| println!("opened {}", m.rows()[row].customer)) // double-click or Return
    .on_toggle(|row, column, on| println!("{column} of row {row} → {on}"))
    .accessibility_label("Orders");
let _ = view;
  • Row numbers are model indices: the position in what you passed to set_rows, whatever the current sort.
  • Clicking a column header sorts (Column::sortable(false) opts out); on_sort tells you the new order.
  • .editable(true) on a column makes its cells editable; on_edit reports (row, column, new text).
  • update_row, append and select change the model in place. Only the rows on screen have views; 200,000 rows load in about 5 ms.
  • Column::date(id, title, |row| Option<SystemTime>) shows dates in the user’s format and language (“Today”, “12 Mar 2024”), sorted by date with rows without one first; .with_time() adds the time, and .none_text("Running") shows a word where a row has no date.
  • .on_key(TableKey::Delete, |rows| …) and TableKey::Space take those keys without ⌘ while rows are selected (Delete to remove them, Space to Quick Look them, as in the Finder). Put the action in a menu too.
  • .selection(&rows) binds the selection to a Signal<Vec<usize>> of model indices, both ways: clicking rows sets it, and setting it selects them. set_rows clears the selection and the signal with it, so set the signal after replacing the rows to select again.
  • .cell_focus(&column) gives the table a focused column, as in a spreadsheet: clicking a cell focuses its column, ← and → move it, and the focused cell of each selected row is outlined. column is a Signal<Option<String>> of the column id, both ways. An action on “the cell” reads the selection and column: a menu item such as Set to NULL on ⌥⌫.

Groups, icons, progress bars, fitted columns

use std::rc::Rc;
use ferrokit::*;

#[derive(Clone)]
struct Download { name: String, day: String, done: f64 }

let model = Rc::new(TableModel::new(
    vec![
        Column::text("name", "Name", |d: &Download| d.name.clone())
            .icon(|_| Some(CellImage::Symbol("doc".into())))   // or CellImage::FileIcon(path)
            .fit(),                                             // as wide as the longest name
        Column::progress("done", "Done", |d: &Download| d.done), // a bar from 0 to 1
    ],
));
model.set_rows(vec![Download { name: "report.pdf".into(), day: "Today".into(), done: 0.4 }]);
model.set_group_by(Some(Box::new(|d: &Download| d.day.clone())));  // a header per day
let view = table(&model).accessibility_label("Downloads");
let _ = view;
  • set_group_by shows a header row before each group. Headers are full width, float while their rows scroll, and can’t be selected. Groups appear in the order of their first row; sorting by a column sorts within each group.
  • Row indices in every event stay model indices, never header positions. row_at(view_row) is None for a header.
  • A progress column sorts and copies as its number; VoiceOver reads the bar’s value.
  • .fit() measures the column’s longest values (by character count, with many rows) whenever the rows change.
  • .style(|row| CellStyle::new()…) colours a text or number cell from its row: .color(..), a .background(..) tint, .italic(..), .strikethrough(..), each given the row’s value (CellStyle::new().strikethrough(o.done).color(o.done.then_some(Color::Secondary))) (a changed value, a NULL, a row about to go). After changing what a style depends on, refresh the row with update_row.

Copy, paste, drag and drop

  • ⌘C copies the selected rows as tab-separated text (Numbers and Excel paste it as cells).
  • .row_drag() lets rows be dragged out.
  • .reorderable(|rows, before| …) reorders them by dragging; apply the move with model.move_rows(&rows, before).
  • .on_files_dropped(&["csv"], |paths, before| …) takes files from the Finder.
  • .on_paste(|text| …) handles ⌘V.

Filtering: the filter builder

filter_editor(&filter, fields) is AppKit’s filter builder (as in Mail’s rules and Finder’s smart folders), editing a Filter: a line choosing whether all, any or none of the rules must hold, then a row per rule, with

  • and − to add and remove them (Option with + adds a nested group). It grows with its rows. Fields are FilterField::text, number or choice, each with a key and a title.

A Filter is plain data. filter.matches(|key| value) tests a row, and filter.to_sql() makes a SQL condition for a WHERE, with column names and values quoted so what the user types can’t change the query. A number rule the user hasn’t filled in yet is left out.

use ferrokit::*;

let filter = Signal::new(Filter::default());
let editor = filter_editor(&filter, vec![
    FilterField::text("name", "Name"),
    FilterField::number("total", "Total"),
    FilterField::choice("city", "City", &["Oslo", "Bergen", "Tromsø"]),
]);
let sql = move || format!("SELECT * FROM orders WHERE {};", filter.get().to_sql());
let _ = (editor, sql);

The SQL browser’s Filter… button opens one for the table shown.

Outlines and the sidebar

outline(roots, title) shows a tree of Identifiable values; expansion and selection survive updates. sidebar(…) is the same in the source-list style of Mail’s or Finder’s sidebar: its roots are section headings, and its rows follow the user’s sidebar icon size (System Settings › Appearance). .icon_color(|item| Some(Color::Green)) gives a row’s symbol its own colour, as Mail’s mailboxes and Reminders’ lists have.

use ferrokit::*;

#[derive(Clone)]
struct Folder {
    id: u32,
    name: String,
}

impl Identifiable for Folder {
    type Id = u32;
    fn id(&self) -> u32 {
        self.id
    }
}

let selected = Signal::new(None::<u32>);
let tree = || {
    vec![TreeNode::branch(
        Folder { id: 1, name: "Projects".into() },
        vec![TreeNode::leaf(Folder { id: 2, name: "ferrokit".into() })],
    )]
};
let view = sidebar(tree, |f: &Folder| f.name.clone()).icon(|_| Some("folder".into())).selection(&selected);
let _ = view;

Column browser

column_browser(roots, title) shows the same kind of tree as Finder’s column view (NSBrowser): the roots in the first column, and the selected item’s children in the next. .selection(&path) binds the selected item’s path, the ids from the first column down, both ways; setting it opens the columns to that item. .on_activate(|item| ..) runs on a double-click, and .icon(|item| ..) gives an SF Symbol per item. Arrow keys move through it and typing selects an item by its title.

use ferrokit::*;

#[derive(Clone)]
struct Place(String);
impl Identifiable for Place {
    type Id = String;
    fn id(&self) -> String { self.0.clone() }
}
let p = |s: &str| Place(s.into());
let path = Signal::new(vec!["Norway".to_string(), "Lofoten".to_string()]);
let places = column_browser(move || vec![
    TreeNode::branch(p("Norway"), vec![TreeNode::branch(p("Lofoten"), vec![TreeNode::leaf(p("Reine"))])]),
], |place: &Place| place.0.clone())
.icon(|_| Some("mappin".into()))
.selection(&path)
.on_activate(|place| println!("open {}", place.0))
.accessibility_label("Places");
let _ = places;

Collections: grids of items

collection(items, describe) shows items in a grid (NSCollectionView), as Finder’s icon view or Photos do. Only the items on screen have views: cells are made once and refilled as they scroll in, so 100,000 items load, lay out and draw in about 5 ms.

use std::path::PathBuf;
use ferrokit::*;

#[derive(Clone)]
struct File(PathBuf);

impl Identifiable for File {
    type Id = PathBuf;
    fn id(&self) -> PathBuf {
        self.0.clone()
    }
}

let files = Signal::new(vec![File("/System/Applications/Calculator.app".into())]);
let selected = Signal::new(Vec::<PathBuf>::new());
let grid = collection(move || files.get(), |file: &File| {
    let name = file.0.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    CollectionItem::new(name, ItemImage::FileIcon(file.0.clone()))
})
.item_size(110.0, 104.0)
.selection(&selected)
.multiple()
.on_activate(|file| println!("open {:?}", file.0))   // double-click or Return
.accessibility_label("Files");
let _ = grid;
  • Each item shows a CollectionItem: a title, an optional subtitle and an image: ItemImage::Symbol (an SF Symbol), FileIcon (the Finder’s icon for a path), Color (a swatch) or None.
  • Items are keyed by Identifiable id: the selection (a signal of ids) follows its items when the list changes.
  • Arrow keys, ⌘-click and ⇧-click work as in any Mac grid; VoiceOver reads each item by its title (and subtitle).

The gallery example browses a folder’s apps with their icons, or 100,000 colour swatches.

Text editor

text_editor shows a TextModel in an NSTextView: spell checking, dictation, input methods, Find, undo, the Services menu.

use ferrokit::*;

let notes = TextModel::new("Meeting notes\n");
let text = Signal::new(String::new());
let editor = text_editor(&notes)
    .bind(&text)                                   // keep a signal in step
    .on_selection(|range| println!("selected bytes {range:?}"))
    .accessibility_label("Notes");
let _ = editor;

Find is in the app’s Edit menu (Edit ▸ Find ▸ Find…, ⌘F, and the rest), enabled while the focus is in the editor; notes.show_find() shows the bar from code. notes.set_wraps(false) lets long lines run on with a horizontal scroller, for code and logs.

Positions are UTF-8 byte offsets. Each editor has its own undo history; .shared_undo() puts its typing in the window’s history instead, between your app’s own undoable changes (see The app shell).

Rich text

.rich() lets the user style the text, as in TextEdit: fonts and sizes (the font panel, ⌘T), bold, italic and underline (⌘B, ⌘I, ⌘U), colours, alignment, spacing and lists; pasted text keeps its styles, and pictures can be pasted or dropped in. .format_bar() adds TextEdit’s format bar above the text and .ruler() the ruler; format_menu() is the Format menu (Font and Text) to give the app.

.bind_rtf(&signal) binds the styled text two ways as RTF, what a rich document saves. On the model, rtf() and html() read the text out with its styles, and set_rtf(..) and set_html(..) load it.

use ferrokit::*;

let journal = DocumentType::new(&["rtf"], Vec::new, |doc: &Document<Vec<u8>>| {
    let model = TextModel::new("");
    text_editor(&model).format_bar().bind_rtf(doc.content()).accessibility_label("Entry")
})
.read(|path| std::fs::read(path))
.write(|rtf, path| std::fs::write(path, rtf));
let app = App::new("Journal").documents(journal).menu("Format", format_menu());
let _ = app;

The journal example is a rich text document app with Export as HTML.

Styled text and syntax highlighting

The text stays plain, but runs of it can be coloured and emphasised. .syntax(...) highlights a language; Syntax::sql() and Syntax::rust() are presets, and Syntax::new() builds others from keywords, strings, comments and numbers.

use ferrokit::*;

let query = TextModel::new("SELECT * FROM orders -- all of them");
query.set_font(Some("Menlo"), 12.0);
let editor = text_editor(&query).syntax(Syntax::sql()).accessibility_label("Query");
let _ = editor;

.syntax(...) also makes it a code editor (.code() does that alone): quotes and dashes stay as typed instead of becoming smart quotes, and there’s no text replacement, autocorrection or spell checking.

For anything else, .highlight(|text| runs) returns UTF-8 byte ranges and their TextStyles (a Color, a background, bold, italic, underline). The colours are the system’s, so they follow Dark Mode. Styles are applied after every edit, before it’s drawn, and only where they changed. If the function reads signals, it runs again when they change, here to mark a search term:

use ferrokit::*;

let doc = TextModel::new("");
let term = Signal::new(String::from("TODO"));
let rust = Syntax::rust();
let editor = text_editor(&doc).highlight(move |text| {
    let mut runs = rust.highlight(text);
    let t = term.get();
    if !t.is_empty() {
        let mark = TextStyle::new().background(Color::Yellow);
        runs.extend(text.match_indices(t.as_str()).map(|(at, m)| (at..at + m.len(), mark)));
    }
    runs
});
let _ = editor;

Styles aren’t part of the text: typing, pasting and undo work on characters only, and the highlighter restyles what changed.

Drawing and charts

canvas(|p| …) draws with a Painter: rectangles, circles, arcs, lines, polygons and text, in points from the top-left corner, in Colors (the system’s follow Dark Mode). The drawing is recorded and replayed by a native view. It’s recorded again when signals it reads change or the canvas resizes, so a canvas is as reactive as a label.

use ferrokit::*;

let level = Signal::new(0.4);
let meter = canvas(move |p| {
    p.fill_rounded_rect(0.0, 0.0, p.width(), p.height(), 6.0, Color::Separator);
    p.fill_rounded_rect(0.0, 0.0, p.width() * level.get(), p.height(), 6.0, Color::Green);
})
.on_click(move |x, _y| println!("clicked at {x}"))          // selects, say
.on_double_click(move |x, _y| println!("opened at {x}"))   // after the click, on the second one
.description(move || format!("Level {:.0}%", level.get() * 100.0))
.min_size(200.0, 24.0);
let _ = meter;

.on_drag(|d| ..) moves things the canvas draws (a card on a diagram): CanvasDrag::Began(x, y) once the pointer has moved a few points with the button down, then Moved(x, y) as it goes and Ended(x, y) when it’s released. Keep the positions in a signal and the canvas redraws as they change.

VoiceOver sees a canvas as an image. .description(…) is what it reads, kept current; a canvas without one is decoration (a tinted circle behind a symbol) and VoiceOver skips it.

p.stroke_arc(cx, cy, r, 0.0..270.0, color, width) draws part of a circle with round ends, clockwise in degrees from the top: a progress ring is a faint full circle and an arc through 0.0..360.0 * done.

Charts are canvases. bar_chart(|| vec![(label, value)…]) draws bars for categories. line_chart(|| vec![Series::new(name, points)…]) draws lines through numeric points. Both give round-number axes and gridlines, show values under the pointer, and describe themselves to VoiceOver (“Bar chart, 72 bars, from … to …”). A line keeps at most a few points per pixel column (the first, lowest, highest and last), so a million rows draw in a few milliseconds and spikes still show. Stacked bars, areas, scatter plots, pies, legends and formats for money, percentages and dates are in More controls and charts.

use ferrokit::*;

let prices = Signal::new(vec![(1.0, 10.0), (2.0, 12.5), (3.0, 11.0)]);
let chart = line_chart(move || vec![Series::new("price", prices.get())]);
let _ = chart;

Clipboard, dragging out, dropping in

Clipboard::general() is the system clipboard: set_text, set_png, set_files, and reading each back. Tables and text already handle ⌘C and ⌘V themselves. Clipboard::private() is a pasteboard of the app’s own, handy in tests.

A canvas can be dragged out. .draggable(|| Some(item)) gives a DragItem: text, a PNG, a file, or a file promised by name and written where it’s dropped (the Finder, Mail, another app). The write runs off the main thread, and only if the drag lands. .exportable("chart") makes a canvas an image: right-click for Copy Image and Save Image…, or drag out chart.png.

use ferrokit::*;

let rows = Signal::new(vec![("a".to_string(), 1.0), ("b".to_string(), 2.0)]);
let chip = canvas(|p| p.text(4.0, 3.0, "data.csv", 11.0, Color::Secondary, Align::Start))
    .draggable(move || {
        let csv: String = rows.get_untracked().iter().map(|(k, v)| format!("{k},{v}\n")).collect();
        Some(DragItem::promise("data.csv", move |path| std::fs::write(path, &csv)))
    })
    .frame(80.0, 20.0);
let chart = bar_chart(move || rows.get()).exportable("chart");
let _ = (chip, chart);

Files dropped on a window go to Window::on_drop_files(extensions, action) (any file if the list is empty). In a document app, files of the app’s kinds dropped on a window open as documents, with no code.

The app shell

Every app gets the standard menu bar. Add your own menus with App::menu; a menu named “File” is merged above the standard Close item.

use ferrokit::*;

let items = Signal::new(0);
let show_sidebar = Signal::new(true);
App::new("Notes")
    .menu("File", vec![
        menu_item("New Note", move || items.update(|n| *n += 1)).key("n"),                // ⌘N
        menu_item("Delete Note", move || items.update(|n| *n -= 1))
            .key_with("n", &[Modifier::Option])                                      // ⌥⌘N
            .disabled(move || !(items.get() > 0)),                                     // greyed out at 0
    ])
    .menu("View", vec![
        menu_item("Show Sidebar", move || show_sidebar.update(|s| *s = !*s))
            .key_with("s", &[Modifier::Control])
            .checked(move || show_sidebar.get()),                                         // ✓ when shown
        menu_separator(),
        submenu("Sort By", vec![menu_item("Name", || {}), menu_item("Date", || {})]),
    ])
    .window(Window::new("Notes"))
    .run();

A menu item’s title, .disabled(..) and .checked(..) take a value or a closure; closures are read when the menu opens or a shortcut is pressed. dynamic_submenu(title, || items) rebuilds its items each time it opens, for menus that list current things (servers, recent files).

Commands: menus that act on the focus

A menu item made with menu_command doesn’t run a fixed closure. It runs the Command handler nearest the focus:

  1. the focused view’s handler, then each enclosing view’s up to the window’s root;
  2. then the window’s;
  3. then the app’s.

The item is enabled only while some handler answers, as with AppKit’s responder chain: below, ⌘K clears whichever field has focus, and is greyed out while the title field has focus and is already empty.

use ferrokit::*;

const CLEAR: Command = Command::new("clear");
const REFRESH: Command = Command::new("refresh");

let (title, tag) = (Signal::new(String::from("Groceries")), Signal::new(String::new()));
let view = vstack((
    text_field(&title)
        .accessibility_label("Title")
        .on_command_when(CLEAR, move || !title.with(String::is_empty), move || title.set(String::new()))
        .focused_value("field", "title"),
    text_field(&tag)
        .accessibility_label("Tag")
        .on_command(CLEAR, move || tag.set(String::new()))
        .focused_value("field", "tag"),
))
.padding(20.0);
App::new("Notes")
    .menu("Note", vec![menu_command("Clear Field", CLEAR).key("k")])  // ⌘K clears the focused field
    .on_command(REFRESH, || println!("refresh everything"))            // app-wide fallback
    .window(Window::new("Notes").view(view).toolbar(vec![toolbar_command("refresh", "Refresh", "arrow.clockwise", REFRESH)]))
    .run();
  • on_command_when(cmd, enabled, action) answers but greys the item out while enabled is false. Handlers further out aren’t asked.
  • A handler on a view answers only while the focus is in that view. With the focus elsewhere, the command’s menu item and its toolbar_command button are greyed out unless the window or the app handles it too. Put Delete (⌘⌫) on the table, so it doesn’t take the key from a text field; for a toolbar button that works wherever the focus is, add Window::on_command_when, or use toolbar_button with its own action.
  • Shortcut keys without a letter are their characters: .key("\u{8}") is ⌘⌫, "\r" ⌘↩, "\u{f700}" ⌘↑ (the list is on MenuItem::key).
  • Window::on_command and App::on_command handle a command for the whole window or app.
  • .focused_value(name, value) publishes a value to the focus (a selection signal, say). focused_value::<T>(name) reads the nearest one, for menu items that need to know what they act on.
  • perform(cmd) and can_perform(cmd) do the same from code; perform_in(window, cmd) names the window.
  • Commands go to the key window, or, when the app isn’t active, the most recently opened visible window (focused_window()).

Document apps

App::documents makes an app document-based, like TextEdit or Numbers. Each window is one file. A document’s window comes back where it was when the file is opened again, and if the user keeps windows when quitting (System Settings › Desktop & Dock, “Close windows when quitting an application” off), the documents open at quit reopen at the next launch, as in Apple’s apps.

  • The File menu: New (⌘N), Open… (⌘O), Open Recent, Save (⌘S), Save As… (⇧⌘S) and Revert to Saved.
  • The title bar: shows the file’s name and proxy icon, and the dot in the close button while there are unsaved changes.
  • Closing or quitting with changes: asks whether to save.
use ferrokit::*;

let text_files = DocumentType::new(&["txt", "md"], String::new, |doc: &Document<String>| {
    let model = TextModel::new(&doc.content().get_untracked());
    text_editor(&model).bind(doc.content()).accessibility_label("Text")
})
.read(|path| std::fs::read_to_string(path))
.write(|text, path| std::fs::write(path, text));

App::new("Notes").documents(text_files).run(); // starts with an untitled document
  • A Document<T>’s content is a signal: bind views to doc.content() or change it. The document is edited while the content differs from the file (so T: PartialEq): undoing back to the saved text clears the dot.
  • Without .write, documents are read-only (a viewer: Save is disabled).
  • .write_returning(|content, path| ..) is for content that saving changes: it returns what the document holds afterwards (a database with staged changes commits them and returns none staged), which becomes the saved state.
  • .related(&["-wal", "-journal"]) names files beside each document that it reads and writes too (a database’s journal): the document holds access to them while it’s open, which the App Sandbox needs.
  • Undo is per document, since each window has its own history.
  • new_document(), open_document(path), save_document(window), save_document_as(window, path), revert_document(window), document_edited(window) and recent_documents() do the same from code, without panels. choose_documents() shows the Open panel, as Open… does.
  • DocumentType::window(|w| ..) styles each document window with [Window]’s chrome methods, e.g. |w| w.full_size_content() for a sidebar that runs up under the title bar.

A welcome window

App::welcome(make) shows a window at launch instead of an untitled document, as Xcode does: recent documents, a sample, Open…. It closes when a document opens, and Window ▸ Welcome to … (⇧⌘1) or show_welcome() brings it back, built again so its list is current.

use ferrokit::*;

fn welcome() -> Window {
    let recent: Vec<AnyView> = recent_documents()
        .into_iter()
        .map(|path| {
            let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
            AnyView::new(text(name).padding(6.0).hover_highlight(Color::Quaternary).on_click(move || {
                open_document(&path).ok();
            }))
        })
        .collect();
    Window::new("Welcome").size(600.0, 400.0).view(hstack((
        vstack((button("Open…", choose_documents), button("New", || {
            new_document();
        }))),
        vstack(recent).width(240.0).material(Material::Sidebar),
    )))
}
let text_files = DocumentType::new(&["txt"], String::new, |_: &Document<String>| text(""));
App::new("Notes").documents(text_files).welcome(welcome).run();

The SQL browser’s welcome window is a fuller one: a large symbol, rows that highlight under the pointer, and recent databases in a sidebar.

Files opened from the Finder (double-click, Open With, a drop on the Dock icon, open file.txt) open as documents; an untouched Untitled window from launch closes. For the Finder to offer your app, declare the types in Cargo.toml, and cargo ferrokit bundle writes them into the app:

[[package.metadata.ferrokit.documents]]
name = "Plain Text"
extensions = ["txt", "md"]

The notes example is a complete text editor built this way.

An app can have its own kind of link, myapp://…, that opens it from a web page, an email, another app or open in Terminal (sign-in callbacks, “open this item” links). Declare the scheme in Cargo.toml; cargo ferrokit bundle writes it into the app’s Info.plist:

[package.metadata.ferrokit]
url-schemes = ["notes"]

App::on_open_url gets each link, whether it launched the app or came while it ran, after the windows are up:

use ferrokit::*;

let shown = Signal::new(String::new());
App::new("Notes")
    .on_open_url(move |url| {
        // notes://open/42 opens note 42.
        if let Some(id) = url.strip_prefix("notes://open/") {
            shown.set(id.to_string());
        }
    })
    .window(Window::new("Notes").view(text(move || shown.get())))
    .run();

macOS learns the scheme the first time the bundled app runs (cargo ferrokit run); after that, a link starts the app if it isn’t running. Until then, opening a link fails with “no application” (a bundle that’s built but never run doesn’t count), and a bare cargo run never gets links. When several copies of the app declare the same scheme (an old build, a copy in /Applications), macOS picks one of them, not necessarily the one you just built. The link arrives as macOS gives it, percent-encoded (notes://open/my%20note); decode it with a crate such as url if you need to. Anyone can send your app a link, so treat it like any other untrusted input: check it before acting on it, and ask before anything destructive.

Toolbar and split view

use ferrokit::*;

let query = Signal::new(String::new());
let window = Window::new("Library")
    .size(900.0, 600.0)
    .toolbar(vec![
        toolbar_button("add", "Add", "plus", || {}),
        toolbar_space(),
        toolbar_search("search", &query),
    ])
    .view(split((text("Sidebar"), text("Content"))).position(220.0).remember("library"));
let _ = window;

Toolbar items show their symbols alone, as in Apple’s apps; their labels are what VoiceOver reads and what the overflow menu shows. With ToolbarStyle::Expanded or Preference (a Settings window), the labels show under the symbols.

A sidebar and an inspector: the window shell

Window::sidebar(view) and Window::inspector(view) lay the window out as Mail, Notes and Keynote are: AppKit’s split view controller, with a full-height sidebar on the sidebar material, the window’s view beside it, and an inspector after it. The title starts beside the sidebar, Toggle Sidebar leads the toolbar and Toggle Inspector ends it, and the user can drag either pane wider, narrower or shut. .sidebar_hidden(&signal) and .inspector_hidden(&signal) bind whether they’re hidden, both ways.

use ferrokit::*;

let (no_sidebar, no_inspector) = (Signal::new(false), Signal::new(true));
let window = Window::new("Library")
    .toolbar(vec![toolbar_button("add", "Add", "plus", || {})])
    .sidebar(text("Mailboxes"))
    .sidebar_hidden(&no_sidebar)
    .view(text("Messages"))
    .inspector(text("Details"))
    .inspector_hidden(&no_inspector);
let _ = window;

Each pane has its own tree; a closed window leaves no more behind than a plain AppKit one built the same way (about 1 KB). The split view below is for splits inside a window’s content.

Groups, pickers and customisation

toolbar_group puts related buttons in one capsule (zoom out and in, back and forward); toolbar_picker is a choice of one as segments, bound to a signal (Finder’s view modes). toolbar_fixed_space() is a fixed gap, toolbar_space() a flexible one.

Window::customizable_toolbar(name) lets the user change the toolbar: Customize Toolbar… on its right-click menu, or customize_toolbar_item() in a View menu, opens AppKit’s sheet, where items and spaces can be added, removed and moved. Items marked .optional() are offered there without being shown at first. The user’s layout is remembered under name; until they change it, the app’s own layout shows (so a later version’s new default still reaches them).

use ferrokit::*;

#[derive(Clone, Copy, PartialEq)]
enum Mode { List, Grid }
let (zoom, mode) = (Signal::new(1.0), Signal::new(Mode::List));
let window = Window::new("Photos")
    .toolbar(vec![
        toolbar_group("zoom", "Zoom", vec![
            toolbar_button("out", "Zoom Out", "minus.magnifyingglass", move || zoom.update(|z| *z /= 1.25)),
            toolbar_button("in", "Zoom In", "plus.magnifyingglass", move || zoom.update(|z| *z *= 1.25)),
        ]),
        toolbar_space(),
        toolbar_picker("mode", "View", &mode, vec![("List", "list.bullet", Mode::List), ("Grid", "square.grid.2x2", Mode::Grid)]),
        toolbar_button("share", "Share", "square.and.arrow.up", || {}).optional(),
    ])
    .customizable_toolbar("photos");
let _ = window;

.remember(name) keeps the divider’s position across launches; Window::remember_frame(name) does the same for the window’s frame.

.stacked() puts the panes top to bottom (an editor over its results).

.collapsible(index, &signal) hides a pane while the signal is true and sets the signal when the user drags the pane shut. The first pane and collapsible ones keep their size as the window resizes, and a pane reopens at the size it had. .trailing(points) gives the last pane (an inspector) its first width. The menu items follow the Mac convention: ⌃⌘S and ⌥⌘I, titled “Hide…” or “Show…” by a closure as the title:

use ferrokit::*;

let (no_sidebar, no_inspector) = (Signal::new(false), Signal::new(false));
let app = App::new("Library")
    .menu(
        "View",
        vec![
            menu_item(move || format!("{} Sidebar", if no_sidebar.get() { "Show" } else { "Hide" }), move || no_sidebar.update(|h| *h = !*h))
                .key_with("s", &[Modifier::Control]),
            menu_item(move || format!("{} Inspector", if no_inspector.get() { "Show" } else { "Hide" }), move || no_inspector.update(|h| *h = !*h))
                .key_with("i", &[Modifier::Option]),
        ],
    )
    .window(Window::new("Library").view(
        split((text("Sidebar"), text("Content"), text("Inspector")))
            .collapsible(0, &no_sidebar)
            .collapsible(2, &no_inspector)
            .position(220.0)
            .trailing(260.0),
    ));
let _ = app;

In a document app, make these commands (see above) so they act on the focused window: the SQL browser example does.

Popovers

.popover(&shown, || content) shows content in a popover pointing at a view while shown is true. Escape or a click outside closes it and sets shown back to false. The content is built each time it opens and freed when it closes. popover_on(Edge::Trailing, …) picks the side.

use ferrokit::*;

let shown = Signal::new(false);
let info = button("Info", move || shown.set(true))
    .popover(&shown, || vstack((text("Version 1.0"), text("Made with ferrokit"))).padding(12.0));
let _ = info;

Sheets, alerts and panels

use ferrokit::*;

fn delete(window: &WindowRef) {
    let alert_box = Alert::new("Delete the note?", "This can't be undone.").button("Delete").button("Cancel").destructive(0);
    alert(window, alert_box, |index| if index == 0 { println!("deleted") });
}

fn rename(window: &WindowRef) {
    // Built in `sheet_with`: the sheet's signals are freed when it closes.
    let handle = sheet_with(window, || {
        let name = Signal::new(String::from("Untitled"));
        Window::new("Rename").size(320.0, 100.0).view(text_field(&name).accessibility_label("Name").padding(16.0))
    }, || println!("sheet closed"));
    // handle.close() ends it, e.g. from a Done button.
    let _ = handle;
}

fn choose(window: &WindowRef) {
    open_panel(window, OpenOptions::new().extensions(&["csv"]), |paths| {
        println!("{paths:?}");
    });
    save_panel(window, "Untitled.csv", None, |path| println!("{path:?}"));
}
fn main() {}

A WindowRef is a handle to one of the app’s windows: open returns one, windows() lists them and focused_window() gives the one commands go to. It has the window’s title, size and close(); .ns() reaches AppKit’s NSWindow for anything else.

Where signals live. A signal belongs to what was being built when it was made, and goes with it: a window’s view, a row of a list. One made in an action (a button, a menu item), outside any view, belongs to the window or app the action is in, and lives as long as that. So build a sheet or a new window with sheet_with(parent, || …) or open_with(|| …): the signals its builder makes (the form’s fields) are freed when it closes. The habits soak found New Habit keeping three signals per sheet before it did this.

Settings

App::settings(window) adds Settings… (⌘,) to the app menu. The window is built the first time it opens and kept; pair it with stored signals so the values persist.

use ferrokit::*;

let dark_tables = stored("dark tables", false);
App::new("Viewer")
    .settings(Window::new("Settings").size(360.0, 120.0).view(toggle("Dark tables", &dark_tables).padding(20.0)))
    .window(Window::new("Viewer"))
    .run();

Undo

Every window has its own undo history, shared by its text fields. Make your own changes undoable, and they appear in the Edit menu by name (“Undo Rename”):

use ferrokit::*;

let title = Signal::new(String::from("Draft"));
set_undoable("Rename", &title, "Final".into());     // ⌘Z puts "Draft" back

let count = Signal::new(0);
undoable("Add Item", move || count.update(|n| *n += 1), move || count.update(|n| *n -= 1));

Steps go to the frontmost window’s history (undoable_in names the window). Closing a window clears its history.

Windows, appearance, quitting

  • open(window) opens a window; the close button, ⌘W and close_window tear it down.
  • set_appearance(Appearance::Dark) pins the app’s look; System follows the system setting. App::on_event delivers AppEvent::AppearanceChanged.
  • quit() ends the app, as ⌘Q does (starting on the next run-loop pass, so a document app’s save prompts don’t block the UI).

Tabs, full screen and the Dock

use ferrokit::*;

App::new("Notes")
    // The Dock icon's menu, built each time it opens.
    .dock_menu(|| vec![menu_item("New Note", || {})])
    .window(Window::new("Note").tabbing(Tabbing::Preferred, Some("notes")).view(text("…")))
    .on_launch(|| set_dock_badge(Some("2")))
    .run();
  • Tabs: .tabbing(Tabbing::Preferred, group) opens windows as tabs of the group’s other windows (Automatic follows the user’s “Prefer tabs” setting; Disallowed never). open_tab(&window, Window::new(..)) adds one. The Window menu’s tab commands work as in any Mac app.
  • Full screen: resizable windows can go full screen; .no_full_screen() stops it for palettes and small utilities. toggle_full_screen(&w) and is_full_screen(&w) for your own commands.
  • Dock: set_dock_badge(Some("3")) shows a badge on the Dock icon (None clears it); App::dock_menu adds items above the system’s.

Languages

Strings the user reads go through t, with the English text as the key. The app’s translations are .strings tables, one per language:

use ferrokit::*;

App::new("Notes")
    .translations(&[("de", "\"Run Query\" = \"Abfrage ausführen\";\n\"{n} row\" = \"{n} Zeile\";\n\"{n} rows\" = \"{n} Zeilen\";")])
    .menu(&t("Query"), vec![menu_item(&t("Run Query"), || {})])
    .window(Window::new(&t("Notes")).view(text(|| t_plural(3, "{n} row", "{n} rows"))))
    .run();

In a real app the table is a file, include_str!("../locales/de.strings"):

"Run Query" = "Abfrage ausführen";
"{n} row" = "{n} Zeile";
"{n} rows" = "{n} Zeilen";
  • The language is the first of the user’s preferred languages (System Settings, or the app’s own setting there) that the app has a table for. Strings without a translation stay in English.
  • The framework’s own strings (the standard menus, document alerts, “Untitled”) come in German, French and Japanese. An app’s table can override them.
  • t_with("Open “{file}”", &[("file", &name)]) fills named placeholders, which a translation can reorder.
  • t_plural(n, "{n} row", "{n} rows") picks the language’s plural form. For languages with more than two (Russian, Polish), the table gives "{n} rows#one", "#few", "#many" and "#other". {n} is formatted for the user’s region, as is format_number(value, decimals).
  • format_date(seconds, template) writes a date as the user’s locale does from a template: "EEEEdMMMM" is “Friday, 31 October” in English and “Freitag, 31. Oktober” in German. today(), local_day(seconds), local_day_start(day) and weekday(day) count calendar days in the user’s time zone, through daylight saving: the key for “done today”, streaks and calendars.
  • Try another language without changing the system: my-app -AppleLanguages "(de)".
  • In the bundle, list the languages under languages in [package.metadata.ferrokit]. macOS then shows AppKit’s own panels and menu items (Close All, the Open panel) in that language too.

Right-to-left languages

In Arabic, Hebrew, Persian or Urdu (an app localised in one, for a user who prefers it), the layout mirrors, as AppKit’s own does: a row’s first view is on the right, padding and spacing flip, a form’s labels sit to the right of their controls, and a slide from the leading edge comes from the right. AppKit mirrors the controls themselves (sliders, switches, the window’s buttons). Text keeps its natural direction. right_to_left() says which way the app lays out, for drawing of your own on a canvas.

To try a layout right to left without translating it, launch the app with -AppleTextDirection YES -NSForceRightToLeftWritingDirection YES; checks can call testing::set_right_to_left(Some(true)) before opening a window.

Live data

Data that arrives faster than people read it (a log tail, telemetry, a download list) should be applied once per display frame, not once per item. on_frame gives you that.

use std::rc::Rc;
use std::sync::{Arc, Mutex};
use ferrokit::*;

// Lines from a background reader, applied each frame.
let incoming: Arc<Mutex<Vec<String>>> = Arc::default();
let model = Rc::new(TableModel::new(vec![Column::text("line", "Line", |l: &String| l.clone())]));

let writer = incoming.clone();
std::thread::spawn(move || loop {
    writer.lock().unwrap().push(format!("event at {:?}", std::time::Instant::now()));
    std::thread::sleep(std::time::Duration::from_millis(1));
});

let m = model.clone();
App::new("Tail")
    .window(Window::new("Tail").size(600.0, 400.0).view(table(&model)))
    .on_launch(move || {
        let m = m.clone();
        let incoming = incoming.clone();
        let frames = on_frame(&windows()[0], move |_time| {
            let new = std::mem::take(&mut *incoming.lock().unwrap());
            if new.is_empty() {
                return;
            }
            let follow = m.is_at_end();
            m.append(new);            // cost doesn't depend on the rows already there
            if follow {
                m.scroll_to_end();    // keep following unless the user scrolled up
            }
        });
        std::mem::forget(frames);     // keep it for the app's life (dropping it stops the calls)
    })
    .run();
  • on_frame(window, f) calls f once per frame of the window’s display (60 or 120 Hz), inside a batch, with the frame’s target time. While the display isn’t drawing (asleep, the screen locked) a 10 Hz timer stands in, so data keeps flowing in small steps.
  • Keep the returned FrameLoop; dropping it stops the calls.
  • TableModel::append adds rows without touching the existing ones; is_at_end and scroll_to_end implement “follow unless scrolled up”.

The log_viewer example follows a 1,000,000-line file this way: new lines cost under 1 ms per frame at 10,000 lines a second, and filtering 1.26M lines takes about 70 ms.

Testing and shipping

Self-checks

The example apps test themselves: run with CHECK=all and they drive their own UI, print [check] <name> PASS|FAIL … lines and exit non-zero on a failure. The pattern is simple to copy:

use ferrokit::*;

fn main() {
    let name = Signal::new(String::new());
    App::new("Form")
        .window(Window::new("Form").view(text_field(&name).accessibility_label("Name").padding(20.0)))
        .on_launch(move || {
            if std::env::var("CHECK").as_deref() != Ok("all") {
                return;
            }
            // Each step runs in a turn of its own: act in one, look in the
            // next. After the last, the run reports and exits.
            testing::steps(100, vec![
                Box::new(move || name.set("Ada".into())),
                Box::new(|| {
                    let window = windows()[0].clone();
                    let problems = testing::ax_audit(&window);
                    testing::check("accessibility", problems.is_empty(), format!("{problems:?}"));
                    let shown = testing::view_labeled(&window, "Name").is_some();
                    testing::check("name-field", shown, "the field VoiceOver calls Name is there");
                }),
            ]);
        })
        .run();
}

ferrokit::testing has the helpers the suites use:

HelperFor
check, skip, steps, finishthe [check] lines, the count of failures, steps a turn apart, the exit status
wait_for, wait_untilthe next step waits until a condition is true (a save, a network call), up to a timeout
press_sheet_buttonanswer an alert or a sheet: press its “Delete” or “Cancel”
view_labeledthe view with an accessibility label, to read or drive
ax_audit, ax_elements, ax_treewhat VoiceOver reads (each element’s role, name and value); controls without a name
post_edit, send_action, shortcut, menu_keytyping, clicks and shortcuts without a mouse
snapshot_windows, capture_window, captured_pixelsimages of windows, in process or as the window server shows them
footprint_mb, peak_footprint_mbmemory, as Activity Monitor shows it
is_misspelled, context_menu_for_wordthe text system
live_signals, live_nodes, heap_in_use_mbleak checks: what a closed window leaves behind

testing::probes holds counters that look inside Ferrokit itself (layout passes, effect runs, animations in flight), for its own suites. They’re outside the stability promise; an app’s checks shouldn’t need them.

cargo ferrokit check runs the app with CHECK=all and counts the [check] lines (a name may have several words); it shows only those lines, so run the bundled app with CHECK=all yourself to see everything it prints. Things that catch people out, usually once:

  • One turn to act, the next to look. A spawn or later callback runs inside a batch, so effects and table updates happen after it returns: change something in one step, check it in the next.
  • Undo steps. AppKit closes an event’s undo group only when the app handles an event, so in an unattended run the groups stay open across turns and one ⌘Z can undo several changes. Make each step its own group: undo.setGroupsByEvent(false) on the window’s undoManager(), then beginUndoGrouping() and endUndoGrouping() around each step (the AGENTS.md that cargo ferrokit new writes has the helper).
  • Selecting from code is silent. TableModel::select doesn’t call on_select, and set_rows clears the selection.
  • The real settings. Checks run against the app’s own user defaults, so stored values from the last run are still there: reset the ones a check depends on at its start.
  • Menu items: testing::menu_key presses a menu’s shortcut, including your own menu_commands; testing::shortcut does the same for a ⌘ or ⇧⌘ shortcut without the app being active: your own items run if they’re enabled, and standard ones (Undo, Copy) go along the window’s responder chain.
  • AppKit types in checks: looking at a native view directly needs objc2, objc2-foundation and objc2-app-kit (0.6, 0.3 and 0.3) in your Cargo.toml, with the AppKit features you use.
  • A panic doesn’t end the app. It’s caught and reported (see below), so check stops 15 s after one if no more checks arrive.

Unattended runs see AppKit’s real behaviour in most places. Two exceptions: clicks posted to a window that isn’t active are ignored, so drive controls through their own entry points (as the helpers do); and mouse drags between apps need a person.

Real input

testing::input sends clicks and keystrokes along the user’s path:

  • Event-queue input works whenever the app is active and the window key (input::ready(&window)). input::click(&view), click_at, double_click, type_text(&window, "Ada") and key(&window, Key::Down, &[ferrokit::Modifier::Command]) post events to the app’s own queue, so AppKit dispatches them as it does the window server’s: hit-testing, the first responder, the field editor, the menus’ key equivalents.
  • Window-server input (server_click, server_type) goes through the window server like a real keyboard and mouse, without moving the pointer. It needs the process to be trusted for Accessibility; input::server_available() says whether it is, and checks report SKIP when it isn’t.
use ferrokit::testing::input::{self, Key};
use ferrokit::*;

fn check(window: &WindowRef, field: &objc2_app_kit::NSView) {
    if input::ready(window) {
        input::click(field);
        input::type_text(window, "Ada Lovelace");
        input::key(window, Key::Char('s'), &[ferrokit::Modifier::Command]);
        // Look at the effect a moment later: events arrive on the next turns.
    }
}
let _ = check;

A posted Return doesn’t press a window’s default button (not even in a plain AppKit app), so click it instead; window-server input does press it.

The input example’s suite and the real-input checks in habits and sql_browser use it. They found that a shortcut typed straight after text ran on the old text; menu items, buttons and commands now deliver an editor’s pending changes first.

Soak tests

testing::soak runs an app’s own list of user actions (clicks, typing, page switches, sheets, resizing) at random for a long time, and watches:

  • a watchdog thread reports the main thread not answering for over two seconds;
  • every 30 seconds it samples the footprint and the live views, signals and windows;
  • at the end it prints the footprint’s growth over the second half of the run.
use ferrokit::testing::input::{self, Key};
use ferrokit::testing::soak::{self, Rng, Settings, action};
use ferrokit::*;

fn start(window: WindowRef) {
    let w = window.clone();
    soak::run(Settings::from_env(), vec![
        action("arrow", 3, move |r: &mut Rng| input::key(&w, *r.pick(&[Key::Up, Key::Down]), &[])),
        action("resize", 1, move |r: &mut Rng| {
            window.set_size(600.0 + r.below(400) as f64, 400.0 + r.below(300) as f64);
        }),
    ]);
}
let _ = start;

SOAK=<minutes> sets the length, SOAK_SEED the seed (printed at the start, so a run can be repeated) and SOAK_MS the time between actions. The app takes the front at the start and pauses while another app is in front. The habits and sql_browser examples have soaks (in Ferrokit’s repository, scripts/soak.sh runs one and summarises the log and crash reports).

When something fails

An Objective-C exception (AppKit refusing a call: an index out of range, a row that isn’t loaded yet) or a Rust panic in code AppKit calls into your app, such as a control’s action, a menu item, a timer, a notification or a sheet’s completion, is caught where it came in. It’s printed to stderr with where it happened, and the app goes on. Without that, AppKit swallows the exception, and the rest of that work silently never runs.

App::on_error(|failure| ..) hears about each one (log it, report it, tell the user), and testing::failures() lists them for self-checks: a check can assert that a run caused none.

use ferrokit::*;

let app = App::new("Notes").on_error(|failure| eprintln!("to the crash log: {failure}"));
let _ = app;

Crash reports

on_error hears about failures the app survives. A panic Ferrokit doesn’t catch (outside a control’s action, menu item, timer and the like, or on a background thread) ends the app. App::crash_reports(|report| ..) writes a report for each one before the app ends: the app and its version, macOS, the thread, the panic’s message and place, and the backtrace, in ~/Library/Logs/<app>/Crashes (inside the container when sandboxed). At the next launch, once the windows are up, the handler gets each report not yet marked sent. Panics caught at the places AppKit calls in stay on_error failures and write no report.

What to do with a report is the app’s choice. Two common ones:

  • Ask the user. Show an alert saying the app quit unexpectedly, and offer to show the report in the Finder (for attaching to an email or an issue). Mark it sent either way, so it isn’t asked about again.
  • Send it to a service. Post report.text to your server or a crash service from a background thread (spawn), and mark it sent when the upload succeeds. Sentry’s Rust SDK (sentry crate) can also capture panics itself; if you use it, its own hook replaces this one.
use ferrokit::*;

let app = App::new("Notes").crash_reports(|report| {
    let Some(window) = windows().into_iter().next() else { return };
    let path = report.path.clone();
    alert(
        &window,
        Alert::new("Notes quit unexpectedly last time.", "A report was saved. You can attach it to an email to the developer.")
            .button("Show Report")
            .button("Not Now"),
        move |choice| {
            if choice == 0 {
                reveal_in_finder(&[&path]);
            }
        },
    );
    let _ = report.mark_sent();
});
let _ = app;

A crash that isn’t a panic, such as a bad memory access in unsafe code or a C library, ends the app at once. macOS keeps those in ~/Library/Logs/DiagnosticReports (the user sees them in Console), and offers to send them to Apple, not to you. Uploading a build’s debug symbols isn’t needed for Rust panics: the backtrace names the functions, as long as release builds keep their symbols (the default; don’t set strip = true if you want readable reports).

For checks, FERROKIT_CRASH_DIR points the reports at a folder of the check’s own, testing::pending_crash_reports(dir) reads them, and testing::catching(|| ..) runs code as Ferrokit runs an action, so a panic in it is caught. The ui_checklist example’s crash-report check crashes a child run of itself and reads the report back at its next launch.

Packaging: cargo ferrokit

cargo ferrokit (install it with cargo install cargo-ferrokit) does the packaging. The app’s settings live in its Cargo.toml:

[package.metadata.ferrokit]
name = "My App"            # in the menu bar, Finder and Dock
id = "com.example.myapp"   # the bundle identifier
icon = "icon.png"          # a square PNG (1024 px) or .icns
min-macos = "15.0"
# bin = "myapp-gui"       # the app, when the package has several binaries
[[package.metadata.ferrokit.documents]]  # files the app opens
name = "Text"
extensions = ["txt", "md"]
cargo ferrokit run
cargo ferrokit check
cargo ferrokit bundle --zip
  • run bundles a debug build and runs it, so it has its name, icon and identity, with its output in the terminal.
  • check runs clippy (warnings are errors) and the tests, bundles, runs the self-checks (the app with CHECK=all, as above) and verifies the signature.
  • bundle makes a signed My App.app with the hardened runtime: ad hoc, or with sign from Cargo.toml. --universal builds for Apple silicon and Intel (after rustup target add x86_64-apple-darwin).

The App Sandbox

The Mac App Store needs the App Sandbox, and any app can opt in for safety. sandbox = true in [package.metadata.ferrokit] makes cargo ferrokit bundle sign with its entitlements: files the user chooses (open and save panels, dropped files) and bookmarks to reach them again; network = true adds outgoing connections. Document apps keep working sandboxed: Ferrokit keeps a security-scoped bookmark for each document, so Open Recent and reopening at launch reach the files after a relaunch.

[package.metadata.ferrokit]
sandbox = true
network = true

What else the sandbox must allow goes in a table of entitlements, under Apple’s names: an app that prints (print(..)) needs com.apple.security.print. More Info.plist keys (a usage description, the App Store’s export compliance answer) go in a plist table. Both take true/false, strings and lists of strings.

[package.metadata.ferrokit.entitlements]
"com.apple.security.print" = true

[package.metadata.ferrokit.plist]
ITSAppUsesNonExemptEncryption = false

A document that needs files beside it (a SQLite database’s -journal, -wal and -shm) gets only the document itself from the user’s choice. Declare the others as related files, in the document type (DocumentType::related) and in Cargo.toml, and Ferrokit claims them before reading the document:

[[package.metadata.ferrokit.documents]]
name = "SQLite Database"
extensions = ["sqlite", "db"]
related = ["-journal", "-wal", "-shm"]

Files the app opens but never saves as themselves (a CSV it shows as a table, saved with Save As… as a database) are a viewer’s: say so with role = "viewer" in their document type.

check-all runs the notes example sandboxed. A file outside the app’s container can only be granted by the user choosing it, so try Open Recent on one by hand once.

Notarisation

To hand the app to other people, sign it with a Developer ID and have Apple notarise it. Once per machine, save your notary credentials (an app-specific password from account.apple.com, for the Apple ID of your developer account):

xcrun notarytool store-credentials my-profile --apple-id you@example.com --team-id TEAMID

Set sign = "Developer ID Application: Your Name (TEAMID)" and notary-profile = "my-profile" in [package.metadata.ferrokit]. Then one command builds, signs, notarises, staples and zips (--dry-run stops before the upload):

cargo ferrokit notarize

The zip opens on any Mac running macOS 15 or later with no Gatekeeper warning.

Updates

Apps outside the Mac App Store usually update through Sparkle, and Ferrokit uses Sparkle 2. When the app is bundled with it, the app menu gets Check for Updates…, and Sparkle does the rest. At the second launch it asks the user whether to check automatically. When there’s a new version it shows the release notes, downloads the update, checks its signature, installs it and relaunches. The app’s code doesn’t change.

Once:

  1. Download Sparkle 2 (Sparkle-2.x.tar.xz from github.com/sparkle-project/Sparkle/releases) and unpack it, for example in ~/Developer/Sparkle-2.10.1. Its licence is MIT-style: include its notice with your app’s credits.
  2. Make the key that signs your updates. Sparkle’s bin/generate_keys keeps the private key in your login keychain and prints the public key. Back the private key up (generate_keys -x <file>): without it you can’t publish updates your users will accept.
  3. Tell cargo ferrokit where updates come from:
[package.metadata.ferrokit.updates]
feed = "https://example.com/myapp/appcast.xml"
public-key = "…"                           # what generate_keys printed
sparkle = "~/Developer/Sparkle-2.10.1"      # or set FERROKIT_SPARKLE

cargo ferrokit bundle (and run, check, notarize) then embeds Sparkle.framework, signs its parts with the app’s identity, and puts the feed and the public key in Info.plist. A sandboxed app gets the settings and entitlements that Sparkle’s installer (and, without network = true, its downloader) needs. bundle --app-store leaves Sparkle out: the App Store does the updating there.

Each release:

  1. Raise version in Cargo.toml.
  2. cargo ferrokit notarize (a Developer ID signature and Apple’s ticket).
  3. cargo ferrokit appcast. It zips the app into updates/ as My-App-1.1.0.zip and writes updates/appcast.xml with Sparkle’s generate_appcast, signing the update with your key.
  4. Upload the new files to the feed’s folder. Any HTTPS host works: your site, S3, GitHub Pages, or a GitHub release that holds the feed and the updates (feed = "https://github.com/you/myapp/releases/download/updates/appcast.xml", then gh release upload updates <the new files> --clobber).

Keep updates/ between releases. generate_appcast keeps the feed’s history and makes small delta updates from the earlier versions.

Nothing in the app has to call Sparkle. The updates module is for an app that wants more: updates::check() runs a check from a button, set_automatic_checks and set_automatic_downloads back a Settings checkbox, and updates::on_event reports what the updater does:

use ferrokit::*;

updates::on_event(|event| match event {
    // Downloaded and checked; it installs when the app quits.
    UpdateEvent::ReadyOnQuit { version } => set_dock_badge(Some(version.as_str())),
    UpdateEvent::Failed { message } => eprintln!("update failed: {message}"),
    _ => {}
});

Run unbundled (cargo run), the app has no Sparkle, and these functions do nothing (updates::available() is false). A bundle that’s set up for updates but can’t start Sparkle prints why and reports it to on_event. Ad hoc builds turn off library validation so they can load Sparkle; with a Developer ID, the app and Sparkle share your team and need no exception.

check-ferrokit.sh (part of check-all) tests the whole path when Sparkle is unpacked in target/sparkle-<version> or FERROKIT_SPARKLE names it. It installs version 1.0.0, serves 1.1.0 from a feed on 127.0.0.1, shows that an update signed with the wrong key is refused, and that the right one installs when the app quits. It runs both plain and sandboxed. A feed on 127.0.0.1 is only for testing like this: a real feed must be HTTPS.

The Mac App Store

The Mac App Store takes an installer package of a sandboxed app, signed with your App Store identities. You need, from your Apple Developer account:

  • an Apple Distribution certificate (signs the app) and a Mac Installer Distribution certificate (signs the package; Keychain Access shows it as “3rd Party Mac Developer Installer”), both in your keychain;
  • a Mac App Store provisioning profile for the app’s bundle id (developer.apple.com ▸ Profiles), saved next to the app;
  • the app in App Store Connect, with the same bundle id.
[package.metadata.ferrokit]
sandbox = true
category = "public.app-category.productivity"
app-store-sign = "Apple Distribution: Your Name (TEAMID)"
installer-sign = "3rd Party Mac Developer Installer: Your Name (TEAMID)"
provisioning-profile = "MyApp.provisionprofile"
cargo ferrokit bundle --app-store --build 42

It builds the app for Apple silicon and Intel, embeds the profile, signs the app with its sandbox entitlements and the profile’s app and team ids (a profile for another app, or for iOS, is refused with the reason), and writes My App.pkg. --build is the build number (CFBundleVersion; each upload needs a higher one), and the version is the package’s. --dry-run does all of it without your identities: ad hoc signing and an unsigned package, then the signing commands it would run.

Upload the package with Apple’s Transporter app (from the Mac App Store). Before submitting, run the sandboxed build yourself (cargo ferrokit run with sandbox = true): App Review checks that the app works in the sandbox, and files outside the container are reachable only through open and save panels, drops and the bookmarks Ferrokit keeps.

Styling

Ferrokit’s views are AppKit’s own, so they already look like a Mac app. Styling adds the rest of what makes an app look designed: a hierarchy of type, colour, cards, and imagery. Everything here follows Dark Mode, Increase Contrast and the user’s accent colour by itself.

The styles example builds a whole screen this way:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit
cargo run -p ferrokit --example styles

Text

text takes a font and a colour, each fixed or from signals. .font(..) and .color(..) also work on any view (a row, a card) and after other modifiers, for all the text inside:

use ferrokit::*;

let total = Signal::new(48_210.0);
let header = vstack((
    text("Good morning").font(Font::subheadline()).color(Color::Secondary),
    text("Your money this month").font(Font::large_title().weight(Weight::Bold)),
    text(move || format!("${}", format_number(total.get(), 0)))
        .font(Font::title().monospaced_digits())
        .color(move || if total.get() < 0.0 { Color::Red } else { Color::Primary }),
))
.alignment(Align::Start);
let _ = header;

The system’s text styles, sized as the Mac sizes them:

StyleSizeFor
Font::large_title()26 pta screen’s main title
Font::title(), title2(), title3()22, 17, 15 ptsection titles
Font::headline()13 pt boldheadings in lists
Font::body()13 ptwhat labels use
Font::callout(), subheadline()12, 11 pttext set apart
Font::footnote(), caption(), caption2()10 ptsmall print

Custom fonts:

  • Font::system(size), Font::monospaced(size) (SF Mono);
  • Font::named("Avenir Next", 15.0) (the system font if it isn’t installed).

Font changes:

  • .weight(Weight::Semibold), .bold();
  • .size(points), .italic();
  • .monospaced_digits(), so changing numbers don’t shift.

Colours:

  • Text: Color::Primary, Secondary, Tertiary and Quaternary, the system’s levels of emphasis.
  • Accent: Color::Accent, the user’s accent colour.
  • System colours: Red, Blue, Teal and the rest.
  • Fixed colours: Color::rgb(r, g, b), Color::rgba(..) and Color::hex("#3a7bd5"). They stay the same in light and dark.
  • Opacity: .opacity(0.5) gives a colour at half its own opacity.

Cards and surfaces

Any view can have a background, rounded corners, a border and a shadow:

use ferrokit::*;

let card = vstack((
    text("Balance").font(Font::subheadline()).color(Color::Secondary),
    text("$48,210").font(Font::title().weight(Weight::Semibold)),
))
.alignment(Align::Start)
.padding(16.0)
.fill_width()
.background(Color::ControlBackground)
.corner_radius(12.0)
.border(Color::Separator, 0.5)
.shadow(Shadow::soft());
let _ = card;
  • Colours: Color::QuaternaryFill is the system’s fill for grouped content: cards as SwiftUI’s GroupBox and grouped forms draw them, a translucent grey that suits light and dark. Fill, SecondaryFill and TertiaryFill are stronger, for smaller shapes (a ring’s track, a field). Color::ControlBackground is the colour for panels and lists, and Color::WindowBackground the window’s.
  • Shadows: Shadow::soft() suits cards on a background, Shadow::floating() something above the content, and Shadow::new(radius, y) sets your own.
  • Opacity: .opacity(0.4) fades a whole view.

Modifiers apply in the order written, as in SwiftUI:

  • Padding then background: .padding(16.0).background(..) puts the background under the padding.
  • Background then padding: .background(..).padding(16.0) keeps it to the view.
  • Frame then padding: .frame(18.0, 18.0).padding(7.0) is an 18-point view in a 32-point tile.

Rows of cards that all .fill_width() share a stack’s width equally, whatever their content.

Images

SF Symbols:

use ferrokit::*;

let icons = hstack((
    image("cart.fill").symbol_size(15.0).symbol_weight(Weight::Semibold).hierarchical(Color::Orange),
    image("cloud.sun.fill").multicolor(),
    image("bag.fill").color(Color::rgb(1.0, 1.0, 1.0)).frame(18.0, 18.0).padding(7.0).background(Color::Pink).corner_radius(8.0),
));
let _ = icons;

Symbol styling:

  • .symbol_size(points) and .symbol_weight(..), to match the text beside it;
  • .color(..) for one colour;
  • .hierarchical(..) for shades of one colour;
  • .palette(&[..]) for a colour per layer;
  • .multicolor() for the symbol’s own colours.

Symbol effects (macOS 14; AppKit draws them and tones them down under Reduce motion):

use ferrokit::*;

let searching = Signal::new(true);
let unread = Signal::new(0u32);
let status = hstack((
    // Runs while `searching` is true.
    image("wifi").effect(SymbolEffect::VariableColor, move || searching.get()),
    // Plays once each time `unread` changes.
    image("bell.fill").effect_on(SymbolEffect::Bounce, move || unread.get()),
));
let _ = status;

Repeating effects (.effect): Pulse, VariableColor, Scale, Rotate, Breathe. One-shot effects (.effect_on): Bounce, Wiggle, Rotate. Wiggle, Rotate and Breathe need macOS 15; on older systems an effect does nothing.

Pictures, from a file or from bytes built into the app:

use ferrokit::*;

let avatar = image_file("avatar.jpg").fill().corner_radius(24.0).description("Ada's photo").frame(48.0, 48.0);
let logo = image_data(include_bytes!("../README.md")).frame(120.0, 40.0);
let _ = (avatar, logo);
  • Fit: pictures fit inside their frame by default, all of it shown.
  • Fill: .fill() fills the frame and crops the edges, for covers and avatars.
  • Rounding: an image’s own .corner_radius(..) rounds the picture itself; use half its size for a circle.
  • VoiceOver: give pictures that carry meaning a .description(..). Without one, VoiceOver skips the image as decorative.

An image’s own methods (.fill(), .corner_radius(..), .description(..), the symbol ones) come before the modifiers every view has (.frame(..), .padding(..)).

Materials and windows

Mac apps feel native partly through what’s behind their content: the translucent sidebar that runs up behind the window buttons, glass over photos, a title bar that blends into the window. This chapter covers those, and layering one view over another.

The materials example builds a travel journal this way:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit
cargo run -p ferrokit --example materials

Materials

.material(..) puts one of the system’s materials behind a view, its padding included. Materials blur what’s behind them, and they follow Dark Mode, Reduce Transparency and whether the window is active, as the system’s own sidebars and panels do:

use ferrokit::*;

let sidebar = vstack((
    text("Places").font(Font::subheadline().weight(Weight::Semibold)).color(Color::Secondary),
    text("Lofoten"),
    text("Kyoto"),
    spacer(),
))
.alignment(Align::Start)
.padding(10.0)
.material(Material::Sidebar);
let _ = sidebar;
MaterialFor
Material::Sidebarsidebars and source lists
Material::Header, Titlebarheaders over scrolling content, a title bar area
Material::Popover, Menu, Sheet, ToolTippanels like the system’s own
Material::Huddark floating panels (a player, an inspector over media)
Material::Window, Content, UnderWindow, UnderPagebackgrounds
Material::Selectiona selection highlight in the accent colour

Sidebars, panels and backgrounds show the desktop through the window; headers, title bars and content materials blend with the window’s own content. .corner_radius(..) rounds a material.

Liquid Glass

.glass(..) puts Liquid Glass behind a view on macOS 26 and later. On macOS 15, which has no Liquid Glass, a translucent popover material takes its place, so the same code runs on both:

use ferrokit::*;

let caption = vstack((
    text("Lofoten").font(Font::title().weight(Weight::Bold)),
    text("Nine days above the Arctic Circle").font(Font::callout()).color(Color::Secondary),
))
.alignment(Align::Start)
.padding(14.0)
.glass(Glass::Regular)
.corner_radius(14.0);
let _ = caption;
  • Glass::Regular: frosted glass, for controls and panels.
  • Glass::Clear: clearer glass, over rich backgrounds like photos.
  • Glass::Tinted(color): regular glass with a tint; give the colour some transparency (Color::Blue.opacity(0.3)).

has_liquid_glass() says whether this Mac has it, for the rare design that should differ.

Layers

zstack puts children on top of one another, the first at the back. It’s as large as its largest child. Children that fill take its whole size, and the others keep their own size and are centred, or placed by .alignment(horizontal, vertical):

use ferrokit::*;

let hero = zstack((
    image_file("cover.jpg").fill().corner_radius(14.0).fill_width().fill_height(),
    text("Lofoten").font(Font::title()).padding(14.0).glass(Glass::Regular).corner_radius(14.0).padding(16.0),
))
.alignment(Align::Start, Align::End)
.height(280.0);
let _ = hero;

Here the picture fills the stack, and the caption sits 16 points in from its bottom-left corner. Glass and materials blur the views behind them in the stack, so glass over a picture refracts the picture.

Window chrome

A Window chooses how its title bar and toolbar look:

use ferrokit::*;

let window = Window::new("Journal")
    .full_size_content()
    .hide_title()
    .toolbar(vec![toolbar_space(), toolbar_button("share", "Share", "square.and.arrow.up", || {})])
    .view(split((text("Sidebar").material(Material::Sidebar), text("Content"))).position(210.0));
let _ = window;
  • .full_size_content(): content goes under the title bar and toolbar, which become transparent. Backgrounds and materials, and a split view’s panes, reach the window’s top edge, so a sidebar’s material runs up behind the window buttons, as in Apple’s apps. The content itself starts below the bar, with no padding to work out.
  • .transparent_title_bar(): the title bar shows the window’s background, so bar and content read as one surface.
  • .hide_title(): no title in the bar, for windows whose content says what they are. The title still names the window in the Window menu and Mission Control.
  • .toolbar_style(..): ToolbarStyle::Unified (the default), UnifiedCompact for a shorter bar, Expanded with the title above the items, or Preference for Settings-style tabs.
  • .background(color): the window’s own colour. Named colours follow Dark Mode; fixed ones (Color::hex("#e9dcc4")) stay as they are, so give a fixed background text colours that suit it.

Panels

A panel is a secondary window serving the main ones: an inspector, a palette, a heads-up display over media. Window::panel makes one:

use ferrokit::*;

let inspector = Window::new("Inspector").size(260.0, 320.0).panel(PanelStyle::Floating).view(text("Selection"));
let tools = Window::new("Tools").size(180.0, 240.0).panel(PanelStyle::Utility).view(text("Brushes"));
let hud = Window::new("Adjust").size(240.0, 120.0).panel(PanelStyle::Hud).view(text("Exposure"));
let _ = (inspector, tools, hud);

Panels float above the app’s other windows, hide while the app is in the background, stay out of the Window menu’s list, and take the keyboard only when a field in them is clicked, so typing still goes to the main window. Utility has a slimmer title bar; Hud is dark and translucent.

Motion

Good Mac apps move a little. A panel fades in, the list below it slides down to make room, and a finished row fades back. A row highlights under the pointer and dims as it’s clicked. Ferrokit animates these with Core Animation, as AppKit’s own views do, and respects Reduce Motion by itself.

The motion example is a packing list built this way:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit
cargo run -p ferrokit --example motion

Animated changes

Wrap a change in animated, and whatever it changes moves instead of jumping:

use ferrokit::*;

let details = Signal::new(false);
let toggle = button("Details", move || animated(|| details.set(!details.get())));
let _ = toggle;

Inside animated:

  • Views that move or resize because of the change slide to their new place. That covers the list pushed down by a panel that appears.
  • Opacity and colours set by .opacity(..) and .background(..) fade to their new values.
  • Views with a transition that are added or removed come and go as it says.

Outside animated, the same change lands at once. The default is a quarter of a second, easing in and out. animated_with(Animation::ease_out(0.4), ..) sets your own timing; there’s also ease_in, ease_in_out and linear.

Opacity and colours that follow state

use ferrokit::*;

let done = Signal::new(false);
let row = hstack((text("Boots"), spacer()))
    .padding(10.0)
    .background(move || if done.get() { Color::Green.opacity(0.18) } else { Color::Clear })
    .corner_radius(8.0)
    .opacity(move || if done.get() { 0.45 } else { 1.0 });
let _ = row;

Transitions

.transition(..) says how a view comes and goes when dynamic or for_each adds or removes it inside animated:

  • Transition::Fade: fades in and out.
  • Transition::Slide(Edge::Leading): fades while sliding a short way in from that edge (Above, Below, Leading or Trailing), and back out to it.
use ferrokit::*;

#[derive(Clone)]
struct Item { id: u32, name: String }
impl Identifiable for Item {
    type Id = u32;
    fn id(&self) -> u32 { self.id }
}

let items = Signal::new(vec![Item { id: 1, name: "Boots".into() }]);
let list = vstack((for_each(move || items.get(), |item: Item| {
    text(&item.name).padding(8.0).transition(Transition::Slide(Edge::Leading))
}),));
let add = button("Add", move || animated(|| items.update(|v| v.push(Item { id: 2, name: "Map".into() }))));
let _ = (list, add);

A removed view stays on screen until its transition ends, then goes, and the views around it close the gap as it leaves.

Springs

Animation::spring(response, damping) moves like a spring, as SwiftUI’s do: response is how quickly (its period undamped, in seconds) and damping how it settles, 1 without overshooting and less with a bounce. Animation::bouncy(), snappy() and smooth() are ready-made ones. A spring lasts until it’s still, and a view moved again mid-flight goes on from where it is.

use ferrokit::*;

let open = Signal::new(false);
let toggle = button("Details", move || animated_with(Animation::bouncy(), || open.set(!open.get())));
let _ = toggle;

Core Animation’s curves can’t overshoot, so frames under a spring are set a frame at a time instead; fades and colours in the same change ease out alongside.

Animating values and keyframes

animate(&signal, to, animation) takes an f64 signal to to over time, setting it each frame: anything that reads it follows (a canvas drawing, an opacity, a size). keyframes(&signal, frames) takes it through several values, each reached with its own timing, as SwiftUI’s keyframe animator does: a shake, a pulse, a count-up. .repeating() loops it until stop_animation(&signal).

use ferrokit::*;

let level = Signal::new(0.0);
let fill = button("Fill", move || animate(&level, 1.0, Animation::snappy()));

let nudge = Signal::new(0.0);
let shake = button("Shake", move || {
    keyframes(&nudge, Keyframes::new(0.0).to(8.0, 0.06).to(-6.0, 0.08).with(0.0, Animation::snappy()))
});
let _ = (fill, shake);

Matched geometry

.matched_geometry("id") pairs views across an animated change: when one with that id goes and another with it comes (a thumbnail and its detail, a marker under the selected tab), the new one starts where and as large as the old one was, then moves to its place. The motion example’s trail name moves from the header into the details panel this way.

Hover and click

Any view can respond to the pointer:

  • .on_hover(|inside| ..) hears the pointer come and go.
  • .hover_highlight(Color::Quaternary) shows a background while the pointer is over the view, fading in and out. It’s the quiet highlight of the system’s lists.
  • .on_click(|| ..) makes the whole view a button. It dims while pressed, and VoiceOver reads it as a button named by its text (or by .accessibility_label(..)). Use it for rows, cards and tiles; controls inside it don’t get clicks.
use ferrokit::*;

let selected = Signal::new(0);
let row = hstack((image("map.fill"), text("Lofoten"), spacer()))
    .padding(8.0)
    .hover_highlight(Color::Quaternary)
    .corner_radius(6.0)
    .on_click(move || animated(|| selected.set(1)));
let _ = row;

Reduce Motion

Springs and matched geometry don’t move either, and animate and keyframes set the end value at once.

With Reduce Motion on (System Settings › Accessibility › Display), animated changes don’t move anything: views land in their new places at once, and slides become plain fades. Fades and colour changes still animate, as Apple’s guidelines suggest. reduce_motion() says whether it’s on, for the rare animation of your own.

More controls and charts

This chapter covers the rest of AppKit’s standard controls (tabs, radio buttons, links, gauges and ratings, token fields, path controls and tooltips) and the full set of charts. The components example is a trip budget that uses all of them:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit
cargo run -p ferrokit --example components

Tabs

tabs shows one of several panes, bound two ways to a signal. Each page is a title, the value that selects it, and its content:

use ferrokit::*;

let page = Signal::new(0);
let view = tabs(&page, vec![
    ("Overview", 0, AnyView::new(text("Charts here"))),
    ("Settings", 1, AnyView::new(text("Controls here"))),
])
.style(TabStyle::Segmented);
let _ = view;
  • TabStyle::Segmented: a segmented control above borderless content, as most modern Mac apps do.
  • TabStyle::Bordered: the default. AppKit’s tab view, with tabs along the top of a bordered box, as in inspectors and older settings panes.

Every pane is built once and keeps its state while hidden. A pane sits at the top left of the tab view, unless it fills it (a chart, a list).

Choices and values

use ferrokit::*;

let currency = Signal::new("USD".to_string());
let tags = Signal::new(vec!["Hiking".to_string()]);
let stars = Signal::new(4.0);
let used = Signal::new(62.0);
let folder = Signal::new(std::env::temp_dir());

let form = vstack((
    radio_group(&currency, vec![("US dollar", "USD".to_string()), ("Euro", "EUR".to_string())]).horizontal(),
    token_field(&tags).suggestions(&["Hiking", "Hotels", "Islands"]).placeholder("Add tags"),
    rating(&stars, 5).accessibility_label("Rating"),
    gauge(move || used.get(), 100.0).warning(75.0).critical(90.0).accessibility_label("Storage"),
    path_control(&folder).accessibility_label("Export folder"),
    link("Read the guide", "https://github.com/lhassa8/ferrokit"),
));
let _ = form;
  • radio_group: radio buttons choosing one value, one above another or .horizontal().
  • token_field: words or names as tokens (tags, recipients), finished with Return or a comma. .suggestions(..) offers completions as the user types.
  • rating: stars the user clicks, as in Music and Photos.
  • gauge: a level from 0 to a maximum (storage, a battery). .warning(..) and .critical(..) turn it yellow and red, and .discrete() draws segments.
  • path_control: the folders down to a file, as the Finder’s path bar shows them. Clicking a folder chooses it, and when there isn’t room the middle folders shorten to fit.
  • link: text that opens a web page, a mailto: address or a file in its app. VoiceOver reads it as a link and can open it.

Tooltips

.tooltip(..) works on any view: the text appears when the pointer rests on it, and VoiceOver reads it as the view’s help. SwiftUI calls this help.

use ferrokit::*;

let reset = button("Reset", || {}).tooltip("Clears the rating");
let _ = reset;

Disabled controls

.disabled(|| ..) works on any view: its controls are disabled while the function returns true, following the signals it reads. SwiftUI’s disabled.

use ferrokit::*;

let remind = Signal::new(false);
let hour = Signal::new(8);
let row = hstack((
    checkbox("Remind me at", &remind),
    picker(&hour, vec![("8:00", 8), ("9:00", 9)]).disabled(move || !remind.get()),
));
let _ = row;

Charts

Every chart is drawn natively, redraws when the signals its data function reads change, shows values under the pointer, and has a legend when it has more than one series. VoiceOver reads each one as an image, described by a summary.

ChartDataFor
bar_chart(label, value) pairscomparing categories
stacked_bar_chart(label, values), plus .series_names(..)parts of each category (.grouped() puts them side by side)
line_chartSeries of (x, y) pointschange over time; millions of points draw quickly
area_chartSeriestotals over time, filled down to zero
scatter_chartSerieshow two values relate
pie_chart(label, value) pairsshares of a whole (.donut() for a ring with the total inside)
histogramvalueshow many fall in each range (about 10 round-number bins, or .bins(n))
heatmap(column, row, value) triplesa grid shaded by value: activity by weekday and week, by hour
sparklinevaluesa small trend beside a number or in a row: no axes, the last value marked
use ferrokit::*;

const DAY: f64 = 86_400.0;
let balance: Vec<(f64, f64)> = (0..90).map(|d| (1_767_225_600.0 + d as f64 * DAY, 4200.0 - d as f64 * 31.0)).collect();
let chart = area_chart(move || vec![Series::new("Balance", balance.clone()).color(Color::Green)])
    .value_format(Format::Currency("USD".into()))
    .x_format(Format::Date);

let spending = pie_chart(|| vec![("Lodging".to_string(), 1240.0), ("Food".to_string(), 520.0)])
    .donut()
    .value_format(Format::Currency("USD".into()))
    .colors(&[Color::Indigo, Color::Orange]);
let _ = (chart, spending);

Formats, for values (.value_format(..)) and for the x axis of line, area and scatter charts (.x_format(..)):

  • Format::Number: the default; large numbers are compact on the axis (12k, 1.5M).
  • Format::Decimals(n): fixed decimals, grouped as the user’s locale does.
  • Format::Currency("USD"): money as the user’s locale writes it.
  • Format::Percent: fractions as percentages (0.25 is 25%).
  • Format::Date and Format::DateTime: values are seconds since 1970. Ticks fall on whole hours, days, Mondays, months or years in the user’s time zone, through daylight saving changes.

Colours: .colors(&[..]) sets the series’ (or bars’ or slices’) colours in order, and Series::color(..) gives one series its own. .no_legend() hides the legend. A heatmap shades its first colour, with a scale from the lowest value to the highest above it.

Selection: .selection(&signal) makes a bar, stacked bar, pie, histogram or heatmap chart selectable: clicking a mark sets the signal to its index (a heatmap’s cell is row × columns + column), clicking off the marks to None, and the other marks dim while one is selected. On line, area and scatter charts, .x_selection(&signal) sets the clicked x (the nearest point’s) and marks it with a line and each series’ value. Both work the other way too: setting the signal selects. VoiceOver’s summary says what’s selected.

Zooming and scrolling: .zoomable() lets the user pinch (or ⌘-scroll) a line, area or scatter chart to zoom in around the pointer, scroll sideways to move along it, and pinch out to see it all again; vertical scrolling still scrolls what the chart is in. .x_range(&signal) binds the range shown (None is everything), so the app can zoom too. The value axis fits what’s shown, and a million points stay quick: only those in range are drawn, a few per pixel column.

use ferrokit::*;

let picked = Signal::new(None::<usize>);
let months = bar_chart(|| vec![("Jan".to_string(), 1180.0), ("Feb".to_string(), 1110.0)]).selection(&picked);

let range = Signal::new(None::<(f64, f64)>);
let day = Signal::new(None::<f64>);
let readings: Vec<(f64, f64)> = (0..100_000).map(|i| (i as f64, (i as f64 / 500.0).sin())).collect();
let trace = line_chart(move || vec![Series::new("Signal", readings.clone())]).zoomable().x_range(&range).x_selection(&day);
let _ = (months, trace);

Rules mark a threshold, a target or an average: Rule::y(value) runs across the chart, Rule::x(x) down it (on line, area and scatter charts and histograms). The chart’s range takes them in, their labels sit on a patch of the background so they read over the data, and VoiceOver’s summary includes them (“Budget at $1,300”).

use ferrokit::*;

let minutes = vec![12.0, 18.0, 25.0, 31.0, 33.0, 47.0, 52.0];
let average = minutes.iter().sum::<f64>() / minutes.len() as f64;
let rides = histogram(move || minutes.clone()).bins(5).rule(Rule::x(average).label("Average"));

let sales = bar_chart(|| vec![("Mon".to_string(), 1200.0), ("Tue".to_string(), 800.0)])
    .rule(Rule::y(1000.0).label("Target").color(Color::Green));

let week = vec![3.0, 5.0, 4.0, 7.0, 6.0, 8.0, 9.0];
let trend = hstack((text("Orders"), sparkline(move || week.clone()).colors(&[Color::Green])));
let _ = (rides, sales, trend);

Web, PDF, video and the system’s services

This chapter covers the views that show other kinds of content (web pages, PDFs, video) and the system services apps hand things to: the Share menu, printing, notifications and the menu bar. The media example is a trip briefing that uses all of them:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit
cargo run -p ferrokit --example media

Web pages

web_view shows a WebPage: WebKit’s own view, with the system’s scrolling, text selection, find and Look Up. The page says what to load and reports its title, address and loading state as signals, so views showing them follow along, as with SwiftUI’s WebPage:

use ferrokit::*;

let page = WebPage::new();
page.load("https://www.rust-lang.org");
let (p1, p2, p3) = (page.clone(), page.clone(), page.clone());
let browser = vstack((
    hstack((
        button("Back", move || p1.back()).disabled(move || !p2.can_go_back()),
        text(move || p3.title()).font(Font::headline()),
        spacer(),
    )),
    web_view(&page),
));
let _ = browser;
  • Loading: load(url) for a web address, load_html(html, base_url) for HTML the app makes, load_file(path) for a local file (allowed to read the files beside it).
  • State: title(), url(), is_loading(), can_go_back() and can_go_forward() read signals; back(), forward() and reload() navigate.
  • Scripts: evaluate(script, |result| ..) runs JavaScript in the page and hands back its result as text.
  • .links_open_in_browser() sends the links the user clicks to their browser: for help pages and HTML the app made itself.

PDFs

pdf_view is Preview’s view: zoom, text selection, copy and find.

use ferrokit::*;

let page = Signal::new(0);
let count = Signal::new(0);
let query = Signal::new(String::new());
let viewer = pdf_view(|| Some("manual.pdf".into()))
    .page(&page)
    .page_count(&count)
    .highlight(move || query.get());
let _ = viewer;
  • .page(&signal) is the page shown, from 0, both ways: scrolling changes it, and setting it goes there.
  • .page_count(&signal) reports the number of pages.
  • .highlight(|| query) highlights every match and goes to the first.
  • .single_page() and .two_up() change the layout from a continuous scroll.
  • pdf_view_data(|| bytes) shows a PDF held in memory.

Video and sound

video_player is AVKit’s player, with the system’s controls, Picture in Picture and full screen. It plays sound files too.

use ferrokit::*;

let playing = Signal::new(false);
let time = Signal::new(0.0);
let length = Signal::new(0.0);
let player = video_player(|| Some("trailer.mov".into()))
    .playing(&playing)
    .time(&time)
    .duration(&length)
    .controls(VideoControls::Floating);
let _ = player;
  • .playing(&signal) is both ways: the controls set it, and setting it plays or pauses.
  • .time(&signal) follows playback four times a second; setting it jumps there (a chapter list, a “back 10 seconds” button).
  • .duration(&signal) reports the length once it’s known.
  • .muted(|| ..), .loops(), and .controls(..) (Inline, Floating, Minimal or Hidden).
  • video_stream(|| Some(url)) plays from a web address (an HLS playlist or a video file on a server).

Quick Look

quick_look(paths, index) opens the panel Finder opens with Space, previewing the files (PDFs, pictures, video, documents, folders), at paths[index]: the arrow keys move between them, and the panel offers Open With and Share. If it’s open, it shows the new files. close_quick_look() and is_quick_look_open() do what they say.

thumbnail(|| path) is a file’s picture as Finder draws it: a PDF’s first page, a frame of a video, a photo. Its icon shows until Quick Look has made the thumbnail on a worker thread; VoiceOver reads the file’s name.

use ferrokit::*;

let report = std::path::PathBuf::from("report.pdf");
let r = report.clone();
let row = hstack((
    thumbnail(move || Some(r.clone())).size(28.0, 36.0),
    button("Quick Look", move || quick_look(vec![report.clone()], 0)).symbol("eye"),
));
let _ = row;

Sharing

share_button shows the system’s Share menu (Mail, Messages, AirDrop, Notes…) for what its function returns when it’s clicked:

use ferrokit::*;

let share = share_button(|| vec![ShareItem::File("report.pdf".into()), ShareItem::Text("Our trip".into())]);
let _ = share;

Items are ShareItem::Text, ShareItem::Url or ShareItem::File.

Printing and PDFs

print(window, title, view) prints any view: it’s built again on its own, laid out at the page’s width, and split over as many pages as it needs, with the Print sheet on window (where the user can also save a PDF). save_pdf(view, path) and pdf_data(view) make the same pages with no panel.

use ferrokit::*;

fn report() -> impl View {
    vstack((
        text("July report").font(Font::large_title().weight(Weight::Bold)),
        bar_chart(|| vec![("Lodging".to_string(), 1240.0), ("Food".to_string(), 520.0)]),
    ))
    .alignment(Align::Start)
}

let print_button = button("Print…", || {
    if let Some(w) = focused_window() {
        print(&w, "July report", report());
    }
});
save_pdf(report(), std::env::temp_dir().join("July report.pdf")).ok();
let _ = print_button;

What prints: text, pictures, symbols, charts, backgrounds, borders and rounded corners, always in the light appearance (paper is white). Shadows and materials don’t print. Pages get half-inch margins when the printer gives none.

Notifications

use ferrokit::*;

let tab = Signal::new(0);
notify(
    Notification::new("Ferry to Moskenes")
        .subtitle("Monday 6 July, 15:30")
        .body("Be at the terminal by 14:45.")
        .sound()
        .on_click(move || tab.set(1)),
);

The first notification makes macOS ask the user whether to allow the app’s notifications. They show as banners while the app is in front too, and .on_click(..) runs when the user clicks one while the app is running. .id(..) replaces an earlier notification with the same id. .daily_at(hour, minute) repeats it every day at that time instead of showing it now (a habit’s reminder), until cancel_notification(id).

Notifications need an app bundle with a bundle identifier (cargo ferrokit bundle, or cargo ferrokit run); from a plain cargo run binary, notify does nothing and notifications_supported() is false.

The menu bar

App::menu_bar_extra puts an item on the right side of the menu bar, with a menu or a panel of the app’s own views:

use ferrokit::*;

let days = Signal::new(3);
App::new("Countdown")
    .menu_bar_extra(
        MenuBarExtra::new("ferry")
            .title(move || format!("{} days", days.get()))
            .menu(vec![menu_item("Reset", move || days.set(0)), menu_separator(), menu_item("Quit", quit)]),
    )
    .run();
  • MenuBarExtra::new(symbol) shows an SF Symbol, drawn to match the menu bar; .title(..) adds text beside it that follows its signals.
  • .menu(items) shows a menu when it’s clicked; .panel(view) shows a panel of views under it (as the Wi-Fi and Sound panels do), built once so it keeps its state.
  • App::menu_bar_only() makes a menu-bar app: no Dock icon and no menu bar of its own.

Files

Three calls cover what a file list needs from the Finder:

  • reveal_in_finder(&[path]) shows the items selected in a Finder window (File ▸ Show in Finder).
  • move_to_trash(path) moves an item to its volume’s Trash and returns where it went. Keep that path to undo: std::fs::rename(trashed, old) puts it back.
  • file_dates(path) reads a file’s dates without a Spotlight query: modified, created, added to its folder, and last opened (what the Finder calls Last Opened). Copying files to a new Mac resets the date added, so for “not used in a year”, count from the last opening or, for files never opened, the date modified.
use ferrokit::*;

let path = std::path::Path::new("/tmp/old.zip");
if let Ok(dates) = file_dates(path) {
    let used = dates.last_opened.max(dates.modified);
    let _ = used;
}
if let Ok(trashed) = move_to_trash(path) {
    let undo = move || std::fs::rename(&trashed, "/tmp/old.zip");
    let _ = undo;
}
reveal_in_finder(&["/tmp"]);

Walking the disk

macOS asks the user before an app reads some folders: Desktop, Documents, Downloads, ~/Library, other volumes, and the media libraries. A file call waiting for that answer can’t be cancelled, and a walk that reaches many at once can stall the whole Mac until the app quits. So an app that walks folders asks first:

  • has_full_disk_access() says whether the user allowed this app to read everything (it never prompts). Read it once, at launch or before a walk; access takes effect after a relaunch.
  • asks_before_reading(path, access) says whether reading a folder may stop to ask. Skip those, and show them as not scanned. The media libraries ask even with Full Disk Access. A folder the user chose in an Open panel is readable whatever it says.
  • open_url(FULL_DISK_ACCESS_SETTINGS) opens the System Settings pane where the user allows it; open_url opens any URL in its app.
use ferrokit::*;

let access = has_full_disk_access();
let mut skipped = Vec::new();
for entry in std::fs::read_dir("/Users").into_iter().flatten().flatten() {
    let path = entry.path();
    if asks_before_reading(&path, access) {
        skipped.push(path);
        continue;
    }
    // … read it
}
if !skipped.is_empty() && !access {
    open_url(FULL_DISK_ACCESS_SETTINGS);
}

Testing

testing::capture_reveals(true) makes reveal_in_finder record what it’s asked to show (testing::revealed()) instead of opening Finder windows, and testing::set_last_opened(path, secs) back-dates a file for checks. testing::hold_notifications() makes notify record notifications instead of posting them (no permission prompt), sent_notifications() reads them and click_notification(id) runs a click. testing::shared_items(button) says what a share button would share, and testing::menu_bar_extras() returns the status items and their panels’ popovers. testing::thumbnails_made() counts finished thumbnails, and testing::quick_look_state() says what the Quick Look panel was given and shows. The media example’s CHECK=all uses all of them.

Custom native views

Ferrokit wraps a lot of AppKit, but not all of it, and not the frameworks beside it: MapKit’s map, SceneKit’s 3D view, a third-party chart, or a view your app draws itself. native wraps any NSView as a Ferrokit view. It takes part in layout, identity, signals, focus and teardown like the built-in ones. The native_views example wraps MKMapView and a clock dial the app draws:

git clone https://github.com/lhassa8/ferrokit && cd ferrokit
cargo run -p ferrokit --example native_views

You’ll use the objc2 crates directly here (objc2, objc2-app-kit, and the framework’s own crate, such as objc2-map-kit), with the features for the classes you call.

Wrapping a view

native(make) calls make(mtm) once, when the view is built, and shows the view it returns. update(f) changes it in place: f runs as an effect, now and again whenever a signal it read changes, as text and controls follow their signals.

use ferrokit::*;
use objc2_app_kit::NSLevelIndicator;

let level = Signal::new(3.0);
let meter = native(|mtm| {
    let m = NSLevelIndicator::new(mtm);
    m.setMaxValue(5.0);
    m
})
.update(move |m| m.setDoubleValue(level.get()))
.measure(|_| Size { w: 120.0, h: 18.0 })
.flexible(false, false)
.accessibility_label("Signal strength");

let view = vstack((meter, slider(&level, 0.0, 5.0)));
let _ = view;

Make the view in make, not before: the closure runs on the main thread when the window is built, and the view belongs to that one place in the tree. Don’t rebuild the view to change it. Each update is its own effect, so give unrelated properties their own updates and a change to one doesn’t re-apply the others.

Size and layout

A wrapped view is a leaf in Ferrokit’s layout, placed by setting its frame:

  • Its ideal size is measure’s answer, asked when it’s built and again after each update, so a change that resizes it moves its neighbours. Without measure it’s the view’s fittingSize, which is right for views with an intrinsic size (AppKit’s controls) and zero for a plain NSView.
  • It stretches across and down by default (a map or a drawing fills the room it’s given). .flexible(false, false) keeps it at its measured size, like a control.
  • The usual modifiers apply on top: .width, .height, .min_width, .min_height, .fill_width, .padding, .hidden, .opacity, backgrounds and borders.

The layout doesn’t offer a width and ask for a height, so a view whose height depends on its width (wrapping text of its own) needs a fixed width or a measure that assumes one.

Delegates and teardown

AppKit holds delegates and targets weakly, so something has to keep them. .keep(object) keeps an object as long as the view. Make it when you describe the view, set it in make, and keep it:

use ferrokit::*;
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSTextField, NSTextFieldDelegate, NSControlTextEditingDelegate};
use objc2_foundation::{NSNotification, NSObject, NSObjectProtocol};

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "GuideEdits"]
    struct Edits;

    unsafe impl NSObjectProtocol for Edits {}
    unsafe impl NSControlTextEditingDelegate for Edits {}
    unsafe impl NSTextFieldDelegate for Edits {
        #[unsafe(method(controlTextDidEndEditing:))]
        fn ended(&self, _note: &NSNotification) {
            println!("editing ended");
        }
    }
);

let mtm = MainThreadMarker::new().unwrap();
// SAFETY: NSObject's designated initialiser.
let edits: Retained<Edits> = unsafe { msg_send![super(Edits::alloc(mtm).set_ivars(())), init] };
let field = native({
    let edits = edits.clone();
    move |mtm| {
        let f = NSTextField::new(mtm);
        // SAFETY: the delegate is kept as long as the field (below).
        unsafe { f.setDelegate(Some(ProtocolObject::from_ref(&*edits))) };
        f
    }
})
.keep(edits)
.on_remove(|f| unsafe { f.setDelegate(None) })
.flexible(true, false);
let _ = field;

When the view leaves the tree (a dynamic switches it out, a for_each row goes, its window closes), its updates stop, it leaves the window, on_remove runs, and then the view, its kept objects and its closures are released. Use on_remove for what AppKit won’t undo for you: a timer, a notification observer, key-value observation, a delegate that might call back late.

Drawing your own view

A view of your own is an NSView subclass made with define_class!. It keeps its state in its ivars, draws in drawRect:, and gets its state from signals through update. Ferrokit marks the view for display after each update, so drawRect: runs again with the new state:

use std::cell::Cell;
use ferrokit::*;
use objc2::rc::Retained;
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSBezierPath, NSColor, NSView};
use objc2_foundation::NSRect;

define_class!(
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[name = "GuideBar"]
    #[ivars = Cell<f64>]
    struct Bar;

    impl Bar {
        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, _dirty: NSRect) {
            let mut b = self.bounds();
            b.size.width *= self.ivars().get();
            NSColor::controlAccentColor().setFill();
            NSBezierPath::fillRect(b);
        }
    }
);

impl Bar {
    fn new(mtm: MainThreadMarker) -> Retained<Bar> {
        let this = Bar::alloc(mtm).set_ivars(Cell::new(0.0));
        // SAFETY: NSView's designated initialiser.
        unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] }
    }
}

let done = Signal::new(0.4);
let bar = native(Bar::new)
    .update(move |bar| bar.ivars().set(done.get()))
    .height(8.0)
    .accessibility_label("Progress");
let _ = bar;

For anything drawn from data, Ferrokit’s own canvas may be enough. A subclass is for drawing that needs AppKit’s whole view API: its own mouse tracking, a layer, or text input.

Focus and accessibility

Ferrokit’s windows use AppKit’s key view loop, so Tab reaches a wrapped view that accepts the focus (acceptsFirstResponder, or AppKit’s controls on their own) in the order its frame puts it.

Accessibility is the view’s own. AppKit’s views and the system frameworks’ views have theirs. A view of your own should say what it is: override accessibilityRole (and isAccessibilityElement) in the subclass, and give it a name with .accessibility_label(..) and, for a value, .accessibility_value(..). testing::ax_audit finds a wrapped view without a name, as it does Ferrokit’s own. It also reports a system view’s own parts that come without names: MapKit’s zoom buttons, for one. That’s Apple’s to fix, and the native_views example’s check leaves out what’s inside the map.

What native doesn’t do

  • Implement View yourself. Cx and Node stay internal; native covers any NSView.
  • View controllers. Wrap the controller’s view (native(move |_| controller.view())) and keep the controller with .keep(controller). It isn’t added as a child of the window’s controller.
  • Ferrokit views inside a wrapped view. A wrapped view is a leaf: its subviews are its own.
  • SwiftUI needs Swift: see the next section.

SwiftUI views

Some of Apple’s views exist only in SwiftUI: Swift Charts, Gauge’s styles, MapKit’s SwiftUI Map, and many third-party packages. An NSHostingView is an NSView, so native wraps it. The SwiftUI view is written in Swift, and ferrokit-build compiles it into the app from build.rs:

# Cargo.toml
[build-dependencies]
ferrokit-build = "0.15"
// build.rs
fn main() {
    ferrokit_build::swift("swift").compile();
}

The Swift side makes the view and exports C functions: one that returns the hosting view, retained, and one per value the app sets:

// swift/Sales.swift
import Charts
import SwiftUI

final class SalesModel: ObservableObject {
    @Published var values: [Double] = []
}

struct SalesChart: View {
    @ObservedObject var model: SalesModel
    var body: some View {
        Chart(Array(model.values.enumerated()), id: \.offset) {
            BarMark(x: .value("Month", $0.offset), y: .value("Sales", $0.element))
        }
        .padding()
    }
}

@MainActor @_cdecl("sales_chart_new")
public func salesChartNew() -> UnsafeMutableRawPointer {
    let view = NSHostingView(rootView: SalesChart(model: SalesModel()))
    return Unmanaged.passRetained(view).toOpaque()
}

@MainActor @_cdecl("sales_chart_set")
public func salesChartSet(_ view: UnsafeMutableRawPointer, _ values: UnsafePointer<Double>, _ count: Int) {
    let host = Unmanaged<NSHostingView<SalesChart>>.fromOpaque(view).takeUnretainedValue()
    host.rootView.model.values = Array(UnsafeBufferPointer(start: values, count: count))
}

The Rust side wraps the hosting view and sets its values from a signal:

use ferrokit::*;
use objc2::rc::Retained;
use objc2_app_kit::NSView;
use std::ffi::c_void;

unsafe extern "C" {
    fn sales_chart_new() -> *mut c_void;
    fn sales_chart_set(view: *mut c_void, values: *const f64, count: isize);
}

let sales = Signal::new(vec![12.0, 30.0, 22.0, 48.0]);
let chart = native(|_| {
    // SAFETY: a +1 NSHostingView, owned from here on.
    unsafe { Retained::from_raw(sales_chart_new().cast::<NSView>()) }.expect("a view")
})
.update(move |view| {
    let v: *mut c_void = (view as *const NSView).cast_mut().cast();
    // SAFETY: the chart's own view; a buffer of `len` values.
    sales.with(|s| unsafe { sales_chart_set(v, s.as_ptr(), s.len() as isize) })
});

(These two blocks are ignored here: they need the Swift file to link.)

For values coming back, such as a SwiftUI slider, pass a C callback and a context pointer (a boxed signal, freed in .on_remove) to the Swift function. SwiftUI’s view is released when the Ferrokit view leaves the tree. Its ideal size is the hosting view’s fittingSize, which native already uses; by default it fills the room it gets, like a map.

Things to know:

  • Swift runtime: it comes with macOS, so nothing is added to the app.
  • Toolchain: swiftc comes with the Command Line Tools. Since the macOS 27 SDK, SwiftUI’s @State, @Entry and #Preview are macros, and only Xcode has the plugin that expands them. ferrokit-build uses an Xcode in /Applications for them, with a warning; without one, it stops the build and says to install Xcode. Swift without those macros (like the example above, which uses ObservableObject) needs only the Command Line Tools.
  • Accessibility: SwiftUI’s views are in the window’s accessibility tree, for VoiceOver and for testing::ax_elements and ax_audit, which find a SwiftUI control without a name as they do Ferrokit’s own.
  • The glue is by hand for now. A smaller bridge, with named SwiftUI views and .prop, .binding and .on, is being designed in issue #7.

Coming from egui, Iced or Slint

If you’ve built a GUI in Rust before, most of Ferrokit will feel familiar. Two things are different, and the rest follows from them:

  • The views are AppKit’s. A button is an NSButton and a table is an NSTableView. Ferrokit doesn’t draw widgets, and nothing renders a frame on the GPU. That’s why it’s Mac only, and why VoiceOver, text input, Dark Mode and the system’s tables work without extra code.
  • Views are built once, then updated in place. egui runs your UI code every frame and Iced calls view after every message. Ferrokit runs your view code once, when the window opens. The parts that change are closures over signals, and when a signal changes, only the views that read it update.

The same ideas, side by side

eguiIcedSlintFerrokit
Statefields of your app struct, read each framethe state struct update changespropertys in the .slint fileSignal<T>: a Copy handle, read with get(), changed with set/update
Eventsif ui.button(..).clicked()a Message enum, matched in updatecallbacks (clicked => { .. })closures: button("Add", move || ..)
Describing the UIcode that runs every frameview(&self) -> Element, rebuilt after each message.slint markupfunctions returning impl View, run once
What changes on screeneverything, every framethe diff of the new viewbound propertieseach view reading a changed signal, and nothing else
Layoutui.horizontal, ui.verticalrow!, column!HorizontalLayout, VerticalLayouthstack, vstack, grid, spacer, .padding(..), .frame(..)
Listsa for loopcolumn(items.iter().map(..))for item in itemsfor_each(items, row), keyed by Identifiable
Tablesegui_extras::TableBuildertable (0.14)StandardTableViewtable(&model): an NSTableView, a million rows
Background workyour own threadsTask::performspawn_local, threadsspawn, background(..).await in spawn_local, Resource::new
Windowseframe::run_nativeiced::applicationone component per windowApp::new(..).window(Window::new(..)), open(..)
LookVisualsthemesstyles and propertiesthe system’s, plus .font(..), .color(..), .background(..), .corner_radius(..)
Testsegui_kittesticed_testthe testing backendself-checks that drive the real controls (ferrokit::testing)

One app, four ways

A counter: a label and a button. In egui, the UI is code that runs every frame, and the button’s result is a bool you test:

struct Counter { count: i32 }

impl eframe::App for Counter {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.label(format!("Clicked {} times", self.count));
            if ui.button("Click me").clicked() {
                self.count += 1;
            }
        });
    }
}

In Iced, a click sends a message, update changes the state, and view builds the whole tree again:

#[derive(Default)]
struct Counter { count: i32 }

#[derive(Debug, Clone)]
enum Message { Clicked }

impl Counter {
    fn update(&mut self, message: Message) {
        match message {
            Message::Clicked => self.count += 1,
        }
    }

    fn view(&self) -> Element<'_, Message> {
        column![
            text(format!("Clicked {} times", self.count)),
            button("Click me").on_press(Message::Clicked),
        ]
        .padding(20)
        .into()
    }
}

In Slint, the UI is markup with properties, and Rust code drives it from outside:

export component Counter inherits Window {
    in-out property <int> count: 0;
    VerticalLayout {
        Text { text: "Clicked \{count} times"; }
        Button { text: "Click me"; clicked => { count += 1; } }
    }
}

In Ferrokit, the state is a signal. The label is given a closure, so it follows the signal, and the button is given the action to run:

use ferrokit::*;

fn main() {
    let count = Signal::new(0);
    App::new("Counter")
        .window(Window::new("Counter").size(320.0, 140.0).view(
            vstack((
                text(move || format!("Clicked {} times", count.get())),
                button("Click me", move || count.update(|n| *n += 1)),
            ))
            .padding(20.0),
        ))
        .run();
}

There’s no Message enum and no update function. A click runs its closure, the closure changes count, and the one NSTextField that reads count gets new text. The stack, the button and the window are never touched again.

A bigger example: a to-do list

Here’s a list you can add to and clear items from, with a count. Where Iced would have Message::DraftChanged, Message::Add and Message::Remove(id), here each control gets a signal or a closure:

use ferrokit::*;

#[derive(Clone)]
struct Todo {
    id: u32,
    title: String,
}

impl Identifiable for Todo {
    type Id = u32;
    fn id(&self) -> u32 {
        self.id
    }
}

fn main() {
    let todos = Signal::new(Vec::<Todo>::new());
    let draft = Signal::new(String::new());
    let next_id = Signal::new(1);
    // A closure that captures only signals is `Copy`: use it twice.
    let add = move || {
        let title = draft.get_untracked().trim().to_string();
        if title.is_empty() {
            return;
        }
        let id = next_id.get_untracked();
        next_id.set(id + 1);
        todos.update(|v| v.push(Todo { id, title }));
        draft.set(String::new());
    };
    let list = for_each(move || todos.get(), move |todo: Todo| {
        let id = todo.id;
        hstack((
            text(todo.title),
            spacer(),
            button("Done", move || todos.update(|v| v.retain(|t| t.id != id))),
        ))
    });
    App::new("Todos")
        .window(Window::new("Todos").size(360.0, 400.0).view(
            vstack((
                hstack((
                    text_field(&draft).placeholder("New to-do").on_submit(add),
                    button("Add", add).disabled(move || draft.with(|d| d.trim().is_empty())),
                )),
                scroll(vstack((list,))),
                text(move || format!("{} left", todos.with(Vec::len))),
            ))
            .padding(16.0),
        ))
        .run();
}

What to notice, coming from the other toolkits:

  • text_field(&draft) is bound both ways. Typing changes draft, and draft.set(..) changes the field. There’s no on_input message to handle.
  • for_each keeps rows by identity. Adding a to-do builds one row, and removing one drops one. The others, their NSViews included, stay as they are, so a row’s focus or scroll position isn’t lost.
  • get() tracks and get_untracked() doesn’t. Inside a view’s closure (text(move || ..), .disabled(move || ..)), get() subscribes the view to the signal. In an action you just want the value, so use get_untracked().
  • button("Add", add).disabled(..) takes a closure, so the button enables and disables itself as draft changes.

Habits to unlearn

  • A value isn’t a binding. text(format!("{}", count.get())) reads the count once, when the window opens, and never changes. Give text a closure: text(move || format!("{}", count.get())). The same goes for every modifier that takes impl IntoValue: a plain value is fixed, and a closure follows its signals.
  • Don’t rebuild views to change them. In Iced the whole tree is rebuilt after each message; here, building a new view means a new AppKit view. That’s slow, and it loses focus and selection. Put the changing part in a closure, or in dynamic(..) when a whole subtree has to change.
  • No per-frame loop. Nothing runs unless a signal changes or an event arrives. For a clock or a live feed, on_frame calls you once per display frame, and a background thread can spawn its results back.
  • Main thread only. AppKit is single-threaded, and so are signals and views. Heavy work goes to spawn or background(..), which hand the result back to the main thread.
  • Most styling is already done. Controls look and behave as macOS draws them, in light and Dark Mode, at every text size. Reach for .font, .color, .background and .corner_radius when you want your own look, not to make a button look like a button.

Where to go next

For AI coding agents

If you’re an AI coding agent (Claude Code, Codex, Cursor…) helping someone build a Mac app in Rust, these are written for you:

  • llms.txt: what Ferrokit is, when to use it and when not, and where everything is.
  • llms-full.txt: AGENTS.md and API.md in one file.
  • AGENTS.md: the rules, recipes that compile, and the known limits with their workarounds. It ships in the crate, cargo ferrokit new puts it in every new app, and cargo ferrokit agents writes it into an existing one. On GitHub.
  • Adding a GUI to someone’s existing Rust CLI or library: this page and AGENTS.md’s A GUI for an existing Rust project: a second binary behind a gui feature, bin = "…" for cargo ferrokit, a plain fn main (not #[tokio::main]).
  • API.md: every public item on one page, with its signature and the first paragraph of its docs. On GitHub.

When Ferrokit fits

  • The app is for the Mac only, and should look and behave like a Mac app.
  • It’s heavy on data: tables, outlines, text editors, logs, charts.
  • The person has Rust code (a CLI, a library) to put a Mac GUI on, or wants Rust rather than Swift, and real AppKit controls rather than a web view or custom-drawn widgets.

When it doesn’t

  • The app must also run on Windows, Linux, iOS or the web.
  • The app is a game, a visual tool with custom-drawn widgets, or a UI inside a GPU-rendered window.
  • The person needs a stable API today: Ferrokit is 0.15, an alpha, with one maintainer.

See the comparison for the alternatives.

Working with it

cargo ferrokit check runs clippy, tests, a bundle and the app’s self-checks; run it after every change. Self-checks print [check] <name> PASS|FAIL <note>.