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.21.1", 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("id", 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.upgrade() {
// if the app runs with `run_headless(/* with_renderer: */ true)` an image is captured
// and saved here.
img.get().save("screenshot.png").await.ok();
}
// 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 Extensions
Services and events bundles are named app extensions. They are usually implemented in a crate with zng-ext- prefix and a
selection of the API is reexported in the zng crate in a module. Custom services and events can be declared using the same
API the built-in services use, these custom extensions have the same level of access and performance as the built-in extensions.
§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 can use the UPDATES.once_update
method to delegate requests to after the current update pass ends.
This is even true for the INSTANT service, although this can be configured for this service using APP.pause_time_for_update.
§Examples
The example below demonstrates a service.
use zng::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> {
let (responder, response) = response_var();
UPDATES.once_update("FOO.request", move || {
let mut s = FOO_SV.write();
if request == '\n' {
s.state = true;
}
let r = if s.config.get() {
request.to_ascii_uppercase()
} else {
request.to_ascii_lowercase()
};
responder.respond(r);
});
response
}
}
struct FooService {
config: Var<bool>,
state: bool,
}
app_local! {
static FOO_SV: FooService = {
foo_hooks();
FooService {
config: var(false),
state: false,
}
};
}
fn foo_hooks() {
// Event hooks can be setup here
}Note that in the example requests are processed in the UPDATES.once_update update that is called
after all widgets have had a chance to make requests. Requests can also be made from parallel task threads,
that causes the app main loop to wake and immediately process the request.
§Init & Main Loop
A headed app initializes in this sequence once run starts:
- View-process spawns asynchronously.
APP.on_inithandlers are called.- Schedule the app run future to run in the first preview update.
- Does updates 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 level handlers update in the
register order, 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 an updates 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
§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.
- Windows and widgets that requested info (re)build are called.
- Info rebuild happens in parallel by default (between windows and widgets).
- Takes events, vars and other updates requests.
- var updates loop, note that includes events that are also vars.
- Calls
UPDATES.on_pre_updatehandlers if needed.- Both
Event::on_pre_eventandVar::on_pre_neware implemented as pre updates too.
- Both
- Updates windows and widgets, in parallel by default.
- 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
UPDATES.on_updatehandlers if needed.- Both
Event::on_eventandVar::on_neware implemented as updates too.
- Both
- 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.
Note that events are just specialized variables, they update (notify) at the same time as variables modify,
the UPDATES.once_update closure is also called here.
Think of this loop as a staging loop for the main update notifications, it should quickly prepare data that will be immutable during the updates loop, affected hooks all run sequentially and must not block, UI node methods also should never be called inside hooks.
§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.
- 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.
- 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§
- APP
- Start and manage an app process.
- AppBuilder
- Application builder.
- 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.
- 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.
Functions§
- can_new
- Defines if
on_newandon_pre_newcommand handlers are enabled in the widget and descendants. - can_
open - Defines if
on_openandon_pre_opencommand handlers are enabled in the widget and descendants. - can_
save - Defines if
on_saveandon_pre_savecommand handlers are enabled in the widget and descendants. - can_
save_ as - Defines if
on_save_asandon_pre_save_ascommand handlers are enabled in the widget and descendants. - on_new
POn new command.- on_open
POn open command.- on_
pre_ new POn new command.- on_
pre_ open POn open command.- on_
pre_ save POn save command.- on_
pre_ save_ as POn save-as command.- 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.