Docs App frameworks
App lifecycle
This chapter covers the parts of a BifrOSt app that run after it starts: the App trait, the Ctx the shell hands to every call, drawing and input, size and scale, appearance and accessibility, suspend and quit, sudden termination and activities, state restoration, host statistics, undo, observable values, logging, and preferences. Read Manifest first for the package fields.
The App trait
Your app implements bifrost_app::App. Only id and draw are required. Every other method has an empty or false default, so you add only the ones you need. The trait is the counterpart of NSApplicationDelegate and UIApplicationDelegate for the app's own view code.
Start the app with bifrost_app::run(app). It takes the app's socket and data folder from the environment that the shell sets, then waits for the first configuration.
struct Hello;
impl bifrost_app::App for Hello {
fn id(&self) -> &str { "is.example.hello" }
fn draw(&mut self, ctx: &bifrost_app::Ctx, s: &mut bifrost_app::Surface, t: f64) -> bifrost_app::Damage {
/* paint into s, return what changed */
}
}
fn main() {
bifrost_app::run(Hello);
}
The methods, grouped by what they are for. Each one that returns bool returns true when the app needs a new frame.
- fn id(&self) -> &str
- Required. The reverse-DNS id, the same as
idinmanifest.toml. - fn draw(&mut self, ctx: &Ctx, surface: &mut Surface, t: f64) -> Damage
- Required. Paints into
surfaceand returns the area that changed. See Surface, Damage and partial redraw. - fn configure(&mut self, ctx: &Ctx)
- Called before the first frame, on every size or scale change, and when the appearance changes. Read the new size, scale and scheme from
ctx, and drop anything you cached for the old ones. - fn event(&mut self, ctx: &Ctx, ev: Input) -> bool
- A touch, key, URL, shell command, accessibility activation, or context-menu choice. See Input events.
- fn tick(&mut self, ctx: &Ctx, t: f64) -> bool
- Runs on every loop turn while the app is in the foreground. Use it for animation and timers.
- fn next_wake(&self, t: f64) -> Option<f64>
- When
ticknext has work, in the same clock ast.Nonesleeps until an event arrives. - fn wake_fd(&self) -> Option<i32>
- A file descriptor the loop also waits on while the app is in the foreground. When it is readable,
tickruns. For a web view engine, for example. - fn full_redraw(&self) -> bool
- Return
truewhendrawpaints every pixel each frame. See Surface, Damage and partial redraw. - fn suspend(&mut self, ctx: &Ctx)
- The app leaves the foreground. Save state here. No frame is drawn until
resume. - fn resume(&mut self, ctx: &Ctx)
- The app is in the foreground again.
- fn controls(&self, ctx: &Ctx) -> Vec<controls::Node>
- Accessibility nodes in points. The shell gets them only when they change. When the list is empty, the nodes the kit drew in the last frame are used.
- fn controls_tree(&self, ctx: &Ctx) -> Vec<NodeExt>
- Parent and child relations, and focus and checked state, for the nodes from
controls. Without it, every node is a direct child of the window. - fn ax_set(&mut self, ctx: &Ctx, id: u64, action: AxAction) -> bool
- An assistive technology acts on node
id: press, set a value, or focus. The default turnsPressintoInput::Activate(id). - fn commands(&self, ctx: &Ctx) -> Commands
- The semantic commands the focused control can take.
- fn main_menu(&self, ctx: &Ctx) -> Vec<AppMenu>
- The app's own menu items, shown in the desktop bar after the app-name menu while the app is in front. Recompute enabled and checked state here. The shell receives the menus only when they differ from the last ones.
- fn menu_action(&mut self, ctx: &Ctx, id: u32) -> bool
- The user chose a menu item, from the bar or from its key equivalent.
- fn text_input(&mut self, ctx: &Ctx, ev: ToApp) -> bool
- Composition events: marked text, commit, delete surrounding text, and input accessory buttons.
- fn keyboard_config(&mut self, ctx: &Ctx, config: KeyboardConfig) -> bool
- Only for the keyboard system app. Other apps never receive it.
- fn document(&mut self, ctx: &Ctx, ev: DocumentEvent) -> bool
- The answer to an open or save request. See Ctx.
- fn keychain(&mut self, ctx: &Ctx, reply: keychain::Reply) -> bool
- The answer to a keychain add, get, update or delete call.
- fn notification(&mut self, ctx: &Ctx, ev: usernotif::Event) -> bool
- The user's response to a notification, or the answer to a notification request.
- fn share_done(&mut self, ctx: &Ctx, request: u32, target: Option<String>) -> bool
- The app the user chose in the share menu.
Nonemeans the menu was dismissed. - fn drag(&mut self, ctx: &Ctx, ev: dnd::Event) -> bool
- A drag and drop event for a window that registered types, or the end of a drag the app began.
- fn intents(&self) -> Vec<intents::Intent>
- App Intents. Each one is served over the control socket and must also be declared as
[[intent]]in the manifest. - fn perform_intent(&mut self, ctx: Option<&Ctx>, data_dir: &Path, id: &str, params: &Json) -> Result<IntentResult, RpcError>
- Runs the intent
id. The parameters are already checked against the declaration. - fn entities(&mut self, data_dir: &Path, ty: &str, query: &EntityQuery) -> Result<Vec<Entity>, RpcError>
- The entities of type
tythat match a query. - fn rpc_methods(&self) -> Vec<&'static str>
- The app's own control-socket methods, listed by
app.methods. The SDK addsapp.infoandapp.methods. - fn rpc(&mut self, ctx: Option<&Ctx>, data_dir: &Path, method: &str, params: &Json) -> Result<Json, RpcError>
- Answers one control-socket request on the app's main thread.
ctxisNonebefore the first configuration. Unknown methods returnMETHOD_NOT_FOUND.
The four methods configure, event, draw and tick are the ones most apps write. The others are for specific features such as the keyboard, documents, the keychain and drag and drop. Each has a true return value only where a frame may be needed.
Ctx
Every call receives a Ctx. It holds three fields and a set of methods. The methods do not run at once. Each one queues a message that the shell gets when the loop turns, like NSApplication sending work to the window server.
- pub ui: Ui
- The drawing and text kit, with the font, the scale and the text settings. See Size, scale and ui.pt().
- pub cfg: Configure
- The current size, scale, safe insets, scheme and text settings, as the shell sent them.
- pub data_dir: PathBuf
- The app's private storage folder. See Preferences.
- fn defaults(&self) -> Ref<UserDefaults>
- Reads the app's preferences.
- fn defaults_mut(&self) -> RefMut<UserDefaults>
- Changes the app's preferences. Each change is saved at once.
- fn appearance(&self) -> kit::appearance::Appearance
- The system appearance settings. See Appearance and accessibility.
- fn pasteboard_string(&self) -> Option<String>
- The text on the general pasteboard. Like
NSPasteboard.generalwith the string type. - fn set_pasteboard_string(&self, text: &str)
- Puts text on the general pasteboard.
- fn open_url(&self, url: &str)
- Opens an HTTP or HTTPS link in BifrOSt Browser, like
NSWorkspace.open(_:). - fn notify(&self, title: &str, body: &str)
- Sends a notification. Needs the
notificationspermission. - fn set_badge(&self, label: &str)
- Sets the dock badge, such as an unread count, like
NSDockTile.badgeLabel. The shell shows at most four characters. An empty label clears it. Needs thenotificationspermission. - fn haptic(&self)
- A short haptic tap, where the device has one.
- fn context_menu(&self, x: f32, y: f32, items: Vec<ContextItem>)
- Shows a context menu at
x,y, in the app's pixels. The chosen item comes back asInput::ContextAction. Disabled items never fire. Up to 32 items. - fn log(&self, text: &str)
- Writes one line to the shell log. For structured logging, use Logging.
- fn wants_keyboard(&self, on: bool)
- Shows or hides the system keyboard. Typed text then arrives as
Input::Key. - fn open_document(&self, mode: DocMode, title: &str, filters: &[&str]) -> u32
- Shows an open panel, like
NSOpenPanel. The answer arrives inApp::document. Needs thedocumentspermission. - fn open_panel(&self, options: &OpenOptions) -> u32
- As
open_document, with several files, folders or New Folder. A panel withmultipleanswersOpenedMany. - fn save_document(&self, suggested_name: &str, filters: &[&str]) -> u32
- Shows a save panel, like
NSSavePanel. The app writes to the file it is given, then callscommit_document. - fn save_document_in_place(&self, grant: GrantId) -> u32
- Saves over a file already granted, with no panel. Needs a write grant.
- fn commit_document(&self, request: u32) / fn abort_document(&self, request: u32)
- Puts a finished save in place, or throws it away. The file at the chosen place is unchanged until the commit.
- fn reopen_document(&self, grant: GrantId) -> u32 / fn release_document(&self, grant: GrantId)
- Opens a recent file again by its grant, or releases the grant.
- fn set_document_state(&self, title: &str, edited: bool, represented: &str)
- Sets the window's document state: the title, the edited dot and the file name, like
NSDocument.
The app never gets a file's path. A document event carries an open File and a grant. Keep the grant if you want to reopen the file later.
Each call that needs a permission answers Failed without it. Declare the permission in the manifest. See Manifest.
Surface, Damage and partial redraw
draw paints into a Surface. The surface holds premultiplied pixels, one u32 per pixel, with a stride equal to the width. It returns a Damage: the rectangles that changed. The shell sends only those rectangles, which is the same idea as NSView's dirty rectangle.
- Surface. Its fields are
w,h,strideandpx. Drawing calls includefill_rect(x, y, w, h, color),blit(image, x, y, tint, alpha)andblit_colored(image, x, y, color, alpha). Usebifrost_app::kit::packandkit::rgbato build colours. - Damage.
Damage::new(w, h)starts empty.all()marks the whole frame.add(x, y, w, h)marks a rectangle and clips it to the frame.is_empty(),areas(),pixels()andunion(&other)report or combine the marks.Damage::between(previous, current, w, h)returns the exact changed rows of two frames. - Nothing changed. When
drawreturns an emptyDamage, no frame is sent. - First frame. The first frame after a new size is always sent whole.
- Two buffers. The shell uses two frame buffers. Before each draw, the SDK copies into the buffer you are about to draw the rectangles that the other buffer changed since it was last drawn. So the buffer you get already holds the previous frame, and you only need to paint what changed since then.
- Full redraw. Return
truefromfull_redrawwhen you paint every pixel every frame. The copy step is then skipped.
A partial redraw is only correct when every change is also reported in the returned Damage. If you change a pixel and do not add it to the damage, the shell does not show it until the next full frame.
Input events
The shell passes input to event as an Input value. Return true when the event changed what the app shows.
- Input::Touch { kind: TouchKind, id: u32, x: f32, y: f32, t: f64 }
- A pointer or touch.
kindisDown,Move,UporCancel.xandyare in the app's pixels.tis the time of the event on the same clock asdraw. The desktop pointer usesid0. - Input::Key(KeyInput)
- A key.
KeyInput::Text(String)is typed text.KeyInput::Code(u32)is a named key: 8 Backspace, 9 Tab, 13 Enter, 1 Escape, 37 Left, 38 Up, 39 Right, 40 Down. - Input::Open(String)
- A URL handed to the app.
- Input::Command(Command)
- A semantic command from the shell, such as copy or paste.
- Input::Activate(u64)
- An accessibility node was activated.
- Input::Context { x: f32, y: f32 }
- A right-click, in the app's pixels. Answer with
context_menu. - Input::ContextAction(u32)
- The menu item the user chose.
- Chords. A Ctrl or Cmd chord the shell does not use arrives as
KeyInput::CodewithCHORD_FLAGset. Read it withKeyInput::as_chord(), which returns the key and theCHORD_CTRL,CHORD_SHIFT,CHORD_ALTorCHORD_METAbits. - Scroll wheel. The shell turns a wheel step into a touch sequence:
Down, then aMove, thenUp. Your app does not need a separate wheel event. Feed it tokit::Scrollerlike a touch. - Lists. Use
kit::Scroller, so your lists scroll like the system's. Calldown(y, t),moved(y, t)andup(y, t)from the touch events,tick(t)on each frame, and draw atoffset(). - Text input. Call
ctx.wants_keyboard(true)to show the system keyboard. Report the focused field withctx.input_traits,ctx.text_stateandctx.caret_rectso composition and predictive text work.
Size, scale and ui.pt()
Configure carries the size and the scale. w and h are the window size in pixels. scale is pixels per point. The safe insets are in pixels too. Draw in points and convert with ctx.ui.pt(v), which returns v times the scale.
fn configure(&mut self, ctx: &Ctx) {
let ui = &ctx.ui;
let margin = ui.pt(20.0); // 20 points at this scale
let (w_pt, h_pt) = (ctx.cfg.w as f32 / ctx.cfg.scale, ctx.cfg.h as f32 / ctx.cfg.scale);
let layout = bifrost_app::layout::Layout::new(&ctx.cfg);
// layout.margin, layout.sidebar and layout.content_top are points
}
- Size changes. The shell reallocates the frame buffers, the next frame is sent whole, and
configureruns first. - Layout.
bifrost_app::layout::Layoutderives margins, the sidebar width, the content top and the size class from the window in points. Use it instead of fixed numbers, so the same code lays out a small window and a large one. - Text size.
ctx.ui.text_scaleis set fromConfigure::text_scaleand scales every text size. - No fixed screen. Do not assume a resolution, an aspect ratio or a pixel position. Read the size from
ctx.cfgeach time.
Appearance and accessibility
The shell sends the light or dark scheme in Configure::dark, and sends changes to a running app as ToApp::Appearance. The SDK then calls configure so you can repaint.
- Light and Dark. Colours from the system colour set in
bifrost_app::kit::colorsarePairvalues with a dark and a light value. Call.now()on aPairto get the colour for the current scheme. The SDK switches the scheme at once when it receives a change. The shell's own fade lasts 280 ms. - Light and Dark in Auto mode. Auto switches to light from 07:00 and to dark from 19:00. Apps can be told up to 500 ms after the shell's switch. The gap is recorded as not yet matched in the developer notes.
- Read the settings.
ctx.appearance()returns the current settings. Its fields aretext_scale,zoom,hold_ms,bold,reduce_motion,increase_contrast,reduce_transparencyandbutton_shapes.
| Setting | What changes in your app |
|---|---|
| Larger Text | text_scale. The kit scales every text size with it. |
| Bold Text | bold. The kit draws text one weight heavier. |
| Reduce Motion | reduce_motion in Configure. Animations should shorten to a cross-fade or stop. A scheme change happens at once. |
| Increase Contrast | increase_contrast. Use stronger separators and text when it is on. |
| Reduce Transparency | reduce_transparency. Translucent surfaces must be opaque. The vibrancy flag is off, and widgets::vibrancy() returns false. |
| Button Shapes | button_shapes. Tappable text draws a visible shape. |
| Touch hold time | hold_ms, the time a press must last for a hold. |
The kit draws the standard controls with these settings already applied. Only code that draws its own text or shapes needs to read them.
Suspend, resume and quit
The shell starts your app, keeps it running while it is in the foreground, and stops it when it is no longer needed. Save state on suspend and on quit, because the shell can stop a background app at any time to free memory.
- Start. The shell passes the socket in
BIFROST_SOCK, the app's data folder inBIFROST_DATA, and the shell's files inBIFROST_SHELL_DIR. The SDK sends a hello with the app id and the SDK version, then waits for the first configuration.configureruns, and the first frame is sent whole. - Foreground.
tickruns on every loop turn. The loop sleeps until the next event or untilnext_wakereturns a time. - Background. The shell sends
Suspend. The SDK callssuspend, and draws nothing until the app is resumed.tickdoes not run. - Foreground again. The shell sends
Resume. The SDK callsresume, then draws a frame. - Quit. The shell sends
Quit. The SDK callssuspendfirst if the app is in the foreground, then the loop ends and the process exits. If the app does not exit in a short grace period, the shell kills it.
Save state in suspend. Do not rely on quit to run. If the app is killed, it gets no chance to save.
A crash in your app does not take the shell down. The shell records the exit as app <id> exited <code>, with 128 plus the signal number when a signal killed the app. The next time the user opens the app, it starts again.
Sudden termination
The process_info counter is ProcessInfo sudden termination. It tells the shell whether your app can be killed without a chance to save. Use it when the app has no unsaved state: every change is already on disk, or can be rebuilt from disk.
// Once, when the app starts, if it keeps no unsaved state:
ctx.enable_sudden_termination();
// Around work that must finish, such as a multi-step file write:
ctx.disable_sudden_termination();
write_document_in_steps()?;
ctx.enable_sudden_termination();
- ctx.enable_sudden_termination() / ctx.disable_sudden_termination()
- Balance each other. The counter starts at one, so an app is not terminable until it calls
enableonce. Eachdisableneeds oneenable, and termination is allowed only when the count is zero. An unbalancedenableis ignored. - Shell message (tag 0x160)
- The shell hears of the state only when it changes, so a counter that moves between one and two costs nothing.
The shell acts on the state when it closes an app, when the user logs out or shuts down, and when it restarts:
- Terminable. The shell kills the app at once with
SIGKILL. Nothing is waiting. - Not terminable. The shell sends
Quitand gives the app 1.5 seconds to save and exit. The shell does not wait on the app. It notes the pending kill and reaps the process on a later turn of its loop. - Power off, restart and update restart. The shell stops every app together with one shared 1.5 second deadline, so the total wait is the same however many apps are open.
Calculator, Console and Weather opt in. An app that keeps documents should not opt in, because a save is then always followed by a Quit round trip.
Terminating an app at once runs none of your code. If an app opts in, it must already have written everything it needs before the next enable.
Apple also turns termination off by itself while a document save is in flight. BifrOSt does not do that yet, so bracket a save with disable and enable yourself.
Activities
An activity tells the shell that the app has work in progress that it must not pause, the counterpart of ProcessInfo.beginActivity(options:reason:). Begin one with ctx.begin_activity(options, reason), keep the Activity it returns, and end it with ctx.end_activity(activity).
// A copy the user started, which must go on when the app leaves the foreground.
let copy = ctx.begin_activity(ActivityOptions::USER_INITIATED, "Copying photos");
// ... when the copy is done:
ctx.end_activity(copy);
ctx.begin_activity(ActivityOptions, reason) -> Activity- Starts an activity. Each call adds its options to the set of live options. The reason is a short text for the record.
ctx.end_activity(Activity)- Ends that activity. Each activity ends once, and the shell hears of the change only when the set of live options changes.
ActivityOptions::USER_INITIATED,LATENCY_CRITICAL- While one of these is live, the shell does not suspend the app when it leaves the foreground. Use them for work the user asked for, such as a transfer or playback.
ActivityOptions::BACKGROUND,IDLE_SYSTEM_SLEEP_DISABLED- Recorded in the set. The shell does not yet act on either one.
An activity keeps the app from being suspended. It does not stop the CPU from being throttled, and it does not keep the system awake.
State restoration
An app can save what it needs to put its window back. The desktop then reopens the window after a relaunch, a restart, a shut down, an update or a crash. This is the counterpart of NSWindowRestoration. The app sets a restoration identifier, saves its state when the state changes, and reads it back when it starts again.
impl App for Notes {
fn restoration_identifier(&self) -> Option<&str> {
Some("main")
}
fn encode_restorable_state(&self, _ctx: &Ctx, state: &mut RestorableState) {
state.encode_for("folder", &self.folder);
state.encode_for("openNote", &self.open_note);
}
fn restore_state(&mut self, _ctx: &Ctx, state: &RestorableState) -> bool {
match (state.decode_for::<String>("folder"), state.decode_for::<String>("openNote")) {
(Some(folder), Some(note)) => {
self.folder = folder;
self.open_note = note;
true
}
_ => false,
}
}
}
// In the event handler, after the user opens another folder or note:
ctx.invalidate_restorable_state();
fn restoration_identifier(&self) -> Option<&str>- The identifier of the app's window.
None, the default, means the window is not restored. fn is_restorable(&self) -> bool- Whether the window is restored. It is
truewhen the identifier is set. fn encode_restorable_state(&self, ctx: &Ctx, state: &mut RestorableState)- Called when the state is written. Put in it everything the window needs to come back.
fn restore_state(&mut self, ctx: &Ctx, state: &RestorableState) -> bool- Called once after the first configuration, when the shell asks for a restore. Return
truewhen the app needs a new frame. RestorableState::encode_for(&mut self, key: &str, value: &T)- Stores a value under a key. Any type that is
Encodableworks. RestorableState::decode_for::<T>(&self, key: &str) -> Option<T>- The value under a key, or
Nonewhen the key is missing or holds another type. RestorableState::contains(&self, key: &str) -> bool- Whether a key is set.
ctx.invalidate_restorable_state()- Asks for a write of the state soon. Calls in a short burst share one write, about 750 ms after the first.
- Storage. The state is one JSON file,
restorable-state.json, in the app's data folder. The write replaces the file at once, so a crash keeps the last full state. A file that is corrupt, belongs to another identifier or has a newer format is ignored and removed. - Unchanged state. A write whose state equals the file on disk is skipped.
- Window size. The window size is saved with the state and comes back on its own. Read it in
configure. - Reopen at login. The shell keeps a record of the open windows, their order, their places, and whether they are zoomed or minimized. On the next login it opens them again and starts each app with its restore request set. Apps that are no longer installed are dropped. A restart or shut down asks whether to reopen the windows, and the answer is remembered.
- Close windows when quitting. Settings > General has a setting that stops an app from reopening its windows when the user opens it by hand. It is off by default.
Gaps: an app has one restorable window, so the state is one file per app and not one per window. The window position is chosen by the shell, not the app. Only Notes uses these hooks so far. After a crash, the window reopens even when the user had quit the app on purpose, because Apple's rule for that case is not modelled.
Host statistics and ProcessInfo
Use bifrost_app::host to read the CPU and memory figures of the machine and the process. Use bifrost_app::process_info::ProcessInfo for facts about the machine, such as the memory size and the thermal state. These are the counterparts of host_statistics64, ProcessInfo and task_info. Each call reads the system when it runs. The SDK keeps no cache and no sampling thread, so the app decides how often to read.
use bifrost_app::host::{HostCpuLoadInfo, HostSampler};
use bifrost_app::process_info::{ProcessInfo, ThermalState};
let mut sampler = HostSampler::new();
let before = sampler.host_cpu_load_info();
// ... about a second later:
let after = sampler.host_cpu_load_info();
if let (Some(a), Some(b)) = (&before, &after) {
let busy = HostCpuLoadInfo::usage_percent(a, b);
}
let ram = ProcessInfo::physical_memory();
if ProcessInfo::thermal_state() >= ThermalState::Serious {
// The machine is hot. Do less work.
}
HostSampler::new()- Makes a sampler. It reuses its read buffer between calls.
HostSampler::host_cpu_load_info(&mut self) -> Option<HostCpuLoadInfo>- The CPU ticks of the whole machine. Take two reads and use
HostCpuLoadInfo::usage_percent(previous, now)for the busy share. HostSampler::processor_info(&self) -> &[HostCpuLoadInfo]- The ticks of each core, from the last
host_cpu_load_inforead. HostSampler::memory(&mut self) -> Option<MemorySample>- The memory counts of the machine. Its
used_percent()andused_bytes()give the Memory Used figure that Activity Monitor shows. HostSampler::task_vm_info(&mut self) -> TaskVmInfo- The memory that this process is charged for.
HostSampler::os_proc_available_memory(&mut self) -> u64- The memory this process can still use. Under a cgroup limit, it is the room left under the limit.
ProcessInfo::physical_memory() -> u64,processor_count(),active_processor_count()- The installed memory in bytes, and the number of processors, all or currently active.
ProcessInfo::system_uptime() -> f64- The seconds since the machine started.
ProcessInfo::thermal_state() -> ThermalState- The worst thermal state of the machine:
Nominal,Fair,SeriousorCritical. ProcessInfo::observe_thermal_state(queue, handler)- Calls
handleronqueuewhen the thermal state changes. PassDispatchQueue::main()to get the calls on the main thread. ProcessInfo::is_low_power_mode_enabled() -> bool,observe_low_power_mode(queue, handler)- Whether Low Power Mode is on, and a call when it changes.
DispatchSource::memory_pressure(queue, handler)- Calls
handlerwithNormal,WarningorCriticalwhen the machine runs short of memory. Release caches when the level rises.
Gaps: there are no per-process energy figures. The thermal and Low Power changes are checked every 10 seconds, not pushed by the kernel, and the shell does not yet send them to apps. Memory pressure handlers cannot be cancelled. The memory counts have no purgeable, throttled or zero-fill figures. The Active count includes file-backed pages, so there is no split of anonymous pages.
Undo
An undo manager keeps the steps that the user can reverse. It is the counterpart of NSUndoManager, in bifrost_ui::undo::UndoManager. Each window has one, in its undo field. The Edit menu runs it: Edit > Undo and Edit > Redo reach it through Cmd+Z and Cmd+Shift+Z.
The app makes the change itself, then records a step. A step holds two closures. One reverses the change and the other repeats it.
let old = doc.title.clone();
doc.title = new_title.clone();
let (before, after) = (old, new_title);
window.undo.register(
"Rename",
move |d: &mut Doc| d.title = before.clone(),
move |d: &mut Doc| d.title = after.clone(),
);
register(name, undo, redo)- Records one step. The name appears in the Edit menu. A new step clears the redo steps.
register_for(target, name, undo, redo)- Records a step for a target, so
remove_all_actionscan drop it later. register_coalesced(key, now_ms, gap_ms, name, undo, redo)- Joins the newest step when it has the same key and came within
gap_ms. Use it for typing, so that a word is one step. set_action_name(name)- Names the open group, or the newest step when no group is open.
begin_undo_grouping(),end_undo_grouping(),grouping_level()- Start and end a group. Groups nest, and only the outermost end makes one step.
set_groups_by_event(on),end_event()- When on, the edits made in one event form one step. Call
end_eventat the end of each event. It is off by default. undo_menu_item_title(),redo_menu_item_title()- The Edit menu titles, such as Undo Move. The plain word Undo or Redo is used when the step has no name.
can_undo(),can_redo()- Whether a step is waiting on either stack.
levels_of_undo(),set_levels_of_undo(n)- How many steps are kept. Zero keeps them all. A smaller number drops the oldest steps at once.
remove_all_actions(target),clear()- Drops the steps of a target, or every step on both stacks.
fn undo_titles(&self, ctx: &Ctx) -> (String, String)- For an app without windows, the undo and redo titles to show in the Edit menu. The shell gets them when they change. An empty string keeps the plain word.
Gaps: there is no registration by selector, so the closures take its place. Registering a step from inside an undo handler is not supported. remove_all_actions drops a whole group when one of its parts matches. There is no undoNestedGroup and no actionIsUndoable. The control-socket undo method is separate from the menu titles.
Observable values
bifrost_app::observable::Observable holds a value and tells subscribers when it changes. It is the counterpart of CurrentValueSubject and @Published. It runs on one thread only, the main thread, and it needs no shell.
use bifrost_app::observable::{Cancellables, Observable};
let count = Observable::new(0);
let mut bag = Cancellables::new();
count.sink(|n| println!("count is {}", n)).store(&mut bag); // runs now, with 0
count.set(1); // runs again, with 1
Observable::new(value: T)- Makes an observable with a starting value.
get(&self) -> T,set(&self, value: T)- Reads the value, or sets it and tells the subscribers.
update(&self, f)- Changes the value in place with one closure. There is one notification per call.
set_if_changed(&self, value: T) -> bool- Sets the value only when it differs from the current one. Returns whether it changed.
sink(&self, f) -> Subscription- Calls
fwith the current value at once, then with each change. subscribe(&self, f) -> Subscription- Calls
fwith each change only, without the current value. map(&self, f) -> (Observable<U>, Subscription)- A new observable that follows this one through
f. remove_duplicates(&self) -> (Observable<T>, Subscription)- A new observable that passes on a change only when the value is different from the one before.
Subscription- Dropping it cancels the subscription.
cancel()does the same at once.store(&mut Cancellables)keeps it until the bag is cleared or dropped.
Gaps: there is no ObservableObject aggregate that fires for any of its properties, so use one observable per property or one struct value. There is no automatic capture of what a view reads. There are no threaded publishers, no schedulers and no debounce. A set from inside a callback of the same observable updates the value, but no subscriber is told until the next change.
Logging
Use bifrost_app::log::Logger for structured logs. It is the counterpart of os.Logger. Entries go to the system journal, where you read them with bifrost-log.
use bifrost_app::log::{private, Logger};
let log = Logger::new("is.example.notes", "sync");
log.notice("synced");
log.error(format!("cannot open {}", private(path.display())));
- Logger::new(subsystem: &str, category: &str) -> Logger
- Makes a logger. It is cheap to create and to call.
- debug, info, notice, error, fault (msg)
- Writes a message at that level.
noticeis the default. Syslog priorities are 7, 6, 5, 3 and 2. - enabled(&self, level: Level) -> bool
- Whether a message at this level is written. Check it before building an expensive message.
- private(v: impl Display) -> String
- Marks a value as private. It is stored as
<private>unless the subsystem setsprivate = true. - LogStore::current_process() -> LogStore
- Reads this process's own recent entries, from an in-process ring of 2000 entries.
Declare the subsystem and its categories in the manifest, so the level and privacy can be set:
[[log.subsystem]]
id = "is.example.notes"
categories = ["sync"]
level = "notice"
- Reading logs.
bifrost-log show --last 1hprints entries, andbifrost-log streamfollows them. Filter with a predicate, for examplesubsystem == "is.example.notes" AND level >= error. - Changing levels.
bifrost-log config --subsystem X --level debugchanges a subsystem's level. The logger picks up the change within a second. - Shell log.
ctx.log(text)writes one line to the shell log. Use it for a quick diagnostic line.
Gaps: format specifiers are not supported, and a value is either public or private as a whole. The privacy setting applies to the subsystem, not to each value. Reading the system journal is limited to apps that declare the log-store entitlement.
Preferences
ctx.defaults() is the app's preferences store, the counterpart of NSUserDefaults.standard. It holds string, boolean, integer, double and data values. Every change is written at once to defaults.txt in the app's data folder, with an atomic replace, so a crash keeps the last consistent state.
- string(&self, key: &str) -> Option<String>
- The string stored under
key, orNone. - bool(&self, key: &str) -> bool
- The boolean stored under
key.falsewhen missing. - int(&self, key: &str) -> i64 / double(&self, key: &str) -> f64
- The number stored under
key.0when missing. - data(&self, key: &str) -> Option<Vec<u8>>
- The bytes stored under
key, orNone. - set_string, set_bool, set_int, set_double, set_data
- Stores a value under a key. Each one takes the key and the value.
- remove(&mut self, key: &str)
- Removes a key.
- contains(&self, key: &str) -> bool / keys(&self) -> Vec<String>
- Whether a key is set, and every key, sorted.
ctx.defaults_mut().set_bool("showSidebar", true);
let show = ctx.defaults().bool("showSidebar");
- Missing keys. A missing or wrongly typed key reads as the zero value. Check
containswhen you need to tell the two apart. - Location. The file is in the app's data folder,
BIFROST_DATA. Store everything the app needs there. Do not write outside it.
The preferences file is plain text. Do not store passwords or tokens in it. Use bifrost_app::keychain for secrets.