Expand description
App extensions, context, events and commands API.
§Runtime
A typical app instance has two processes, the initial process called the app-process, and a second process called the view-process. The app-process implements the event loop and updates, the view-process implements the platform integration and renderer, the app-process controls the view-process, most of the time app implementers don’t interact directly with it, except at the start where the view-process is spawned.
The reason for this dual process architecture is mostly for resilience, the unsafe interactions with the operating system and graphics driver are isolated in a different process, in case of crashes the view-process is respawned automatically and all windows are recreated. It is possible to run the app in a single process, in this case the view runs in the main thread and the app main loop in another.
§View-Process
To simplify distribution the view-process is an instance of the same app executable, the view-process crate injects
their own “main” in the zng::env::init!
call, automatically taking over the process if the executable spawns as a view-process.
On the first instance of the app executable the init
only inits the env and returns, the app init spawns a second process
marked as the view-process, on this second instance the init call never returns, for this reason the init
must be called early in main, all code before the init
call runs in both the app and view processes.
[dependencies]
zng = { version = "0.13.0", features = ["view_prebuilt"] }
use zng::prelude::*;
fn main() {
app_and_view();
zng::env::init!(); // init only returns if it is not called in the view-process.
app();
}
fn app_and_view() {
// code here runs in the app-process and view-process.
}
fn app() {
// code here only runs in the app-process.
APP.defaults().run(async {
// ..
})
}
§Same Process
You can also run the view in the same process, this mode of execution is slightly more efficient, but your app will not be resilient to crashes caused by the operating system or graphics driver, the app code will also run in a different thread, not the main.
use zng::prelude::*;
fn main() {
zng::env::init!();
zng::view_process::prebuilt::run_same_process(app);
}
fn app() {
// code here runs in a different thread, the main thread becomes the view.
APP.defaults().run(async {
// ..
})
}
Note that you must still call init!
as it also initializes the app metadata and directories.
§Headless
The app can also run headless, where no window is actually created, optionally with real rendering. This mode is useful for running integration tests, or for rendering images.
use zng::prelude::*;
let mut app = APP.defaults().run_headless(/* with_renderer: */ false);
app.run_window(async {
Window! {
child = Text!("Some text");
auto_size = true;
render_mode = window::RenderMode::Software;
frame_capture_mode = window::FrameCaptureMode::Next;
on_frame_image_ready = async_hn!(|args: window::FrameImageReadyArgs| {
if let Some(img) = args.frame_image {
// if the app runs with `run_headless(/* with_renderer: */ true)` an image is captured
// and saved here.
img.save("screenshot.png").await.unwrap();
}
// close the window, causing the app to exit.
WINDOW.close();
});
}
});
You can also run multiple headless apps in the same process, one per thread, if the crate is build using the "multi_app"
feature.
§App Extension
Apps can be extended to provide new services and events, in fact all default services and events are implemented as extensions
loaded by APP.defaults()
. The app extension API is AppExtension
. Usually extensions are named with suffix Manager
, but
that is not a requirement.
use zng::{app::{AppExtended, AppExtension}, APP};
#[derive(Default)]
pub struct HelloManager {}
impl AppExtension for HelloManager {
fn init(&mut self) {
println!("Hello init!");
}
fn update_preview(&mut self) {
println!("Hello before UI!");
}
fn update(&mut self) {
println!("Hello after UI!");
}
}
pub fn app() -> AppExtended<impl AppExtension> {
APP.defaults().extend(HelloManager::default())
}
§Services
App services are defined by convention, there is no service trait or struct. Proper service implementations follow these rules:
§App services are an unit struct named like a static
This is because services are a kind of singleton. The service API is implemented as methods on the service struct.
#[expect(non_camel_case_types)]
pub struct SCREAMING_CASE;
impl SCREAMING_CASE {
pub fn state(&self) -> impl Var<bool> {
}
}
Note that you need to suppress a lint if the service name has more then one word.
Service state and config methods should prefer variables over direct values. The use of variables allows the service state
to be plugged directly into the UI. Async operations should prefer using ResponseVar<R>
over async
methods for
the same reason.
§App services lifetime is the current app lifetime
Unlike a simple singleton app services must only live for the duration of the app and must support
multiple parallel instances if built with the "multi_app"
feature. You can use private
app_local!
static variables as backing storage to fulfill this requirement.
A common pattern in the zng services is to name the app locals with a _SV
suffix.
Services do not expose the app local locking, all state output is cloned the state is only locked for the duration of the service method call.
§App services don’t change public state mid update
All widgets using the service during the same update see the same state. State change requests are scheduled
for the next update, just like variable updates or event notifications. Services also request
an UPDATES.update
after scheduling to wake-up the app in case the service request was made from a task
thread.
This is even true for the INSTANT
service, although this can be configured for this service using APP.pause_time_for_update
.
§Examples
Fulfilling service requests is where the AppExtension
comes in, it is possible to declare a simple standalone
service using only variables, Event::on_event
and UPDATES.run_hn_once
, but an app extension is more efficient
and more easy to implement.
If the service request can fail or be delayed it is common for the request method to return a ResponseVar<R>
that is updated once the request is finished. You can also make the method async
, but a response var is superior
because it can be plugged directly into any UI property, and it can still be awaited using the variable async methods.
If the service request cannot fail and it is guaranteed to affect an observable change in the service state in the next update a response var is not needed.
The example below demonstrates an app extension implementation that provides a service.
use zng::{prelude_wgt::*, app::AppExtension};
/// Foo service.
pub struct FOO;
impl FOO {
/// Foo read-write var.
pub fn config(&self) -> impl Var<bool> {
FOO_SV.read().config.clone()
}
/// Foo request.
pub fn request(&self, request: char) -> ResponseVar<char> {
UPDATES.update(None);
let mut foo = FOO_SV.write();
let (responder, response) = response_var();
foo.requests.push((request, responder));
response
}
}
struct FooService {
config: ArcVar<bool>,
requests: Vec<(char, ResponderVar<char>)>,
}
app_local! {
static FOO_SV: FooService = FooService { config: var(false), requests: vec![] };
}
/// Foo app extension.
///
/// # Services
///
/// Services provided by this extension.
///
/// * [`FOO`]
#[derive(Default)]
pub struct FooManager { }
impl AppExtension for FooManager {
fn update(&mut self) {
let mut foo = FOO_SV.write();
if let Some(cfg) = foo.config.get_new() {
println!("foo cfg={cfg}");
}
for (request, responder) in foo.requests.drain(..) {
println!("foo request {request:?}");
responder.respond(request);
}
}
}
Note that in the example requests are processed in the AppExtension::update
update that is called
after all widgets have had a chance to make requests. Requests can also be made from parallel task
threads so
the service also requests an UPDATES.update
just in case there is no update running. If you expect to receive many
requests from parallel tasks you can also process requests in the AppExtension::update
instead, but there is probably
little practical difference.
§Init & Main Loop
A headed app initializes in this sequence:
AppExtension::register
is called.AppExtension::enable_device_events
is queried.- Spawn view-process.
AppExtension::init
is called.- Schedule the app run future to run in the first preview update.
- Does updates loop.
- Does update events loop.
- Does main loop.
§Main Loop
The main loop coordinates view-process events, timers, app events and updates. There is no scheduler, update and event requests
are captured and coalesced to various buffers that are drained in known sequential order. App extensions update one at a time
in the order they are registered. Windows and widgets update in parallel by default, this is controlled by WINDOWS.parallel
and parallel
.
- Sleep if there are not pending events or updates.
- If the view-process is busy blocks until it sends a message, this is a mechanism to stop the app-process from overwhelming the view-process.
- Block until a message is received, from the view-process or from other app threads.
- If there are
TIMERS
orVARS
animations the message block has a deadline to the nearest timer or animation frame.- Animations have a fixed frame-rate defined in
VARS.frame_duration
, it is 60 frames-per-second by default.
- Animations have a fixed frame-rate defined in
- Calls elapsed timer handlers.
- Calls elapsed animation handlers.
- These handlers mostly just request var updates are applied in the updates loop.
- Does a view events loop.
- Does an updates loop.
- Does an update events loop.
- If the view-process is not busy does a layout loop and render.
- If exit was requested and not cancelled breaks the loop.
- Exit is requested automatically when the last open window closes, this is controlled by
WINDOWS.exit_on_last_close
. - Exit can also be requested using
APP.exit
.
- Exit is requested automatically when the last open window closes, this is controlled by
§View Events Loop
All pending events send by the view-process are coalesced and notify sequentially.
- For each event in the received order (FIFO) that converts to a RAW event.
- Calls
AppExtension::event_preview
. - Calls
Event::on_pre_event
handlers. - Calls
AppExtension::event_ui
.- Raw events don’t target any widget, but widgets can subscribe, subscribers receive the event in parallel by default.
- Calls
AppExtension::event
. - Calls
Event::on_event
handlers. - Does an updates loop.
- Calls
- Frame rendered raw event.
- Same notification sequence as other view-events, just delayed.
§Updates Loop
The updates loop rebuilds info trees if needed , applies pending variable updates and hooks and collects event updates requested by the app.
- Takes info rebuild request flag.
- Calls
AppExtension::info
if needed. - Windows and widgets that requested info (re)build are called.
- Info rebuild happens in parallel by default.
- Calls
- Takes events and updates requests.
- Event hooks are called for new event requests.
- Full event notification is delayed to after the updates loop.
- var updates loop
- Calls
AppExtension::update_preview
if any update was requested. - Calls
UPDATES.on_pre_update
handlers if needed. - Calls
AppExtension::update_ui
if any update was requested.- Windows and widgets that requested update receive it here.
- All the pending updates are processed in one pass, all targeted widgets are visited once, in parallel by default.
- Calls
AppExtension::update
if any update was requested. - Calls
UPDATES.on_update
handlers if needed.
- Event hooks are called for new event requests.
- The loop repeats immediately if any info rebuild or update was requested by update callbacks.
- The loops breaks if it repeats over 1000 times.
- An error is logged with a trace the most frequent sources of update requests.
§Var Updates Loop
The variable updates loop applies pending modifications, calls hooks to update variable and bindings.
- Pending variable modifications are applied.
- Var hooks are called.
- The mapping and binding mechanism is implemented using hooks.
- The loop repeats until hooks have stopped modifying variables.
- The loop breaks if it repeats over 1000 times.
- An error is logged if this happens.
§Update Events Loop
The update events loop notifies each event raised by the app code during previous updates.
- For each event in the request order (FIFO).
- Calls
AppExtension::event_preview
. - Calls
Event::on_pre_event
handlers. - Calls
AppExtension::event_ui
.- Windows and widgets targeted by the event update receive it here.
- If the event targets multiple widgets they receive it in parallel by default.
- Calls
AppExtension::event
. - Calls
Event::on_event
handlers. - Does an updates loop.
- Calls
§Layout Loop and Render
Layout and render requests are coalesced, multiple layout requests for the same widget update it once, multiple render requests become one frame, and if both render and render_update are requested for a window it will fully render.
- Take layout and render requests.
- Layout loop.
- Calls
AppExtension::layout
.- Windows and widgets that requested layout update in parallel by default.
- Does an updates loop.
- Take layout and render requests, the loop repeats immediately if layout was requested again.
- The loop breaks if it repeats over 1000 times.
- An error is logged with a trace the most frequent sources of update requests.
- Calls
- If render was requested, calls
AppExtension::render
.- Windows and widgets that requested render (or render_update) do know in parallel by default.
- The render pass updates widget transforms and hit-test, generates a display list and sends it to the view-process.
§Full API
This module provides most of the app API needed to make and extend apps, some more advanced or experimental API
may be available at the zng_app
, zng_app_context
and zng_ext_single_instance
base crates.
Modules§
- App-process crash handler.
- Input device hardware ID and events.
Macros§
- Declares new app local variable.
- Declares new app and context local variable.
Structs§
- Application builder.
- Info about an app-extension.
- Identifies an app instance.
- Arguments for
APP_INSTANCE_EVENT
. - An app local storage.
- Represents an app lifetime, ends the app on drop.
- Arguments for
on_app_start
handlers. - Represents an
AppLocal<T>
value that can be temporarily overridden in a context. - Identifies a selection of
LocalContext
values. - Duration elapsed since an epoch.
- Represents a timeout instant.
- Arguments for
EXIT_REQUESTED_EVENT
. - A headless app controller.
- Instant service.
- Tracks the current execution context.
- Arguments for
LOW_MEMORY_EVENT
. - Represents a read guard for an
Arc<RwLock<T>>
that owns a reference to it, mapped from another read guard. - Represents a write guard for an
Arc<RwLock<T>>
that owns a reference to it, mapped from another read guard. - Read-only wrapper on an
Arc<RwLock<T>>
contextual value. - Helper, runs a cleanup action once on drop.
- Represents a read guard for an
Arc<RwLock<T>>
that owns a reference to it. - Represents a read guard for an
Arc<RwLock<T>>
that owns a reference to it.
Enums§
- Desired next step of app main loop.
- Defines a
LocalContext::capture_filtered
filter. - Defines how the
INSTANT.now
value updates in the app.
Statics§
- App instance init event, with the arguments.
- Represents the app process
exit
request. - Cancellable event raised when app process exit is requested.
- System low memory warning, some platforms may kill the app if it does not release memory.
- Represents the new action.
- Represents the open action.
- Represents the save-as action.
- Represents the save action.
Traits§
- Observer for
HeadlessApp::update_observed
. - An app extension.
Functions§
- Register a
handler
to run when anAPP
starts running in the process. P
On new command.P
On open command.P
Previewon_new
command.P
Previewon_open
command.P
Previewon_save
command.P
Previewon_save_as
command.P
On save command.P
On save-as command.- Enables
tracing
events printing if a subscriber is not already set. - Filter used by
print_tracing
, removes some log noise from dependencies. - Modifies the
print_tracing
subscriber to panic for error logs in the current app.