zng/
app.rs

1//! App extensions, context, events and commands API.
2//!
3//! # Runtime
4//!
5//! A typical app instance has two processes, the initial process called the *app-process*, and a second process called the
6//! *view-process*. The app-process implements the event loop and updates, the view-process implements the platform integration and
7//! renderer, the app-process controls the view-process, most of the time app implementers don't interact directly with it, except
8//! at the start where the view-process is spawned.
9//!
10//! The reason for this dual process architecture is mostly for resilience, the unsafe interactions with the operating system and
11//! graphics driver are isolated in a different process, in case of crashes the view-process is respawned automatically and
12//! 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
13//! and the app main loop in another.
14//!
15//! ## View-Process
16//!
17//! To simplify distribution the view-process is an instance of the same app executable, the view-process crate injects
18//! their own "main" in the [`zng::env::init!`] call, automatically taking over the process if the executable spawns as a view-process.
19//!
20//! On the first instance of the app executable the `init` only inits the env and returns, the app init spawns a second process
21//! marked as the view-process, on this second instance the init call never returns, for this reason the init
22//! must be called early in main, all code before the `init` call runs in both the app and view processes.
23//!
24//! ```toml
25//! [dependencies]
26//! zng = { version = "0.21.1", features = ["view_prebuilt"] }
27//! ```
28//!
29//! ```no_run
30//! use zng::prelude::*;
31//!
32//! fn main() {
33//!     app_and_view();
34//!     zng::env::init!(); // init only returns if it is not called in the view-process.
35//!     app();
36//! }
37//!
38//! fn app_and_view() {
39//!     // code here runs in the app-process and view-process.
40//! }
41//!
42//! fn app() {
43//!     // code here only runs in the app-process.
44//!
45//!     APP.defaults().run(async {
46//!         // ..
47//!     })
48//! }
49//! ```
50//!
51//! ## Same Process
52//!
53//! You can also run the view in the same process, this mode of execution is slightly more efficient, but
54//! your app will not be resilient to crashes caused by the operating system or graphics driver, the app code
55//! will also run in a different thread, not the main.
56//!
57//! ```no_run
58//! use zng::prelude::*;
59//!
60//! fn main() {
61//!     zng::env::init!();
62//!     zng::view_process::prebuilt::run_same_process(app);
63//! }
64//!
65//! fn app() {
66//!     // code here runs in a different thread, the main thread becomes the view.
67//!     APP.defaults().run(async {
68//!         // ..
69//!     })
70//! }
71//! ```
72//!
73//! Note that you must still call `init!` as it also initializes the app metadata and directories.
74//!
75//! # Headless
76//!
77//! The app can also run *headless*, where no window is actually created, optionally with real rendering.
78//! This mode is useful for running integration tests, or for rendering images.
79//!
80//! ```
81//! use zng::prelude::*;
82//!
83//! let mut app = APP.defaults().run_headless(/* with_renderer: */ false);
84//! app.run_window("id", async {
85//!     Window! {
86//!         child = Text!("Some text");
87//!         auto_size = true;
88//!
89//!         render_mode = window::RenderMode::Software;
90//!         frame_capture_mode = window::FrameCaptureMode::Next;
91//!
92//!         on_frame_image_ready = async_hn!(|args| {
93//!             if let Some(img) = args.frame_image.upgrade() {
94//!                 // if the app runs with `run_headless(/* with_renderer: */ true)` an image is captured
95//!                 // and saved here.
96//!                 img.get().save("screenshot.png").await.ok();
97//!             }
98//!
99//!             // close the window, causing the app to exit.
100//!             WINDOW.close();
101//!         });
102//!     }
103//! });
104//! ```
105//!
106//! You can also run multiple headless apps in the same process, one per thread, if the crate is build using the `"multi_app"` feature.
107//!
108//! # App Extensions
109//!
110//! Services and events bundles are named *app extensions*. They are usually implemented in a crate with `zng-ext-` prefix and a
111//! selection of the API is reexported in the `zng` crate in a module. Custom services and events can be declared using the same
112//! API the built-in services use, these custom extensions have the same level of access and performance as the built-in extensions.
113//!
114//! ## Services
115//!
116//! App services are defined by convention, there is no service trait or struct. Proper service implementations follow
117//! these rules:
118//!
119//! #### App services are an unit struct named like a static
120//!
121//! This is because services are a kind of *singleton*. The service API is implemented as methods on the service struct.
122//!
123//! ```
124//! # use zng::var::*;
125//! #[expect(non_camel_case_types)]
126//! pub struct SCREAMING_CASE;
127//! impl SCREAMING_CASE {
128//!     pub fn state(&self) -> Var<bool> {
129//!         # var(true)
130//!     }
131//! }
132//! ```
133//!
134//! Note that you need to suppress a lint if the service name has more then one word.
135//!
136//! Service state and config methods should prefer variables over direct values. The use of variables allows the service state
137//! to be plugged directly into the UI. Async operations should prefer using [`ResponseVar<R>`] over `async` methods for
138//! the same reason.
139//!
140//! #### App services lifetime is the current app lifetime
141//!
142//! Unlike a simple singleton app services must only live for the duration of the app and must support
143//! multiple parallel instances if built with the `"multi_app"` feature. You can use private
144//! [`app_local!`] static variables as backing storage to fulfill this requirement.
145//!
146//! A common pattern in the zng services is to name the app locals with a `_SV` suffix.
147//!
148//! Services do not expose the app local locking, all state output is cloned the state is only locked
149//! for the duration of the service method call.
150//!
151//! #### App services don't change public state mid update
152//!
153//! All widgets using the service during the same update see the same state. State change requests are scheduled
154//! for the next update, just like variable updates or event notifications. Services can use the [`UPDATES.once_update`]
155//! method to delegate requests to after the current update pass ends.
156//!
157//! This is even true for the [`INSTANT`] service, although this can be configured for this service using [`APP.pause_time_for_update`].
158//!
159//! [`APP.pause_time_for_update`]: zng_app::APP::pause_time_for_update
160//!
161//! ### Examples
162//!
163//! The example below demonstrates a service.
164//!
165//! ```
166//! use zng::prelude_wgt::*;
167//! # fn main() {}
168//!
169//! /// Foo service.
170//! pub struct FOO;
171//!
172//! impl FOO {
173//!     /// Foo read-write var.
174//!     pub fn config(&self) -> Var<bool> {
175//!         FOO_SV.read().config.clone()
176//!     }
177//!
178//!     /// Foo request.
179//!     pub fn request(&self, request: char) -> ResponseVar<char> {
180//!         let (responder, response) = response_var();
181//!         UPDATES.once_update("FOO.request", move || {
182//!             let mut s = FOO_SV.write();
183//!             if request == '\n' {
184//!                 s.state = true;
185//!             }
186//!             let r = if s.config.get() {
187//!                 request.to_ascii_uppercase()
188//!             } else {
189//!                 request.to_ascii_lowercase()
190//!             };
191//!             responder.respond(r);
192//!         });
193//!         response
194//!     }
195//! }
196//!
197//! struct FooService {
198//!     config: Var<bool>,
199//!     state: bool,
200//! }
201//!
202//! app_local! {
203//!     static FOO_SV: FooService = {
204//!         foo_hooks();
205//!         FooService {
206//!             config: var(false),
207//!             state: false,
208//!         }
209//!     };
210//! }
211//! fn foo_hooks() {
212//!     // Event hooks can be setup here
213//! }
214//! ```
215//!
216//! Note that in the example requests are processed in the [`UPDATES.once_update`] update that is called
217//! after all widgets have had a chance to make requests. Requests can also be made from parallel [`task`] threads,
218//! that causes the app main loop to wake and immediately process the request.
219//!
220//! # Init & Main Loop
221//!
222//! A headed app initializes in this sequence once run starts:
223//!
224//! 1. View-process spawns asynchronously.
225//! 2. [`APP.on_init`] handlers are called.
226//! 4. Schedule the app run future to run in the first preview update.
227//! 5. Does [updates loop](#updates-loop).
228//! 7. Does [main loop](#main-loop).
229//!
230//! #### Main Loop
231//!
232//! The main loop coordinates view-process events, timers, app events and updates. There is no scheduler, update and event requests
233//! are captured and coalesced to various buffers that are drained in known sequential order. App level handlers update in the
234//! register order, windows and widgets update in parallel by default, this is controlled by [`WINDOWS.parallel`] and [`parallel`].
235//!
236//! 1. Sleep if there are not pending events or updates.
237//!    * If the view-process is busy blocks until it sends a message, this is a mechanism to stop the app-process
238//!      from overwhelming the view-process.
239//!    * Block until a message is received, from the view-process or from other app threads.
240//!    * If there are [`TIMERS`] or [`VARS`] animations the message block has a deadline to the nearest timer or animation frame.
241//!        * Animations have a fixed frame-rate defined in [`VARS.frame_duration`], it is 60 frames-per-second by default.
242//! 2. Calls elapsed timer handlers.
243//! 3. Calls elapsed animation handlers.
244//!     * These handlers mostly just request var updates that are applied in the updates loop.
245//! 4. Does an [updates loop](#updates-loop).
246//! 5. If the view-process is not busy does a [layout loop and render](#layout-loop-and-render).
247//! 6. If exit was requested and not cancelled breaks the loop.
248//!     * Exit is requested automatically when the last open window closes, this is controlled by [`WINDOWS.exit_on_last_close`].
249//!     * Exit can also be requested using [`APP.exit`].
250//!
251//! #### Updates Loop
252//!
253//! The updates loop rebuilds info trees if needed, applies pending variable updates and hooks and collects event updates
254//! requested by the app.
255//!
256//! 1. Takes info rebuild request flag.
257//!     * Windows and widgets that requested info (re)build are called.
258//!     * Info rebuild happens in parallel by default (between windows and widgets).
259//! 2. Takes events, vars and other updates requests.
260//!     1. [var updates loop](#var-updates-loop), note that includes events that are also vars.
261//!     2. Calls [`UPDATES.on_pre_update`] handlers if needed.
262//!         * Both [`Event::on_pre_event`] and [`Var::on_pre_new`] are implemented as pre updates too.
263//!     3. Updates windows and widgets, in parallel by default.
264//!         * Windows and widgets that requested update receive it here.
265//!         * All the pending updates are processed in one pass, all targeted widgets are visited once, in parallel by default.
266//!     4. Calls [`UPDATES.on_update`] handlers if needed.
267//!         * Both [`Event::on_event`] and [`Var::on_new`] are implemented as updates too.
268//! 3. The loop repeats immediately if any info rebuild or update was requested by update callbacks.
269//!     * The loops breaks if it repeats over 1000 times.
270//!     * An error is logged with a trace of the most frequent sources of update requests.
271//!
272//! #### Var Updates Loop
273//!
274//! The variable updates loop applies pending modifications, calls hooks to update variable and bindings.
275//!
276//! 1. Pending variable modifications are applied.
277//! 2. Var hooks are called.
278//!     * The mapping and binding mechanism is implemented using hooks.
279//! 3. The loop repeats until hooks have stopped modifying variables.
280//!     * The loop breaks if it repeats over 1000 times.
281//!     * An error is logged if this happens.
282//!
283//! Note that events are just specialized variables, they update (notify) at the same time as variables modify,
284//! the [`UPDATES.once_update`] closure is also called here.
285//!
286//! Think of this loop as a *staging loop* for the main update notifications, it should quickly prepare data that will
287//! be immutable during the [updates loop](#updates-loop), affected hooks all run sequentially and **must not block**,
288//! UI node methods also should never be called inside hooks.
289//!
290//! #### Layout Loop and Render
291//!
292//! Layout and render requests are coalesced, multiple layout requests for the same widget update it once, multiple
293//! render requests become one frame, and if both `render` and `render_update` are requested for a window it will just fully `render`.
294//!
295//! 1. Take layout and render requests.
296//! 2. Layout loop.
297//!     1. Windows and widgets that requested layout update, in parallel by default.
298//!     2. Does an [updates loop](#updates-loop).
299//!     3. Take layout and render requests, the loop repeats immediately if layout was requested again.
300//!         * The loop breaks if it repeats over 1000 times.
301//!         * An error is logged with a trace the most frequent sources of update requests.
302//! 3. Windows and widgets that requested render (or render_update) are rendered, in parallel by default.
303//!     * The render pass updates widget transforms and hit-test, generates a display list and sends it to the view-process.
304//!
305//! [`APP.defaults()`]: crate::app::APP::defaults
306//! [`APP.on_init`]: crate::app::APP::on_init
307//! [`UPDATES.update`]: crate::update::UPDATES::update
308//! [`task`]: crate::task
309//! [`ResponseVar<R>`]: crate::var::ResponseVar
310//! [`TIMERS`]: crate::timer::TIMERS
311//! [`VARS`]: crate::var::VARS
312//! [`VARS.frame_duration`]: crate::var::VARS::frame_duration
313//! [`WINDOWS.parallel`]: crate::window::WINDOWS::parallel
314//! [`parallel`]: fn@crate::widget::parallel
315//! [`UPDATES.on_pre_update`]: crate::update::UPDATES::on_pre_update
316//! [`UPDATES.on_update`]: crate::update::UPDATES::on_update
317//! [`Var::on_pre_new`]: crate::var::VarSubscribe::on_pre_new
318//! [`Var::on_new`]: crate::var::VarSubscribe::on_new
319//! [`Event::on_pre_event`]: crate::event::Event::on_pre_event
320//! [`Event::on_event`]: crate::event::Event::on_event
321//! [`WINDOWS.exit_on_last_close`]: crate::window::WINDOWS::exit_on_last_close
322//! [`APP.exit`]: crate::app::APP#method.exit
323//! [`UPDATES.once_update`]: zng::update::UPDATES::once_update
324//!
325//! # Full API
326//!
327//! This module provides most of the app API needed to make and extend apps, some more advanced or experimental API
328//! may be available at the [`zng_app`], [`zng_app_context`] and [`zng_ext_single_instance`] base crates.
329
330pub use zng_app::{
331    APP, AppBuilder, AppControlFlow, DInstant, Deadline, EXIT_CMD, EXIT_REQUESTED_EVENT, ExitRequestedArgs, HeadlessApp, INSTANT,
332    InstantMode, print_tracing, print_tracing_filter, spawn_deadlock_detection,
333};
334
335#[cfg(feature = "test_util")]
336pub use zng_app::test_log;
337
338pub use zng_app_context::{
339    AppId, AppLocal, AppScope, CaptureFilter, ContextLocal, ContextValueSet, LocalContext, MappedRwLockReadGuardOwned,
340    MappedRwLockWriteGuardOwned, ReadOnlyRwLock, RunOnDrop, RwLockReadGuardOwned, RwLockWriteGuardOwned, app_local, context_local,
341};
342pub use zng_wgt_input::cmd::{
343    NEW_CMD, OPEN_CMD, SAVE_AS_CMD, SAVE_CMD, can_new, can_open, can_save, can_save_as, on_new, on_open, on_pre_new, on_pre_open,
344    on_pre_save, on_pre_save_as, on_save, on_save_as,
345};
346
347pub use zng_app::view_process::raw_events::{LOW_MEMORY_EVENT, LowMemoryArgs};
348
349/// Input device hardware ID and events.
350///
351/// # Full API
352///
353/// See [`zng_app::view_process::raw_device_events`] for the full API.
354pub mod raw_device_events {
355    pub use zng_app::view_process::raw_device_events::{
356        AXIS_MOTION_EVENT, AxisId, AxisMotionArgs, INPUT_DEVICES, INPUT_DEVICES_CHANGED_EVENT, InputDeviceCapability, InputDeviceId,
357        InputDeviceInfo, InputDevicesChangedArgs,
358    };
359}
360
361#[cfg(single_instance)]
362pub use zng_ext_single_instance::{APP_INSTANCE_EVENT, AppInstanceArgs};
363
364/// App-process crash handler.
365///
366/// In builds with `"crash_handler"` feature the crash handler takes over the first "app-process" turning it into
367/// the monitor-process, it spawns another process that is the monitored app-process. If the app-process crashes
368/// the monitor-process spawns a dialog-process that calls the dialog handler to show an error message, upload crash reports, etc.
369///
370/// The dialog handler can be set using [`crash_handler_config!`].
371///
372/// [`crash_handler_config!`]: crate::app::crash_handler::crash_handler_config
373///
374/// # Examples
375///
376/// The example below demonstrates an app setup to show a custom crash dialog.
377///
378/// ```no_run
379/// use zng::prelude::*;
380///
381/// fn main() {
382///     // tracing applied to all processes.
383///     zng::app::print_tracing(tracing::Level::INFO, false, |_| true);
384///
385///     // monitor-process spawns app-process and if needed dialog-process here.
386///     zng::env::init!();
387///
388///     // app-process:
389///     app_main();
390/// }
391///
392/// fn app_main() {
393///     APP.defaults().run_window("main", async {
394///         Window! {
395///             child_align = Align::CENTER;
396///             child = Stack! {
397///                 direction = StackDirection::top_to_bottom();
398///                 spacing = 5;
399///                 children = ui_vec![
400///                     Button! {
401///                         child = Text!("Crash (panic)");
402///                         on_click = hn_once!(|_| {
403///                             panic!("Test panic!");
404///                         });
405///                     },
406///                     Button! {
407///                         child = Text!("Crash (access violation)");
408///                         on_click = hn_once!(|_| {
409///                             // SAFETY: deliberate access violation
410///                             #[expect(deref_nullptr)]
411///                             unsafe {
412///                                 *std::ptr::null_mut() = true;
413///                             }
414///                         });
415///                     }
416///                 ];
417///             };
418///         }
419///     });
420/// }
421///
422/// zng::app::crash_handler::crash_handler_config!(|cfg| {
423///     // monitor-process and dialog-process
424///
425///     cfg.dialog(|args| {
426///         // dialog-process
427///         APP.defaults().run_window("crash-dialog", async move {
428///             Window! {
429///                 title = "App Crashed!";
430///                 auto_size = true;
431///                 min_size = (300, 100);
432///                 start_position = window::StartPosition::CenterMonitor;
433///                 on_load = hn_once!(|_| WINDOW.bring_to_top());
434///                 padding = 10;
435///                 child_spacing = 10;
436///                 child = Text!(args.latest().message());
437///                 child_bottom = Stack! {
438///                     direction = StackDirection::start_to_end();
439///                     layout::align = Align::BOTTOM_END;
440///                     spacing = 5;
441///                     children = ui_vec![
442///                         Button! {
443///                             child = Text!("Restart App");
444///                             on_click = hn_once!(args, |_| {
445///                                 args.restart();
446///                             });
447///                         },
448///                         Button! {
449///                             child = Text!("Exit App");
450///                             on_click = hn_once!(|_| {
451///                                 args.exit(0);
452///                             });
453///                         },
454///                     ];
455///                 };
456///             }
457///         });
458///     });
459/// });
460/// ```
461///
462/// # Debugger
463///
464/// Note that because the crash handler spawns a different process for the app debuggers will not
465/// stop at break points in the app code. You can configure your debugger to set the `NO_ZNG_CRASH_HANDLER` environment
466/// variable to not use a crash handler in debug runs.
467///
468/// On VS Code with the CodeLLDB extension you can add this workspace configuration:
469///
470/// ```json
471/// "lldb.launch.env": {
472///    "ZNG_NO_CRASH_HANDLER": ""
473/// }
474/// ```
475///
476/// # Full API
477///
478/// See [`zng_app::crash_handler`] and [`zng_wgt_inspector::crash_handler`] for the full API.
479#[cfg(crash_handler)]
480pub mod crash_handler {
481    pub use zng_app::crash_handler::{BacktraceFrame, CrashArgs, CrashConfig, CrashError, CrashPanic, crash_handler_config};
482
483    #[cfg(feature = "crash_handler_debug")]
484    pub use zng_wgt_inspector::crash_handler::debug_dialog;
485
486    crash_handler_config!(|cfg| {
487        cfg.default_dialog(|args| {
488            if let Some(c) = &args.dialog_crash {
489                eprintln!("DEBUG CRASH DIALOG ALSO CRASHED");
490                eprintln!("   {}", c.message());
491                eprintln!("ORIGINAL APP CRASH");
492                eprintln!("   {}", args.latest().message());
493                args.exit(0xBADC0DE)
494            } else {
495                #[cfg(feature = "crash_handler_debug")]
496                {
497                    use crate::prelude::*;
498                    APP.defaults().run_window(
499                        "debug-crash-dialog",
500                        async_clmv!(args, { zng_wgt_inspector::crash_handler::debug_dialog(args) }),
501                    );
502                }
503
504                #[cfg(not(feature = "crash_handler_debug"))]
505                {
506                    eprintln!(
507                        "app crashed {}\n\nbuild with feature = \"crash_handler_debug\" to se the debug crash dialog",
508                        args.latest().message()
509                    );
510                }
511            }
512            args.exit(0)
513        });
514    });
515}
516
517/// Trace recording and data model.
518///
519/// All tracing instrumentation in Zng projects is done using the `tracing` crate, trace recording is done using the `tracing-chrome` crate.
520/// The recorded traces can be viewed in `chrome://tracing` or `ui.perfetto.dev` and can be parsed by the [`Trace`] data model.
521///
522/// Build the app with `"trace_recorder"` and run the with the `"ZNG_RECORD_TRACE"` env var set to record all other processes spawned by the app.
523///
524/// ```no_run
525/// use zng::prelude::*;
526///
527/// fn main() {
528///     unsafe {
529///         std::env::set_var("ZNG_RECORD_TRACE", "");
530///     }
531///     unsafe {
532///         std::env::set_var("ZNG_RECORD_TRACE_FILTER", "debug");
533///     }
534///
535///     // recording start here for all app processes when ZNG_RECORD_TRACE is set.
536///     zng::env::init!();
537///
538///     // .. app
539/// }
540/// ```
541///
542/// The example above hardcodes trace recording for all app processes by setting the `"ZNG_RECORD_TRACE"` environment
543/// variable before the `init!()` call. It also sets `"ZNG_RECORD_TRACE_FILTER"` to a slightly less verbose level.
544///
545/// # Config
546///
547/// The `"ZNG_RECORD_TRACE_DIR"` variable can be set to define a custom output directory path, relative to the current dir.
548/// The default dir is `"./zng-trace/"`.
549///
550/// The `"ZNG_RECORD_TRACE_FILTER"` or `"RUST_LOG"` variables can be used to set custom tracing filters, see the [filter syntax] for details.
551/// The default filter is `"trace"` that records all spans and events.
552///
553/// # Output
554///
555/// Raw trace files are saved to `"{ZNG_RECORD_TRACE_DIR}/{timestamp}/{pid}.json"`.
556///
557/// The timestamp is in microseconds from Unix epoch and is defined by the first process that runs. All processes are
558/// recorded to the same *timestamp* folder.
559///
560/// The process name is defined by an event INFO message that reads `"pid: {pid}, name: {name}"`. See [`zng::env::process_name`] for more details.
561///
562/// The process record start timestamp is defined by an event INFO message that reads `"zng-record-start: {timestamp}"`. This timestamp is also
563/// in microseconds from Unix epoch.
564///
565/// # Cargo Zng
566///
567/// You can also use the `cargo zng trace` subcommand to record traces, it handles setting the env variables, merges the multi
568/// process traces into a single file and properly names the processes for better compatibility with trace viewers.
569///
570/// ```console
571/// cargo zng trace --filter debug "path/my-exe"
572/// ```
573///
574/// You can also run using custom commands after `--`:
575///
576/// ```console
577/// cargo zng trace -- cargo run my-exe
578/// ```
579///
580/// Call `cargo zng trace --help` for more details.
581///
582/// # Full API
583///
584/// See [`zng_app::trace_recorder`] for the full API.
585///
586/// [`Trace`]: zng::app::trace_recorder::Trace
587/// [filter syntax]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/index.html#filtering-events-with-environment-variables
588#[cfg(trace_recorder)]
589pub mod trace_recorder {
590    pub use zng_app::trace_recorder::{EventTrace, ProcessTrace, ThreadTrace, Trace, stop_recording};
591}
592
593/// Heap memory usage profiling.
594///
595/// Build with debug symbols and `"memory_profiler"` feature to record heap allocations.
596///
597/// Instrumentation and recording is done with the `dhat` crate. Recorded profiles can be visualized using the
598/// [online DHAT Viewer](https://nnethercote.github.io/dh_view/dh_view.html). Stack traces are captured for each significant allocation.
599///
600/// # Config
601///
602/// The `"ZNG_MEMORY_PROFILER_DIR"` variable can be set to define a custom output directory path, relative to the current dir.
603/// The default dir is `"./zng-dhat/"`.
604///
605/// # Output
606///
607/// The recorded data is saved to `"{ZNG_MEMORY_PROFILER_DIR}/{timestamp}/{pname}-{pid}.json"`.
608///
609/// The timestamp is in microseconds from Unix epoch and is defined by the first process that runs. All processes are recorded
610/// to the same *timestamp* folder, even worker processes started later.
611///
612/// The primary process is named `"app-process"`. See [`zng::env::process_name`] for more details about the default processes.
613///
614/// # Limitations
615///
616/// Only heap allocations using the `#[global_allocator]` are captured, some dependencies can skip the allocator, for example, the view-process
617/// only traces a fraction of allocations because most of its heap usage comes from the graphics driver.
618///
619/// Compiling with `"memory_profiler"` feature replaces the global allocator, so if you use a custom allocator you need to setup
620/// a feature that disables it, otherwise it will not compile. The instrumented allocator also has an impact in performance so
621/// it is only recommended for test builds.
622///
623/// As an alternative on Unix you can use the external [Valgrind DHAT tool](https://valgrind.org/docs/manual/dh-manual.html).
624/// On Windows you can [Record a Heap Snapshot](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/record-heap-snapshot).
625///
626/// # Full API
627///
628/// See [`zng_app::memory_profiler`] for the full API.
629#[cfg(memory_profiler)]
630pub mod memory_profiler {
631    pub use zng_app::memory_profiler::stop_recording;
632}