zng_app/
lib.rs

1#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
2#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
3//!
4//! App process implementation.
5//!
6//! # Widget Instantiation
7//!
8//! See [`enable_widget_macros!`] if you want to instantiate widgets without depending on the `zng` crate.
9//!
10//! # Crate
11//!
12#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
13#![recursion_limit = "256"]
14// suppress nag about very simple boxed closure signatures.
15#![expect(clippy::type_complexity)]
16#![warn(unused_extern_crates)]
17#![warn(missing_docs)]
18
19use std::{
20    any::{TypeId, type_name},
21    collections::HashMap,
22    fmt, ops,
23    path::PathBuf,
24    sync::Arc,
25};
26
27pub mod access;
28pub mod crash_handler;
29pub mod event;
30pub mod handler;
31pub mod render;
32pub mod shortcut;
33pub mod third_party;
34pub mod timer;
35pub mod update;
36pub mod view_process;
37pub mod widget;
38pub mod window;
39
40mod tests;
41
42use view_process::VIEW_PROCESS;
43use widget::UiTaskWidget;
44#[doc(hidden)]
45pub use zng_layout as layout;
46use zng_txt::Txt;
47#[doc(hidden)]
48pub use zng_var as var;
49
50pub use zng_time::{DInstant, Deadline, INSTANT, InstantMode};
51
52use update::{EventUpdate, InfoUpdates, LayoutUpdates, RenderUpdates, UPDATES, UpdatesTrace, WidgetUpdates};
53use window::WindowMode;
54use zng_app_context::{AppId, AppScope, LocalContext};
55use zng_task::UiTask;
56
57pub use zng_unique_id::static_id;
58
59/// Enable widget instantiation in crates that can't depend on the `zng` crate.
60///
61/// This must be called at the top of the crate:
62///
63/// ```
64/// // in lib.rs or main.rs
65/// # use zng_app::*;
66/// enable_widget_macros!();
67/// ```
68#[macro_export]
69macro_rules! enable_widget_macros {
70    () => {
71        #[doc(hidden)]
72        #[allow(unused_extern_crates)]
73        extern crate self as zng;
74
75        #[doc(hidden)]
76        pub use $crate::__proc_macro_util;
77    };
78}
79
80#[doc(hidden)]
81#[allow(unused_extern_crates)]
82extern crate self as zng;
83
84#[doc(hidden)]
85#[allow(unused_extern_crates)]
86extern crate self as zng_app; // for doc-tests
87
88#[doc(hidden)]
89pub mod __proc_macro_util {
90    // * don't add glob re-exports, the types leak in rust-analyzer even if all is doc(hidden).
91    // * don't use macro_rules! macros that use $crate , they will fail with "unresolved import" when used from the re-exports.
92
93    #[doc(hidden)]
94    pub use zng_unique_id::static_id;
95
96    #[doc(hidden)]
97    pub mod widget {
98        #[doc(hidden)]
99        pub mod builder {
100            #[doc(hidden)]
101            pub use crate::widget::builder::{
102                AnyArcWidgetHandler, ArcWidgetHandler, Importance, InputKind, PropertyArgs, PropertyId, PropertyInfo, PropertyInput,
103                PropertyInputTypes, PropertyNewArgs, SourceLocation, UiNodeInWhenExprError, UiNodeListInWhenExprError, WgtInfo, WhenInput,
104                WhenInputMember, WhenInputVar, WidgetHandlerInWhenExprError, WidgetType, getter_var, iter_input_build_actions,
105                nest_group_items, new_dyn_other, new_dyn_ui_node, new_dyn_ui_node_list, new_dyn_var, new_dyn_widget_handler, panic_input,
106                state_var, ui_node_list_to_args, ui_node_to_args, value_to_args, var_to_args, when_condition_expr_var,
107                widget_handler_to_args,
108            };
109        }
110
111        #[doc(hidden)]
112        pub mod base {
113            pub use crate::widget::base::{NonWidgetBase, WidgetBase, WidgetExt, WidgetImpl};
114        }
115
116        #[doc(hidden)]
117        pub mod node {
118            pub use crate::widget::node::{
119                ArcNode, ArcNodeList, BoxedUiNode, BoxedUiNodeList, NilUiNode, UiNode, UiNodeList, UiVec, ui_node_list_default,
120            };
121        }
122
123        #[doc(hidden)]
124        pub mod info {
125            pub use crate::widget::info::{WidgetInfoBuilder, WidgetLayout, WidgetMeasure};
126        }
127
128        #[doc(hidden)]
129        pub use crate::widget::{easing_property, widget_new};
130
131        #[doc(hidden)]
132        pub use crate::widget::WIDGET;
133    }
134
135    #[doc(hidden)]
136    pub mod update {
137        pub use crate::update::{EventUpdate, WidgetUpdates};
138    }
139
140    #[doc(hidden)]
141    pub mod layout {
142        #[doc(hidden)]
143        pub mod unit {
144            #[doc(hidden)]
145            pub use crate::layout::unit::{PxSize, TimeUnits};
146        }
147
148        #[doc(hidden)]
149        pub mod context {
150            #[doc(hidden)]
151            pub use crate::layout::context::LAYOUT;
152        }
153    }
154
155    #[doc(hidden)]
156    pub mod render {
157        pub use crate::render::{FrameBuilder, FrameUpdate};
158    }
159
160    #[doc(hidden)]
161    pub mod handler {
162        #[doc(hidden)]
163        pub use crate::handler::hn;
164    }
165
166    #[doc(hidden)]
167    pub mod var {
168        #[doc(hidden)]
169        pub use crate::var::{AnyVar, AnyVarValue, BoxedVar, Var, expr_var};
170
171        #[doc(hidden)]
172        pub mod animation {
173            #[doc(hidden)]
174            pub mod easing {
175                #[doc(hidden)]
176                pub use crate::var::animation::easing::{
177                    back, bounce, circ, cubic, cubic_bezier, ease_in, ease_in_out, ease_out, ease_out_in, elastic, expo, linear, none,
178                    quad, quart, quint, reverse, reverse_out, sine, step_ceil, step_floor,
179                };
180            }
181        }
182    }
183}
184
185/// An app extension.
186///
187/// App extensions setup and update core features such as services and events. App instances
188/// are fully composed of app extensions.
189///
190/// See the `zng::app` module level documentation for more details, including the call order of methods
191/// of this trait.
192pub trait AppExtension: 'static {
193    /// Register info abound this extension on the info list.
194    #[inline(always)]
195    fn register(&self, info: &mut AppExtensionsInfo)
196    where
197        Self: Sized,
198    {
199        info.push::<Self>()
200    }
201
202    /// Initializes this extension.
203    #[inline(always)]
204    fn init(&mut self) {}
205
206    /// If the application should notify raw device events.
207    ///
208    /// Device events are raw events not targeting any window, like a mouse move on any part of the screen.
209    /// They tend to be high-volume events so there is a performance cost to activating this. Note that if
210    /// this is `false` you still get the mouse move over windows of the app.
211    ///
212    /// This is called zero or one times before [`init`](Self::init).
213    ///
214    /// Returns `false` by default.
215    #[inline(always)]
216    fn enable_device_events(&self) -> bool {
217        false
218    }
219
220    /// Called just before [`event_ui`](Self::event_ui) when an event notifies.
221    ///
222    /// Extensions can handle this method to intercept event updates before the UI.
223    ///
224    /// Note that this is not related to the `on_event_preview` properties, all UI events
225    /// happen in `event_ui`.
226    #[inline(always)]
227    fn event_preview(&mut self, update: &mut EventUpdate) {
228        let _ = update;
229    }
230
231    /// Called just before [`event`](Self::event).
232    ///
233    /// Only extensions that generate windows should handle this method. The [`UiNode::event`](crate::widget::node::UiNode::event)
234    /// method is called here.
235    #[inline(always)]
236    fn event_ui(&mut self, update: &mut EventUpdate) {
237        let _ = update;
238    }
239
240    /// Called after [`event_ui`](Self::event_ui).
241    ///
242    /// This is the general extensions event handler, it gives the chance for the UI to signal stop propagation.
243    #[inline(always)]
244    fn event(&mut self, update: &mut EventUpdate) {
245        let _ = update;
246    }
247
248    /// Called when info rebuild is requested for windows and widgets.
249    ///
250    /// The [`UiNode::info`] method is called here.
251    ///
252    /// [`UiNode::info`]: crate::widget::node::UiNode::info
253    #[inline(always)]
254    fn info(&mut self, info_widgets: &mut InfoUpdates) {
255        let _ = info_widgets;
256    }
257
258    /// Called just before [`update_ui`](Self::update_ui).
259    ///
260    /// Extensions can handle this method to react to updates before the UI.
261    ///
262    /// Note that this is not related to the `on_event_preview` properties, all UI events
263    /// happen in `update_ui`.
264    #[inline(always)]
265    fn update_preview(&mut self) {}
266
267    /// Called just before [`update`](Self::update).
268    ///
269    /// Only extensions that manage windows should handle this method.
270    ///
271    /// The [`UiNode::update`] method is called here.
272    ///
273    /// [`UiNode::update`]: crate::widget::node::UiNode::update
274    #[inline(always)]
275    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
276        let _ = update_widgets;
277    }
278
279    /// Called after every [`update_ui`](Self::update_ui) and [`info`](Self::info).
280    ///
281    /// This is the general extensions update, it gives the chance for
282    /// the UI to make service requests.
283    #[inline(always)]
284    fn update(&mut self) {}
285
286    /// Called when layout is requested for windows and widgets.
287    ///
288    /// The [`UiNode::layout`] method is called here.
289    ///
290    /// [`UiNode::layout`]: crate::widget::node::UiNode::layout
291    #[inline(always)]
292    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
293        let _ = layout_widgets;
294    }
295
296    /// Called when render is requested for windows and widgets.
297    ///
298    /// The [`UiNode::render`] and [`UiNode::render_update`] methods are called here.
299    ///
300    /// [`UiNode::render`]: crate::widget::node::UiNode::render
301    /// [`UiNode::render_update`]: crate::widget::node::UiNode::render_update
302    #[inline(always)]
303    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
304        let _ = (render_widgets, render_update_widgets);
305    }
306
307    /// Called when the application is exiting.
308    ///
309    /// Update requests and event notifications generated during this call are ignored,
310    /// the extensions will be dropped after every extension received this call.
311    #[inline(always)]
312    fn deinit(&mut self) {}
313
314    /// Gets the extension boxed.
315    ///
316    /// Boxed app extensions also implement `AppExtension`, this method does not double box.
317    #[inline(always)]
318    fn boxed(self) -> Box<dyn AppExtensionBoxed>
319    where
320        Self: Sized,
321    {
322        Box::new(self)
323    }
324}
325
326/// Boxed version of [`AppExtension`].
327#[doc(hidden)]
328pub trait AppExtensionBoxed: 'static {
329    fn register_boxed(&self, info: &mut AppExtensionsInfo);
330    fn init_boxed(&mut self);
331    fn enable_device_events_boxed(&self) -> bool;
332    fn update_preview_boxed(&mut self);
333    fn update_ui_boxed(&mut self, updates: &mut WidgetUpdates);
334    fn update_boxed(&mut self);
335    fn event_preview_boxed(&mut self, update: &mut EventUpdate);
336    fn event_ui_boxed(&mut self, update: &mut EventUpdate);
337    fn event_boxed(&mut self, update: &mut EventUpdate);
338    fn info_boxed(&mut self, info_widgets: &mut InfoUpdates);
339    fn layout_boxed(&mut self, layout_widgets: &mut LayoutUpdates);
340    fn render_boxed(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates);
341    fn deinit_boxed(&mut self);
342}
343impl<T: AppExtension> AppExtensionBoxed for T {
344    fn register_boxed(&self, info: &mut AppExtensionsInfo) {
345        self.register(info);
346    }
347
348    fn init_boxed(&mut self) {
349        self.init();
350    }
351
352    fn enable_device_events_boxed(&self) -> bool {
353        self.enable_device_events()
354    }
355
356    fn update_preview_boxed(&mut self) {
357        self.update_preview();
358    }
359
360    fn update_ui_boxed(&mut self, updates: &mut WidgetUpdates) {
361        self.update_ui(updates);
362    }
363
364    fn info_boxed(&mut self, info_widgets: &mut InfoUpdates) {
365        self.info(info_widgets);
366    }
367
368    fn update_boxed(&mut self) {
369        self.update();
370    }
371
372    fn event_preview_boxed(&mut self, update: &mut EventUpdate) {
373        self.event_preview(update);
374    }
375
376    fn event_ui_boxed(&mut self, update: &mut EventUpdate) {
377        self.event_ui(update);
378    }
379
380    fn event_boxed(&mut self, update: &mut EventUpdate) {
381        self.event(update);
382    }
383
384    fn layout_boxed(&mut self, layout_widgets: &mut LayoutUpdates) {
385        self.layout(layout_widgets);
386    }
387
388    fn render_boxed(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
389        self.render(render_widgets, render_update_widgets);
390    }
391
392    fn deinit_boxed(&mut self) {
393        self.deinit();
394    }
395}
396impl AppExtension for Box<dyn AppExtensionBoxed> {
397    fn register(&self, info: &mut AppExtensionsInfo) {
398        self.as_ref().register_boxed(info);
399    }
400
401    fn init(&mut self) {
402        self.as_mut().init_boxed();
403    }
404
405    fn enable_device_events(&self) -> bool {
406        self.as_ref().enable_device_events_boxed()
407    }
408
409    fn update_preview(&mut self) {
410        self.as_mut().update_preview_boxed();
411    }
412
413    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
414        self.as_mut().update_ui_boxed(update_widgets);
415    }
416
417    fn update(&mut self) {
418        self.as_mut().update_boxed();
419    }
420
421    fn event_preview(&mut self, update: &mut EventUpdate) {
422        self.as_mut().event_preview_boxed(update);
423    }
424
425    fn event_ui(&mut self, update: &mut EventUpdate) {
426        self.as_mut().event_ui_boxed(update);
427    }
428
429    fn event(&mut self, update: &mut EventUpdate) {
430        self.as_mut().event_boxed(update);
431    }
432
433    fn info(&mut self, info_widgets: &mut InfoUpdates) {
434        self.as_mut().info_boxed(info_widgets);
435    }
436
437    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
438        self.as_mut().layout_boxed(layout_widgets);
439    }
440
441    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
442        self.as_mut().render_boxed(render_widgets, render_update_widgets);
443    }
444
445    fn deinit(&mut self) {
446        self.as_mut().deinit_boxed();
447    }
448
449    fn boxed(self) -> Box<dyn AppExtensionBoxed>
450    where
451        Self: Sized,
452    {
453        self
454    }
455}
456
457struct TraceAppExt<E: AppExtension>(E);
458impl<E: AppExtension> AppExtension for TraceAppExt<E> {
459    fn register(&self, info: &mut AppExtensionsInfo) {
460        self.0.register(info)
461    }
462
463    fn init(&mut self) {
464        let _span = UpdatesTrace::extension_span::<E>("init");
465        self.0.init();
466    }
467
468    fn enable_device_events(&self) -> bool {
469        self.0.enable_device_events()
470    }
471
472    fn event_preview(&mut self, update: &mut EventUpdate) {
473        let _span = UpdatesTrace::extension_span::<E>("event_preview");
474        self.0.event_preview(update);
475    }
476
477    fn event_ui(&mut self, update: &mut EventUpdate) {
478        let _span = UpdatesTrace::extension_span::<E>("event_ui");
479        self.0.event_ui(update);
480    }
481
482    fn event(&mut self, update: &mut EventUpdate) {
483        let _span = UpdatesTrace::extension_span::<E>("event");
484        self.0.event(update);
485    }
486
487    fn update_preview(&mut self) {
488        let _span = UpdatesTrace::extension_span::<E>("update_preview");
489        self.0.update_preview();
490    }
491
492    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
493        let _span = UpdatesTrace::extension_span::<E>("update_ui");
494        self.0.update_ui(update_widgets);
495    }
496
497    fn update(&mut self) {
498        let _span = UpdatesTrace::extension_span::<E>("update");
499        self.0.update();
500    }
501
502    fn info(&mut self, info_widgets: &mut InfoUpdates) {
503        let _span = UpdatesTrace::extension_span::<E>("info");
504        self.0.info(info_widgets);
505    }
506
507    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
508        let _span = UpdatesTrace::extension_span::<E>("layout");
509        self.0.layout(layout_widgets);
510    }
511
512    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
513        let _span = UpdatesTrace::extension_span::<E>("render");
514        self.0.render(render_widgets, render_update_widgets);
515    }
516
517    fn deinit(&mut self) {
518        let _span = UpdatesTrace::extension_span::<E>("deinit");
519        self.0.deinit();
520    }
521
522    fn boxed(self) -> Box<dyn AppExtensionBoxed>
523    where
524        Self: Sized,
525    {
526        Box::new(self)
527    }
528}
529
530/// Info about an app-extension.
531///
532/// See [`APP::extensions`] for more details.
533#[derive(Clone, Copy)]
534pub struct AppExtensionInfo {
535    /// Extension type ID.
536    pub type_id: TypeId,
537    /// Extension type name.
538    pub type_name: &'static str,
539}
540impl PartialEq for AppExtensionInfo {
541    fn eq(&self, other: &Self) -> bool {
542        self.type_id == other.type_id
543    }
544}
545impl fmt::Debug for AppExtensionInfo {
546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
547        write!(f, "{}", self.type_name)
548    }
549}
550impl Eq for AppExtensionInfo {}
551impl AppExtensionInfo {
552    /// New info for `E`.
553    pub fn new<E: AppExtension>() -> Self {
554        Self {
555            type_id: TypeId::of::<E>(),
556            type_name: type_name::<E>(),
557        }
558    }
559}
560
561/// List of app-extensions that are part of an app.
562#[derive(Clone, PartialEq)]
563pub struct AppExtensionsInfo {
564    infos: Vec<AppExtensionInfo>,
565}
566impl fmt::Debug for AppExtensionsInfo {
567    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
568        f.debug_list().entries(&self.infos).finish()
569    }
570}
571impl AppExtensionsInfo {
572    pub(crate) fn start() -> Self {
573        Self { infos: vec![] }
574    }
575
576    /// Push the extension info.
577    pub fn push<E: AppExtension>(&mut self) {
578        let info = AppExtensionInfo::new::<E>();
579        assert!(!self.contains::<E>(), "app-extension `{info:?}` is already in the list");
580        self.infos.push(info);
581    }
582
583    /// Gets if the extension `E` is in the list.
584    pub fn contains<E: AppExtension>(&self) -> bool {
585        self.contains_info(AppExtensionInfo::new::<E>())
586    }
587
588    /// Gets i the extension is in the list.
589    pub fn contains_info(&self, info: AppExtensionInfo) -> bool {
590        self.infos.iter().any(|e| e.type_id == info.type_id)
591    }
592
593    /// Panics if the extension `E` is not present.
594    #[track_caller]
595    pub fn require<E: AppExtension>(&self) {
596        let info = AppExtensionInfo::new::<E>();
597        assert!(self.contains_info(info), "app-extension `{info:?}` is required");
598    }
599}
600impl ops::Deref for AppExtensionsInfo {
601    type Target = [AppExtensionInfo];
602
603    fn deref(&self) -> &Self::Target {
604        &self.infos
605    }
606}
607
608/// Desired next step of app main loop.
609#[derive(Copy, Clone, Debug, PartialEq, Eq)]
610#[must_use = "methods that return `AppControlFlow` expect to be inside a controlled loop"]
611pub enum AppControlFlow {
612    /// Immediately try to receive more app events.
613    Poll,
614    /// Sleep until an app event is received.
615    ///
616    /// Note that a deadline might be set in case a timer is running.
617    Wait,
618    /// Exit the loop and drop the app.
619    Exit,
620}
621impl AppControlFlow {
622    /// Assert that the value is [`AppControlFlow::Wait`].
623    #[track_caller]
624    pub fn assert_wait(self) {
625        assert_eq!(AppControlFlow::Wait, self)
626    }
627
628    /// Assert that the value is [`AppControlFlow::Exit`].
629    #[track_caller]
630    pub fn assert_exit(self) {
631        assert_eq!(AppControlFlow::Exit, self)
632    }
633}
634
635/// A headless app controller.
636///
637/// Headless apps don't cause external side-effects like visible windows and don't listen to system events.
638/// They can be used for creating apps like a command line app that renders widgets, or for creating integration tests.
639///
640/// You can start a headless app using [`AppExtended::run_headless`].
641pub struct HeadlessApp {
642    app: RunningApp<Box<dyn AppExtensionBoxed>>,
643}
644impl HeadlessApp {
645    /// If headless rendering is enabled.
646    ///
647    /// When enabled windows are still not visible but frames will be rendered and the frame
648    /// image can be requested.
649    ///
650    /// Note that [`UiNode::render`] is still called when a renderer is disabled and you can still
651    /// query the latest frame from `WINDOWS.widget_tree`. The only thing that
652    /// is disabled is the actual renderer that converts display lists to pixels.
653    ///
654    /// [`UiNode::render`]: crate::widget::node::UiNode::render
655    pub fn renderer_enabled(&mut self) -> bool {
656        VIEW_PROCESS.is_available()
657    }
658
659    /// Does updates unobserved.
660    ///
661    /// See [`update_observed`] for more details.
662    ///
663    /// [`update_observed`]: HeadlessApp::update
664    pub fn update(&mut self, wait_app_event: bool) -> AppControlFlow {
665        self.update_observed(&mut (), wait_app_event)
666    }
667
668    /// Does updates observing [`update`] only.
669    ///
670    /// See [`update_observed`] for more details.
671    ///
672    /// [`update`]: AppEventObserver::update
673    /// [`update_observed`]: HeadlessApp::update
674    pub fn update_observe(&mut self, on_update: impl FnMut(), wait_app_event: bool) -> AppControlFlow {
675        struct Observer<F>(F);
676        impl<F: FnMut()> AppEventObserver for Observer<F> {
677            fn update(&mut self) {
678                (self.0)()
679            }
680        }
681        let mut observer = Observer(on_update);
682
683        self.update_observed(&mut observer, wait_app_event)
684    }
685
686    /// Does updates observing [`event`] only.
687    ///
688    /// See [`update_observed`] for more details.
689    ///
690    /// [`event`]: AppEventObserver::event
691    /// [`update_observed`]: HeadlessApp::update
692    pub fn update_observe_event(&mut self, on_event: impl FnMut(&mut EventUpdate), wait_app_event: bool) -> AppControlFlow {
693        struct Observer<F>(F);
694        impl<F: FnMut(&mut EventUpdate)> AppEventObserver for Observer<F> {
695            fn event(&mut self, update: &mut EventUpdate) {
696                (self.0)(update);
697            }
698        }
699        let mut observer = Observer(on_event);
700        self.update_observed(&mut observer, wait_app_event)
701    }
702
703    /// Does updates with an [`AppEventObserver`].
704    ///
705    /// If `wait_app_event` is `true` the thread sleeps until at least one app event is received or a timer elapses,
706    /// if it is `false` only responds to app events already in the buffer.
707    pub fn update_observed<O: AppEventObserver>(&mut self, observer: &mut O, mut wait_app_event: bool) -> AppControlFlow {
708        if self.app.has_exited() {
709            return AppControlFlow::Exit;
710        }
711
712        loop {
713            match self.app.poll(wait_app_event, observer) {
714                AppControlFlow::Poll => {
715                    wait_app_event = false;
716                    continue;
717                }
718                flow => return flow,
719            }
720        }
721    }
722
723    /// Execute the async `task` in the UI thread, updating the app until it finishes or the app shuts-down.
724    ///
725    /// Returns the task result if the app has not shut-down.
726    pub fn run_task<R, T>(&mut self, task: impl IntoFuture<IntoFuture = T>) -> Option<R>
727    where
728        R: 'static,
729        T: Future<Output = R> + Send + Sync + 'static,
730    {
731        let mut task = UiTask::new(None, task);
732
733        let mut flow = self.update_observe(
734            || {
735                task.update();
736            },
737            false,
738        );
739
740        if task.update().is_some() {
741            let r = task.into_result().ok();
742            debug_assert!(r.is_some());
743            return r;
744        }
745
746        let mut n = 0;
747        while flow != AppControlFlow::Exit {
748            flow = self.update_observe(
749                || {
750                    task.update();
751                },
752                true,
753            );
754
755            if n == 10_000 {
756                tracing::error!("excessive future awaking, run_task ran 10_000 update cycles without finishing");
757            } else if n == 100_000 {
758                panic!("run_task stuck, ran 100_000 update cycles without finishing");
759            }
760            n += 1;
761
762            match task.into_result() {
763                Ok(r) => return Some(r),
764                Err(t) => task = t,
765            }
766        }
767        task.cancel();
768
769        None
770    }
771
772    /// Requests and wait for app exit.
773    ///
774    /// Forces deinit if exit is cancelled.
775    pub fn exit(mut self) {
776        self.run_task(async move {
777            let req = APP.exit();
778            req.wait_rsp().await;
779        });
780    }
781
782    /// If the app has exited.
783    ///
784    /// Exited apps cannot update anymore. The app should be dropped to unload the app scope.
785    pub fn has_exited(&self) -> bool {
786        self.app.has_exited()
787    }
788}
789
790/// Observer for [`HeadlessApp::update_observed`].
791///
792/// This works like a temporary app extension that runs only for the update call.
793pub trait AppEventObserver {
794    /// Called for each raw event received.
795    fn raw_event(&mut self, ev: &zng_view_api::Event) {
796        let _ = ev;
797    }
798
799    /// Called just after [`AppExtension::event_preview`].
800    fn event_preview(&mut self, update: &mut EventUpdate) {
801        let _ = update;
802    }
803
804    /// Called just after [`AppExtension::event_ui`].
805    fn event_ui(&mut self, update: &mut EventUpdate) {
806        let _ = update;
807    }
808
809    /// Called just after [`AppExtension::event`].
810    fn event(&mut self, update: &mut EventUpdate) {
811        let _ = update;
812    }
813
814    /// Called just after [`AppExtension::update_preview`].
815    fn update_preview(&mut self) {}
816
817    /// Called just after [`AppExtension::update_ui`].
818    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
819        let _ = update_widgets;
820    }
821
822    /// Called just after [`AppExtension::update`].
823    fn update(&mut self) {}
824
825    /// Called just after [`AppExtension::info`].
826    fn info(&mut self, info_widgets: &mut InfoUpdates) {
827        let _ = info_widgets;
828    }
829
830    /// Called just after [`AppExtension::layout`].
831    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
832        let _ = layout_widgets;
833    }
834
835    /// Called just after [`AppExtension::render`].
836    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
837        let _ = (render_widgets, render_update_widgets);
838    }
839
840    /// Cast to dynamically dispatched observer, this can help avoid code bloat.
841    ///
842    /// The app methods that accept observers automatically use this method if the feature `"dyn_app_extension"` is active.
843    fn as_dyn(&mut self) -> DynAppEventObserver
844    where
845        Self: Sized,
846    {
847        DynAppEventObserver(self)
848    }
849}
850/// Nil observer, does nothing.
851impl AppEventObserver for () {}
852
853#[doc(hidden)]
854pub struct DynAppEventObserver<'a>(&'a mut dyn AppEventObserverDyn);
855
856trait AppEventObserverDyn {
857    fn raw_event_dyn(&mut self, ev: &zng_view_api::Event);
858    fn event_preview_dyn(&mut self, update: &mut EventUpdate);
859    fn event_ui_dyn(&mut self, update: &mut EventUpdate);
860    fn event_dyn(&mut self, update: &mut EventUpdate);
861    fn update_preview_dyn(&mut self);
862    fn update_ui_dyn(&mut self, updates: &mut WidgetUpdates);
863    fn update_dyn(&mut self);
864    fn info_dyn(&mut self, info_widgets: &mut InfoUpdates);
865    fn layout_dyn(&mut self, layout_widgets: &mut LayoutUpdates);
866    fn render_dyn(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates);
867}
868impl<O: AppEventObserver> AppEventObserverDyn for O {
869    fn raw_event_dyn(&mut self, ev: &zng_view_api::Event) {
870        self.raw_event(ev)
871    }
872
873    fn event_preview_dyn(&mut self, update: &mut EventUpdate) {
874        self.event_preview(update)
875    }
876
877    fn event_ui_dyn(&mut self, update: &mut EventUpdate) {
878        self.event_ui(update)
879    }
880
881    fn event_dyn(&mut self, update: &mut EventUpdate) {
882        self.event(update)
883    }
884
885    fn update_preview_dyn(&mut self) {
886        self.update_preview()
887    }
888
889    fn update_ui_dyn(&mut self, update_widgets: &mut WidgetUpdates) {
890        self.update_ui(update_widgets)
891    }
892
893    fn update_dyn(&mut self) {
894        self.update()
895    }
896
897    fn info_dyn(&mut self, info_widgets: &mut InfoUpdates) {
898        self.info(info_widgets)
899    }
900
901    fn layout_dyn(&mut self, layout_widgets: &mut LayoutUpdates) {
902        self.layout(layout_widgets)
903    }
904
905    fn render_dyn(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
906        self.render(render_widgets, render_update_widgets)
907    }
908}
909impl AppEventObserver for DynAppEventObserver<'_> {
910    fn raw_event(&mut self, ev: &zng_view_api::Event) {
911        self.0.raw_event_dyn(ev)
912    }
913
914    fn event_preview(&mut self, update: &mut EventUpdate) {
915        self.0.event_preview_dyn(update)
916    }
917
918    fn event_ui(&mut self, update: &mut EventUpdate) {
919        self.0.event_ui_dyn(update)
920    }
921
922    fn event(&mut self, update: &mut EventUpdate) {
923        self.0.event_dyn(update)
924    }
925
926    fn update_preview(&mut self) {
927        self.0.update_preview_dyn()
928    }
929
930    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
931        self.0.update_ui_dyn(update_widgets)
932    }
933
934    fn update(&mut self) {
935        self.0.update_dyn()
936    }
937
938    fn info(&mut self, info_widgets: &mut InfoUpdates) {
939        self.0.info_dyn(info_widgets)
940    }
941
942    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
943        self.0.layout_dyn(layout_widgets)
944    }
945
946    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
947        self.0.render_dyn(render_widgets, render_update_widgets)
948    }
949
950    fn as_dyn(&mut self) -> DynAppEventObserver {
951        DynAppEventObserver(self.0)
952    }
953}
954
955impl AppExtension for () {
956    fn register(&self, _: &mut AppExtensionsInfo) {}
957}
958impl<A: AppExtension, B: AppExtension> AppExtension for (A, B) {
959    fn init(&mut self) {
960        self.0.init();
961        self.1.init();
962    }
963
964    fn register(&self, info: &mut AppExtensionsInfo) {
965        self.0.register(info);
966        self.1.register(info);
967    }
968
969    fn enable_device_events(&self) -> bool {
970        self.0.enable_device_events() || self.1.enable_device_events()
971    }
972
973    fn update_preview(&mut self) {
974        self.0.update_preview();
975        self.1.update_preview();
976    }
977
978    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
979        self.0.update_ui(update_widgets);
980        self.1.update_ui(update_widgets);
981    }
982
983    fn update(&mut self) {
984        self.0.update();
985        self.1.update();
986    }
987
988    fn info(&mut self, info_widgets: &mut InfoUpdates) {
989        self.0.info(info_widgets);
990        self.1.info(info_widgets);
991    }
992
993    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
994        self.0.layout(layout_widgets);
995        self.1.layout(layout_widgets);
996    }
997
998    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
999        self.0.render(render_widgets, render_update_widgets);
1000        self.1.render(render_widgets, render_update_widgets);
1001    }
1002
1003    fn event_preview(&mut self, update: &mut EventUpdate) {
1004        self.0.event_preview(update);
1005        self.1.event_preview(update);
1006    }
1007
1008    fn event_ui(&mut self, update: &mut EventUpdate) {
1009        self.0.event_ui(update);
1010        self.1.event_ui(update);
1011    }
1012
1013    fn event(&mut self, update: &mut EventUpdate) {
1014        self.0.event(update);
1015        self.1.event(update);
1016    }
1017
1018    fn deinit(&mut self) {
1019        self.1.deinit();
1020        self.0.deinit();
1021    }
1022}
1023
1024#[cfg(feature = "dyn_app_extension")]
1025impl AppExtension for Vec<Box<dyn AppExtensionBoxed>> {
1026    fn init(&mut self) {
1027        for ext in self {
1028            ext.init();
1029        }
1030    }
1031
1032    fn register(&self, info: &mut AppExtensionsInfo) {
1033        for ext in self {
1034            ext.register(info);
1035        }
1036    }
1037
1038    fn enable_device_events(&self) -> bool {
1039        self.iter().any(|e| e.enable_device_events())
1040    }
1041
1042    fn update_preview(&mut self) {
1043        for ext in self {
1044            ext.update_preview();
1045        }
1046    }
1047
1048    fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
1049        for ext in self {
1050            ext.update_ui(update_widgets);
1051        }
1052    }
1053
1054    fn update(&mut self) {
1055        for ext in self {
1056            ext.update();
1057        }
1058    }
1059
1060    fn event_preview(&mut self, update: &mut EventUpdate) {
1061        for ext in self {
1062            ext.event_preview(update);
1063        }
1064    }
1065
1066    fn event_ui(&mut self, update: &mut EventUpdate) {
1067        for ext in self {
1068            ext.event_ui(update);
1069        }
1070    }
1071
1072    fn event(&mut self, update: &mut EventUpdate) {
1073        for ext in self {
1074            ext.event(update);
1075        }
1076    }
1077
1078    fn info(&mut self, info_widgets: &mut InfoUpdates) {
1079        for ext in self {
1080            ext.info(info_widgets);
1081        }
1082    }
1083
1084    fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
1085        for ext in self {
1086            ext.layout(layout_widgets);
1087        }
1088    }
1089
1090    fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
1091        for ext in self {
1092            ext.render(render_widgets, render_update_widgets);
1093        }
1094    }
1095
1096    fn deinit(&mut self) {
1097        for ext in self.iter_mut().rev() {
1098            ext.deinit();
1099        }
1100    }
1101}
1102
1103/// Start and manage an app process.
1104pub struct APP;
1105impl APP {
1106    /// If the crate was built with `feature="multi_app"`.
1107    ///
1108    /// If `true` multiple apps can run in the same process, but only one app per thread at a time.
1109    pub fn multi_app_enabled(&self) -> bool {
1110        cfg!(feature = "multi_app")
1111    }
1112
1113    /// If an app is already running in the current thread.
1114    ///
1115    /// Apps are *running* as soon as they start building, and stop running after
1116    /// [`AppExtended::run`] returns or the [`HeadlessApp`] is dropped.
1117    ///
1118    /// You can use [`app_local!`] to create *static* resources that live for the app lifetime.
1119    ///
1120    /// [`app_local!`]: zng_app_context::app_local
1121    pub fn is_running(&self) -> bool {
1122        LocalContext::current_app().is_some()
1123    }
1124
1125    /// Gets the unique ID of the current app.
1126    ///
1127    /// This ID usually does not change as most apps only run once per process, but it can change often during tests.
1128    /// Resources that interact with [`app_local!`] values can use this ID to ensure that they are still operating in the same
1129    /// app.
1130    ///
1131    /// [`app_local!`]: zng_app_context::app_local
1132    pub fn id(&self) -> Option<AppId> {
1133        LocalContext::current_app()
1134    }
1135
1136    #[cfg(not(feature = "multi_app"))]
1137    fn assert_can_run_single() {
1138        use std::sync::atomic::*;
1139        static CAN_RUN: AtomicBool = AtomicBool::new(true);
1140
1141        if !CAN_RUN.swap(false, Ordering::SeqCst) {
1142            panic!("only one app is allowed per process")
1143        }
1144    }
1145
1146    fn assert_can_run() {
1147        #[cfg(not(feature = "multi_app"))]
1148        Self::assert_can_run_single();
1149        if APP.is_running() {
1150            panic!("only one app is allowed per thread")
1151        }
1152    }
1153
1154    /// Returns a [`WindowMode`] value that indicates if the app is headless, headless with renderer or headed.
1155    ///
1156    /// Note that specific windows can be in headless mode even if the app is headed.
1157    pub fn window_mode(&self) -> WindowMode {
1158        if VIEW_PROCESS.is_available() {
1159            if VIEW_PROCESS.is_headless_with_render() {
1160                WindowMode::HeadlessWithRenderer
1161            } else {
1162                WindowMode::Headed
1163            }
1164        } else {
1165            WindowMode::Headless
1166        }
1167    }
1168    /// List of app extensions that are part of the current app.
1169    pub fn extensions(&self) -> Arc<AppExtensionsInfo> {
1170        APP_PROCESS_SV.read().extensions()
1171    }
1172
1173    /// If device events are enabled for the current app.
1174    ///
1175    /// See [`AppExtension::enable_device_events`] for more details.
1176    pub fn device_events(&self) -> bool {
1177        APP_PROCESS_SV.read().device_events
1178    }
1179}
1180
1181impl APP {
1182    /// Starts building an application with no extensions.
1183    #[cfg(feature = "dyn_app_extension")]
1184    pub fn minimal(&self) -> AppExtended<Vec<Box<dyn AppExtensionBoxed>>> {
1185        #[cfg(debug_assertions)]
1186        print_tracing(tracing::Level::INFO);
1187        assert_not_view_process();
1188        Self::assert_can_run();
1189        check_deadlock();
1190        let _ = INSTANT.now();
1191        let scope = LocalContext::start_app(AppId::new_unique());
1192        AppExtended {
1193            extensions: vec![],
1194            view_process_exe: None,
1195            view_process_env: HashMap::new(),
1196            _cleanup: scope,
1197        }
1198    }
1199
1200    /// Starts building an application with no extensions.
1201    #[cfg(not(feature = "dyn_app_extension"))]
1202    pub fn minimal(&self) -> AppExtended<()> {
1203        #[cfg(debug_assertions)]
1204        print_tracing(tracing::Level::INFO);
1205        assert_not_view_process();
1206        Self::assert_can_run();
1207        check_deadlock();
1208        let scope = LocalContext::start_app(AppId::new_unique());
1209        AppExtended {
1210            extensions: (),
1211            view_process_exe: None,
1212            view_process_env: HashMap::new(),
1213            _cleanup: scope,
1214        }
1215    }
1216}
1217
1218/// Application builder.
1219///
1220/// You can use `APP` to start building the app.
1221pub struct AppExtended<E: AppExtension> {
1222    extensions: E,
1223    view_process_exe: Option<PathBuf>,
1224    view_process_env: HashMap<Txt, Txt>,
1225
1226    // cleanup on drop.
1227    _cleanup: AppScope,
1228}
1229#[cfg(feature = "dyn_app_extension")]
1230impl AppExtended<Vec<Box<dyn AppExtensionBoxed>>> {
1231    /// Includes an application extension.
1232    pub fn extend<F: AppExtension>(mut self, extension: F) -> AppExtended<Vec<Box<dyn AppExtensionBoxed>>> {
1233        self.extensions.push(TraceAppExt(extension).boxed());
1234        self
1235    }
1236
1237    /// If the application should notify raw device events.
1238    ///
1239    /// Device events are raw events not targeting any window, like a mouse move on any part of the screen.
1240    /// They tend to be high-volume events so there is a performance cost to activating this. Note that if
1241    /// this is `false` you still get the mouse move over windows of the app.
1242    pub fn enable_device_events(self) -> AppExtended<Vec<Box<dyn AppExtensionBoxed>>> {
1243        struct EnableDeviceEvents;
1244        impl AppExtension for EnableDeviceEvents {
1245            fn enable_device_events(&self) -> bool {
1246                true
1247            }
1248        }
1249        self.extend(EnableDeviceEvents)
1250    }
1251
1252    fn run_dyn(self, start: std::pin::Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
1253        let app = RunningApp::start(
1254            self._cleanup,
1255            self.extensions,
1256            true,
1257            true,
1258            self.view_process_exe,
1259            self.view_process_env,
1260        );
1261
1262        UPDATES.run(start).perm();
1263
1264        app.run_headed();
1265    }
1266
1267    fn run_headless_dyn(self, with_renderer: bool) -> HeadlessApp {
1268        let app = RunningApp::start(
1269            self._cleanup,
1270            self.extensions.boxed(),
1271            false,
1272            with_renderer,
1273            self.view_process_exe,
1274            self.view_process_env,
1275        );
1276
1277        HeadlessApp { app }
1278    }
1279}
1280
1281// Monomorphize dyn app. Without this the entire RunningApp code is generic that must build on the dependent crates.
1282#[cfg(feature = "dyn_app_extension")]
1283impl<E: AppExtension> AppExtended<E> {
1284    fn cast_app(self) -> AppExtended<Vec<Box<dyn AppExtensionBoxed>>> {
1285        let app: Box<dyn std::any::Any> = Box::new(self);
1286        match app.downcast::<AppExtended<Vec<Box<dyn AppExtensionBoxed>>>>() {
1287            Ok(ok) => *ok,
1288            Err(e) => {
1289                let app = *e.downcast::<Self>().unwrap();
1290                AppExtended {
1291                    extensions: vec![app.extensions.boxed()],
1292                    view_process_exe: app.view_process_exe,
1293                    view_process_env: app.view_process_env,
1294                    _cleanup: app._cleanup,
1295                }
1296            }
1297        }
1298    }
1299
1300    fn run_impl(self, start: impl Future<Output = ()> + Send + 'static) {
1301        self.cast_app().run_dyn(Box::pin(start))
1302    }
1303
1304    fn run_headless_impl(self, with_renderer: bool) -> HeadlessApp {
1305        self.cast_app().run_headless_dyn(with_renderer)
1306    }
1307}
1308
1309#[cfg(not(feature = "dyn_app_extension"))]
1310impl<E: AppExtension> AppExtended<E> {
1311    /// Includes an application extension.
1312    pub fn extend<F: AppExtension>(self, extension: F) -> AppExtended<impl AppExtension> {
1313        AppExtended {
1314            _cleanup: self._cleanup,
1315            extensions: (self.extensions, TraceAppExt(extension)),
1316            view_process_exe: self.view_process_exe,
1317            view_process_env: self.view_process_env,
1318        }
1319    }
1320
1321    /// If the application should notify raw device events.
1322    ///
1323    /// Device events are raw events not targeting any window, like a mouse move on any part of the screen.
1324    /// They tend to be high-volume events so there is a performance cost to activating this. Note that if
1325    /// this is `false` you still get the mouse move over windows of the app.
1326    pub fn enable_device_events(self) -> AppExtended<impl AppExtension> {
1327        struct EnableDeviceEvents;
1328        impl AppExtension for EnableDeviceEvents {
1329            fn enable_device_events(&self) -> bool {
1330                true
1331            }
1332        }
1333        self.extend(EnableDeviceEvents)
1334    }
1335
1336    fn run_impl(self, start: impl Future<Output = ()> + Send + 'static) {
1337        let app = RunningApp::start(
1338            self._cleanup,
1339            self.extensions,
1340            true,
1341            true,
1342            self.view_process_exe,
1343            self.view_process_env,
1344        );
1345
1346        UPDATES.run(start).perm();
1347
1348        app.run_headed();
1349    }
1350
1351    fn run_headless_impl(self, with_renderer: bool) -> HeadlessApp {
1352        let app = RunningApp::start(
1353            self._cleanup,
1354            self.extensions.boxed(),
1355            false,
1356            with_renderer,
1357            self.view_process_exe,
1358            self.view_process_env,
1359        );
1360
1361        HeadlessApp { app }
1362    }
1363}
1364impl<E: AppExtension> AppExtended<E> {
1365    /// Set the path to the executable for the *View Process*.
1366    ///
1367    /// By the default the current executable is started again as a *View Process*, you can use
1368    /// two executables instead, by setting this value.
1369    ///
1370    /// Note that the `view_process_exe` must start a view server and both
1371    /// executables must be build using the same exact [`VERSION`].
1372    ///
1373    /// [`VERSION`]: zng_view_api::VERSION  
1374    pub fn view_process_exe(mut self, view_process_exe: impl Into<PathBuf>) -> Self {
1375        self.view_process_exe = Some(view_process_exe.into());
1376        self
1377    }
1378
1379    /// Set an env variable for the view-process.
1380    pub fn view_process_env(mut self, name: impl Into<Txt>, value: impl Into<Txt>) -> Self {
1381        self.view_process_env.insert(name.into(), value.into());
1382        self
1383    }
1384
1385    /// Starts the app, then starts polling `start` to run.
1386    ///
1387    /// This method only returns when the app has exited.
1388    ///
1389    /// The `start` task runs in a [`UiTask`] in the app context, note that it only needs to start the app, usually
1390    /// by opening a window, the app will keep running after `start` is finished.
1391    pub fn run<F: Future<Output = ()> + Send + 'static>(self, start: impl IntoFuture<IntoFuture = F>) {
1392        let start = start.into_future();
1393        #[cfg(feature = "dyn_closure")]
1394        let start = Box::pin(start);
1395        self.run_impl(start)
1396    }
1397
1398    /// Initializes extensions in headless mode and returns an [`HeadlessApp`].
1399    ///
1400    /// If `with_renderer` is `true` spawns a renderer process for headless rendering. See [`HeadlessApp::renderer_enabled`]
1401    /// for more details.
1402    pub fn run_headless(self, with_renderer: bool) -> HeadlessApp {
1403        self.run_headless_impl(with_renderer)
1404    }
1405}
1406
1407// this module is declared here on purpose so that advanced `impl APP` blocks show later in the docs.
1408mod running;
1409pub use running::*;
1410
1411mod private {
1412    // https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
1413    pub trait Sealed {}
1414}
1415
1416/// Enables [`tracing`] events printing if a subscriber is not already set.
1417///
1418/// All non-fatal errors in the Zng project are logged using tracing.
1419///
1420/// In debug builds this function is called automatically with level INFO on app start.
1421///
1422/// In `"wasm32"` builds logs to the browser console.
1423///
1424/// In `"android"` builds logs to logcat.
1425///
1426/// See also [`test_log`] to enable panicking on error log.
1427///
1428/// See also [`print_tracing_filter`] for the filter used by this.
1429///
1430/// [`tracing`]: https://docs.rs/tracing
1431pub fn print_tracing(max: tracing::Level) -> bool {
1432    use tracing_subscriber::prelude::*;
1433
1434    let layers = tracing_subscriber::registry().with(FilterLayer(max));
1435
1436    #[cfg(target_os = "android")]
1437    let layers = layers.with(tracing_android::layer(&zng_env::about().pkg_name).unwrap());
1438
1439    #[cfg(not(target_os = "android"))]
1440    let layers = {
1441        let fmt_layer = tracing_subscriber::fmt::layer().without_time();
1442
1443        #[cfg(target_arch = "wasm32")]
1444        let fmt_layer = fmt_layer.with_ansi(false).with_writer(tracing_web::MakeWebConsoleWriter::new());
1445
1446        layers.with(fmt_layer)
1447    };
1448
1449    layers.try_init().is_ok()
1450}
1451
1452struct FilterLayer(tracing::Level);
1453impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for FilterLayer {
1454    fn enabled(&self, metadata: &tracing::Metadata<'_>, _: tracing_subscriber::layer::Context<'_, S>) -> bool {
1455        print_tracing_filter(&self.0, metadata)
1456    }
1457
1458    fn max_level_hint(&self) -> Option<tracing::metadata::LevelFilter> {
1459        Some(self.0.into())
1460    }
1461
1462    #[cfg(any(test, feature = "test_util"))]
1463    fn on_event(&self, event: &tracing::Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) {
1464        if event.metadata().level() == &tracing::Level::ERROR && APP.is_running() && TEST_LOG.get() {
1465            struct MsgCollector<'a>(&'a mut String);
1466            impl tracing::field::Visit for MsgCollector<'_> {
1467                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
1468                    use std::fmt::Write;
1469                    write!(self.0, "\n  {} = {:?}", field.name(), value).unwrap();
1470                }
1471            }
1472
1473            let meta = event.metadata();
1474            let file = meta.file().unwrap_or("");
1475            let line = meta.line().unwrap_or(0);
1476
1477            let mut msg = format!("[{file}:{line}]");
1478            event.record(&mut MsgCollector(&mut msg));
1479
1480            panic!("[LOG-ERROR]{msg}")
1481        }
1482    }
1483}
1484/// Filter used by [`print_tracing`], removes some log noise from dependencies.
1485///
1486/// Use `tracing_subscriber::filter::FilterFn` plug this filter into a tracing setup.
1487pub fn print_tracing_filter(level: &tracing::Level, metadata: &tracing::Metadata) -> bool {
1488    if metadata.level() > level {
1489        return false;
1490    }
1491
1492    if metadata.level() == &tracing::Level::INFO {
1493        // suppress large info about texture cache
1494        if metadata.target() == "zng_webrender::device::gl" {
1495            return false;
1496        }
1497        // suppress config dump
1498        if metadata.target() == "zng_webrender::renderer::init" {
1499            return false;
1500        }
1501    } else if metadata.level() == &tracing::Level::WARN {
1502        // suppress webrender warnings:
1503        //
1504        if metadata.target() == "zng_webrender::device::gl" {
1505            // Suppress "Cropping texture upload Box2D((0, 0), (0, 1)) to None"
1506            // This happens when an empty frame is rendered.
1507            if metadata.line() == Some(4647) {
1508                return false;
1509            }
1510        }
1511
1512        // suppress font-kit warnings:
1513        //
1514        if metadata.target() == "font_kit::loaders::freetype" {
1515            // Suppress "$fn(): found invalid platform ID $n"
1516            // This does not look fully implemented and generates a lot of warns
1517            // with the default Ubuntu font set all with valid platform IDs.
1518            if metadata.line() == Some(734) {
1519                return false;
1520            }
1521        }
1522    }
1523
1524    true
1525}
1526
1527/// Modifies the [`print_tracing`] subscriber to panic for error logs in the current app.
1528#[cfg(any(test, feature = "test_util"))]
1529pub fn test_log() {
1530    TEST_LOG.set(true);
1531}
1532
1533#[cfg(any(test, feature = "test_util"))]
1534zng_app_context::app_local! {
1535    static TEST_LOG: bool = false;
1536}
1537
1538#[doc(hidden)]
1539pub fn name_from_pkg_name(name: &'static str) -> Txt {
1540    let mut n = String::new();
1541    let mut sep = "";
1542    for part in name.split(&['-', '_']) {
1543        n.push_str(sep);
1544        let mut chars = part.char_indices();
1545        let (_, c) = chars.next().unwrap();
1546        c.to_uppercase().for_each(|c| n.push(c));
1547        if let Some((i, _)) = chars.next() {
1548            n.push_str(&part[i..]);
1549        }
1550        sep = " ";
1551    }
1552    n.into()
1553}
1554
1555#[doc(hidden)]
1556pub fn txt_from_pkg_meta(value: &'static str) -> Txt {
1557    value.into()
1558}