1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! 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.
//!
//! ```toml
//! [dependencies]
//! zng = { version = "0.22.0", features = ["view_prebuilt"] }
//! ```
//!
//! ```no_run
//! 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.
//!
//! ```no_run
//! 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.doc_test_deadline();
//! 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.
//!
//! ```
//! # use zng::var::*;
//! #[expect(non_camel_case_types)]
//! pub struct SCREAMING_CASE;
//! impl SCREAMING_CASE {
//! pub fn state(&self) -> Var<bool> {
//! # var(true)
//! }
//! }
//! ```
//!
//! 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`].
//!
//! [`APP.pause_time_for_update`]: zng_app::APP::pause_time_for_update
//!
//! ### Examples
//!
//! The example below demonstrates a service.
//!
//! ```
//! use zng::prelude_wgt::*;
//! # fn main() {}
//!
//! /// 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.
//! 4. Schedule the app run future to run in the first preview update.
//! 5. Does [updates loop](#updates-loop).
//! 7. Does [main loop](#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`], by default it is set to the monitor refresh
//! rate by the [`WINDOWS`] service.
//! 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](#updates-loop).
//! 5. If the view-process is not busy does a [layout loop and render](#layout-loop-and-render).
//! 6. 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`].
//!
//! #### 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](#var-updates-loop), note that includes events that are also vars.
//! 2. Calls [`UPDATES.on_pre_update`] handlers if needed.
//! * Both [`Event::on_pre_event`] and [`Var::on_pre_new`] are implemented as pre updates too.
//! 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.
//! * Both [`Event::on_event`] and [`Var::on_new`] are implemented as updates too.
//! 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](#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](#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.
//!
//! [`APP.defaults()`]: crate::app::APP::defaults
//! [`APP.on_init`]: crate::app::APP::on_init
//! [`UPDATES.update`]: crate::update::UPDATES::update
//! [`task`]: crate::task
//! [`ResponseVar<R>`]: crate::var::ResponseVar
//! [`TIMERS`]: crate::timer::TIMERS
//! [`VARS`]: crate::var::VARS
//! [`VARS.frame_duration`]: crate::var::VARS::frame_duration
//! [`WINDOWS`]: crate::window::WINDOWS
//! [`WINDOWS.parallel`]: crate::window::WINDOWS::parallel
//! [`parallel`]: fn@crate::widget::parallel
//! [`UPDATES.on_pre_update`]: crate::update::UPDATES::on_pre_update
//! [`UPDATES.on_update`]: crate::update::UPDATES::on_update
//! [`Var::on_pre_new`]: crate::var::VarSubscribe::on_pre_new
//! [`Var::on_new`]: crate::var::VarSubscribe::on_new
//! [`Event::on_pre_event`]: crate::event::Event::on_pre_event
//! [`Event::on_event`]: crate::event::Event::on_event
//! [`WINDOWS.exit_on_last_close`]: crate::window::WINDOWS::exit_on_last_close
//! [`APP.exit`]: crate::app::APP#method.exit
//! [`UPDATES.once_update`]: zng::update::UPDATES::once_update
//!
//! # 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.
pub use ;
pub use test_log;
pub use ;
pub use ;
pub use ;
/// Input device hardware ID and events.
///
/// # Full API
///
/// See [`zng_app::view_process::raw_device_events`] for the full API.
pub use ;
/// App-process crash handler.
///
/// In builds with `"crash_handler"` feature the crash handler takes over the first "app-process" turning it into
/// the monitor-process, it spawns another process that is the monitored app-process. If the app-process crashes
/// the monitor-process spawns a dialog-process that calls the dialog handler to show an error message, upload crash reports, etc.
///
/// The dialog handler can be set using [`crash_handler_config!`].
///
/// [`crash_handler_config!`]: crate::app::crash_handler::crash_handler_config
///
/// # Examples
///
/// The example below demonstrates an app setup to show a custom crash dialog.
///
/// ```no_run
/// use zng::prelude::*;
///
/// fn main() {
/// // tracing applied to all processes.
/// zng::app::print_tracing(tracing::Level::INFO, false, |_| true);
///
/// // monitor-process spawns app-process and if needed dialog-process here.
/// zng::env::init!();
///
/// // app-process:
/// app_main();
/// }
///
/// fn app_main() {
/// APP.defaults().run_window("main", async {
/// Window! {
/// child_align = Align::CENTER;
/// child = Stack! {
/// direction = StackDirection::top_to_bottom();
/// spacing = 5;
/// children = ui_vec![
/// Button! {
/// child = Text!("Crash (panic)");
/// on_click = hn_once!(|_| {
/// panic!("Test panic!");
/// });
/// },
/// Button! {
/// child = Text!("Crash (access violation)");
/// on_click = hn_once!(|_| {
/// // SAFETY: deliberate access violation
/// #[expect(deref_nullptr)]
/// unsafe {
/// *std::ptr::null_mut() = true;
/// }
/// });
/// }
/// ];
/// };
/// }
/// });
/// }
///
/// zng::app::crash_handler::crash_handler_config!(|cfg| {
/// // monitor-process and dialog-process
///
/// cfg.dialog(|args| {
/// // dialog-process
/// APP.defaults().run_window("crash-dialog", async move {
/// Window! {
/// title = "App Crashed!";
/// auto_size = true;
/// min_size = (300, 100);
/// start_position = window::StartPosition::CenterMonitor;
/// on_load = hn_once!(|_| WINDOW.bring_to_top());
/// padding = 10;
/// child_spacing = 10;
/// child = Text!(args.latest().message());
/// child_bottom = Stack! {
/// direction = StackDirection::start_to_end();
/// layout::align = Align::BOTTOM_END;
/// spacing = 5;
/// children = ui_vec![
/// Button! {
/// child = Text!("Restart App");
/// on_click = hn_once!(args, |_| {
/// args.restart();
/// });
/// },
/// Button! {
/// child = Text!("Exit App");
/// on_click = hn_once!(|_| {
/// args.exit(0);
/// });
/// },
/// ];
/// };
/// }
/// });
/// });
/// });
/// ```
///
/// # Debugger
///
/// Note that because the crash handler spawns a different process for the app debuggers will not
/// stop at break points in the app code. You can configure your debugger to set the `NO_ZNG_CRASH_HANDLER` environment
/// variable to not use a crash handler in debug runs.
///
/// On VS Code with the CodeLLDB extension you can add this workspace configuration:
///
/// ```json
/// "lldb.launch.env": {
/// "ZNG_NO_CRASH_HANDLER": ""
/// }
/// ```
///
/// # Full API
///
/// See [`zng_app::crash_handler`] and [`zng_wgt_inspector::crash_handler`] for the full API.
/// Trace recording and data model.
///
/// All tracing instrumentation in Zng projects is done using the `tracing` crate, trace recording is done using the `tracing-chrome` crate.
/// The recorded traces can be viewed in `chrome://tracing` or `ui.perfetto.dev` and can be parsed by the [`Trace`] data model.
///
/// Build the app with `"trace_recorder"` and run it with the `"ZNG_RECORD_TRACE"` env var to record all processes spawned by the app.
///
/// ```no_run
/// use zng::prelude::*;
///
/// fn main() {
/// unsafe {
/// std::env::set_var("ZNG_RECORD_TRACE", "");
/// }
/// unsafe {
/// std::env::set_var("ZNG_RECORD_TRACE_FILTER", "debug");
/// }
///
/// // recording start here for all app processes when ZNG_RECORD_TRACE is set.
/// zng::env::init!();
///
/// // .. app
/// }
/// ```
///
/// The example above hardcodes trace recording for all app processes by setting the `"ZNG_RECORD_TRACE"` environment
/// variable before the `init!()` call. It also sets `"ZNG_RECORD_TRACE_FILTER"` to a slightly less verbose level.
///
/// # Config
///
/// The `"ZNG_RECORD_TRACE_DIR"` variable can be set to define a custom output directory path, relative to the current dir.
/// The default dir is `"./zng-trace/"`.
///
/// The `"ZNG_RECORD_TRACE_FILTER"` or `"RUST_LOG"` variables can be used to set custom tracing filters, see the [filter syntax] for details.
/// The default filter is `"trace"` that records all spans and events.
///
/// # Output
///
/// Raw trace files are saved to `"{ZNG_RECORD_TRACE_DIR}/{timestamp}/{pid}.json"`.
///
/// The timestamp is in microseconds from Unix epoch and is defined by the first process that runs. All processes are
/// recorded to the same *timestamp* folder.
///
/// The process name is defined by an event INFO message that reads `"pid: {pid}, name: {name}"`. See [`zng::env::process_name`] for more details.
///
/// The process record start timestamp is defined by an event INFO message that reads `"zng-record-start: {timestamp}"`. This timestamp is also
/// in microseconds from Unix epoch.
///
/// Fake *threads* can be defined to better track a *task span* by setting a `thread = "<name>"` argument in the span. Both fake threads and process
/// names are converted to real entries by `cargo zng trace`.
///
/// # Cargo Zng
///
/// You can also use the `cargo zng trace` subcommand to record traces, it handles setting the env variables, merges the multi
/// process traces into a single file and properly names the processes for better compatibility with trace viewers.
///
/// ```console
/// cargo zng trace --filter debug "path/my-exe"
/// ```
///
/// You can also run using custom commands after `--`:
///
/// ```console
/// cargo zng trace -- cargo run my-exe
/// ```
///
/// Call `cargo zng trace --help` for more details.
///
/// # Full API
///
/// See [`zng_app::trace_recorder`] for the full API.
///
/// [`Trace`]: zng::app::trace_recorder::Trace
/// [filter syntax]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/index.html#filtering-events-with-environment-variables
/// Heap memory usage profiling.
///
/// Build with debug symbols and `"memory_profiler"` feature to record heap allocations.
///
/// Instrumentation and recording is done with the `dhat` crate. Recorded profiles can be visualized using the
/// [online DHAT Viewer](https://nnethercote.github.io/dh_view/dh_view.html). Stack traces are captured for each significant allocation.
///
/// # Config
///
/// The `"ZNG_MEMORY_PROFILER_DIR"` variable can be set to define a custom output directory path, relative to the current dir.
/// The default dir is `"./zng-dhat/"`.
///
/// # Output
///
/// The recorded data is saved to `"{ZNG_MEMORY_PROFILER_DIR}/{timestamp}/{pname}-{pid}.json"`.
///
/// The timestamp is in microseconds from Unix epoch and is defined by the first process that runs. All processes are recorded
/// to the same *timestamp* folder, even worker processes started later.
///
/// The primary process is named `"app-process"`. See [`zng::env::process_name`] for more details about the default processes.
///
/// # Limitations
///
/// Only heap allocations using the `#[global_allocator]` are captured, some dependencies can skip the allocator, for example, the view-process
/// only traces a fraction of allocations because most of its heap usage comes from the graphics driver.
///
/// Compiling with `"memory_profiler"` feature replaces the global allocator, so if you use a custom allocator you need to setup
/// a feature that disables it, otherwise it will not compile. The instrumented allocator also has an impact in performance so
/// it is only recommended for test builds.
///
/// As an alternative on Unix you can use the external [Valgrind DHAT tool](https://valgrind.org/docs/manual/dh-manual.html).
/// On Windows you can [Record a Heap Snapshot](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/record-heap-snapshot).
///
/// # Full API
///
/// See `zng_app::memory_profiler` for the full API.