zng/lib.rs
1#![expect(clippy::needless_doctest_main)]
2#![doc(html_favicon_url = "https://zng-ui.github.io/res/zng-logo-icon.png")]
3#![doc(html_logo_url = "https://zng-ui.github.io/res/zng-logo.png")]
4
5//! Zng is a cross-platform GUI framework, it provides ready made highly customizable widgets, responsive layout,
6//! live data binding, easy localization, automatic focus navigation and accessibility, async and multi-threaded tasks, robust
7//! multi-process architecture and more.
8//!
9//! Zng is pronounced "zing", or as an initialism: ZNG (Z Nesting Graphics).
10//!
11//! Every component of the framework can be extended, you can create new widgets or add properties to existing ones,
12//! at a lower level you can introduce new events and services, seamless integrating custom hardware.
13//!
14//! # Usage
15//!
16//! First add this to your `Cargo.toml`:
17//!
18//! ```toml
19//! [dependencies]
20//! zng = { version = "0.21.1", features = ["view_prebuilt"] }
21//! ```
22//!
23//! Then create your first app:
24//!
25//! ```no_run
26//! use zng::prelude::*;
27//!
28//! fn main() {
29//! zng::env::init!();
30//! app();
31//! }
32//!
33//! fn app() {
34//! APP.defaults().run_window("main", async {
35//! Window! {
36//! child_align = Align::CENTER;
37//! child = {
38//! let size = var(28i32);
39//! Button! {
40//! child = Text! {
41//! txt = "Hello World!";
42//!
43//! #[easing(200.ms())]
44//! font_size = size.map_into();
45//! };
46//! on_click = hn!(|_| {
47//! let next = size.get() + 10;
48//! size.set(if next > 80 { 28 } else { next });
49//! });
50//! }
51//! };
52//! }
53//! })
54//! }
55//! ```
56//!
57//! You can also use a [prebuild view](app#prebuild) and run in the [same process](app#same-process), see [`app`] for more details.
58//!
59//! # Widgets & Properties
60//!
61//! The high-level building blocks of UI.
62//!
63//! ```
64//! use zng::prelude::*;
65//!
66//! # fn example() {
67//! # let _ =
68//! Button! {
69//! child = Text!("Green?");
70//! widget::background_color = colors::GREEN;
71//! on_click = hn!(|_| println!("SUPER GREEN!"));
72//! }
73//! # ; }
74//! ```
75//!
76//! In the example above [`Button!`] and [`Text!`] are widgets and `child`, [`background_color`] and [`on_click`] are properties.
77//! Widgets are mostly an aggregation of properties that define an specific function and presentation, most properties are standalone
78//! implementations of an specific behavior or appearance, in the example only `child` is implemented by the button widget, the
79//! other two properties can be set in any widget.
80//!
81//! Each widget is a dual macro and `struct` of the same name, in the documentation only the `struct` is visible, when
82//! an struct represents a widget it is tagged with <strong><code>W</code></strong>. Each properties is declared as a function,
83//! in the documentation property functions are tagged with <strong><code>P</code></strong>.
84//!
85//! Widget instances can be of any type, usually they are an opaque [`UiNode`] or a type that is [`IntoUiNode`],
86//! some special widgets have non node instance type, the [`Window!`] widget for example has the instance type [`WindowRoot`].
87//! Property instances are always of type [`UiNode`], each property function takes an `impl IntoUiNode` input plus one or more value
88//! inputs and returns an `UiNode` output that wraps the input node adding the property behavior, the widgets take care of this
89//! node chaining nesting each property instance in the proper order, internally every widget instance is a tree of nested node instances.
90//!
91//! Widgets and properties are very versatile and extendable, widget docs will promote properties that are explicitly associated
92//! with the widget type, but that is only a starting point, many other standalone properties can be set in any widget.
93//!
94//! ```
95//! use zng::prelude::*;
96//!
97//! # let _app = APP.minimal();
98//! # let _ =
99//! Wgt! {
100//! layout::align = layout::Align::CENTER;
101//! layout::size = 50;
102//!
103//! #[easing(200.ms())]
104//! widget::background_color = colors::RED;
105//!
106//! when *#gesture::is_hovered {
107//! widget::background_color = colors::GREEN;
108//! }
109//! }
110//! # ;
111//! ```
112//!
113//! In the example above an [`Wgt!`] is completely defined by stand-alone properties, [`align`] and [`size`] define
114//! the layout bounds of the widget, [`background_color`] fills the bounds with color and [`is_hovered`] reacts to pointer interaction.
115//!
116//! The example also introduces [`when`] blocks, [state properties] and the [`easing`] property attribute. State properties
117//! compute an state from the widget, this state can be used to change the value of other properties. When blocks are a powerful
118//! feature of widgets, they declare conditional property values. The easing attribute can be set in any property with transitionable
119//! values to smoothly animate between changes.
120//!
121//! The [`widget`](mod@widget) module documentation provides an in-depth explanation of how widgets and properties work.
122//!
123//! [`Button!`]: struct@button::Button
124//! [`Window!`]: struct@window::Window
125//! [`Text!`]: struct@text::Text
126//! [`Wgt!`]: struct@widget::Wgt
127//! [`background_color`]: fn@widget::background_color
128//! [`on_click`]: fn@gesture::on_click
129//! [`is_hovered`]: fn@gesture::is_hovered
130//! [`align`]: fn@layout::align
131//! [`size`]: fn@layout::size
132//! [`when`]: widget#when
133//! [state properties]: widget#state-properties
134//! [`easing`]: widget::easing
135//! [`UiNode`]: widget::node::UiNode
136//! [`IntoUiNode`]: widget::node::IntoUiNode
137//! [`WindowRoot`]: window::WindowRoot
138//!
139//! # Variables
140//!
141//! Observable values that glue most of the UI together.
142//!
143//! ```
144//! use zng::prelude::*;
145//!
146//! # let _app = APP.minimal();
147//! let btn_pressed = var(false);
148//!
149//! # let _ =
150//! Stack! {
151//! direction = StackDirection::top_to_bottom();
152//! spacing = 10;
153//! children = ui_vec![
154//! Button! {
155//! child = Text! {
156//! txt = "Press Me!";
157//! };
158//! gesture::is_pressed = btn_pressed.clone();
159//! },
160//! Text! {
161//! txt = btn_pressed.map(|&b| if b { "Button is pressed!" } else { "Button is not pressed." }.into());
162//! }
163//! ];
164//! }
165//! # ;
166//! ```
167//!
168//! The example above binds the pressed state of a widget with the text content of another using a [`var`]. Variables
169//! are the most common property input kind, in the example `direction`, `spacing`, `is_pressed` and `txt` all accept
170//! an [`IntoVar<T>`] input that gets converted into a [`Var<T>`] when the property is instantiated.
171//!
172//! There are multiple variable kinds, they can be a simple constant value, a shared observable and modifiable value or a
173//! contextual value. Variables can also depend on other variables automatically updating when input variables update.
174//!
175//! ```
176//! use zng::prelude::*;
177//!
178//! # let _app = APP.minimal();
179//! fn ui(txt: impl IntoVar<Txt>) -> UiNode {
180//! Text!(txt)
181//! }
182//!
183//! ui("const value");
184//!
185//! let txt = var(Txt::from("dynamic value"));
186//! ui(txt.clone());
187//! txt.set("change applied next update");
188//!
189//! let show_txt = var(true);
190//! ui(expr_var!(if *#{show_txt} { #{txt}.clone() } else { Txt::from("") }));
191//!
192//! ui(text::FONT_COLOR_VAR.map(|s| formatx!("font color is {s}")));
193//! ```
194//!
195//! In the example a [`var`] clone is shared with the UI and a new value is scheduled for the next app update. Variable
196//! updates are batched, during each app update pass every property can observe the current value and schedule modifications to
197//! the value, the modifications are only applied after, potentially causing a new update pass if any value actually changed, see
198//! [var updates] in the [var module] documentation for more details.
199//!
200//! The example also demonstrates the [`expr_var!`], a read-only observable variable that interpolates other variables, the
201//! value of this variable automatically update when any of the interpolated variables update.
202//!
203//! And finally the example demonstrates a context var, `FONT_COLOR_VAR`. Context variables get their value from the
204//! *environment* where they are used, the UI in the example can show a different text depending on where it is placed.
205//! Context variables are usually encapsulated by properties strongly associated with a widget, most of [`Text!`] properties just
206//! set a context var that affects all text instances in the widget they are placed and descendant widgets.
207//!
208//! There are other useful variable kinds, see the [var module] module documentation for more details.
209//!
210//! [`var`]: var::var
211//! [`expr_var!`]: var::expr_var
212//! [var module]: crate::var
213//! [`IntoVar<T>`]: var::IntoVar
214//! [`Var<T>`]: var::Var
215//!
216//! # Context
217//!
218//! Context or *ambient* values set on parent widgets affecting descendant widgets.
219//!
220//! ```
221//! use zng::prelude::*;
222//!
223//! # let _app = APP.minimal();
224//! # let _ =
225//! Stack! {
226//! direction = StackDirection::top_to_bottom();
227//! spacing = 10;
228//!
229//! text::font_color = colors::RED;
230//!
231//! children = ui_vec![
232//! Button! {
233//! child = Text!("Text 1");
234//! },
235//! Button! {
236//! child = Text!("Text 2");
237//! },
238//! Button! {
239//! child = Text!("Text 3");
240//! text::font_color = colors::GREEN;
241//! },
242//! ];
243//! }
244//! # ;
245//! ```
246//!
247//! In the example above "Text 1" and "Text 2" are rendered in red and "Text 3" is rendered in green. The context
248//! of a widget is important, `text::font_color` sets text color in the `Stack!` widget and all descendant widgets,
249//! the color is overridden in the third `Button!` for the context of that button and descendants, the `Text!`
250//! widget has a different appearance just by being in a different context.
251//!
252//! Note that the text widget can also set the color directly, in the following example the "Text 4" is blue, this
253//! value is still contextual, but texts are usually leaf widgets so only the text is affected.
254//!
255//! ```
256//! # use zng::prelude::*;
257//! # let _app = APP.minimal();
258//! # let _ =
259//! Text! {
260//! txt = "Text 4";
261//! font_color = colors::BLUE;
262//! }
263//! # ;
264//! ```
265//!
266//! In the example above a context variable defines the text color, but not just variables are contextual, layout
267//! units and widget services are also contextual, widget implementers may declare custom contextual values too,
268//! see [context local] in the app module documentation for more details.
269//!
270//! [context local]: app#context-local
271//!
272//! # Services
273//!
274//! App or contextual value and function providers.
275//!
276//! ```
277//! use zng::clipboard::CLIPBOARD;
278//! use zng::prelude::*;
279//!
280//! # let _app = APP.minimal();
281//! # let _ =
282//! Stack! {
283//! direction = StackDirection::top_to_bottom();
284//! spacing = 10;
285//!
286//! children = {
287//! let txt = var(Txt::from(""));
288//! let txt_is_err = var(false);
289//! ui_vec![
290//! Button! {
291//! child = Text!("Paste");
292//! on_click = hn!(txt, txt_is_err, |_| {
293//! match CLIPBOARD.text() {
294//! Ok(p) => {
295//! if let Some(t) = p {
296//! txt.set(t);
297//! txt_is_err.set(false);
298//! }
299//! }
300//! Err(e) => {
301//! let t = WIDGET.trace_path();
302//! txt.set(formatx!("error in {t}: {e}"));
303//! txt_is_err.set(true);
304//! }
305//! }
306//! });
307//! },
308//! Text! {
309//! txt;
310//! when *#{txt_is_err} {
311//! font_color = colors::RED;
312//! }
313//! }
314//! ]
315//! };
316//! }
317//! # ;
318//! ```
319//!
320//! The example above uses two services, `CLIPBOARD` and `WIDGET`. Services are represented
321//! by an unit struct named like a static item, service functionality is available as methods on
322//! this unit struct. Services are contextual, `CLIPBOARD` exists on the app context, it can only operate
323//! in app threads, `WIDGET` represents the current widget and can only be used inside a widget.
324//!
325//! The default app provides multiple services, some common ones are [`APP`], [`WINDOWS`], [`WINDOW`], [`WIDGET`],
326//! [`FOCUS`], [`POPUP`], [`DATA`] and more. Services all follow the same pattern, they are a unit struct named like a static
327//! item, if you see such a type it is a service.
328//!
329//! Most services are synchronized with the update cycle. If the service provides a value that value does not change mid-update, all
330//! widgets read the same value in the same update. If the service run some operation it takes requests to run the operation, the
331//! requests are only applied after the current UI update. This is even true for the [`INSTANT`] service that provides the current
332//! time.
333//!
334//! [`APP`]: app::APP
335//! [`WINDOWS`]: window::WINDOWS
336//! [`WINDOW`]: window::WINDOW
337//! [`WIDGET`]: widget::WIDGET
338//! [`FOCUS`]: focus::FOCUS
339//! [`POPUP`]: popup::POPUP
340//! [`DATA`]: data_context::DATA
341//! [`INSTANT`]: app::INSTANT
342//!
343//! # Events & Commands
344//!
345//! Targeted messages send from the system to widgets or from one widget to another.
346//!
347//! ```no_run
348//! use zng::{
349//! clipboard::{CLIPBOARD, PASTE_CMD, on_paste},
350//! prelude::*,
351//! };
352//!
353//! APP.defaults().run_window("main", async {
354//! let cmd = PASTE_CMD.scoped(WINDOW.id());
355//! let paste_btn = Button! {
356//! child = Text!(cmd.name());
357//! widget::enabled = cmd.is_enabled();
358//! widget::visibility = cmd.has_handlers().map_into();
359//! tooltip = Tip!(Text!(cmd.name_with_shortcut()));
360//! on_click = hn!(|args: &gesture::ClickArgs| {
361//! args.propagation.stop();
362//! cmd.notify();
363//! });
364//! };
365//!
366//! let pasted_txt = var(Txt::from(""));
367//!
368//! Window! {
369//! on_paste = hn!(pasted_txt, |_| {
370//! if let Some(t) = CLIPBOARD.text().ok().flatten() {
371//! pasted_txt.set(t);
372//! }
373//! });
374//!
375//! child = Stack! {
376//! children_align = Align::CENTER;
377//! direction = StackDirection::top_to_bottom();
378//! spacing = 20;
379//! children = ui_vec![paste_btn, Text!(pasted_txt)];
380//! };
381//! }
382//! });
383//! ```
384//!
385//! The example above uses events and command events. Events are represented by a static instance
386//! of [`Event<A>`] with name suffix `_EVENT`. Events are usually abstracted by
387//! one or more event property, event properties are named with prefix `on_` and accept one input of
388//! [`Handler<A>`]. Commands are specialized events represented by a static instance of [`Command`]
389//! with name suffix `_CMD`. Every command is also an `Event<CommandArgs>`, unlike other events it is common
390//! for the command instance to be used directly.
391//!
392//! The `on_click` property handles the `CLICK_EVENT` when the click was done with the primary button and targets
393//! the widget or a descendant of the widget. The [`hn!`] is a widget handler that synchronously handles the event.
394//! See the [`event`] module documentation for details about event propagation, targeting and route. And see
395//! [`handler`] module for other handler types, including [`async_hn!`] that enables async `.await` in any event property.
396//!
397//! The example above defines a button for the `PASTE_CMD` command scoped on the window. Scoped commands are different
398//! instances of [`Command`], the command scope can be a window or widget ID, the scope is the target of the command and
399//! the context of the command metadata. In the example the button is only visible if the command scope (window) has
400//! a paste handler, the button is only enabled it at least one paste handler on the scope is enabled, the button also
401//! displays the command name and shortcut metadata, and finally on click the button notifies a command event that is
402//! received in `on_click`.
403//!
404//! Commands enable separation of concerns, the button in the example does not need to know what the window will do on paste,
405//! in fact the button does not even need to know what command it is requesting. Widgets can also be controlled using commands,
406//! the `Scroll!` widget for example can be controlled from anywhere else in the app using the [`scroll::cmd`] commands. See
407//! the [commands](event#commands) section in the event module documentation for more details.
408//!
409//! [`Event<A>`]: event::Event
410//! [`Command`]: event::Command
411//! [`Handler<A>`]: handler::Handler
412//! [`hn!`]: handler::hn!
413//! [`async_hn!`]: handler::async_hn!
414//!
415//! # Layout
416//!
417//! Contextual properties and constraints that affect how a widget is sized and placed on the screen.
418//!
419//! ```
420//! use zng::prelude::*;
421//! # let _app = APP.minimal();
422//!
423//! # let _ =
424//! Container! {
425//! layout::size = (400, 350);
426//! widget::background_color = colors::BLUE.darken(70.pct());
427//!
428//! child = Button! {
429//! child = Text!("Text");
430//!
431//! layout::align = layout::Align::CENTER;
432//! layout::size = (60.pct(), 70.pct());
433//! };
434//! }
435//! # ;
436//! ```
437//!
438//! In the example above the container widget sets an exact size using `layout::size` with exact units, the
439//! button widget sets a relative size using percentage units and positions itself in the container using `layout::align`.
440//! All the layout properties are stand-alone, in the example only the text widget implements layout directly. Layout
441//! properties modify the layout context by setting constraints and defining units, this context is available for all
442//! properties that need it during layout, see the [`layout`] module documentation for more details.
443//!
444//! # Error Handling
445//!
446//! Recoverable errors handled internally are logged using [`tracing`], in debug builds tracing events (info, warn and error)
447//! are printed using [`app::print_tracing`] by default if no tracing subscriber is set before the app starts building.
448//!
449//! Components always attempt to recover from errors when possible, or at least attempt to contain errors and turn then into
450//! a displayable message. The general idea is to at least give the end user a chance to workaround the issue.
451//!
452//! Components do not generally attempt to recover from panics, with some notable exceptions. The view-process will attempt to respawn
453//! if it crashes, because all state is safe in the app-process all windows and frames can be recreated, this lets the app survive
454//! some catastrophic video driver errors, like a forced disconnect caused by a driver update. The [`task::spawn`] and related
455//! fire-and-forget task runners will also just log the panic as an error.
456//!
457//! The [`zng::app::crash_handler`] is enabled by default, it collect panic backtraces, crash minidumps, show a crash dialog to the user
458//! and restart the app. During development a debug crash dialog is provided, it shows the stdout/stderr, panics stacktrace and
459//! minidumps collected if any non-panic fatal error happens. Note that the crash handler **stops debuggers from working**, see the
460//! [Debugger section] of the crash-handler docs on how to automatically disable the crash handler for debugger runs.
461//!
462//! [`tracing`]: https://docs.rs/tracing
463//! [Debugger section]: zng::app::crash_handler#debugger
464//!
465//! # In-Depth Documentation
466//!
467//! This crate level documentation only gives an overview required to start making apps using existing widgets and properties.
468//! All top-level modules in this crate contains in-depth documentation about their subject, of particular importance the
469//! [`app`], [`widget`](mod@widget), [`layout`] and [`render`] modules should give you a solid understanding of how everything works.
470//!
471//! ## Cargo Features
472//!
473//! See the [Cargo Features] section in the crate README for Cargo features documentation.
474//!
475//! [Cargo Features]: https://github.com/zng-ui/zng/tree/main/crates/zng#cargo-features
476
477#![warn(unused_extern_crates)]
478#![warn(missing_docs)]
479
480// manually expanded enable_widget_macros to avoid error running doc tests:
481// macro-expanded `extern crate` items cannot shadow names passed with `--extern`
482#[doc(hidden)]
483#[allow(unused_extern_crates)]
484extern crate self as zng;
485#[doc(hidden)]
486pub use zng_app::__proc_macro_util;
487
488pub use zng_clone_move::{async_clmv, async_clmv_fn, async_clmv_fn_once, clmv};
489
490pub use crate::app::APP;
491
492pub mod access;
493pub mod ansi_text;
494pub mod app;
495pub mod audio;
496pub mod button;
497pub mod checkerboard;
498pub mod clipboard;
499pub mod color;
500pub mod config;
501pub mod container;
502pub mod data_context;
503pub mod data_view;
504pub mod dialog;
505pub mod drag_drop;
506pub mod env;
507pub mod event;
508pub mod focus;
509pub mod font;
510pub mod fs_watcher;
511pub mod gesture;
512pub mod grid;
513pub mod handler;
514pub mod hot_reload;
515pub mod icon;
516pub mod image;
517pub mod keyboard;
518pub mod l10n;
519pub mod label;
520pub mod layer;
521pub mod layout;
522pub mod markdown;
523pub mod menu;
524pub mod mouse;
525pub mod panel;
526pub mod pointer_capture;
527pub mod popup;
528pub mod progress;
529pub mod render;
530pub mod rule_line;
531pub mod scroll;
532pub mod selectable;
533pub mod shortcut_text;
534pub mod slider;
535pub mod stack;
536pub mod state_map;
537pub mod style;
538pub mod task;
539pub mod text;
540pub mod text_input;
541pub mod third_party;
542pub mod timer;
543pub mod tip;
544pub mod toggle;
545pub mod touch;
546pub mod undo;
547pub mod update;
548pub mod var;
549pub mod view_process;
550pub mod widget;
551pub mod window;
552pub mod wrap;
553
554/// Types for general app development.
555///
556/// See also [`prelude_wgt`] for declaring new widgets and properties.
557pub mod prelude {
558 #[doc(no_inline)]
559 pub use crate::__prelude::*;
560}
561mod __prelude {
562 pub use crate::{color, gesture, keyboard, layout, mouse, task, timer, touch, widget};
563
564 pub use zng_task::rayon::prelude::{
565 FromParallelIterator as _, IndexedParallelIterator as _, IntoParallelIterator as _, IntoParallelRefIterator as _,
566 IntoParallelRefMutIterator as _, ParallelBridge as _, ParallelDrainFull as _, ParallelDrainRange as _, ParallelExtend as _,
567 ParallelIterator as _, ParallelSlice as _, ParallelSliceMut as _, ParallelString as _,
568 };
569
570 pub use zng_task::io::{
571 AsyncBufRead as _, AsyncRead as _, AsyncReadExt as _, AsyncSeek as _, AsyncSeekExt as _, AsyncWrite as _, AsyncWriteExt as _,
572 };
573
574 pub use zng_app::{
575 APP, INSTANT,
576 event::{AnyEventArgs as _, CommandInfoExt as _, CommandNameExt as _, CommandParam, EventArgs as _},
577 handler::{HandlerExt as _, async_hn, async_hn_once, hn, hn_once},
578 shortcut::{CommandShortcutExt as _, shortcut},
579 widget::{
580 AnyVarSubscribe as _, ResponseVarSubscribe as _, VarLayout as _, VarSubscribe as _, WIDGET, WidgetId, easing,
581 node::{IntoUiNode, UiNode, UiVec, ui_vec},
582 },
583 window::{WINDOW, WindowId},
584 };
585
586 pub use zng_app::widget::inspector::WidgetInfoInspectorExt as _;
587
588 pub use zng_var::{
589 IntoValue, IntoVar, Var, VarValue, const_var, context_var, expr_var, flat_expr_var, merge_var, var, var_from, var_getter,
590 var_state, when_var,
591 };
592
593 pub use crate::var::animation::easing;
594
595 pub use zng_layout::unit::{
596 Align, AngleUnits as _, ByteUnits as _, DipToPx as _, FactorUnits as _, Layout1d as _, Layout2d as _, Length, LengthUnits as _,
597 LineFromTuplesBuilder as _, PxDensityUnits as _, PxToDip as _, RectFromTuplesBuilder as _, TimeUnits as _,
598 };
599
600 pub use zng_txt::{ToTxt as _, Txt, formatx};
601
602 pub use zng_clone_move::{async_clmv, async_clmv_fn, async_clmv_fn_once, clmv};
603
604 pub use zng_color::{LightDarkVarExt as _, MixAdjust as _, colors, hex, hsl, hsla, hsv, hsva, light_dark, rgb, rgba, web_colors};
605
606 #[cfg(feature = "clipboard")]
607 pub use zng_ext_clipboard::CLIPBOARD;
608
609 #[cfg(feature = "config")]
610 pub use zng_ext_config::CONFIG;
611
612 pub use zng_ext_font::{FontStretch, FontStyle, FontWeight};
613
614 #[cfg(feature = "image")]
615 pub use zng_ext_image::ImageSource;
616
617 #[cfg(feature = "image")]
618 pub use zng_wgt_image::Image;
619
620 pub use zng_ext_input::{
621 focus::{FOCUS, WidgetInfoFocusExt as _, cmd::CommandFocusExt as _, iter::IterFocusableExt as _},
622 gesture::{CommandShortcutMatchesExt as _, HeadlessAppGestureExt as _},
623 keyboard::HeadlessAppKeyboardExt as _,
624 mouse::WidgetInfoMouseExt as _,
625 };
626
627 pub use zng_ext_l10n::{L10N, l10n, lang};
628
629 pub use zng_wgt_text::lang;
630
631 #[cfg(feature = "undo")]
632 pub use zng_ext_undo::{CommandUndoExt as _, REDO_CMD, UNDO, UNDO_CMD};
633
634 #[cfg(feature = "window")]
635 pub use zng_ext_window::{
636 AppRunWindowExt as _, HeadlessAppWindowExt as _, WINDOW_Ext as _, WINDOWS, WidgetInfoImeArea as _, WindowCloseRequestedArgs,
637 WindowIcon,
638 };
639 #[cfg(feature = "window")]
640 pub use zng_wgt_window::WINDOWS_Ext as _;
641
642 pub use zng_wgt::{CommandIconExt as _, ICONS, Wgt};
643
644 pub use crate::text;
645 pub use zng_wgt_text::Text;
646
647 #[cfg(feature = "text_input")]
648 pub use zng_wgt_text_input::{TextInput, selectable::SelectableText};
649
650 #[cfg(feature = "window")]
651 pub use crate::window;
652 #[cfg(feature = "window")]
653 pub use zng_wgt_window::Window;
654
655 pub use zng_wgt_container::Container;
656
657 #[cfg(feature = "button")]
658 pub use zng_wgt_button::Button;
659
660 #[cfg(feature = "data_context")]
661 pub use zng_wgt_data::{DATA, data};
662
663 #[cfg(feature = "grid")]
664 pub use crate::grid;
665 #[cfg(feature = "grid")]
666 pub use zng_wgt_grid::Grid;
667
668 pub use crate::layer;
669 pub use zng_wgt_layer::{AnchorMode, LAYERS, LayerIndex};
670
671 pub use crate::popup;
672 pub use zng_wgt_layer::popup::POPUP;
673
674 #[cfg(feature = "menu")]
675 pub use crate::menu;
676 #[cfg(feature = "menu")]
677 pub use zng_wgt_menu::{
678 Menu,
679 context::{ContextMenu, context_menu, context_menu_fn},
680 sub::SubMenu,
681 };
682
683 #[cfg(feature = "rule_line")]
684 pub use zng_wgt_rule_line::{hr::Hr, vr::Vr};
685
686 #[cfg(feature = "scroll")]
687 pub use zng_wgt_scroll::{SCROLL, Scroll};
688
689 #[cfg(feature = "toggle")]
690 pub use crate::toggle;
691 #[cfg(feature = "toggle")]
692 pub use zng_wgt_toggle::Toggle;
693
694 #[cfg(feature = "tooltip")]
695 pub use crate::tip;
696 #[cfg(feature = "tooltip")]
697 pub use zng_wgt_tooltip::{Tip, tooltip, tooltip_fn};
698
699 pub use zng_wgt::{
700 WidgetFn,
701 node::{VarPresent as _, VarPresentData as _, VarPresentList as _, VarPresentListFromIter as _, VarPresentOpt as _},
702 wgt_fn,
703 };
704
705 pub use zng_wgt_style::{Style, style_fn};
706
707 #[cfg(feature = "stack")]
708 pub use zng_wgt_stack::{Stack, StackDirection};
709
710 #[cfg(feature = "wrap")]
711 pub use zng_wgt_wrap::Wrap;
712
713 #[cfg(feature = "data_view")]
714 pub use zng_wgt_data_view::{DataView, DataViewArgs};
715
716 #[cfg(feature = "settings_editor")]
717 pub use zng_wgt_settings::SettingBuilderEditorExt as _;
718
719 #[cfg(feature = "dialog")]
720 pub use crate::dialog;
721 #[cfg(feature = "dialog")]
722 pub use zng_wgt_dialog::DIALOG;
723
724 #[cfg(all(feature = "fs_watcher", feature = "image"))]
725 pub use crate::fs_watcher::IMAGES_Ext as _;
726}
727
728/// Prelude for declaring new properties and widgets.
729///
730/// This prelude can be imported over [`prelude`].
731///
732/// # Examples
733///
734/// ```
735/// # fn main() { }
736/// use zng::{prelude::*, prelude_wgt::*};
737///
738/// /// A button with only text child.
739/// #[widget($crate::TextButton)]
740/// pub struct TextButton(Button);
741///
742/// /// Button text.
743/// #[property(CHILD, widget_impl(TextButton))]
744/// pub fn txt(wgt: &mut WidgetBuilding, txt: impl IntoVar<Txt>) {
745/// let _ = txt;
746/// wgt.expect_property_capture();
747/// }
748///
749/// impl TextButton {
750/// fn widget_intrinsic(&mut self) {
751/// self.widget_builder().push_build_action(|b| {
752/// let txt = b
753/// .capture_var::<Txt>(property_id!(Self::txt))
754/// .unwrap_or_else(|| const_var(Txt::from("")));
755/// b.set_child(Text!(txt));
756/// });
757/// }
758/// }
759/// ```
760pub mod prelude_wgt {
761 #[doc(no_inline)]
762 pub use crate::__prelude_wgt::*;
763}
764mod __prelude_wgt {
765 pub use zng_app::{
766 DInstant, Deadline, INSTANT,
767 event::{
768 AnyEventArgs as _, Command, CommandArgs, CommandHandle, CommandInfoExt as _, CommandNameExt as _, CommandParam, Event,
769 EventArgs as _, EventPropagationHandle, command, event, event_args,
770 },
771 handler::{Handler, HandlerExt as _, async_hn, async_hn_once, hn, hn_once},
772 render::{FrameBuilder, FrameUpdate, FrameValue, FrameValueKey, FrameValueUpdate, SpatialFrameId, TransformStyle},
773 shortcut::{CommandShortcutExt as _, Shortcut, ShortcutFilter, Shortcuts, shortcut},
774 timer::{DeadlineHandle, DeadlineVar, TIMERS, TimerHandle, TimerVar},
775 update::{UPDATES, UpdateDeliveryList, UpdateOp, WidgetUpdates},
776 widget::{
777 AnyVarSubscribe as _, ResponseVarSubscribe as _, VarLayout as _, VarSubscribe as _, WIDGET, WidgetId, WidgetUpdateMode,
778 base::{WidgetBase, WidgetImpl},
779 border::{BORDER, BorderSides, BorderStyle, CornerRadius, CornerRadiusFit, LineOrientation, LineStyle},
780 builder::{NestGroup, WidgetBuilder, WidgetBuilding, property_id},
781 easing,
782 info::{
783 InteractionPath, Interactivity, Visibility, WidgetBorderInfo, WidgetBoundsInfo, WidgetInfo, WidgetInfoBuilder,
784 WidgetLayout, WidgetMeasure, WidgetPath,
785 },
786 node::{
787 ArcNode, ChainList, EditableUiVec, EditableUiVecRef, FillUiNode, IntoUiNode, PanelList, SORTING_LIST, SortingList, UiNode,
788 UiNodeImpl, UiNodeListObserver, UiNodeOp, UiVec, ZIndex, match_node, match_node_leaf, match_widget, ui_vec,
789 },
790 property, widget, widget_impl, widget_mixin, widget_set,
791 },
792 window::{MonitorId, WINDOW, WindowId},
793 };
794
795 pub use zng_var::{
796 ContextVar, IntoValue, IntoVar, ResponderVar, ResponseVar, Var, VarCapability, VarHandle, VarHandles, VarValue, WeakVarHandle,
797 const_var, context_var, expr_var, flat_expr_var, impl_from_and_into_var, merge_var, response_done_var, response_var, var,
798 var_getter, var_state, when_var,
799 };
800
801 pub use zng_layout::{
802 context::{DIRECTION_VAR, LAYOUT, LayoutDirection, LayoutMetrics},
803 unit::{
804 Align, AngleDegree, AngleGradian, AngleRadian, AngleUnits as _, ByteUnits as _, Dip, DipBox, DipPoint, DipRect, DipSideOffsets,
805 DipSize, DipToPx as _, DipVector, Factor, Factor2d, FactorPercent, FactorSideOffsets, FactorUnits as _, Layout1d as _,
806 Layout2d as _, LayoutAxis, Length, LengthUnits as _, Line, LineFromTuplesBuilder as _, Point, Px, PxBox, PxConstraints,
807 PxConstraints2d, PxCornerRadius, PxDensityUnits as _, PxLine, PxPoint, PxRect, PxSideOffsets, PxSize, PxToDip as _,
808 PxTransform, PxVector, Rect, RectFromTuplesBuilder as _, SideOffsets, Size, TimeUnits as _, Transform, Vector,
809 },
810 };
811
812 pub use zng_txt::{ToTxt as _, Txt, formatx};
813
814 pub use zng_clone_move::{async_clmv, async_clmv_fn, async_clmv_fn_once, clmv};
815
816 pub use crate::task;
817
818 pub use zng_app_context::{CaptureFilter, ContextLocal, ContextValueSet, LocalContext, RunOnDrop, app_local, context_local};
819
820 pub use crate::state_map;
821 pub use zng_state_map::{OwnedStateMap, StateId, StateMapMut, StateMapRef, static_id};
822
823 pub use zng_wgt::prelude::{IdEntry, IdMap, IdSet};
824
825 pub use zng_wgt::{WidgetFn, wgt_fn};
826
827 pub use zng_color::{
828 ColorScheme, Hsla, Hsva, LightDark, MixAdjust as _, MixBlendMode, Rgba, colors, gradient, hex, hsl, hsla, hsv, hsva, light_dark,
829 rgb, rgba, web_colors,
830 };
831
832 pub use zng_wgt::node::{
833 EventNodeBuilder, VarEventNodeBuilder, VarPresent as _, VarPresentData as _, VarPresentList as _, VarPresentListFromIter,
834 VarPresentOpt as _, bind_state, bind_state_init, border_node, command_property, event_property, fill_node, list_presenter,
835 list_presenter_from_iter, presenter, presenter_opt, widget_state_get_state, widget_state_is_state, with_context_blend,
836 with_context_local, with_context_local_init, with_context_var, with_context_var_init, with_widget_state, with_widget_state_modify,
837 };
838
839 #[cfg(feature = "window")]
840 pub use zng_ext_window::WidgetInfoBuilderImeArea as _;
841
842 #[cfg(hot_reload)]
843 pub use crate::hot_reload::hot_node;
844
845 #[cfg(all(feature = "fs_watcher", feature = "image"))]
846 pub use crate::fs_watcher::IMAGES_Ext as _;
847}
848
849// ensure svg on_process_start is linked
850#[cfg(feature = "svg")]
851extern crate zng_ext_svg as _;
852
853zng_env::on_process_start!(|args| {
854 if args.yield_until_app() {
855 return;
856 }
857
858 zng_app::APP.on_init(zng_app::hn!(|args| {
859 if !args.is_minimal {
860 defaults();
861 }
862 }));
863});
864fn defaults() {
865 // Common editors.
866 zng_wgt::EDITORS.register_fallback(zng_wgt::WidgetFn::new(default_editors::handler));
867 tracing::debug!("defaults init, EDITORS set");
868
869 // injected in all windows
870 #[cfg(feature = "window")]
871 {
872 zng_ext_window::WINDOWS_EXTENSIONS.register_root_extender(|a| {
873 let child = a.root;
874
875 #[cfg(feature = "inspector")]
876 let child = zng_wgt_inspector::inspector(child, zng_wgt_inspector::live_inspector(true));
877
878 #[cfg(feature = "menu")]
879 let child = zng_wgt_menu::style_fn(child, crate::style::style_fn!(|_| crate::menu::DefaultStyle!()));
880
881 child
882 });
883 tracing::debug!("defaults init, root_extender set");
884 }
885 #[cfg(any(target_os = "android", target_os = "ios"))]
886 {
887 zng_ext_window::WINDOWS_EXTENSIONS.register_open_nested_handler(crate::window::default_mobile_nested_open_handler);
888 tracing::debug!("defaults init, open_nested_handler set");
889 }
890
891 // setup OPEN_LICENSES_CMD handler
892 #[cfg(all(feature = "third_party_default", feature = "third_party"))]
893 {
894 crate::third_party::setup_default_view();
895 tracing::debug!("defaults init, third_party set");
896 }
897
898 // setup SETTINGS_CMD handler
899 #[cfg(feature = "settings_editor")]
900 {
901 zng_wgt_settings::handle_settings_cmd();
902 tracing::debug!("defaults init, settings set");
903 }
904
905 #[cfg(all(single_instance, feature = "window"))]
906 {
907 crate::app::APP_INSTANCE_EVENT
908 .on_pre_event(
909 true,
910 crate::handler::hn!(|args| {
911 use crate::{focus::*, window::*};
912
913 // focus a window if none are focused.
914 if !args.is_current() && FOCUS.focused().with(|f| f.is_none()) {
915 for w in WINDOWS.widget_trees() {
916 if w.is_rendered() && WINDOWS.mode(w.window_id()) == Some(WindowMode::Headed) {
917 FOCUS.focus_window(w.window_id(), false);
918 break;
919 }
920 }
921 }
922 }),
923 )
924 .perm();
925 tracing::debug!("defaults init, single_instance set");
926 }
927}
928
929#[doc = include_str!("../../README.md")]
930#[cfg(doctest)]
931pub mod read_me_test {}
932
933mod default_editors {
934 use zng::widget::{EditorRequestArgs, node::UiNode};
935
936 pub fn handler(args: EditorRequestArgs) -> UiNode {
937 #[cfg(feature = "text_input")]
938 if let Some(txt) = args.value::<zng::text::Txt>() {
939 return zng::text_input::TextInput! {
940 txt;
941 };
942 }
943 #[cfg(feature = "text_input")]
944 if let Some(s) = args.value::<String>() {
945 return zng::text_input::TextInput! {
946 txt = s.map_bidi(|s| zng::text::Txt::from_str(s), |t: &zng::text::Txt| t.to_string());
947 };
948 }
949 #[cfg(feature = "text_input")]
950 if let Some(c) = args.value::<char>() {
951 return zng::text_input::TextInput! {
952 txt_parse::<char> = c;
953 style_fn = crate::text_input::FieldStyle!();
954 };
955 }
956
957 #[cfg(feature = "toggle")]
958 if let Some(checked) = args.value::<bool>() {
959 return zng::toggle::Toggle! {
960 style_fn = zng::toggle::CheckStyle!();
961 checked;
962 };
963 }
964
965 macro_rules! parse {
966 ($($ty:ty),+ $(,)?) => {
967 $(
968 #[cfg(feature = "text_input")]
969 if let Some(n) = args.value::<$ty>() {
970 return zng::text_input::TextInput! {
971 txt_parse::<$ty> = n;
972 style_fn = crate::text_input::FieldStyle!();
973 };
974 }
975
976 )+
977 }
978 }
979 parse! { u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, f32, f64 }
980
981 let _ = args;
982 UiNode::nil()
983 }
984}