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.19.2", 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| {
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,
app::{AppExtended, AppExtension},
};
#[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) -> 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::{app::AppExtension, prelude_wgt::*};
/// Foo service.
pub struct FOO;
impl FOO {
/// Foo read-write var.
pub fn config(&self) -> 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: Var<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)]
#[non_exhaustive]
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::registeris called.- Spawn view-process.
AppExtension::initis 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
TIMERSorVARSanimations 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 that 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 received from 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_eventhandlers. - 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_eventhandlers. - 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::infoif 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_previewif any update was requested. - Calls
UPDATES.on_pre_updatehandlers if needed. - Calls
AppExtension::update_uiif 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::updateif any update was requested. - Calls
UPDATES.on_updatehandlers 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 of 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_eventhandlers. - 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_eventhandlers. - 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 just 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.
- Does update events 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) are rendered 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§
- crash_
handler - App-process crash handler.
- memory_
profiler - Heap memory usage profiling.
- raw_
device_ events - Input device hardware ID and events.
- trace_
recorder - Trace recording and data model.
Macros§
- app_
local - Declares new app local variable.
- context_
local - Declares new app and context local variable.
Structs§
- AppExtended
- Application builder.
- AppExtension
Info - Info about an app-extension.
- AppId
- Identifies an app instance.
- AppInstance
Args - Arguments for
APP_INSTANCE_EVENT. - AppLocal
- An app local storage.
- AppScope
- Represents an app lifetime, ends the app on drop.
- AppStart
Args - Arguments for
on_app_starthandlers. - Context
Local - Represents an
AppLocal<T>value that can be temporarily overridden in a context. - Context
Value Set - Identifies a selection of
LocalContextvalues. - DInstant
- Duration elapsed since an epoch.
- Deadline
- Represents a timeout instant.
- Exit
Requested Args - Arguments for
EXIT_REQUESTED_EVENT. - Headless
App - A headless app controller.
- INSTANT
- Instant service.
- Local
Context - Tracks the current execution context.
- LowMemory
Args - Arguments for
LOW_MEMORY_EVENT. - Mapped
RwLock Read Guard Owned - Represents a read guard for an
Arc<RwLock<T>>that owns a reference to it, mapped from another read guard. - Mapped
RwLock Write Guard Owned - Represents a write guard for an
Arc<RwLock<T>>that owns a reference to it, mapped from another read guard. - Read
Only RwLock - Read-only wrapper on an
Arc<RwLock<T>>contextual value. - RunOn
Drop - Helper, runs a cleanup action once on drop.
- RwLock
Read Guard Owned - Represents a read guard for an
Arc<RwLock<T>>that owns a reference to it. - RwLock
Write Guard Owned - Represents a read guard for an
Arc<RwLock<T>>that owns a reference to it.
Enums§
- AppControl
Flow - Desired next step of app main loop.
- Capture
Filter - Defines a
LocalContext::capture_filteredfilter. - Instant
Mode - Defines how the
INSTANT.nowvalue updates in the app.
Statics§
- APP_
INSTANCE_ EVENT - App instance init event, with the arguments.
- EXIT_
CMD - Represents the app process
exitrequest. - EXIT_
REQUESTED_ EVENT - Cancellable event raised when app process exit is requested.
- LOW_
MEMORY_ EVENT - System low memory warning, some platforms may kill the app if it does not release memory.
- NEW_CMD
- Represents the new action.
- OPEN_
CMD - Represents the open action.
- SAVE_
AS_ CMD - Represents the save-as action.
- SAVE_
CMD - Represents the save action.
Traits§
- AppEvent
Observer - Observer for
HeadlessApp::update_observed. - AppExtension
- An app extension.
Functions§
- can_new
PDefines ifon_newandon_pre_newcommand handles are enabled in the context.- can_
open PDefines ifon_openandon_pre_opencommand handles are enabled in the context.- can_
save PDefines ifon_saveandon_pre_savecommand handles are enabled in the context.- can_
save_ as PDefines ifon_save_asandon_pre_save_ascommand handles are enabled in the context.- on_
app_ start - Register a
handlerto run when anAPPstarts running in the process. - on_new
POn new command.- on_open
POn open command.- on_
pre_ new PPreviewon_newcommand.- on_
pre_ open PPreviewon_opencommand.- on_
pre_ save PPreviewon_savecommand.- on_
pre_ save_ as PPreviewon_save_ascommand.- on_save
POn save command.- on_
save_ as POn save-as command.- print_
tracing - Enables
tracingevents printing if a subscriber is not already set. - print_
tracing_ filter - Filter used by
print_tracing, removes some log noise from dependencies. - spawn_
deadlock_ detection - When compiled with
"deadlock_detection"spawns a thread that monitors forparking_lotdeadlocks. - test_
log - Modifies the
print_tracingsubscriber to panic for error logs in the current app.