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.8", 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 // TODO(breaking) add FrequencyUnits
563 pub use crate::{color, gesture, keyboard, layout, mouse, task, timer, touch, widget};
564
565 pub use zng_task::rayon::prelude::{
566 FromParallelIterator as _, IndexedParallelIterator as _, IntoParallelIterator as _, IntoParallelRefIterator as _,
567 IntoParallelRefMutIterator as _, ParallelBridge as _, ParallelDrainFull as _, ParallelDrainRange as _, ParallelExtend as _,
568 ParallelIterator as _, ParallelSlice as _, ParallelSliceMut as _, ParallelString as _,
569 };
570
571 pub use zng_task::io::{
572 AsyncBufRead as _, AsyncRead as _, AsyncReadExt as _, AsyncSeek as _, AsyncSeekExt as _, AsyncWrite as _, AsyncWriteExt as _,
573 };
574
575 pub use zng_app::{
576 APP, INSTANT,
577 event::{AnyEventArgs as _, CommandInfoExt as _, CommandNameExt as _, CommandParam, EventArgs as _},
578 handler::{HandlerExt as _, async_hn, async_hn_once, hn, hn_once},
579 shortcut::{CommandShortcutExt as _, shortcut},
580 widget::{
581 AnyVarSubscribe as _, ResponseVarSubscribe as _, VarLayout as _, VarSubscribe as _, WIDGET, WidgetId, easing,
582 node::{IntoUiNode, UiNode, UiVec, ui_vec},
583 },
584 window::{WINDOW, WindowId},
585 };
586
587 pub use zng_app::widget::inspector::WidgetInfoInspectorExt as _;
588
589 pub use zng_var::{
590 IntoValue, IntoVar, Var, VarValue, const_var, context_var, expr_var, flat_expr_var, merge_var, var, var_from, var_getter,
591 var_state, when_var,
592 };
593
594 pub use crate::var::animation::easing;
595
596 pub use zng_layout::unit::{
597 Align, AngleUnits as _, ByteUnits as _, DipToPx as _, FactorUnits as _, Layout1d as _, Layout2d as _, Length, LengthUnits as _,
598 LineFromTuplesBuilder as _, PxDensityUnits as _, PxToDip as _, RectFromTuplesBuilder as _, TimeUnits as _,
599 };
600
601 pub use zng_txt::{ToTxt as _, Txt, formatx};
602
603 pub use zng_clone_move::{async_clmv, async_clmv_fn, async_clmv_fn_once, clmv};
604
605 pub use zng_color::{LightDarkVarExt as _, MixAdjust as _, colors, hex, hsl, hsla, hsv, hsva, light_dark, rgb, rgba, web_colors};
606
607 #[cfg(feature = "clipboard")]
608 pub use zng_ext_clipboard::CLIPBOARD;
609
610 #[cfg(feature = "config")]
611 pub use zng_ext_config::CONFIG;
612
613 pub use zng_ext_font::{FontStretch, FontStyle, FontWeight};
614
615 #[cfg(feature = "image")]
616 pub use zng_ext_image::ImageSource;
617
618 #[cfg(feature = "image")]
619 pub use zng_wgt_image::Image;
620
621 pub use zng_ext_input::{
622 focus::{FOCUS, WidgetInfoFocusExt as _, cmd::CommandFocusExt as _, iter::IterFocusableExt as _},
623 gesture::{CommandShortcutMatchesExt as _, HeadlessAppGestureExt as _},
624 keyboard::HeadlessAppKeyboardExt as _,
625 mouse::WidgetInfoMouseExt as _,
626 };
627
628 pub use zng_ext_l10n::{L10N, l10n, lang};
629
630 pub use zng_wgt_text::lang;
631
632 #[cfg(feature = "undo")]
633 pub use zng_ext_undo::{CommandUndoExt as _, REDO_CMD, UNDO, UNDO_CMD};
634
635 #[cfg(feature = "window")]
636 pub use zng_ext_window::{
637 AppRunWindowExt as _, HeadlessAppWindowExt as _, WINDOW_Ext as _, WINDOWS, WidgetInfoImeArea as _, WindowCloseRequestedArgs,
638 WindowIcon,
639 };
640 #[cfg(feature = "window")]
641 pub use zng_wgt_window::WINDOWS_Ext as _;
642
643 pub use zng_wgt::{CommandIconExt as _, ICONS, Wgt};
644
645 pub use crate::text;
646 pub use zng_wgt_text::Text;
647
648 #[cfg(feature = "text_input")]
649 pub use zng_wgt_text_input::{TextInput, selectable::SelectableText};
650
651 #[cfg(feature = "window")]
652 pub use crate::window;
653 #[cfg(feature = "window")]
654 pub use zng_wgt_window::Window;
655
656 pub use zng_wgt_container::Container;
657
658 #[cfg(feature = "button")]
659 pub use zng_wgt_button::Button;
660
661 #[cfg(feature = "data_context")]
662 pub use zng_wgt_data::{DATA, data};
663
664 #[cfg(feature = "grid")]
665 pub use crate::grid;
666 #[cfg(feature = "grid")]
667 pub use zng_wgt_grid::Grid;
668
669 pub use crate::layer;
670 pub use zng_wgt_layer::{AnchorMode, LAYERS, LayerIndex};
671
672 pub use crate::popup;
673 pub use zng_wgt_layer::popup::POPUP;
674
675 #[cfg(feature = "menu")]
676 pub use crate::menu;
677 #[cfg(feature = "menu")]
678 pub use zng_wgt_menu::{
679 Menu,
680 context::{ContextMenu, context_menu, context_menu_fn},
681 sub::SubMenu,
682 };
683
684 #[cfg(feature = "rule_line")]
685 pub use zng_wgt_rule_line::{hr::Hr, vr::Vr};
686
687 #[cfg(feature = "scroll")]
688 pub use zng_wgt_scroll::{SCROLL, Scroll};
689
690 #[cfg(feature = "toggle")]
691 pub use crate::toggle;
692 #[cfg(feature = "toggle")]
693 pub use zng_wgt_toggle::Toggle;
694
695 #[cfg(feature = "tooltip")]
696 pub use crate::tip;
697 #[cfg(feature = "tooltip")]
698 pub use zng_wgt_tooltip::{Tip, tooltip, tooltip_fn};
699
700 pub use zng_wgt::{
701 WidgetFn,
702 node::{VarPresent as _, VarPresentData as _, VarPresentList as _, VarPresentListFromIter as _, VarPresentOpt as _},
703 wgt_fn,
704 };
705
706 pub use zng_wgt_style::{Style, style_fn};
707
708 #[cfg(feature = "stack")]
709 pub use zng_wgt_stack::{Stack, StackDirection};
710
711 #[cfg(feature = "wrap")]
712 pub use zng_wgt_wrap::Wrap;
713
714 #[cfg(feature = "data_view")]
715 pub use zng_wgt_data_view::{DataView, DataViewArgs};
716
717 #[cfg(feature = "settings_editor")]
718 pub use zng_wgt_settings::SettingBuilderEditorExt as _;
719
720 #[cfg(feature = "dialog")]
721 pub use crate::dialog;
722 #[cfg(feature = "dialog")]
723 pub use zng_wgt_dialog::DIALOG;
724
725 #[cfg(all(feature = "fs_watcher", feature = "image"))]
726 pub use crate::fs_watcher::IMAGES_Ext as _;
727}
728
729/// Prelude for declaring new properties and widgets.
730///
731/// This prelude can be imported over [`prelude`].
732///
733/// # Examples
734///
735/// ```
736/// # fn main() { }
737/// use zng::{prelude::*, prelude_wgt::*};
738///
739/// /// A button with only text child.
740/// #[widget($crate::TextButton)]
741/// pub struct TextButton(Button);
742///
743/// /// Button text.
744/// #[property(CHILD, widget_impl(TextButton))]
745/// pub fn txt(wgt: &mut WidgetBuilding, txt: impl IntoVar<Txt>) {
746/// let _ = txt;
747/// wgt.expect_property_capture();
748/// }
749///
750/// impl TextButton {
751/// fn widget_intrinsic(&mut self) {
752/// self.widget_builder().push_build_action(|b| {
753/// let txt = b
754/// .capture_var::<Txt>(property_id!(Self::txt))
755/// .unwrap_or_else(|| const_var(Txt::from("")));
756/// b.set_child(Text!(txt));
757/// });
758/// }
759/// }
760/// ```
761pub mod prelude_wgt {
762 #[doc(no_inline)]
763 pub use crate::__prelude_wgt::*;
764}
765mod __prelude_wgt {
766 pub use zng_app::{
767 DInstant, Deadline, INSTANT,
768 event::{
769 AnyEventArgs as _, Command, CommandArgs, CommandHandle, CommandInfoExt as _, CommandNameExt as _, CommandParam, Event,
770 EventArgs as _, EventPropagationHandle, command, event, event_args,
771 },
772 handler::{Handler, HandlerExt as _, async_hn, async_hn_once, hn, hn_once},
773 render::{FrameBuilder, FrameUpdate, FrameValue, FrameValueKey, FrameValueUpdate, SpatialFrameId, TransformStyle},
774 shortcut::{CommandShortcutExt as _, Shortcut, ShortcutFilter, Shortcuts, shortcut},
775 timer::{DeadlineHandle, DeadlineVar, TIMERS, TimerHandle, TimerVar},
776 update::{UPDATES, UpdateDeliveryList, UpdateOp, WidgetUpdates},
777 widget::{
778 AnyVarSubscribe as _, ResponseVarSubscribe as _, VarLayout as _, VarSubscribe as _, WIDGET, WidgetId, WidgetUpdateMode,
779 base::{WidgetBase, WidgetImpl},
780 border::{BORDER, BorderSides, BorderStyle, CornerRadius, CornerRadiusFit, LineOrientation, LineStyle},
781 builder::{NestGroup, WidgetBuilder, WidgetBuilding, property_id},
782 easing,
783 info::{
784 InteractionPath, Interactivity, Visibility, WidgetBorderInfo, WidgetBoundsInfo, WidgetInfo, WidgetInfoBuilder,
785 WidgetLayout, WidgetMeasure, WidgetPath,
786 },
787 node::{
788 ArcNode, ChainList, EditableUiVec, EditableUiVecRef, FillUiNode, IntoUiNode, PanelList, SORTING_LIST, SortingList, UiNode,
789 UiNodeImpl, UiNodeListObserver, UiNodeOp, UiVec, ZIndex, match_node, match_node_leaf, match_widget, ui_vec,
790 },
791 property, widget, widget_impl, widget_mixin, widget_set,
792 },
793 window::{MonitorId, WINDOW, WindowId},
794 };
795
796 pub use zng_var::{
797 ContextVar, IntoValue, IntoVar, ResponderVar, ResponseVar, Var, VarCapability, VarHandle, VarHandles, VarValue, WeakVarHandle,
798 const_var, context_var, expr_var, flat_expr_var, impl_from_and_into_var, merge_var, response_done_var, response_var, var,
799 var_getter, var_state, when_var,
800 };
801
802 pub use zng_layout::{
803 context::{DIRECTION_VAR, LAYOUT, LayoutDirection, LayoutMetrics},
804 unit::{
805 Align, AngleDegree, AngleGradian, AngleRadian, AngleUnits as _, ByteUnits as _, Dip, DipBox, DipPoint, DipRect, DipSideOffsets,
806 DipSize, DipToPx as _, DipVector, Factor, Factor2d, FactorPercent, FactorSideOffsets, FactorUnits as _, Layout1d as _,
807 Layout2d as _, LayoutAxis, Length, LengthUnits as _, Line, LineFromTuplesBuilder as _, Point, Px, PxBox, PxConstraints,
808 PxConstraints2d, PxCornerRadius, PxDensityUnits as _, PxLine, PxPoint, PxRect, PxSideOffsets, PxSize, PxToDip as _,
809 PxTransform, PxVector, Rect, RectFromTuplesBuilder as _, SideOffsets, Size, TimeUnits as _, Transform, Vector,
810 },
811 };
812
813 pub use zng_txt::{ToTxt as _, Txt, formatx};
814
815 pub use zng_clone_move::{async_clmv, async_clmv_fn, async_clmv_fn_once, clmv};
816
817 pub use crate::task;
818
819 pub use zng_app_context::{CaptureFilter, ContextLocal, ContextValueSet, LocalContext, RunOnDrop, app_local, context_local};
820
821 pub use crate::state_map;
822 pub use zng_state_map::{OwnedStateMap, StateId, StateMapMut, StateMapRef, static_id};
823
824 pub use zng_wgt::prelude::{IdEntry, IdMap, IdSet};
825
826 pub use zng_wgt::{WidgetFn, wgt_fn};
827
828 pub use zng_color::{
829 ColorScheme, Hsla, Hsva, LightDark, MixAdjust as _, MixBlendMode, Rgba, colors, gradient, hex, hsl, hsla, hsv, hsva, light_dark,
830 rgb, rgba, web_colors,
831 };
832
833 pub use zng_wgt::node::{
834 EventNodeBuilder, VarEventNodeBuilder, VarPresent as _, VarPresentData as _, VarPresentList as _, VarPresentListFromIter,
835 VarPresentOpt as _, bind_state, bind_state_init, border_node, command_property, event_property, fill_node, list_presenter,
836 list_presenter_from_iter, presenter, presenter_opt, widget_state_get_state, widget_state_is_state, with_context_blend,
837 with_context_local, with_context_local_init, with_context_var, with_context_var_init, with_widget_state, with_widget_state_modify,
838 };
839
840 #[cfg(feature = "window")]
841 pub use zng_ext_window::WidgetInfoBuilderImeArea as _;
842
843 #[cfg(hot_reload)]
844 pub use crate::hot_reload::hot_node;
845
846 #[cfg(all(feature = "fs_watcher", feature = "image"))]
847 pub use crate::fs_watcher::IMAGES_Ext as _;
848}
849
850// ensure svg on_process_start is linked
851#[cfg(feature = "svg")]
852extern crate zng_ext_svg as _;
853
854zng_env::on_process_start!(|args| {
855 if args.yield_until_app() {
856 return;
857 }
858
859 zng_app::APP.on_init(zng_app::hn!(|args| {
860 if !args.is_minimal {
861 defaults();
862 }
863 }));
864});
865fn defaults() {
866 // Common editors.
867 zng_wgt::EDITORS.register_fallback(zng_wgt::WidgetFn::new(default_editors::handler));
868 tracing::debug!("defaults init, EDITORS set");
869
870 // injected in all windows
871 #[cfg(feature = "window")]
872 {
873 zng_ext_window::WINDOWS_EXTENSIONS.register_root_extender(|a| {
874 let child = a.root;
875
876 #[cfg(feature = "inspector")]
877 let child = zng_wgt_inspector::inspector(child, zng_wgt_inspector::live_inspector(true));
878
879 #[cfg(feature = "menu")]
880 let child = zng_wgt_menu::style_fn(child, crate::style::style_fn!(|_| crate::menu::DefaultStyle!()));
881
882 child
883 });
884 tracing::debug!("defaults init, root_extender set");
885 }
886 #[cfg(any(target_os = "android", target_os = "ios"))]
887 {
888 zng_ext_window::WINDOWS_EXTENSIONS.register_open_nested_handler(crate::window::default_mobile_nested_open_handler);
889 tracing::debug!("defaults init, open_nested_handler set");
890 }
891
892 // setup OPEN_LICENSES_CMD handler
893 #[cfg(all(feature = "third_party_default", feature = "third_party"))]
894 {
895 crate::third_party::setup_default_view();
896 tracing::debug!("defaults init, third_party set");
897 }
898
899 // setup SETTINGS_CMD handler
900 #[cfg(feature = "settings_editor")]
901 {
902 zng_wgt_settings::handle_settings_cmd();
903 tracing::debug!("defaults init, settings set");
904 }
905
906 #[cfg(all(single_instance, feature = "window"))]
907 {
908 crate::app::APP_INSTANCE_EVENT
909 .on_pre_event(
910 true,
911 crate::handler::hn!(|args| {
912 use crate::{focus::*, window::*};
913
914 // focus a window if none are focused.
915 if !args.is_current() && FOCUS.focused().with(|f| f.is_none()) {
916 for w in WINDOWS.widget_trees() {
917 if w.is_rendered() && WINDOWS.mode(w.window_id()) == Some(WindowMode::Headed) {
918 FOCUS.focus_window(w.window_id(), false);
919 break;
920 }
921 }
922 }
923 }),
924 )
925 .perm();
926 tracing::debug!("defaults init, single_instance set");
927 }
928}
929
930#[doc = include_str!("../../README.md")]
931#[cfg(doctest)]
932pub mod read_me_test {}
933
934mod default_editors {
935 use zng::widget::{EditorRequestArgs, node::UiNode};
936
937 pub fn handler(args: EditorRequestArgs) -> UiNode {
938 #[cfg(feature = "text_input")]
939 if let Some(txt) = args.value::<zng::text::Txt>() {
940 return zng::text_input::TextInput! {
941 txt;
942 };
943 }
944 #[cfg(feature = "text_input")]
945 if let Some(s) = args.value::<String>() {
946 return zng::text_input::TextInput! {
947 txt = s.map_bidi(|s| zng::text::Txt::from_str(s), |t: &zng::text::Txt| t.to_string());
948 };
949 }
950 #[cfg(feature = "text_input")]
951 if let Some(c) = args.value::<char>() {
952 return zng::text_input::TextInput! {
953 txt_parse::<char> = c;
954 style_fn = crate::text_input::FieldStyle!();
955 };
956 }
957
958 #[cfg(feature = "toggle")]
959 if let Some(checked) = args.value::<bool>() {
960 return zng::toggle::Toggle! {
961 style_fn = zng::toggle::CheckStyle!();
962 checked;
963 };
964 }
965
966 macro_rules! parse {
967 ($($ty:ty),+ $(,)?) => {
968 $(
969 #[cfg(feature = "text_input")]
970 if let Some(n) = args.value::<$ty>() {
971 return zng::text_input::TextInput! {
972 txt_parse::<$ty> = n;
973 style_fn = crate::text_input::FieldStyle!();
974 };
975 }
976
977 )+
978 }
979 }
980 parse! { u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, f32, f64 }
981
982 let _ = args;
983 UiNode::nil()
984 }
985}