Module app

Module app 

Source
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:

  1. View-process spawns asynchronously.
  2. APP.on_init handlers are called.
  3. Schedule the app run future to run in the first preview update.
  4. Does updates loop.
  5. 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.

  1. 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 or VARS 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.
  2. Calls elapsed timer handlers.
  3. Calls elapsed animation handlers.
    • These handlers mostly just request var updates that are applied in the updates loop.
  4. Does an updates loop.
  5. If the view-process is not busy does a layout loop and render.
  6. If exit was requested and not cancelled breaks the loop.
§Updates Loop

The updates loop rebuilds info trees if needed, applies pending variable updates and hooks and collects event updates requested by the app.

  1. 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).
  2. Takes events, vars and other updates requests.
    1. var updates loop, note that includes events that are also vars.
    2. Calls UPDATES.on_pre_update handlers if needed.
    3. 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.
    4. Calls UPDATES.on_update handlers if needed.
  3. 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.

  1. Pending variable modifications are applied.
  2. Var hooks are called.
    • The mapping and binding mechanism is implemented using hooks.
  3. 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.

  1. Take layout and render requests.
  2. Layout loop.
    1. Windows and widgets that requested layout update, in parallel by default.
    2. Does an updates loop.
    3. 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.
  3. 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.
AppInstanceArgs
Arguments for APP_INSTANCE_EVENT.
AppLocal
An app local storage.
AppScope
Represents an app lifetime, ends the app on drop.
ContextLocal
Represents an AppLocal<T> value that can be temporarily overridden in a context.
ContextValueSet
Identifies a selection of LocalContext values.
DInstant
Duration elapsed since an epoch.
Deadline
Represents a timeout instant.
ExitRequestedArgs
Arguments for EXIT_REQUESTED_EVENT.
HeadlessApp
A headless app controller.
INSTANT
Instant service.
LocalContext
Tracks the current execution context.
LowMemoryArgs
Arguments for LOW_MEMORY_EVENT.
MappedRwLockReadGuardOwned
Represents a read guard for an Arc<RwLock<T>> that owns a reference to it, mapped from another read guard.
MappedRwLockWriteGuardOwned
Represents a write guard for an Arc<RwLock<T>> that owns a reference to it, mapped from another read guard.
ReadOnlyRwLock
Read-only wrapper on an Arc<RwLock<T>> contextual value.
RunOnDrop
Helper, runs a cleanup action once on drop.
RwLockReadGuardOwned
Represents a read guard for an Arc<RwLock<T>> that owns a reference to it.
RwLockWriteGuardOwned
Represents a read guard for an Arc<RwLock<T>> that owns a reference to it.

Enums§

AppControlFlow
Desired next step of app main loop.
CaptureFilter
Defines a LocalContext::capture_filtered filter.
InstantMode
Defines how the INSTANT.now value updates in the app.

Statics§

APP_INSTANCE_EVENT
App instance init event, with the arguments.
EXIT_CMD
Represents the app process exit request.
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_new and on_pre_new command handlers are enabled in the widget and descendants.
can_open
Defines if on_open and on_pre_open command handlers are enabled in the widget and descendants.
can_save
Defines if on_save and on_pre_save command handlers are enabled in the widget and descendants.
can_save_as
Defines if on_save_as and on_pre_save_as command handlers are enabled in the widget and descendants.
on_new
P On new command.
on_open
P On open command.
on_pre_new
P On new command.
on_pre_open
P On open command.
on_pre_save
P On save command.
on_pre_save_as
P On save-as command.
on_save
P On save command.
on_save_as
P On save-as command.
print_tracing
Enables tracing events 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 for parking_lot deadlocks.
test_log
Modifies the print_tracing subscriber to panic for error logs in the current app.