Docs App frameworks
Interface kit
The interface kit gives an app the same controls, colours, type and motion as the desktop shell. This chapter covers the Golden Gate widgets, full-size windows, semantic colours, the type scale and radii, the retained view layer, Auto Layout, animation, window animations, rich text, sortable table columns, the font and colour panels, sheets and small controls, and the web view.
Golden Gate kit
The kit is the set of drawing functions in bifrost_app::widgets. Each one takes a Surface, the Ui and a rectangle, and draws one control in the desktop's style. Every widget follows Light and Dark. Apps use it the way they use AppKit controls like NSToolbar, NSSearchField and NSPathControl.
| Function | Counterpart | Use it for |
|---|---|---|
toolbar_band, toolbar, toolbar_layout | NSToolbar | A row of glyph buttons in glass capsules. Use ToolbarItem::icon, custom, menu and centered. Hit-test with ToolbarLayout::hit. |
source_list | Source-list NSOutlineView | A sidebar with symbol rows, sections that collapse, and optional subtitles and counts. Hit-test with SourceList::hit. |
search_field | NSSearchField | A capsule with a magnifier, placeholder and clear button. |
path_bar | NSPathControl | A location footer. Long paths shrink from the middle. |
text_field | NSTextField | A single-line editor with selection and caret. |
popup_button, menu, popover | NSPopUpButton, NSMenu, NSPopover | A pop-up button, a menu and a popover with an arrow at its anchor. |
player | Mini player | A glass capsule with artwork, title, progress and skip buttons. |
mini_month | NSDatePicker graphical style | A month grid with a selection and marked days. |
material | NSVisualEffectView | A blurred material over the app's own content. Draw the content first. |
pane, pane_origin_px | NSSplitViewController child view | A clipped sub-surface for a detail pane. |
folder_icon, search_button, capsule | Finder icon, collapsed search item, button plate | Icons and plates that match the toolbar. |
The glyphs module draws a fixed set of line symbols named after SF Symbols. Call glyphs::glyph(s, ui, "magnifyingglass", rect, colour). The names are listed in glyphs::NAMES. An unknown name draws nothing and returns false. Apple's full symbol catalogue is not available.
Every control with a visible state must also be published to accessibility. Give App::controls a Node with the same rectangle for each toolbar button and row.
Moving an app to the kit
- Replace fixed colours with
Paircolours and call.now(). Keep white only for text on the accent. - Draw the sidebar with
source_listand the toolbar withtoolbar_bandandtoolbar. - Use
search_fieldfor search andpath_barfor a location footer. - Set
window = "full-size"andmin_shell = "0.4.84"in the manifest. - Check the result with a host preview in Light and Dark.
Full-size windows
A full-size window draws its content under the title bar, like NSWindowStyleMaskFullSizeContentView. The window has no title row. The shell draws the traffic lights over the app and keeps the top band for moving the window.
id = "is.example.notes"
name = "Notes"
window = "full-size"
min_shell = "0.4.84"
Use these constants and calls to place your content:
layout::UNIFIED_BAR_PT- The height of the top band, 52 points. The band moves the window, except over the traffic lights and the controls your app publishes.
layout::traffic_lights_trailing()- The trailing edge of the traffic lights. Keep the leading space free of controls.
window_size = "WxH"or"fixed:WxH"- The opening size, in points.
fixed:removes the resize edges and zoom. min_size,max_size- The content size limits, in points.
Publish every visible toolbar button with App::controls. The shell lets the window move wherever a control is not published, so an unpublished button can start a window drag instead of a click.
Window animations
The shell animates a window when it opens, closes, minimizes and restores (the counterpart of NSWindow.AnimationBehavior and the Dock's minimize effects). The app does not start these effects. It chooses which kind of window it is in the manifest, and the shell plays the matching effects.
id = "is.example.notes"
name = "Notes"
animation_behavior = "document"
animation_behavior = "default"or"document"- Every effect. A window with no value uses this. Built-in windows use
default. animation_behavior = "utility"or"alert"- Open and close only. Use it for a panel or an alert that should not move while it is open.
animation_behavior = "none"- The window never animates.
kit::appearance::reduce_motion()- Returns
truewhen the user has turned on Reduce Motion. Check it before you run any motion of your own.
The effects are these. Opening scales the window from 0.9 to 1 and fades it in over 220 ms. Minimizing scales the window and moves it toward the app's tile in the Dock over 420 ms, and restoring plays the same motion in reverse. The window stays on screen until the minimize effect ends. The user picks the effect under Desktop & Dock, Minimize Windows Using. Zoom gives a short settle pulse.
Under Reduce Motion each effect becomes a 120 ms cross-fade in place. Nothing scales or slides.
Close does not animate yet, because the window is removed at once. Funnel (Genie) draws as Scale, since the presenter draws each window as a single quad and cannot warp it. Minimize from Show Desktop and Overview does not animate, and neither do native Wayland windows. The slide is clamped to the window's shadow margin, so a window does not reach a Dock tile far away before it fades.
Colours
Use semantic colours, not fixed values. bifrost_app::kit::colors is the same module as ui::system. Each name is a Pair with a dark value and a light value. Call .now() while drawing to get the value for the current appearance.
use bifrost_app::kit::colors;
let window_bg = colors::WINDOW_BACKGROUND.now();
let label = colors::LABEL.now();
AppKit NSColor | Constant |
|---|---|
windowBackgroundColor, controlBackgroundColor, textBackgroundColor | WINDOW_BACKGROUND, CONTROL_BACKGROUND, TEXT_BACKGROUND |
underPageBackgroundColor | UNDER_PAGE_BACKGROUND |
labelColor, secondaryLabelColor, tertiaryLabelColor, quaternaryLabelColor | LABEL, SECONDARY_LABEL, TERTIARY_LABEL, QUATERNARY_LABEL |
separatorColor, gridColor | SEPARATOR, GRID |
selectedContentBackgroundColor | SELECTED_CONTENT_BACKGROUND |
controlAccentColor, linkColor | CONTROL_ACCENT, LINK |
systemRed and the other system colours | SYSTEM_RED, SYSTEM_ORANGE, SYSTEM_BLUE, and so on |
A plain constant such as BLACK, WHITE or a literal pack(...) does not change with the appearance. Do not use one for a window or content background. A guard test in the shell fails when a window or content fill uses BLACK or CELL.
To define a colour of your own, use Pair::new(dark, light). Both values are premultiplied u32 pixels, as made by pack.
Type scale
Text sizes follow the macOS text styles from the Human Interface Guidelines. Use the named constants in bifrost_app::kit::ui rather than literal sizes.
| Constant | Size (points) | Use |
|---|---|---|
MAC_LARGE_TITLE_PT | 26 | Large title on a root screen |
MAC_TITLE1_PT, MAC_TITLE2_PT, MAC_TITLE3_PT | 22, 17, 15 | Titles |
MAC_HEADLINE_PT, MAC_BODY_PT | 13 | Headlines and body text |
MAC_CALLOUT_PT | 12 | Callouts |
MAC_SUBHEAD_PT | 11 | Subheads |
MAC_FOOTNOTE_PT, MAC_GROUP_HEADER_PT | 10 | Footers and group headers, in secondary label colour |
MAC_CAPTION1_PT, MAC_CAPTION2_PT | 10 | Captions |
The constants are defined in springboard/render/src/ui.rs. Use ui.pt(v) to scale a size to the screen. Layouts derive from the window size and the named constants, not from a fixed resolution.
Attributed strings and rich text
An attributed string is text with styles on its ranges. Bold, italic, underline, strikethrough, a link, a size from the type scale and a colour from the semantic set can all be set per range. The model lives in bifrost_app::attributed (the counterpart of NSAttributedString). It needs no shell call, so it can run in a test.
use bifrost_app::attributed::{AttributedString, Attrs, ColorToken, SizeClass};
let mut text = AttributedString::plain("Hello ");
text.append("world", Attrs {
bold: true,
size: SizeClass::Title2,
color: Some(ColorToken::Blue),
..Attrs::default()
});
let rtf = text.to_rtf();
let back = AttributedString::from_rtf(&rtf);
Sizes are the MAC_*_PT text styles and colours are named tokens, so the text follows Light and Dark. New text typed inside a run takes the attributes of the character before it, as typing does.
AttributedString::plain(text),AttributedString::with_attrs(text, attrs)- Makes a string with one run of text, plain or with the given attributes.
.append(text, attrs),.replace_characters(range, text)- Adds text at the end, or replaces a range of characters. A replacement takes the attributes of the character before it.
.attributes_at(index),.substring(range)- Reads the attributes of one character, or copies a range as a new string.
.add_attribute(attr, range),.remove_attribute(key, range)- Sets or clears one attribute over a range. Runs split and merge as needed.
.enumerate_attribute(key, range, f)- Calls
fonce for each maximal range that holds the same value for an attribute. .to_rtf(),AttributedString::from_rtf(rtf)- Writes or reads RTF, with bold, italic, underline, strikethrough, colours, links and Unicode escapes.
.to_html(),AttributedString::from_html(html)- Writes or reads a small HTML subset: bold, italic, underline, links, headings, line breaks and paragraphs.
RichTextView::new(content)- An editing model for rich text, with a content string, a selection and the attributes for the next typed character. Each edit is one step on its undo manager.
.insert_text(s),.delete_backward()- Types text or deletes before the caret. A selection is replaced or removed first.
.toggle(Trait::Bold)- Turns bold, italic or underline on or off for the selection, or for the next typed text when the selection is a caret.
.key_command(ch, shift)- Handles Cmd+B, Cmd+I, Cmd+U, Cmd+Z and Cmd+Shift+Z. Returns
truewhen it used the key. .draw(ui, surface, x, y, width)- Draws the wrapped, styled runs into a surface and returns the height used.
Ranges count characters, not UTF-16 units. Italic is stored and exported, but the system font has no italic face, so it is drawn upright. Caption and Footnote share 10 points, so a Caption reads back as a Footnote from RTF. There are no arbitrary RGB colours, fonts, paragraph styles, attachments, lists or tables. The draw call does not yet map a pointer to a caret, so a rich text editor cannot take mouse input. The plain TextArea control is unchanged.
Table columns and panels
The table model in bifrost_app::controls::table holds the column state of a table: sort order, widths and column order. It draws nothing, so the app draws the header row and passes clicks and drags back to the model. The font and colour panels in bifrost_app::controls::panels work the same way.
use bifrost_app::controls::table::{Column, TableColumns, sort_rows};
let mut columns = TableColumns::new(vec![
Column::new("name", "Name", 220.0),
Column::new("size", "Size", 90.0),
]);
// A click on header 0 returns the new primary sort key.
if let Some(first) = columns.click_header(0) {
sort_rows(&mut rows, &[first], |a, b, key| compare(a, b, key));
}
Column::new(id, title, width),.unsortable()- A column with an id, a title and a width in points. The id is the key that the sort passes to the comparison.
TableColumns::click_header(i)- Sorts by a column. The first click sorts ascending and the second descending. The clicked column becomes the primary key, and the earlier keys stay as secondary keys.
TableColumns::indicator(i)- The sort arrow for a header: ascending, descending, or none.
sort_rows(rows, descriptors, cmp)- Sorts rows by several keys with a stable sort. The caller compares two rows for each key.
TableColumns::resize(i, width),TableColumns::reorder(from, to)- Changes a column's width or moves a column. A resize keeps the width within the column's minimum and maximum.
TableColumns::save(),TableColumns::restore(s)- Writes the widths and order to a string and reads them back, for an autosave name.
FontPanel::new(families, initial)- A font panel for the families the caller supplies. The panel holds one family, one style and one size from 1 to 288 points.
FontPanel::on_change(f)- Calls
fwith the new selection when the user or the app changes it. ColorPanel::new(initial),ColorPanel::on_change(f)- A colour panel with RGB and alpha.
freceives the colour and the alpha. ColorPanel::set_hex(s),ColorPanel::hex(),parse_hex(s)- Reads and writes the hex field.
parse_hexreturnsNonefor a value that is not a colour. wheel_pick(x, y, r, brightness)- Turns a point on the hue and saturation wheel into a colour.
Nothing is drawn yet. The shell does not show the two panels, and the table does not draw a clickable header row. No app uses these models yet. Column hiding from the header menu, the crayon and slider modes of the colour panel, the eyedropper, and font collections are not built. The sort compares rows through the caller's closure, not through key paths.
Corner radii
Corner radii come from the m module in springboard/ui/src/prefs_layout.rs. Use these values for the matching shape.
m::WINDOW_RADIUS- 17 points. Window corners.
m::CARD_RADIUS- 13 points. Grouped cards, such as a
Section. m::SELECTION_RADIUS- 9 points. Selection plates in a source list.
m::ICON_RADIUS- 5 points. Icon tiles in Settings.
Search fields are capsules. Use search_field rather than a rounded rectangle with a fixed radius.
Retained views
The bifrost_app::view module adds a retained layer over the App trait. It follows AppKit's NSView, NSResponder and NSViewController. An app opts in by holding a ViewApp and passing configure, event, controls, commands and draw to it.
Viewtrait withViewBase- A view with a frame,
dirtyandhiddenstate. Methods:set_frame,layout,draw,hit_test,intrinsic,needs_display. Frames are in window points. Window<S>- The view tree. Methods:
make_first_responder,tab,view_mut,layout,draw(which returns the merged damage). It has anundomanager. ViewApp<S>::set_menus- Sets the Edit menu and other menus for the window.
MenuEntry::edit_menu()is the standard Edit menu. ViewController,ControllerHost- A controller that owns a view and sits in the responder chain above it.
Built-in views
| View | AppKit counterpart |
|---|---|
Label, Button, Switch, Slider, Segmented | NSTextField label, NSButton, NSSwitch, NSSlider, NSSegmentedControl |
Checkbox, Stepper, ProgressIndicator | NSButton checkbox, NSStepper, NSProgressIndicator |
TextField | Editable NSTextField, with cut, copy, paste, select all, undo and redo |
PopUpButton | NSPopUpButton. The menu opens as an overlay. |
Stack | NSStackView, with vstack and hstack |
ScrollView | NSScrollView, vertical only |
Form, Section | Inset grouped table with headers and footers |
To read a control's value after an action, call window.view::<Switch>(id). take_sent() returns the actions the window has sent. Send actions with ViewBase::send_action. The window sends them to the sender, its ancestors, then the model.
Keep sibling views from overlapping. Partial redraws clear a dirty view's frame and paint its subtree again. A view that paints outside its frame forces a full repaint.
Sheets and small controls
A sheet is a panel that slides down from the title bar of its window and must be answered before the window can be used again. An alert is a small sheet with a message and buttons. The kit has the model in bifrost_app::controls::sheet, which holds the buttons and the geometry, and the drawing functions in bifrost_app::widgets. The app keeps the sheet, draws it each frame and passes the pointer and keys to it.
use bifrost_app::controls::sheet::{ButtonRole, Hit, Sheet, SheetButton};
use bifrost_app::widgets;
let sheet = Sheet::alert("Delete note?", "This cannot be undone.", vec![
SheetButton::new(1, "Cancel", ButtonRole::Cancel),
SheetButton::new(2, "Delete", ButtonRole::Destructive),
]);
widgets::sheet(&mut surface, &ui, window, titlebar_h, &sheet, progress, pressed);
match sheet.hit(window, titlebar_h, progress, x, y) {
Hit::Button(id) => run_action(id),
Hit::Blocked => {} // a click on the dimmed window is swallowed
_ => {}
}
A sheet with a default button answers Return with that button, and one with a cancel button answers Escape with it. While a sheet is open it takes every key, so nothing reaches the window behind it.
Sheet::new(title, size, buttons),Sheet::alert(title, message, buttons)- A sheet of a fixed size, or an alert sized to its message.
SheetButton::new(id, title, role)- A button with an id, a title and a role: default, cancel, normal or destructive.
.layout(parent, titlebar_h, progress)- The panel's rectangle inside the window. At progress 0 the panel is above the title bar and at 1 it hangs from it.
.hit(parent, titlebar_h, progress, x, y)- Returns
Hit::Buttonfor a button,Hit::Panelfor the panel,Hit::Blockedfor the dimmed window orHit::Outsidefor anything else. .key(key)- Returns the button the key chooses, if any, and whether the sheet took the key.
widgets::sheet(s, ui, parent, titlebar_h, sheet, progress, pressed)- Draws the panel and the dimmed parent, and returns the panel's rectangle.
widgets::segmented(s, ui, bounds, labels, selected, enabled)- Draws a row of segments and returns the rectangle of each one. Use
segments,segment_hitandsegment_keyto hit-test it and move the selection with the keys. widgets::stepper(s, ui, origin, pressed, enabled)- Draws an up and down stepper. Use
stepper_hitandstepper_applyto change its value and clamp it. widgets::focus_ring(s, ui, bounds, radius),focus_ring_rect(bounds, radius)- Draws the 3-point focus ring around a control, or returns the rectangle to draw it in.
widgets::popover(s, ui, anchor, size, bounds, preferred)- Draws a popover with its arrow at the anchor, and returns the panel's rectangle. The panel flips to another edge when the preferred edge has no room.
Metrics: a segmented control is 24 points high, a stepper is 13 by 22 points, a pop-up button is 22 points high, the focus ring is 3 points wide, and a sheet has a 10-point radius. An alert is 260 points wide.
A sheet slides from the title bar over 0.32 s. The parent window is dimmed by 28 percent while the sheet is open. Under Reduce Motion the sheet appears at once.
Sheet buttons size themselves from the number of characters in their titles, because the kit cannot measure text yet. The top corners of a sheet are hidden by extending the panel up into the title bar, not by clipping it.
Auto Layout
Auto Layout is opt-in. A view with no constraints keeps the frame that the top-down layout gives it. The constraint layer is in bifrost_ui::constraint, an incremental Cassowary solver, and in the SDK's bifrost_app::view.
anchors(id).leading(),trailing(),top(),bottom(),width(),height(),center_x(),center_y()- An anchor of a view, as an
Attr. LikeNSLayoutAnchor. Spec::eq(a, b),le,ge- A constraint of the form
a rel multiplier * b + constant. Add.multiplier(m),.constant(c)and.priority(p). Spec::fixed(a, rel, c)- A constraint against a constant, with no second attribute.
Constraints- A collection with helpers:
fill,center,size,equal_widths,chain_h,chain_v,guide(),huggingandcompression. Window::constrain(cs),remove_constraints()- Adds or clears the constraints. The window solves them after the top-down pass in
layout.
Built-in guides are Item::Window, Item::SafeArea (below the top inset) and Item::Margins (inset by m::DETAIL_MARGIN).
Priorities follow UILayoutPriority. A required constraint is 1000. A higher priority wins a conflict. Hugging defaults to 250, and compression resistance defaults to 750.
let mut cs = Constraints::new();
cs.fill(list_id, Item::Margins, 0.0);
window.constrain(cs);
Constraints are solved again on every Window::layout. The window does not keep a solver between layouts yet.
Stack has a Distribution (Fill, FillEqually, FillProportionally, EqualSpacing, EqualCentering) and Align::Trailing.
Animation
Animations follow Core Animation's implicit model. Any change to a view's frame, opacity or background made inside Window::animate runs over the timing you give. You do not create animation objects. Read the model value with target_frame(id) and check progress with is_animating(id).
// Layout changes made inside the closure animate as a spring.
window.animate(Timing::spring(0.8, 0.4), |w| w.layout(ui, bounds));
Window::animate(timing, f)- Like
UIView.animate. The window interpolates each change from the value on screen.Timing::DEFAULTis 0.25 s ease-in-out. Timing::new(seconds, curve),Timing::spring(damping_ratio, response)- A timed curve, or a spring that lasts until it settles.
Window::transaction(Transaction::new(timing).completion(f), f)- Like
NSAnimationContext.runAnimationGroup. The completion receivesfinished, which isfalsewhen the animation was replaced or interrupted. Window::disable_actions(f)- Applies changes at once and cancels any running animation of the changed properties.
Window::next_wake(t),ViewApp::next_wake(ms)- The next frame time while an animation runs, and
Nonewhen idle. Return it fromApp::next_wake. Window::set_reduce_motion(on)- Overrides the system Reduce Motion setting for this window.
Nonefollows the system.
With Reduce Motion, frame changes are instant. Opacity and background cross-fade over 0.12 s.
Opacity below 1 is group opacity. The view draws normally and is blended back, so a view that paints opaquely over its backdrop fades correctly. Opacity 0 skips drawing.
Not yet available
- Typed property objects, such as
CAAnimationand key paths. Use the typed properties. - Keyframe, group and additive animations, and
repeatCountorautoreverses. - Transforms, corner radius, shadows and masks. Views have no layers.
- Springs that keep their velocity when they are retargeted.
Web view
bifrost_app::webview shows web content in an app. Pages run in a separate engine process. A WebProcessPool starts the engine and holds any number of web views. Each view has a WebViewId, and one view is shown in a rectangle of the window.
WebProcessPool::spawn(engine, profile)- Starts the engine. Return
fd()fromApp::wake_fd, and callpoll()fromtick. create(url),load(id, url),show(id),close(id)- Creates and manages views.
go_back,go_forward,reload,stop_loading- Navigation.
stop_loadingdoes nothing in this engine version. state(id)- The title, URL, loading state, progress, and whether back and forward are possible.
set_frame(x, y, w, h, scale),set_dark(on)- Position in window pixels, and the colour scheme for
prefers-color-scheme. touch(kind, finger, x, y),scroll(dx, dy, x, y),key(&KeyInput)- Input. The desktop pointer arrives as a finger, so a drag scrolls and a tap clicks.
draw(surface)- Copies the last frame into the surface.
webview::url_for_input(text)- Turns text in an address field into a URL, a host or a search.
poll() returns WebViewEvent values: LoadStarted, LoadCommitted, LoadFinished, CreateWebView, Closed, ContentProcessTerminated and EngineExited.
Not yet available
- Hover, text selection by drag, and context menus.
selectelements, JavaScript alerts and file panels.evaluateJavaScript, user scripts, find-in-page and snapshots.- Zero-copy drawing. Frames are copied into shared memory and the engine renders in software.
Not yet available
These parts of AppKit and UIKit are not in the kit yet:
- Constraint formats (
withVisualFormat), ambiguity debugging, baseline anchors and per-view layout guides. - Scroll wheel, trackpad scrolling, hover and tracking areas. Horizontal scrolling and clipping.
- Drag and drop inside retained views, and caret placement by pointer in
TextField. - Multi-line text editing with a pointer and a caret (
NSTextView). The rich text model is in Attributed strings and rich text. - Symbols from the full SF Symbols catalogue. Only the names in
glyphs::NAMESdraw.