Docs App frameworks
System services
System services are the shell features an app calls instead of building its own: menus in the desktop menu bar, user notifications, Dock badges, notification centers, the share sheet, drag and drop, App Intents and the search index for Spotlight, the clipboard, opening links and files with the workspace, login items and menu-bar extras, text input, Quick Look previews, web content, dispatch queues, host statistics and purgeable caches.
Menus
An app publishes its main menu the way AppKit sets NSApp.mainMenu. The desktop bar shows the menus of the app in front, after the app-name menu. Override App::main_menu to return the menus, and App::menu_action to receive the item the user chose.
- fn main_menu(&self, ctx: &Ctx) -> Vec<AppMenu>
- The menus of the app. The runtime calls it after every event and frame and sends the menus to the shell only when they differ from the last ones. Recompute
enabledandcheckedhere, asvalidateMenuItem:does. - fn menu_action(&mut self, ctx: &Ctx, id: u32) -> bool
- The user chose item
id, from the bar or from its key equivalent. Returntruewhen the app needs a new frame. - AppMenu { title, items }
- One menu in the bar.
- AppMenuItem::new(id, title)
- An item. Chain
.key("cmd+n"),.enabled(on),.checked(on)and.depth(1). UseAppMenuItem::separator()andAppMenuItem::submenu(title)for the rest.
Key equivalents use the same notation as KeyCombo::parse. The shell matches an enabled item's key equivalent before the key reaches the app, so the app receives menu_action instead of the key. A key without a modifier is ignored by this path.
A menu holds at most 8 menus of 48 items. Titles are cut at 64 characters. Items that do not fit in one packet are dropped, never split.
Context menus
A right-click arrives as Input::Context { x, y }, in the app's pixels. Call ctx.context_menu(x, y, items) with up to 32 ContextItems, each with an id, a label and enabled. The chosen item arrives as Input::ContextAction(id). Disabled items never fire.
User notifications
The usernotif module works like UNUserNotificationCenter. Requests, removals and queries are asynchronous: each call returns a request id, and the answer arrives in App::notification. Add notifications to the manifest permissions. Without it, every request answers NotifStatus::NotPermitted.
use bifrost_app::usernotif::{self, Request, NotifAction, NotifCategory};
usernotif::set_categories(ctx, &[NotifCategory {
id: "message".into(),
actions: vec![NotifAction::button("reply", "Reply")],
}]);
usernotif::add(ctx, Request::new("msg-42", "Ada").body("Lunch?").category("message"));
- set_categories(ctx, &[NotifCategory])
- Replaces the registered categories (
setNotificationCategories). Register them before a request names one. - add(ctx, Request) -> u32
- Posts a request (
add(_:)). A request whose identifier is already pending or delivered replaces it. - Request::new(id, title)
- Chain
.subtitle(),.body(),.thread(),.category(),.after_ms()(a time-interval trigger) and.badge(n). - remove_delivered(ctx, &[ids]) / remove_pending(ctx, &[ids])
- Removes the app's notifications. An empty list removes all of them.
- delivered(ctx) -> u32 / pending(ctx) -> u32
- Lists the identifiers, answered as
Event::List. - Event::Response(Response { id, action, text, thread, category })
- The user acted on a notification (
didReceive).actionis one of the category's action ids,NOTIF_DEFAULT_ACTIONfor a tap, orNOTIF_DISMISS_ACTION.textholds the reply for a text-input action. - Event::Status { request, status }
- The result of an
add:Ok,NotPermitted,Param(an empty field, an unknown category or an oversized field) orFull(more than 64 pending).
A tap on a notification can start the app. If the app is not running, the shell starts it and delivers the response once it is up. Up to 32 responses are held.
Action buttons and reply fields are not drawn on banners or in Notification Center yet. Only the default action, a tap, reaches the app today. A tap answers for the app's newest notification, not the one tapped.
The older ctx.notify(title, body) needs the same permission. The shell accepts one of these from an app per second and drops the rest.
Dock badges
Set the app's Dock badge with ctx.set_badge(label), the counterpart of NSDockTile.badgeLabel. The shell shows the first four characters. An empty label clears the badge. You can also set it with Request::badge(n), where 0 clears it. Both need the notifications permission.
Notification centers
The notification module posts and observes named notifications. NotificationCenter works inside one process. DistributedNotificationCenter (NSDistributedNotificationCenter) sends a notification to every running app. Observers run on the main thread. A post from the main thread is delivered at once, and a post from another thread waits on DispatchQueue::main().
use bifrost_app::notification::NotificationCenter;
use std::collections::HashMap;
let center = NotificationCenter::default();
let _token = center.add_observer("prefs.changed", None, |n| {
println!("now {:?}", n.user_info.get("theme"));
});
center.post("prefs.changed", None, HashMap::from([("theme".to_string(), "dark".to_string())]));
NotificationCenter::default()- The process-wide center.
add_observer(name, object, f) -> ObserverToken- Calls
ffor each post ofname.objectlimits the observer to one poster, orNoneaccepts any. Dropping the token removes the observer. post(name, object, user_info)- Posts a notification to the observers in this process.
user_infois a map of text to text. DistributedNotificationCenter::default()- The center for notifications between apps.
add_observer(name, f) -> ObserverToken- Calls
ffor each post ofnamefrom any app. post_with(ctx, name, user_info)- Sends the notification to every other running app, and to this app's own observers at once.
post(name, user_info)- Posts to this process only. Other apps do not receive it.
A Notification holds the name, the poster's object and the user_info.
A distributed post carries at most 32 entries, and each value is cut at 1024 characters. An app that is not running misses the post. There is no option to hold a post for a suspended app, and no flag that asks for immediate delivery.
Share sheet
The share module shows the share menu, like NSSharingServicePicker. Call share::show_picker(ctx, &[Payload], anchor) with up to 8 items. anchor is the rectangle of the button that opened the menu, in window points. The menu lists the other installed apps whose manifest accepts every item, then Copy.
- Payload::Text(String) / Payload::Url(String)
- Text and web links.
- Payload::File { grant, name }
- A file. Use a document grant the app already holds, from
open_documentorsave_document. An app never sends a path. - App::share_done(ctx, request, Option<String>)
- The app id the user chose,
share::COPY("copy") for Copy, orNonewhen the menu was dismissed. - share::text_from_url(url) -> Option<String>
- Decodes shared text, which arrives as an
Openevent with adata:text/plainURL. - share::is_inbound(request) -> bool
- True for a file someone shared or dropped on the app. Its grant is read-only.
To receive shares, declare what the app opens in the manifest, for example handles = ["public.png"] and schemes = ["https"]. A shared URL arrives as Input::Open. A shared file arrives as a document event whose request is inbound.
Copy puts text and links on the clipboard, one per line. For a file it copies the file's name only.
Not yet available: system services such as Mail or Messages, per-service objects with canPerform, rich items such as image data or attributed text, and share extensions from apps.
Drag and drop
The dnd module provides typed drag and drop, with NSDraggingDestination and NSDraggingSource counterparts. A window receives drags only after it registers the types it takes. The shell sends the drag events to App::drag.
use bifrost_app::dnd;
dnd::register_types(ctx, &["public.image", "public.text"]);
// in App::drag
match ev {
dnd::Event::Dest { session, phase, .. } => dnd::reply(ctx, session, dnd::dragop::COPY),
dnd::Event::Ended { .. } => {}
}
- register_types(ctx, &[uti])
- The UTTypes the window accepts.
public.imageaccepts every image type. An empty list stops accepting drags. - Event::Dest { session, phase, x, y, allowed, items }
phaseisEntered,Updated,ExitedorPerform.xandyare window pixels. AnswerEnteredandUpdatedwithdnd::reply.- dnd::reply(ctx, session, op)
- The operation this window performs at the pointer:
dragop::COPY(1),LINK(2) orMOVE(4). Use 0 to refuse. An operation the source did not allow counts as 0. - dnd::performed(ctx, session, accepted)
- Finishes a drop. On
Perform, the files have already arrived as read-only document grants, with this session as their request. - dnd::begin(ctx, allowed, items, preview) -> u32
- Starts a drag from the source side (
beginDraggingSession).allowedis a mask ofdragopbits, anditemsis a list ofDragItems. Call it from the mouse-down that moved far enough to drag. - Event::Ended { session, op }
- The session finished.
opis 0 when nobody took the drop, or when the shell refused the session. - dnd::preview_from_rgba(w, h, rgba) -> DragPreview
- A drag image from RGBA pixels, scaled down to fit 32 points on the long side.
The shell owns the pointer during a drag, so the source gets no more touches until the session ends. The shell refuses a session when another drag is running, when the app is not in front, or when there are no items.
Not yet available: the Dock, the desktop background and shell chrome as destinations; drags to Wayland or X11 windows; promised files; modifier keys to choose copy or move; spring-loaded folders; Escape to cancel. dnd::cancel exists, but the shell does not yet send Escape to it.
App Intents
The intents module declares typed actions, like AppIntent, AppEntity and AppShortcutsProvider. An app returns its intents from App::intents and runs them in App::perform_intent. The SDK checks parameters against the declaration before the app sees them.
- Intent::new(id, title, description)
- An intent.
idis a short token of lowercase letters, digits,-and_. Chain.param(Param::new(name, title, ParamType::..))and.shortcut(). - Param::new(name, title, ty).optional()
- A named parameter.
ParamTypeisString,Int,Bool,Date(ISO 8601 text),UrlorEntity("Type"). - Entity::new(type, id, title).subtitle(s)
- Something an entity parameter can refer to.
- App::entities(data_dir, type, &EntityQuery)
- Answers
entity.query.EntityQueryisSuggested,IdsorString. - IntentResult::value(json).with_dialog(text)
- The result of an intent: a value, and the text to show.
- intents::str_param(params, name) -> Result<&str, RpcError>
- Reads a required text parameter in
perform_intent.
Intents are also served on the app's control socket. intent.list returns the declarations. intent.<id> runs an intent with a JSON object of parameters. entity.query takes {"type": "Note", "string": "milk"}, {"type": "Note", "ids": [...]} or no other key for suggested entities.
To make an intent appear in Spotlight without launching the app, copy Intent::manifest_toml() into manifest.toml as an [[intent]] table. Put app-level keys above the first table. Spotlight lists the intents with shortcut = true that have no required parameter. Choosing one starts the app and runs the intent.
bifrost pc control call APP intent.list
bifrost pc control call APP intent.add-note '{"text":"milk"}'
Spotlight runs only intents without required parameters, and it does not show the dialog. Voice, parameter pickers, confirmation, entity indexing and intent donation are not yet available.
Search index
The search index (Core Spotlight) lets an app index its own items, so system search finds them without the app running. Build an item from an attribute set, index it, and the shell keeps it for search. Opening a result starts the app and calls App::continue_activity.
use bifrost_app::quicksearch::{CSSearchableIndex, CSSearchableItem, CSSearchableItemAttributeSet};
let attrs = CSSearchableItemAttributeSet::new("Milk")
.content_description("Oat milk, two cartons")
.keywords(&["shop", "dairy"]);
let item = CSSearchableItem::new("note-7", "notes", attrs);
CSSearchableIndex::default_index().index_searchable_items(ctx, &[item]);
CSSearchableItemAttributeSet::new(title)- The attributes of an item. Chain
.content_description(),.keywords(),.thumbnail_path(),.content_url()and.custom_attribute(key, value). CSSearchableItem::new(unique_identifier, domain_identifier, attributes)- An item. Items in one domain can be removed together.
CSSearchableIndex::default_index()- The index of this app.
index_searchable_items(ctx, items)- Adds the items. An item whose identifier is already indexed replaces the old one.
index_checked(ctx, items) -> Vec<(usize, IndexError)>- Indexes the items and returns each refused one with its position and the reason. Use it when the app needs to know which items were refused.
delete_searchable_items(ctx, ids),delete_searchable_items_with_domain_identifiers(ctx, domains),delete_all_searchable_items(ctx)- Removes items by identifier, by domain, or all of them.
quicksearch::search_items(&SearchQuery::new(text), items)- Searches items the app holds itself, by title, description and keywords, best match first. It does not query the shell's index.
App::continue_activity(ctx, activity)- The user opened one of the app's items from Search. Compare
activity.activity_typewithquicksearch::ACTION_TYPE, and show the item named byactivity.unique_identifier.
The shell keeps up to 1000 items for each app and 64 apps. Items stay searchable after the app is removed, because uninstalling does not remove them. Index calls have no completion handler, and items have no expiration date or ranking hint. The Search panel does not draw thumbnails yet.
Clipboard and links
The clipboard holds plain text. Read it with ctx.pasteboard_string() and write it with ctx.set_pasteboard_string(text), the counterparts of NSPasteboard.general. The same functions are in kit::clipboard. The shell sends changes made in other apps to your app, and the SDK updates its copy. Images, pasteboard types and named pasteboards are not yet available.
ctx.open_url(url) opens a link. Only http:// and https:// links are accepted, and the desktop must be active. The link opens in a tab of BifrOSt Browser. The call does not report an error to the app.
Workspace
The workspace module opens files and links, shows files in Files, moves files to the Trash, and reports which apps are running (NSWorkspace). Every call takes a closure, and the shell answers it on the main thread.
A file is a document grant, never a path. Get one with ctx.open_document or ctx.save_document. File calls need the documents permission in the manifest. Moving a file to the Trash needs a write grant.
use bifrost_app::workspace;
// Open a file in its default app, then show it in Files.
workspace::open_file(ctx, grant, |opened| println!("opened: {opened}"));
workspace::activate_file_viewer_selecting(ctx, &[grant], |status| println!("{status:?}"));
workspace::open(ctx, url, done)- Opens a web link in the default browser, or a link of another scheme in the app that declares it. Links with
file,javascript,data,blob,vbscriptoraboutschemes are refused. workspace::open_file(ctx, item, done)- Opens a file in the default app for its type, which the user sets in Settings > Default Apps.
workspace::open_with(ctx, items, app_id, done)- Opens files in the installed app
app_id. Services and system packages are refused. workspace::activate_file_viewer_selecting(ctx, items, done)- Shows the folder of the files in Files.
workspace::recycle(ctx, items, done)- Moves files to Recently Deleted, where Put Back in Files restores them.
donegets the status and the number of files moved. workspace::frontmost_application(ctx, done),workspace::running_applications(ctx, done)- Answers with the id of the app in front, or with the ids of the running apps.
workspace::observe(ctx, kind, f) -> ObserverToken- Calls
fwhen an app launches, quits or comes to the front, as chosen bykind. The kinds are inbifrost_app::proto::WorkspaceEventKind. The notification'suser_infoholdsidandname. An app hears only the kinds it observes. workspace::icon_for_content_type(uttype),workspace::icon_for_file(name)- Return the name of a glyph for a type or a file name, not an image.
The shell does not send sleep and wake events yet. Reveal opens one Files window at the folder of the first file, and does not select the files. Opening a file with a built-in app raises the app but does not pass it the file. The icon calls return names, not images. Opening options, such as activating the app or opening a new instance, are not supported.
Login items and menu-bar extras
An app can start at login, and it can put an item with a title and a menu in the menu bar. Register the app with SMAppService::main_app() (SMAppService.mainApp in ServiceManagement). A status item (NSStatusItem) is made with StatusBar::system(). The shell keeps the login items and starts them once per session, when the desktop is up and unlocked. Settings > General > Login Items lists them, and choosing a row removes it.
use bifrost_app::service_management::SMAppService;
use bifrost_app::status_item::{MenuItem, StatusBar, StatusItemLength};
// Once, at launch. The answer arrives in App::login_item_status.
SMAppService::main_app().register(ctx);
let item = StatusBar::system().status_item(StatusItemLength::Variable);
item.set_title(ctx, "Clock");
item.set_menu(ctx, &[MenuItem::new(1, "Show Window"), MenuItem::separator(), MenuItem::new(2, "Quit")]);
// Later: item.remove(ctx);
SMAppService::main_app()- The login item of this app.
register(ctx) -> u32,unregister(ctx) -> u32,refresh(ctx) -> u32- Adds the app to the login items, removes it, or asks the shell for the current status. Each returns a request id, and the answer arrives in
App::login_item_status. status() -> Status- The last status the shell reported:
NotRegistered,Enabled,RequiresApprovalorNotFound. App::login_item_status(ctx, request, status)- Receives the answer to a call, and the status the shell reports at start.
StatusBar::system().status_item(StatusItemLength::Variable)- Adds a status item to the menu bar. Keep the
StatusItemin the app state while it shows. StatusItem::set_title(ctx, title),StatusItem::set_symbol(ctx, symbol),StatusItem::set_visible(ctx, on)- Changes the title, the symbol name, or whether the item shows. Each call sends the whole item.
StatusItem::set_menu(ctx, &[MenuItem])- Sets the menu. A
MenuItemis made withMenuItem::new(id, title), then.enabled(on)and.checked(on), or withMenuItem::separator(). StatusItem::remove(ctx)- Takes the item off the menu bar.
App::status_item_action(ctx, item, id)- The user chose entry
idof the status itemitem.StatusItem::id()gives the id of an item.
Login items cover the app itself only. BifrOSt apps have no embedded helpers, so there are no helper login items, launch agents or daemons. The status never reports RequiresApproval, because there is no approval step. The app cannot open the Login Items page from code. A status item does not draw its symbol yet, so the title shows, or the first letter of the app name when the title is empty. A square length is drawn like a variable one. There are no submenus, key equivalents or custom views, and a click always opens the menu. The user cannot yet reorder or hide a third-party extra. An app holds up to 4 items, a menu holds 32 entries, and titles are cut at 64 characters.
Quick Look
The peek module is the preview panel (QLPreviewPanel). The app gives the panel a list of items, and the user steps through them with the arrow keys. The panel asks for thumbnails through ThumbnailCache, which keeps the rendered images on disk.
use bifrost_app::peek::{PreviewItem, PreviewPanel};
let mut panel = PreviewPanel::new();
panel.set_items(vec![PreviewItem { url: "file:///home/ada/Invoice.pdf".into(), title: "Invoice.pdf".into() }]);
panel.toggle(ctx); // Space shows the panel, or hides it when it is up
PreviewPanel::new()- An empty panel.
set_items(items),load_from(&source)- Sets the items, or reads them from a
PreviewDataSource, which gives a count and the item at an index. toggle(ctx) -> bool- Shows the panel, or hides it when it is up. Returns whether it is now shown.
make_key_and_order_front(ctx),close(ctx)- Shows the panel and makes it the key window, or closes it.
step(delta)- Moves the current item by
deltaplaces. It stops at either end and does not wrap. current_preview_item_index(),set_current_preview_item_index(i)- Reads or sets the current item. The index always stays in range.
reload_data(ctx)- Redraws the panel after the items change.
set_display_state(i, state) -> bool- Sets an item to
ItemState::Loading,ReadyorFailed. peek::thumbnail_path(url, size, scale)- The path of the cached PNG for a thumbnail of
url. ThumbnailCache::new(),best_representation(url, size, scale, generate)- Returns the cached thumbnail when it is on disk. Otherwise it calls
generatewith the path to write, and caches the result whengeneratereturnstrue.
The shell reads the panel's messages but does not draw the panel yet. No app uses the panel yet. The app renders its own thumbnails, and there is no built-in renderer, preview view, transition frame, full-screen mode, or update handler for thumbnails.
Text input
An app that edits text receives composition events from the shell, the way NSTextInputClient and UITextInput do. Override App::text_input(ctx, ev) and forward the events to a TextBuffer or to view::TextField. The events are SetMarkedText, UnmarkText, DeleteSurrounding and AccessoryAction.
Report the editing state so the shell can position the input method and offer predictive text:
- ctx.text_state(TextState { text, cursor, anchor, marked })
- The text around the caret, at most 4000 bytes. Offsets are UTF-8 bytes.
- ctx.caret_rect(x, y, w, h)
- The caret in window points, for the candidate window.
- ctx.input_traits(InputTraits { return_key, content, flags })
- The return key type, the content kind and the
tiflagsflags. - ctx.input_accessory(Vec<AccessoryItem>)
- Up to 8 buttons above the keyboard. An empty list removes them.
The view layer does this for you. view::TextField reports the state, the caret and the traits when they change, and draws marked text underlined.
Not yet available: the on-screen keyboard does not yet send composition, and no candidate window is drawn. Input accessory buttons are stored but not drawn. Other text widgets, secure entry, double-click word selection, attributedSubstring and dictation are not yet available.
Web content
The webview module puts web pages in an app, like WKWebView and WKProcessPool. Pages run in a separate engine process, bifrost-webview, so a crash in a page does not stop the app. One WebProcessPool owns the engine and any number of views, named by WebViewId. The app shows one view in a rectangle of its window.
- WebProcessPool::spawn(engine, profile) -> io::Result<WebProcessPool>
- Starts the engine. Cookies and site data are kept in
profile. - create(url) -> WebViewId / show(id) / close(id)
- Creates a view, shows it, or closes it.
- load(id, url) / go_back(id) / go_forward(id) / reload(id)
- Navigation.
- state(id) -> Option<&WebViewState>
- The title, URL, loading flag, progress and history flags.
- set_frame(x, y, w, h, scale)
- Places the page in the window, in window pixels.
- poll() -> (Vec<WebViewEvent>, bool)
- Call it from
App::tickwhen the engine's file descriptor is ready. It returns the navigation events and whether a frame arrived. - draw(surface) / touch(kind, finger, x, y) / key(&KeyInput)
- Draws the last frame and forwards input.
Events include LoadStarted, LoadCommitted, LoadFinished, TitleChanged, UrlChanged, CreateWebView (a page opened a window) and Closed. A process that stops is reported as ContentProcessTerminated, and EngineExited means every view is gone.
stop_loading does nothing yet, because the engine cannot cancel a load. Hover and text selection by dragging are not yet available.
Dispatch queues
The dispatch module is Grand Central Dispatch. Work goes to a queue, and the system runs it on a shared pool, so an app does not start and poll its own threads. DispatchQueue::global(Qos) is a concurrent queue for background work, DispatchQueue::main() runs closures on the app loop thread, and DispatchQueue::serial(label) runs its closures one at a time, in order. The pool is shared by the whole process. Across all of its QoS lanes, at most one job per core runs at a time, with higher QoS first, so background work cannot take the cores from the UI. Idle workers sleep on a condition variable and exit after 30 seconds, so an idle queue costs nothing.
| Apple | BifrOSt |
|---|---|
DispatchQueue.main | DispatchQueue::main(). Closures run on the app loop, which draws the frame after them. |
DispatchQueue.global(qos:) | DispatchQueue::global(Qos::Utility), concurrent |
DispatchQueue(label:) | DispatchQueue::serial("com.example.store"), or serial_qos(label, qos) |
async, asyncAfter, sync | async_(f), async_after(duration, f), sync(f) returns the value of f |
DispatchGroup | DispatchGroup::enter, leave, notify, wait, and queue.async_group(&group, f) |
DispatchWorkItem | DispatchWorkItem::new, cancel (stops an item that has not started yet), queue.async_item(&item) |
DispatchQoS | Qos::UserInteractive, UserInitiated, Utility, Background |
A closure is FnOnce() + Send + 'static. A panic inside it is caught and logged, and the worker keeps running. A closure on the main queue gets no reference to the app, so it hands its result back through shared state that tick reads.
use bifrost_app::dispatch::{DispatchQueue, Qos};
use std::sync::{Arc, Mutex};
// Before: thread::spawn(...) and a flag polled in App::tick.
// After: the scan runs on the utility lane, and the answer goes back to the loop.
let photos = Arc::new(Mutex::new(None));
let slot = photos.clone();
DispatchQueue::global(Qos::Utility).async_(move || {
let found = scan_photo_library(); // runs on a pool thread
DispatchQueue::main().async_(move || {
*slot.lock().unwrap() = Some(found); // runs on the app loop, which then draws
});
});
// App::tick takes the value from `photos` when it is Some.
Replace a thread::spawn that loops with a serial queue when the work must not interleave, such as one file or one database. Use async_after for a delay or a repeat, and re-queue from the closure. Do not park a thread in thread::sleep. Keep a thread of your own only for a blocking loop that owns a file descriptor, such as an accept loop or a media decoder.
Calling DispatchQueue::main().sync from the main thread panics, and a serial queue that syncs onto itself deadlocks, as in GCD.
Leeway and width
queue.async_after_leeway(delay, leeway, f) runs f at any time between delay and delay + leeway, the counterpart of Timer.tolerance. The shared timer thread wakes at the earliest moment that any pending timer allows, and runs every timer that is due. A leeway lets the system join your wake-up to one that is already planned, so an idle app wakes less often.
The width cap is the one set out above: the pool runs at most one job per core, across all lanes. A lane may keep blocked threads beyond that number, but only the cap runs at once.
Memory pressure
use bifrost_app::dispatch::{DispatchQueue, DispatchSource, MemoryPressure};
// Runs on the app loop. Drop what can be rebuilt when the system is short of memory.
DispatchSource::memory_pressure(&DispatchQueue::main(), |level| {
if level != MemoryPressure::Normal {
// release decoded images, rebuildable caches, ...
}
});
DispatchSource::memory_pressure(&queue, handler)- Calls
handleronqueuewithMemoryPressure::WarningorCriticalwhen the kernel reports a stall, and withNormalafter four quiet seconds. The shell's caches drop memory on the same signal.
The shared watcher reads the kernel's pressure figures. Without them, no event is sent and the handler never runs.
Not yet available: DispatchSource for timers, descriptors and signals (only memory pressure exists), barriers, concurrentPerform, target queues, DispatchSemaphore (use std::sync or a group), QoS inheritance, and cancelling a pressure handler. Priority comes from the lane order and the nice value only.
Host statistics and ProcessInfo
The host statistics are the counters that Activity Monitor and Foundation read: CPU load, memory, processor counts, uptime, thermal state and Low Power Mode.
Each call reads one file from the kernel. There is no sampler thread and no cache, so the app chooses how often to read, as it does with host_statistics64 on macOS. Keep one HostSampler in the app, because the CPU figures are differences between two reads.
| Apple | BifrOSt |
|---|---|
host_statistics64(HOST_CPU_LOAD_INFO) | HostSampler::host_cpu_load_info() |
host_processor_info(PROCESSOR_CPU_LOAD_INFO) | HostSampler::processor_info(), from the same read |
| Activity Monitor CPU % | HostCpuLoadInfo::usage_percent(&before, &after), from 0 to 100 |
host_statistics64(HOST_VM_INFO64) | HostSampler::memory(), with the vm_statistics64 fields |
task_info(TASK_VM_INFO), phys_footprint | HostSampler::task_vm_info() |
os_proc_available_memory() | HostSampler::os_proc_available_memory() |
ProcessInfo.physicalMemory | ProcessInfo::physical_memory() |
processorCount, activeProcessorCount | ProcessInfo::processor_count(), active_processor_count() |
systemUptime | ProcessInfo::system_uptime() |
thermalState | ProcessInfo::thermal_state(), a ThermalState |
thermalStateDidChangeNotification | ProcessInfo::observe_thermal_state(&queue, handler) |
isLowPowerModeEnabled | ProcessInfo::is_low_power_mode_enabled() |
powerStateDidChangeNotification | ProcessInfo::observe_low_power_mode(&queue, handler) |
The thermal state is the worst of the system's temperature sensors: Fair when a zone reaches its passive trip point, Serious at its hot trip point, and Critical within 5 degrees of the critical point.
CPU usage from two samples
The first read only sets the baseline. Take the second read a second later, from a timer on the main queue, not by sleeping:
use bifrost_app::host::{HostCpuLoadInfo, HostSampler};
// Kept in the app state. The first read only sets the baseline.
let mut sampler = HostSampler::new();
let before = sampler.host_cpu_load_info();
// One second later, from a timer on the main queue:
let after = sampler.host_cpu_load_info();
if let (Some(a), Some(b)) = (before, after) {
let busy = HostCpuLoadInfo::usage_percent(&a, &b); // 0.0 to 100.0
println!("CPU {busy:.0} %");
}
The CPU figures cover the whole machine, not one process. Use task_vm_info() for the app's own memory.
Not yet available: energy impact per process, and thermal and Low Power Mode notifications that arrive as events. The observers check every ten seconds. The shell does not yet broadcast them. The memory counters have no purgeable or zero-fill fields, and Active includes file-backed pages.
Purgeable cache
bifrost_app::cache::Cache<K, V> is NSCache: a least-recently-used cache with limits on its count and on its total cost. It gives memory back when the system is short of it. Store large values as Arc<T>, because a hit returns a clone.
Cache::new(count_limit, total_cost_limit)- A new cache. A limit of 0 means no limit.
set(key, value, cost)/get(&key) -> Option<V>- Stores a value with its cost in bytes or any unit. A hit becomes the most recent entry. A value that costs more than the whole limit is dropped at once.
remove(&key)/remove_all()- Removes one value, or all of them.
set_count_limit(n)/set_total_cost_limit(n)- Changes a limit. The cache evicts the oldest values at once to meet it.
purge(fraction)/purge_all(fraction)- Drops that share of the cost, oldest first.
purge_allreaches every cache in the process.
use bifrost_app::cache::Cache;
use std::sync::Arc;
// At most 200 thumbnails, and about 32 MiB of pixels.
let thumbs: Cache<String, Arc<Vec<u8>>> = Cache::new(200, 32 << 20);
thumbs.set(path.clone(), Arc::new(pixels), pixels_len);
if let Some(px) = thumbs.get(&path) {
// draw from px
}
A shared watcher waits for memory pressure, and when it comes every live cache drops half its cost, oldest first. Without the kernel's pressure figures, the cache is an ordinary limited LRU. The shell's glyph and emoji caches use this type.
The kernel reports pressure in windows of two seconds, so the trigger fires about two seconds after the pressure starts. Apple's NSCacheDelegate, discardable content and per-entry priorities are not yet available.