zng_wgt_inspector/live/
data_model.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use std::{fmt, ops, sync::Arc};

use parking_lot::Mutex;
use zng_app::widget::{
    builder::WidgetType,
    info::WidgetInfoTree,
    inspector::{InspectorInfo, WidgetInfoInspectorExt},
};
use zng_var::{types::WeakArcVar, WeakVar};
use zng_view_api::window::FrameId;
use zng_wgt::prelude::*;

#[derive(Default)]
pub struct InspectedTreeData {
    widgets: IdMap<WidgetId, InspectedWidget>,
    latest_frame: Option<ArcVar<FrameId>>,
}

/// Represents an actively inspected widget tree.
#[derive(Clone)]
pub struct InspectedTree {
    tree: ArcVar<WidgetInfoTree>,
    data: Arc<Mutex<InspectedTreeData>>,
}
impl fmt::Debug for InspectedTree {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InspectedTree")
            .field("tree", &self.tree.get())
            .finish_non_exhaustive()
    }
}
impl PartialEq for InspectedTree {
    fn eq(&self, other: &Self) -> bool {
        self.tree.var_ptr() == other.tree.var_ptr()
    }
}
impl InspectedTree {
    /// Initial inspection.
    pub fn new(tree: WidgetInfoTree) -> Self {
        Self {
            data: Arc::new(Mutex::new(InspectedTreeData::default())),
            tree: var(tree),
        }
    }

    /// Update inspection.
    ///
    /// # Panics
    ///
    /// Panics if info is not for the same window ID.
    pub fn update(&self, tree: WidgetInfoTree) {
        assert_eq!(self.tree.with(|t| t.window_id()), tree.window_id());

        // update and retain
        self.tree.set(tree.clone());

        let mut data = self.data.lock();
        let mut removed = false;
        for (k, v) in data.widgets.iter() {
            if let Some(w) = tree.get(*k) {
                v.update(w);
            } else {
                v.removed.set(true);
                removed = true;
            }
        }
        // update can drop children inspectors so we can't update inside the retain closure.
        data.widgets
            .retain(|k, v| v.info.strong_count() > 1 && (!removed || tree.get(*k).is_some()));

        if let Some(f) = &data.latest_frame {
            if f.strong_count() == 1 {
                data.latest_frame = None;
            } else {
                f.set(tree.stats().last_frame);
            }
        }
    }

    /// Update all render watcher variables.
    pub fn update_render(&self) {
        let mut data = self.data.lock();
        if let Some(f) = &data.latest_frame {
            if f.strong_count() == 1 {
                data.latest_frame = None;
            } else {
                f.set(self.tree.with(|t| t.stats().last_frame));
            }
        }
    }

    /// Create a weak reference to this tree.
    pub fn downgrade(&self) -> WeakInspectedTree {
        WeakInspectedTree {
            tree: self.tree.downgrade(),
            data: Arc::downgrade(&self.data),
        }
    }

    /// Gets a widget inspector if the widget is in the latest info.
    pub fn inspect(&self, widget_id: WidgetId) -> Option<InspectedWidget> {
        match self.data.lock().widgets.entry(widget_id) {
            IdEntry::Occupied(e) => Some(e.get().clone()),
            IdEntry::Vacant(e) => self.tree.with(|t| {
                t.get(widget_id)
                    .map(|w| e.insert(InspectedWidget::new(w, self.downgrade())).clone())
            }),
        }
    }

    /// Gets a widget inspector for the root widget.
    pub fn inspect_root(&self) -> InspectedWidget {
        self.inspect(self.tree.with(|t| t.root().id())).unwrap()
    }

    /// Latest frame updated using [`update_render`].
    ///
    /// [`update_render`]: Self::update_render
    pub fn last_frame(&self) -> impl Var<FrameId> {
        let mut data = self.data.lock();
        data.latest_frame
            .get_or_insert_with(|| var(self.tree.with(|t| t.stats().last_frame)))
            .clone()
    }
}

/// Represents a weak reference to a [`InspectedTree`].
#[derive(Clone)]
pub struct WeakInspectedTree {
    tree: WeakArcVar<WidgetInfoTree>,
    data: std::sync::Weak<Mutex<InspectedTreeData>>,
}
impl WeakInspectedTree {
    /// Try to get a strong reference to the inspected tree.
    pub fn upgrade(&self) -> Option<InspectedTree> {
        Some(InspectedTree {
            tree: self.tree.upgrade()?,
            data: self.data.upgrade()?,
        })
    }
}

struct InspectedWidgetCache {
    tree: WeakInspectedTree,
    children: Option<BoxedVar<Vec<InspectedWidget>>>,
    parent_property_name: Option<BoxedVar<Txt>>,
}

/// Represents an actively inspected widget.
///
/// See [`InspectedTree::inspect`].
#[derive(Clone)]
pub struct InspectedWidget {
    info: ArcVar<WidgetInfo>,
    removed: ArcVar<bool>,
    cache: Arc<Mutex<InspectedWidgetCache>>,
}
impl fmt::Debug for InspectedWidget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InspectedWidget")
            .field("info", &self.info.get())
            .field("removed", &self.removed.get())
            .finish_non_exhaustive()
    }
}
impl PartialEq for InspectedWidget {
    fn eq(&self, other: &Self) -> bool {
        self.info.var_ptr() == other.info.var_ptr()
    }
}
impl Eq for InspectedWidget {}
impl InspectedWidget {
    /// Initial inspection.
    fn new(info: WidgetInfo, tree: WeakInspectedTree) -> Self {
        Self {
            info: var(info),
            removed: var(false),
            cache: Arc::new(Mutex::new(InspectedWidgetCache {
                tree,
                children: None,
                parent_property_name: None,
            })),
        }
    }

    /// Update inspection.
    ///
    /// # Panics
    ///
    /// Panics if info is not for the same widget ID.
    fn update(&self, info: WidgetInfo) {
        assert_eq!(self.info.with(|i| i.id()), info.id());
        self.info.set(info);

        let mut cache = self.cache.lock();
        if let Some(c) = &cache.children {
            if c.strong_count() == 1 {
                cache.children = None;
            }
        }
        if let Some(c) = &cache.parent_property_name {
            if c.strong_count() == 1 {
                cache.parent_property_name = None;
            }
        }
    }

    // /// If this widget inspector is permanently disconnected and will not update.
    // ///
    // /// This is set to `true` when an inspected widget is not found after an update, when `true`
    // /// this inspector will not update even if the same widget ID is re-inserted in another update.
    // pub fn removed(&self) -> impl Var<bool> {
    //     self.removed.read_only()
    // }

    /// Latest info.
    pub fn info(&self) -> impl Var<WidgetInfo> {
        self.info.read_only()
    }

    /// Widget id.
    pub fn id(&self) -> WidgetId {
        self.info.with(|i| i.id())
    }

    // /// Count of ancestor widgets.
    // pub fn depth(&self) -> impl Var<usize> {
    //     self.info.map(|w| w.depth()).actual_var()
    // }

    /// Count of descendant widgets.
    pub fn descendants_len(&self) -> impl Var<usize> {
        self.info.map(|w| w.descendants_len()).actual_var()
    }

    /// Widget type, if the widget was built with inspection info.
    pub fn wgt_type(&self) -> impl Var<Option<WidgetType>> {
        self.info.map(|w| Some(w.inspector_info()?.builder.widget_type())).actual_var()
    }

    /// Widget macro name, or `"<widget>!"` if widget was not built with inspection info.
    pub fn wgt_macro_name(&self) -> impl Var<Txt> {
        self.info
            .map(|w| match w.inspector_info().map(|i| i.builder.widget_type()) {
                Some(t) => formatx!("{}!", t.name()),
                None => Txt::from_static("<widget>!"),
            })
            .actual_var()
    }

    /// Gets the parent's property that has this widget as an input.
    ///
    /// Is an empty string if the widget is not inserted by any property.
    pub fn parent_property_name(&self) -> impl Var<Txt> {
        let mut cache = self.cache.lock();
        cache
            .parent_property_name
            .get_or_insert_with(|| {
                self.info
                    .map(|w| {
                        Txt::from_static(
                            w.parent_property()
                                .map(|(p, _)| w.parent().unwrap().inspect_property(p).unwrap().property().name)
                                .unwrap_or(""),
                        )
                    })
                    .actual_var()
                    .boxed()
            })
            .clone()
    }

    /// Inspect the widget children.
    pub fn children(&self) -> impl Var<Vec<InspectedWidget>> {
        let mut cache = self.cache.lock();
        let cache = &mut *cache;
        cache
            .children
            .get_or_insert_with(|| {
                let tree = cache.tree.clone();
                self.info
                    .map(move |w| {
                        if let Some(tree) = tree.upgrade() {
                            assert_eq!(&tree.tree.get(), w.tree());

                            w.children().map(|w| tree.inspect(w.id()).unwrap()).collect()
                        } else {
                            vec![]
                        }
                    })
                    .actual_var()
                    .boxed()
            })
            .clone()
    }

    /// Inspect the builder, properties and intrinsic nodes that make up the widget.
    ///
    /// Is `None` when the widget is built without inspector info collection.
    pub fn inspector_info(&self) -> impl Var<Option<InspectedInfo>> {
        self.info.map(move |w| w.inspector_info().map(InspectedInfo)).actual_var().boxed()
    }

    /// Create a variable that probes info after every frame is rendered.
    pub fn render_watcher<T: VarValue>(&self, mut probe: impl FnMut(&WidgetInfo) -> T + Send + 'static) -> impl Var<T> {
        merge_var!(
            self.info.clone(),
            self.cache.lock().tree.upgrade().unwrap().last_frame(),
            move |w, _| probe(w)
        )
    }
}

/// [`InspectorInfo`] that can be placed in a variable.
#[derive(Clone)]
pub struct InspectedInfo(pub Arc<InspectorInfo>);
impl fmt::Debug for InspectedInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}
impl PartialEq for InspectedInfo {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}
impl ops::Deref for InspectedInfo {
    type Target = InspectorInfo;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}