zng_wgt_inspector/
live.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
use zng_app::access::ACCESS_CLICK_EVENT;
use zng_ext_config::CONFIG;
use zng_ext_input::{
    gesture::CLICK_EVENT,
    mouse::{MOUSE_HOVERED_EVENT, MOUSE_INPUT_EVENT, MOUSE_MOVE_EVENT, MOUSE_WHEEL_EVENT},
    touch::{TOUCHED_EVENT, TOUCH_INPUT_EVENT, TOUCH_LONG_PRESS_EVENT, TOUCH_MOVE_EVENT, TOUCH_TAP_EVENT, TOUCH_TRANSFORM_EVENT},
};
use zng_ext_window::{WINDOW_Ext as _, WINDOWS};
use zng_view_api::window::CursorIcon;
use zng_wgt::prelude::*;
use zng_wgt_input::CursorSource;

use crate::INSPECT_CMD;

mod data_model;
mod inspector_window;

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Config {
    adorn_selected: bool,
    select_focused: bool,
}
impl Default for Config {
    fn default() -> Self {
        Self {
            adorn_selected: true,
            select_focused: false,
        }
    }
}

/// Node set on the window to inspect.
pub fn inspect_node(can_inspect: impl IntoVar<bool>) -> impl UiNode {
    let mut inspected_tree = None::<data_model::InspectedTree>;
    let inspector = WindowId::new_unique();

    let selected_wgt = var(None);
    let hit_select = var(HitSelect::Disabled);

    // persist config, at least across instances of the Inspector.
    let config = CONFIG.get::<Config>(
        if WINDOW.id().name().is_empty() {
            formatx!("window.sequential({}).inspector", WINDOW.id().sequential())
        } else {
            formatx!("window.{}.inspector", WINDOW.id().name())
        },
        Config::default(),
    );
    let adorn_selected = config.map_ref_bidi(|c| &c.adorn_selected, |c| &mut c.adorn_selected);
    let select_focused = config.map_ref_bidi(|c| &c.select_focused, |c| &mut c.select_focused);

    let can_inspect = can_inspect.into_var();
    let mut cmd_handle = CommandHandle::dummy();

    /// Message send to ourselves as an `INSPECT_CMD` param.
    enum InspectorUpdateOnly {
        /// Pump `inspected_tree.update`
        Info,
        /// Pump `inspected_tree.update_render`
        Render,
    }

    let child = match_node_leaf(clmv!(selected_wgt, hit_select, adorn_selected, select_focused, |op| match op {
        UiNodeOp::Init => {
            WIDGET.sub_var(&can_inspect);
            cmd_handle = INSPECT_CMD.scoped(WINDOW.id()).subscribe_wgt(can_inspect.get(), WIDGET.id());
        }
        UiNodeOp::Update { .. } => {
            if let Some(e) = can_inspect.get_new() {
                cmd_handle.set_enabled(e);
            }
        }
        UiNodeOp::Info { .. } => {
            if inspected_tree.is_some() {
                if WINDOWS.is_open(inspector) {
                    INSPECT_CMD.scoped(WINDOW.id()).notify_param(InspectorUpdateOnly::Info);
                } else if !WINDOWS.is_opening(inspector) {
                    inspected_tree = None;
                }
            }
        }
        UiNodeOp::Event { update } => {
            if let Some(args) = INSPECT_CMD.scoped(WINDOW.id()).on_unhandled(update) {
                args.propagation().stop();

                if let Some(u) = args.param::<InspectorUpdateOnly>() {
                    // pump state
                    if let Some(i) = &inspected_tree {
                        match u {
                            InspectorUpdateOnly::Info => i.update(WINDOW.info()),
                            InspectorUpdateOnly::Render => i.update_render(),
                        }
                    }
                } else if let Some(inspected) = inspector_window::inspected() {
                    // can't inspect inspector window, redirect command to inspected
                    INSPECT_CMD.scoped(inspected).notify();
                } else {
                    // focus or open the inspector window
                    let inspected_tree = match &inspected_tree {
                        Some(i) => {
                            i.update(WINDOW.info());
                            i.clone()
                        }
                        None => {
                            let i = data_model::InspectedTree::new(WINDOW.info());
                            inspected_tree = Some(i.clone());
                            i
                        }
                    };

                    let inspected = WINDOW.id();
                    WINDOWS.focus_or_open(
                        inspector,
                        async_clmv!(inspected_tree, selected_wgt, hit_select, adorn_selected, select_focused, {
                            inspector_window::new(inspected, inspected_tree, selected_wgt, hit_select, adorn_selected, select_focused)
                        }),
                    );
                }
            }
        }
        UiNodeOp::Render { .. } | UiNodeOp::RenderUpdate { .. } => {
            INSPECT_CMD.scoped(WINDOW.id()).notify_param(InspectorUpdateOnly::Render);
        }
        _ => {}
    }));

    let child = self::adorn_selected(child, selected_wgt, adorn_selected);
    select_on_click(child, hit_select)
}

/// Node in the inspected window, draws adorners around widgets selected on the inspector window.
fn adorn_selected(child: impl UiNode, selected_wgt: impl Var<Option<data_model::InspectedWidget>>, enabled: impl Var<bool>) -> impl UiNode {
    use inspector_window::SELECTED_BORDER_VAR;

    let selected_info = selected_wgt.flat_map(|s| {
        if let Some(s) = s {
            s.info().map(|i| Some(i.clone())).boxed()
        } else {
            var(None).boxed()
        }
    });
    let transform_id = SpatialFrameId::new_unique();
    match_node(child, move |c, op| match op {
        UiNodeOp::Init => {
            WIDGET
                .sub_var_render(&selected_info)
                .sub_var_render(&enabled)
                .sub_var_render(&SELECTED_BORDER_VAR);
        }
        UiNodeOp::Render { frame } => {
            c.render(frame);

            if !enabled.get() {
                return;
            }
            selected_info.with(|w| {
                if let Some(w) = w {
                    let bounds = w.bounds_info();
                    let transform = bounds.inner_transform();
                    let size = bounds.inner_size();

                    frame.push_reference_frame(transform_id.into(), transform.into(), false, false, |frame| {
                        let widths = Dip::new(3).to_px(frame.scale_factor());
                        frame.push_border(
                            PxRect::from_size(size).inflate(widths, widths),
                            PxSideOffsets::new_all_same(widths),
                            SELECTED_BORDER_VAR.get().into(),
                            PxCornerRadius::default(),
                        );
                    });
                }
            });
        }
        _ => {}
    })
}

// node in the inspected window, handles selection on click.
fn select_on_click(child: impl UiNode, hit_select: impl Var<HitSelect>) -> impl UiNode {
    // when `pending` we need to block interaction with window content, as if a modal
    // overlay was opened, but we can't rebuild info, and we actually want the click target,
    // so we only manually block common pointer events.

    let mut click_handle = EventHandles::dummy();
    let mut _cursor_handle = VarHandle::dummy();
    match_node(child, move |c, op| match op {
        UiNodeOp::Init => {
            WIDGET.sub_var(&hit_select);
        }
        UiNodeOp::Deinit => {
            _cursor_handle = VarHandle::dummy();
            click_handle.clear();
        }
        UiNodeOp::Update { .. } => {
            if let Some(h) = hit_select.get_new() {
                if matches!(h, HitSelect::Enabled) {
                    let cursor = WINDOW.vars().cursor();

                    // set cursor to Crosshair and lock it in by resetting on a hook.
                    let locked_cur = CursorSource::Icon(CursorIcon::Crosshair);
                    cursor.set(locked_cur.clone());
                    let weak_cursor = cursor.downgrade();
                    _cursor_handle = cursor.hook(move |a| {
                        let icon = a.value();
                        if icon != &locked_cur {
                            let cursor = weak_cursor.upgrade().unwrap();
                            cursor.set(locked_cur.clone());
                        }
                        true
                    });

                    click_handle.push(MOUSE_INPUT_EVENT.subscribe(WIDGET.id()));
                    click_handle.push(TOUCH_INPUT_EVENT.subscribe(WIDGET.id()));
                } else {
                    WINDOW.vars().cursor().set(CursorIcon::Default);
                    _cursor_handle = VarHandle::dummy();

                    click_handle.clear();
                }
            }
        }
        UiNodeOp::Event { update } => {
            if matches!(hit_select.get(), HitSelect::Enabled) {
                let mut select = None;

                if let Some(args) = MOUSE_MOVE_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = MOUSE_INPUT_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                    select = Some(args.target.widget_id());
                } else if let Some(args) = MOUSE_HOVERED_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = MOUSE_WHEEL_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = CLICK_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = ACCESS_CLICK_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = TOUCH_INPUT_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                    select = Some(args.target.widget_id());
                } else if let Some(args) = TOUCHED_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = TOUCH_MOVE_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = TOUCH_TAP_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = TOUCH_TRANSFORM_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                } else if let Some(args) = TOUCH_LONG_PRESS_EVENT.on(update) {
                    args.propagation().stop();
                    c.delegated();
                }

                if let Some(id) = select {
                    let _ = hit_select.set(HitSelect::Select(id));
                }
            }
        }
        _ => {}
    })
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum HitSelect {
    Disabled,
    Enabled,
    Select(WidgetId),
}