waft-widgets 0.18.1

Widget framework and widgets for Waft
Documentation
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
//! The widget inspector's service extensions: Flutter's `WidgetInspectorService`, as far as it is
//! ported. A client names an element or render object by the id the inspector's tree gave it;
//! here that id is the object's arena handle (`inspector-<bits>`), which names it while it lives
//! and nothing after, where Dart keeps a table of ids in object groups.

use std::collections::HashMap;
use std::rc::Rc;

use base64::Engine;
use waft_embedder::{ServiceExtensionError, ServiceExtensionParams, ServiceExtensionResult};
use waft_foundation::{
    App, DiagnosticLevel, DiagnosticsJsonMap, DiagnosticsNode, DiagnosticsSerializationDelegate,
    HandleId, ServiceExtensions, Task,
};
use waft_rendering::{
    AnyRenderObject, BoxParentData, FlexFit, FlexParentData, RenderParagraph, RenderView,
    RendererBinding, screenshot_picture, subtree_bounds,
};

use crate::{AnyElement, ElementFacts, WidgetsBinding};

/// Dart's `WidgetInspectorService.initServiceExtensions`, as far as it is ported.
pub(crate) fn init_service_extensions(app: &mut App) {
    ServiceExtensions::register(
        app,
        "ext.waft.inspector.getRootWidget",
        Rc::new(get_root_widget),
    );
    ServiceExtensions::register(
        app,
        "ext.waft.inspector.getRootWidgetTree",
        Rc::new(get_root_widget_tree),
    );
    ServiceExtensions::register(
        app,
        "ext.waft.inspector.getDetailsSubtree",
        Rc::new(get_details_subtree),
    );
    ServiceExtensions::register(
        app,
        "ext.waft.inspector.getLayoutExplorerNode",
        Rc::new(get_layout_explorer_node),
    );
    ServiceExtensions::register(app, "ext.waft.inspector.screenshot", Rc::new(screenshot));
    // Dart's signal extension: whether widgets carry their creation locations, which a debug
    // build's do.
    ServiceExtensions::register(
        app,
        "ext.waft.inspector.isWidgetCreationTracked",
        Rc::new(|_app, _params| {
            Task::ready(Ok(serde_json::json!({ "result": cfg!(debug_assertions) })))
        }),
    );
}

/// `ext.waft.inspector.getRootWidget`: the root element's node and its children, as
/// `{"result": node}`: where a client starts, its `valueId` naming the root for the other calls.
fn get_root_widget(app: &mut App, params: ServiceExtensionParams) -> Task<ServiceExtensionResult> {
    let delegate = InspectorSerializationDelegate {
        group_name: params.get("objectGroup").map(str::to_owned),
        ..InspectorSerializationDelegate::default()
    };
    let root = WidgetsBinding::instance(app)
        .root_element(app)
        .map(|root| root.to_diagnostics_node(app, None).to_json_map(&delegate));
    Task::ready(Ok(serde_json::json!({ "result": root })))
}

/// `ext.waft.inspector.getRootWidgetTree`: the element tree from the root as the inspector's
/// JSON, `{"result": tree}`, every node's `valueId` its inspector id. With `isSummaryTree`, the
/// widgets the app's own code made, which is every widget until creation locations are tracked,
/// as in Dart when they are not; with `withPreviews`, each element that shows a paragraph has its
/// text as `textPreview`. Dart's `fullDetails=false` is not ported.
fn get_root_widget_tree(
    app: &mut App,
    params: ServiceExtensionParams,
) -> Task<ServiceExtensionResult> {
    let Some(root) = WidgetsBinding::instance(app).root_element(app) else {
        return Task::ready(Ok(serde_json::json!({ "result": null })));
    };
    let text_previews = match params.get("withPreviews") {
        Some("true") => text_previews(app, root),
        _ => HashMap::new(),
    };
    let delegate = InspectorSerializationDelegate {
        group_name: params.get("groupName").map(str::to_owned),
        summary_tree: params.get("isSummaryTree") == Some("true"),
        subtree_depth: 1_000_000,
        text_previews: Rc::new(text_previews),
        ..InspectorSerializationDelegate::default()
    };
    let tree = root.to_diagnostics_node(app, None).to_json_map(&delegate);
    Task::ready(Ok(serde_json::json!({ "result": tree })))
}

/// The text each element under `root` shows, by the element's id, where its render object is a
/// paragraph: what Dart's `withPreviews` adds to a node as `textPreview`.
fn text_previews(app: &App, root: AnyElement) -> HashMap<HandleId, String> {
    let mut previews = HashMap::new();
    add_text_previews(app, root, &mut previews);
    previews
}

fn add_text_previews(app: &App, element: AnyElement, previews: &mut HashMap<HandleId, String>) {
    let paragraph = element
        .find_render_object(app)
        .and_then(|object| object.downcast::<RenderParagraph>(app));
    if let Some(paragraph) = paragraph {
        let text = paragraph.text(app).to_plain_text(true, true);
        previews.insert(element.id(), text);
    }
    element.visit_children(app, &mut |child| add_text_previews(app, child, previews));
}

/// `ext.waft.inspector.getLayoutExplorerNode`: the element `id` names and the summary tree
/// `subtreeDepth` levels under it (1 when not given), each element with its layout: its render
/// object with its properties, its constraints, its size, and its flex factor and fit or its
/// offset in its parent, as `{"result": node}`, the layout explorer's view of a widget in
/// DevTools. Dart's `parentRenderElement` waits for `debugCreator`.
fn get_layout_explorer_node(
    app: &mut App,
    params: ServiceExtensionParams,
) -> Task<ServiceExtensionResult> {
    let subtree_depth = match whole_number(&params, "subtreeDepth") {
        Ok(depth) => depth.unwrap_or(1),
        Err(error) => return Task::ready(Err(error)),
    };
    let Some(element) = params
        .get("id")
        .and_then(from_inspector_id)
        .and_then(|id| Inspected::named(app, id))
        .and_then(|object| match object {
            Inspected::Element(element) => Some(element),
            Inspected::RenderObject(_) => None,
        })
    else {
        return Task::ready(Ok(serde_json::json!({ "result": {} })));
    };
    let group_name = params.get("groupName").map(str::to_owned);
    let layouts = std::iter::once(element)
        .chain(element.descendants(app, false))
        .filter_map(|element| Some((element.id(), layout_of(app, element, &group_name)?)))
        .collect();
    let delegate = InspectorSerializationDelegate {
        group_name,
        summary_tree: true,
        subtree_depth,
        layouts: Rc::new(layouts),
        ..InspectorSerializationDelegate::default()
    };
    let node = element
        .to_diagnostics_node(app, None)
        .to_json_map(&delegate);
    Task::ready(Ok(serde_json::json!({ "result": node })))
}

/// The layout Dart's layout explorer shows of `element`: its render object, constraints, size,
/// and flex or offset; `None` for an element with no render object.
fn layout_of(
    app: &App,
    element: AnyElement,
    group_name: &Option<String>,
) -> Option<DiagnosticsJsonMap> {
    let render = element.find_render_object(app)?;
    let delegate = InspectorSerializationDelegate {
        group_name: group_name.clone(),
        subtree_depth: 0,
        include_properties: true,
        expand_property_values: false,
        ..InspectorSerializationDelegate::default()
    };
    let mut layout = DiagnosticsJsonMap::new();
    layout.insert(
        "renderObject".to_owned(),
        render
            .to_diagnostics_node(app, None)
            .to_json_map(&delegate)
            .into(),
    );
    if let Some(view) = render.downcast::<RenderView>(app) {
        layout.insert("size".to_owned(), size_json(view.size(app)));
        return Some(layout);
    }
    let Some(render_box) = render.as_box().filter(|render| render.has_size(app)) else {
        return Some(layout);
    };
    let constraints = render_box.constraints(app);
    layout.insert(
        "constraints".to_owned(),
        serde_json::json!({
            "type": "BoxConstraints",
            "description": constraints.to_string(),
            "minWidth": dart_double(constraints.min_width),
            "minHeight": dart_double(constraints.min_height),
            "maxWidth": dart_double(constraints.max_width),
            "maxHeight": dart_double(constraints.max_height),
        }),
    );
    layout.insert("isBox".to_owned(), true.into());
    layout.insert("size".to_owned(), size_json(render_box.size(app)));
    let parent_data = render.parent_data(app);
    if let Some(flex) = parent_data.and_then(|data| data.part::<FlexParentData>()) {
        layout.insert("flexFactor".to_owned(), flex.flex.unwrap_or(0).into());
        let fit = match flex.fit.unwrap_or(FlexFit::Tight) {
            FlexFit::Tight => "tight",
            FlexFit::Loose => "loose",
        };
        layout.insert("flexFit".to_owned(), fit.into());
    } else if let Some(data) = parent_data.and_then(|data| data.part::<BoxParentData>()) {
        layout.insert(
            "parentData".to_owned(),
            serde_json::json!({
                "offsetX": dart_double(data.offset.dx()),
                "offsetY": dart_double(data.offset.dy()),
            }),
        );
    }
    Some(layout)
}

fn size_json(size: waft_embedder::Size) -> serde_json::Value {
    serde_json::json!({ "width": dart_double(size.width()), "height": dart_double(size.height()) })
}

/// A number as Dart's `double.toString` writes it: `100.0`, `0.5`, `Infinity`.
fn dart_double(value: f64) -> String {
    match value {
        value if value == f64::INFINITY => "Infinity".to_owned(),
        value if value == f64::NEG_INFINITY => "-Infinity".to_owned(),
        value if value.is_finite() && value.fract() == 0.0 => format!("{value:.1}"),
        value => value.to_string(),
    }
}

/// `ext.waft.inspector.getDetailsSubtree`: the object `arg` names, with its properties, and its
/// descendants `subtreeDepth` levels down (2 when not given), as `{"result": node}`.
fn get_details_subtree(
    app: &mut App,
    params: ServiceExtensionParams,
) -> Task<ServiceExtensionResult> {
    let subtree_depth = match whole_number(&params, "subtreeDepth") {
        Ok(depth) => depth.unwrap_or(2),
        Err(error) => return Task::ready(Err(error)),
    };
    let arg = match params.require("arg") {
        Ok(arg) => arg.to_owned(),
        Err(error) => return Task::ready(Err(error)),
    };
    let delegate = InspectorSerializationDelegate {
        group_name: params.get("objectGroup").map(str::to_owned),
        subtree_depth,
        include_properties: true,
        ..InspectorSerializationDelegate::default()
    };
    let node = from_inspector_id(&arg)
        .and_then(|id| Inspected::named(app, id))
        .map(|object| object.diagnostics_node(app).to_json_map(&delegate));
    Task::ready(Ok(serde_json::json!({ "result": node })))
}

/// Dart's `InspectorSerializationDelegate`: how the inspector's JSON walks a tree, naming each
/// node's object by its inspector id.
#[derive(Clone, Debug)]
pub struct InspectorSerializationDelegate {
    /// The client's object group; a node's `valueId` is given where there is one.
    pub group_name: Option<String>,
    /// Whether children the app's own code did not make are passed over for theirs.
    pub summary_tree: bool,
    /// How many children a node shows before the rest are cut, or every one when negative.
    pub max_descendants_truncatable_node: i32,
    pub expand_property_values: bool,
    pub subtree_depth: i32,
    pub include_properties: bool,
    /// The text of each element showing a paragraph, by its id, given as its node's
    /// `textPreview`: Dart's `withPreviews`, gathered before the walk, which reads no render
    /// object.
    pub text_previews: Rc<HashMap<HandleId, String>>,
    /// The layout of each element, by its id, added to its node: what Dart's layout explorer's
    /// callback adds, gathered before the walk likewise.
    pub layouts: Rc<HashMap<HandleId, DiagnosticsJsonMap>>,
}

impl Default for InspectorSerializationDelegate {
    /// Dart's defaults.
    fn default() -> InspectorSerializationDelegate {
        InspectorSerializationDelegate {
            group_name: None,
            summary_tree: false,
            max_descendants_truncatable_node: -1,
            expand_property_values: true,
            subtree_depth: 1,
            include_properties: false,
            text_previews: Rc::default(),
            layouts: Rc::default(),
        }
    }
}

impl DiagnosticsSerializationDelegate for InspectorSerializationDelegate {
    fn additional_node_properties(
        &self,
        node: &dyn DiagnosticsNode,
        full_details: bool,
    ) -> DiagnosticsJsonMap {
        let mut result = DiagnosticsJsonMap::new();
        if self.summary_tree && full_details {
            result.insert("summaryTree".to_owned(), true.into());
        }
        if self.group_name.is_some() {
            let value_id = node.value_id().map(inspector_id);
            result.insert("valueId".to_owned(), value_id.into());
        }
        if let Some(preview) = node.value_id().and_then(|id| self.text_previews.get(&id)) {
            result.insert("textPreview".to_owned(), preview.clone().into());
        }
        if let Some(layout) = node.value_id().and_then(|id| self.layouts.get(&id)) {
            result.extend(layout.clone());
        }
        if let Some(facts) = element_facts(node)
            && let Some(location) = facts.creation_location
        {
            if full_details {
                result.insert(
                    "creationLocation".to_owned(),
                    serde_json::json!({
                        "file": location.file(),
                        "line": location.line(),
                        "column": location.column(),
                        "name": facts.widget_runtime_type,
                    }),
                );
            }
            if facts.created_by_local_project() {
                result.insert("createdByLocalProject".to_owned(), true.into());
            }
        }
        result
    }

    fn delegate_for_node(
        &self,
        node: &dyn DiagnosticsNode,
    ) -> Rc<dyn DiagnosticsSerializationDelegate> {
        // In the details tree the depth holds until the nodes the summary tree shares, so
        // expanding a node shows the whole subtree down to them.
        if self.summary_tree || self.subtree_depth > 1 || should_show_in_summary_tree(node) {
            self.copy_with(Some(self.subtree_depth - 1), None)
        } else {
            Rc::new(self.clone())
        }
    }

    fn filter_children(
        &self,
        nodes: Vec<Rc<dyn DiagnosticsNode>>,
        _owner: &dyn DiagnosticsNode,
    ) -> Vec<Rc<dyn DiagnosticsNode>> {
        self.children_shown(nodes)
    }

    /// The app's own widgets show their fine properties too.
    fn filter_properties(
        &self,
        nodes: Vec<Rc<dyn DiagnosticsNode>>,
        owner: &dyn DiagnosticsNode,
    ) -> Vec<Rc<dyn DiagnosticsNode>> {
        let created_by_local_project =
            element_facts(owner).is_some_and(ElementFacts::created_by_local_project);
        let level = if created_by_local_project {
            DiagnosticLevel::Fine
        } else {
            DiagnosticLevel::Info
        };
        nodes
            .into_iter()
            .filter(|node| !node.is_filtered(level))
            .collect()
    }

    fn truncate_nodes_list(
        &self,
        nodes: Vec<Rc<dyn DiagnosticsNode>>,
        owner: Option<&dyn DiagnosticsNode>,
    ) -> Vec<Rc<dyn DiagnosticsNode>> {
        let limit = self.max_descendants_truncatable_node;
        let truncates = limit >= 0
            && owner.is_some_and(|owner| owner.allow_truncate())
            && nodes.len() > limit as usize;
        if !truncates {
            return nodes;
        }
        // Dart's `_truncateNodes`: of elements whose locations are tracked, the app's own.
        let facts_of = |node: &Rc<dyn DiagnosticsNode>| element_facts(&**node).cloned();
        if nodes
            .iter()
            .all(|node| facts_of(node).is_some_and(|facts| facts.creation_location.is_some()))
        {
            let local: Vec<_> = nodes
                .iter()
                .filter(|node| facts_of(node).is_some_and(|facts| facts.created_by_local_project()))
                .cloned()
                .collect();
            if !local.is_empty() {
                return local;
            }
        }
        nodes.into_iter().take(limit as usize).collect()
    }

    fn subtree_depth(&self) -> i32 {
        self.subtree_depth
    }

    fn include_properties(&self) -> bool {
        self.include_properties
    }

    fn expand_property_values(&self) -> bool {
        self.expand_property_values
    }

    fn copy_with(
        &self,
        subtree_depth: Option<i32>,
        include_properties: Option<bool>,
    ) -> Rc<dyn DiagnosticsSerializationDelegate> {
        Rc::new(InspectorSerializationDelegate {
            subtree_depth: subtree_depth.unwrap_or(self.subtree_depth),
            include_properties: include_properties.unwrap_or(self.include_properties),
            ..self.clone()
        })
    }
}

impl InspectorSerializationDelegate {
    /// Dart's `_filterChildren`: in the summary tree, a child it does not show is replaced by
    /// its own children shown.
    fn children_shown(&self, nodes: Vec<Rc<dyn DiagnosticsNode>>) -> Vec<Rc<dyn DiagnosticsNode>> {
        let mut children = Vec::new();
        for child in nodes {
            if !self.summary_tree || should_show_in_summary_tree(&*child) {
                children.push(child);
            } else {
                children.extend(self.children_shown(child.get_children()));
            }
        }
        children
    }
}

/// Dart's `_shouldShowInSummaryTree`: an error, a node that is not an element's, and an element
/// whose widget's location is not tracked (a release build) are shown; an element otherwise when
/// the app's own code made its widget.
fn should_show_in_summary_tree(node: &dyn DiagnosticsNode) -> bool {
    if node.level() == DiagnosticLevel::Error {
        return true;
    }
    match element_facts(node) {
        Some(facts) if facts.creation_location.is_some() => facts.created_by_local_project(),
        _ => true,
    }
}

/// What `node` knows of its element, when it is an element's: Dart's `node.value is Element`.
fn element_facts(node: &dyn DiagnosticsNode) -> Option<&ElementFacts> {
    node.value()?.downcast_ref::<ElementFacts>()
}

/// The id the inspector names `id`'s object by: Dart's `toId`.
pub fn inspector_id(id: HandleId) -> String {
    format!("inspector-{}", id.to_bits())
}

/// The object `text` names, as [`inspector_id`] wrote it: Dart's `toObject`.
pub fn from_inspector_id(text: &str) -> Option<HandleId> {
    text.strip_prefix("inspector-")?
        .parse()
        .ok()
        .map(HandleId::from_bits)
}

/// `ext.waft.inspector.screenshot`: a PNG of the element or render object `id` names and its
/// descendants, fit within `width` by `height` pixels at no more than `maxPixelRatio`, with
/// `margin` around it, as `{"result": base64}`, or `{"result": null}` where it cannot be taken.
/// Dart's `debugPaint` is not ported, and is ignored.
fn screenshot(app: &mut App, params: ServiceExtensionParams) -> Task<ServiceExtensionResult> {
    match screenshot_image(app, &params) {
        Err(error) => Task::ready(Err(error)),
        Ok(None) => Task::ready(Ok(serde_json::json!({ "result": null }))),
        Ok(Some(image)) => png_answer(app, &image),
    }
}

/// The PNG of `image`, read back from the host, as `{"result": base64}`.
pub(crate) fn png_answer(
    app: &mut App,
    image: &waft_embedder::Image,
) -> Task<ServiceExtensionResult> {
    let pixels = app.platform().read_image_pixels(image);
    app.spawn(async move |_cx| {
        let pixels = pixels
            .await
            .map_err(|error| ServiceExtensionError::Failed(error.to_string()))?;
        let png = waft_embedder::encode_png(&pixels).map_err(ServiceExtensionError::Failed)?;
        let encoded = base64::engine::general_purpose::STANDARD.encode(png);
        Ok(serde_json::json!({ "result": encoded }))
    })
}

/// `picture` drawn by the host into an image of `width` by `height` pixels.
pub(crate) fn image_of(
    app: &mut App,
    picture: &waft_embedder::Picture,
    width: u32,
    height: u32,
) -> Result<waft_embedder::Image, ServiceExtensionError> {
    app.platform()
        .picture_to_image_sync(picture, width, height)
        .ok_or_else(|| {
            ServiceExtensionError::Failed("this host draws no pictures into images".to_owned())
        })
}

/// Dart's `WidgetInspectorService.screenshot`: the image, or `None` where the object is gone,
/// detached, not laid out, or paints nothing.
fn screenshot_image(
    app: &mut App,
    params: &ServiceExtensionParams,
) -> Result<Option<waft_embedder::Image>, ServiceExtensionError> {
    let id = params.require("id")?;
    let width = positive(params, "width")?.ok_or_else(|| missing("width"))?;
    let height = positive(params, "height")?.ok_or_else(|| missing("height"))?;
    let margin = number(params, "margin")?.unwrap_or(0.0);
    let max_pixel_ratio = positive(params, "maxPixelRatio")?.unwrap_or(1.0);
    let Some(render_object) = from_inspector_id(id)
        .and_then(|id| Inspected::named(app, id))
        .and_then(|object| object.render_object(app))
    else {
        return Ok(None);
    };
    if !render_object.attached(app) {
        return Ok(None);
    }
    if render_object.debug_needs_layout(app) {
        let owner = render_object
            .owner(app)
            .expect("an attached object has an owner");
        owner.flush_layout(app);
        owner.flush_compositing_bits(app);
        owner.flush_paint(app);
        // Skipped by layout, the object cannot be painted.
        if render_object.debug_needs_layout(app) {
            return Ok(None);
        }
    }
    let mut bounds = subtree_bounds(app, render_object);
    if margin != 0.0 {
        bounds = bounds.inflate(margin);
    }
    if bounds.is_empty() {
        return Ok(None);
    }
    let pixel_ratio = max_pixel_ratio.min((width / bounds.width()).min(height / bounds.height()));
    let Some(picture) = screenshot_picture(app, render_object, bounds, pixel_ratio) else {
        return Ok(None);
    };
    let width = (bounds.width() * pixel_ratio).ceil() as u32;
    let height = (bounds.height() * pixel_ratio).ceil() as u32;
    image_of(app, &picture, width, height).map(Some)
}

/// The parameter `name` as a number, where the client sent it.
pub(crate) fn number(
    params: &ServiceExtensionParams,
    name: &str,
) -> Result<Option<f64>, ServiceExtensionError> {
    params
        .get(name)
        .map(|text| {
            text.parse().map_err(|_| {
                ServiceExtensionError::InvalidParams(format!("`{name}` is a number, not `{text}`"))
            })
        })
        .transpose()
}

/// The parameter `name` as a whole number, where the client sent it.
fn whole_number(
    params: &ServiceExtensionParams,
    name: &str,
) -> Result<Option<i32>, ServiceExtensionError> {
    params
        .get(name)
        .map(|text| {
            text.parse().map_err(|_| {
                ServiceExtensionError::InvalidParams(format!("`{name}` is a whole number"))
            })
        })
        .transpose()
}

/// The parameter `name` as a number above zero, where the client sent it.
pub(crate) fn positive(
    params: &ServiceExtensionParams,
    name: &str,
) -> Result<Option<f64>, ServiceExtensionError> {
    match number(params, name)? {
        Some(value) if !(value > 0.0 && value.is_finite()) => Err(
            ServiceExtensionError::InvalidParams(format!("`{name}` is a number above zero")),
        ),
        value => Ok(value),
    }
}

fn missing(name: &str) -> ServiceExtensionError {
    ServiceExtensionError::InvalidParams(format!("`{name}` is required"))
}

/// An object an inspector id names: Dart's `toObject`, for the two kinds the inspector names.
#[derive(Clone, Copy)]
enum Inspected {
    Element(AnyElement),
    RenderObject(AnyRenderObject),
}

impl Inspected {
    /// The element or render object `id` names, in the element tree or a view's render tree.
    fn named(app: &mut App, id: HandleId) -> Option<Inspected> {
        if let Some(root) = WidgetsBinding::instance(app).root_element(app)
            && let Some(element) = element_named(app, root, id)
        {
            return Some(Inspected::Element(element));
        }
        let views = RendererBinding::instance(app).render_views(app);
        views
            .into_iter()
            .find_map(|view| render_object_in(app, view.as_object(), id))
            .map(Inspected::RenderObject)
    }

    /// Its render object: Dart's `_renderObjectOrNull`.
    fn render_object(self, app: &App) -> Option<AnyRenderObject> {
        match self {
            Inspected::Element(element) => element.find_render_object(app),
            Inspected::RenderObject(render_object) => Some(render_object),
        }
    }

    /// Its diagnostics node: Dart's `_idToDiagnosticsNode`.
    fn diagnostics_node(self, app: &App) -> Rc<dyn DiagnosticsNode> {
        match self {
            Inspected::Element(element) => Rc::new(element.to_diagnostics_node(app, None)),
            Inspected::RenderObject(render_object) => {
                Rc::new(render_object.to_diagnostics_node(app, None))
            }
        }
    }
}

/// The element `id` names under `element`, itself included.
pub(crate) fn element_named(app: &App, element: AnyElement, id: HandleId) -> Option<AnyElement> {
    if element.id() == id {
        return Some(element);
    }
    let mut found = None;
    element.visit_children(app, &mut |child| {
        if found.is_none() {
            found = element_named(app, child, id);
        }
    });
    found
}

fn render_object_in(app: &App, object: AnyRenderObject, id: HandleId) -> Option<AnyRenderObject> {
    if object.id() == id {
        return Some(object);
    }
    let mut found = None;
    object.visit_children(app, &mut |child| {
        if found.is_none() {
            found = render_object_in(app, child, id);
        }
    });
    found
}

#[cfg(test)]
mod tests {
    use std::future::Future;
    use std::task::{Context, Poll, Waker};

    use waft_embedder::Color;
    use waft_test::TestPlatform;

    use super::*;
    use crate::testing::WidgetTester;
    use waft_embedder::ViewRef;

    use crate::IntoWidget;
    use crate::view::{View, ViewCollection};
    use crate::{Center, ColoredBox, GlobalKey, Padding, SizedBox};

    const GREEN: Color = Color::new(0xFF00FF00);

    /// A green box padded inside a red one: its screenshot by its element's id, at twice its
    /// size, is an 80 by 80 PNG of green alone.
    #[test]
    fn a_screenshot_is_the_named_widget_alone_as_a_png() {
        let mut tester = WidgetTester::with_platform(TestPlatform::new().with_gpu());
        let green = GlobalKey::new();
        tester.pump_widget(
            Center::new().child(
                ColoredBox::new(Color::new(0xFFFF0000)).child(
                    Padding::new(waft_painting::EdgeInsets::all(10.0)).child(
                        SizedBox::new()
                            .width(40.0)
                            .height(40.0)
                            .key(green.clone().into())
                            .child(ColoredBox::new(GREEN)),
                    ),
                ),
            ),
        );
        let mut task = tester.update(|app| {
            let element = green.current_context(app).expect("mounted");
            let params = ServiceExtensionParams::new([
                ("id".to_owned(), inspector_id(element.id())),
                ("width".to_owned(), "1000".to_owned()),
                ("height".to_owned(), "1000".to_owned()),
                ("maxPixelRatio".to_owned(), "2".to_owned()),
            ]);
            ServiceExtensions::call(app, "ext.waft.inspector.screenshot", params)
        });
        tester.pump();
        let answer =
            match std::pin::Pin::new(&mut task).poll(&mut Context::from_waker(Waker::noop())) {
                Poll::Ready(answer) => answer.expect("answered"),
                Poll::Pending => panic!("the screenshot is read back by the next pump"),
            };
        let png = base64::engine::general_purpose::STANDARD
            .decode(answer["result"].as_str().expect("a base64 PNG"))
            .expect("base64");
        use waft_embedder::valo::{AlphaType, PixelBuffer, PixelFormat, PixelLayout};
        let layout = PixelLayout::packed([80, 80], PixelFormat::Rgba8, AlphaType::Straight);
        let all_green = PixelBuffer::new(layout, [0, 255, 0, 255].repeat(80 * 80)).expect("pixels");
        assert!(
            png == waft_embedder::encode_png(&all_green).expect("a PNG"),
            "80 by 80 of green alone, without the red around it"
        );
    }

    /// The answer of an extension that answers at once.
    fn answered_now(app: &mut App, name: &str, params: &[(&str, &str)]) -> serde_json::Value {
        let params = ServiceExtensionParams::new(
            params
                .iter()
                .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())),
        );
        let mut task = ServiceExtensions::call(app, name, params);
        match std::pin::Pin::new(&mut task).poll(&mut Context::from_waker(Waker::noop())) {
            Poll::Ready(answer) => answer.expect("answered"),
            Poll::Pending => panic!("{name} answers at once"),
        }
    }

    /// The first node of `tree` whose description begins with `description`.
    fn find_node<'a>(
        tree: &'a serde_json::Value,
        description: &str,
    ) -> Option<&'a serde_json::Value> {
        if tree["description"]
            .as_str()
            .is_some_and(|text| text.starts_with(description))
        {
            return Some(tree);
        }
        tree["children"]
            .as_array()?
            .iter()
            .find_map(|child| find_node(child, description))
    }

    /// As DevTools and Flutter's MCP server ask for it, the summary tree with previews gives each
    /// element that shows a paragraph its text, and the others none.
    #[test]
    fn the_root_tree_with_previews_gives_each_paragraph_its_text() {
        let mut tester = WidgetTester::new();
        tester.pump_widget(crate::Directionality::new(
            waft_painting::TextDirection::Ltr,
            Center::new().child(crate::Text::new("Programs")),
        ));
        tester.update(|app| {
            let tree = answered_now(
                app,
                "ext.waft.inspector.getRootWidgetTree",
                &[
                    ("groupName", "g"),
                    ("isSummaryTree", "true"),
                    ("withPreviews", "true"),
                ],
            );
            let root = &tree["result"];
            let text = find_node(root, "Text").expect("the Text is in the tree");
            assert_eq!(text["textPreview"], "Programs");
            let center = find_node(root, "Center").expect("the Center is in the tree");
            assert_eq!(center.get("textPreview"), None);
            let without = answered_now(
                app,
                "ext.waft.inspector.getRootWidgetTree",
                &[("groupName", "g"), ("isSummaryTree", "true")],
            );
            let text = find_node(&without["result"], "Text").expect("the Text is in the tree");
            assert_eq!(text.get("textPreview"), None, "previews only when asked");
        });
    }

    /// As DevTools reads it: the root tree names each element by an id, which the details of
    /// one ask for back, answering its widget's properties.
    #[test]
    fn the_root_tree_names_each_element_and_its_details_answer_its_properties() {
        let mut tester = WidgetTester::new();
        tester.pump_widget(Center::new().child(SizedBox::new().width(10.0).height(20.0)));
        tester.update(|app| {
            let tree = answered_now(
                app,
                "ext.waft.inspector.getRootWidgetTree",
                &[("groupName", "tree_1"), ("isSummaryTree", "true")],
            );
            let root = &tree["result"];
            assert_eq!(root["description"], "[root]");
            assert_eq!(root["type"], "_ElementDiagnosticableTreeNode");
            let sized = find_node(root, "SizedBox").expect("the SizedBox is in the tree");
            assert_eq!(sized["widgetRuntimeType"], "SizedBox");
            assert_eq!(sized["stateful"], false);
            let id = sized["valueId"].as_str().expect("an inspector id");

            let details = answered_now(
                app,
                "ext.waft.inspector.getDetailsSubtree",
                &[
                    ("arg", id),
                    ("objectGroup", "details_1"),
                    ("subtreeDepth", "1"),
                ],
            );
            let node = &details["result"];
            assert_eq!(node["valueId"], id);
            let properties: Vec<(&str, &str)> = node["properties"]
                .as_array()
                .expect("the details carry properties")
                .iter()
                .filter_map(|property| {
                    Some((
                        property["name"].as_str()?,
                        property["description"].as_str()?,
                    ))
                })
                .collect();
            assert!(properties.contains(&("width", "10.0")), "{properties:?}");
            assert!(properties.contains(&("height", "20.0")), "{properties:?}");
        });
    }

    #[derive(Debug)]
    struct Greeting;

    impl crate::StatelessWidget for Greeting {
        fn build(&self, _app: &mut App, _context: crate::BuildContext) -> crate::WidgetRef {
            crate::IntoWidget::into_widget(SizedBox::new())
        }
    }

    /// In a debug build a widget carries the line that made it, which the tree names, and the
    /// app's own code made it: Dart's `creationLocation` and `createdByLocalProject`.
    #[test]
    fn the_tree_names_where_each_widget_was_made() {
        let mut tester = WidgetTester::new();
        let line = line!() + 1;
        let greeting = crate::IntoWidget::into_widget(Greeting);
        tester.pump_widget(greeting);
        tester.update(|app| {
            let tree = answered_now(
                app,
                "ext.waft.inspector.getRootWidgetTree",
                &[("groupName", "g")],
            );
            let node = find_node(&tree["result"], "Greeting").expect("the Greeting is in the tree");
            assert_eq!(node["creationLocation"]["file"], file!());
            assert_eq!(node["creationLocation"]["line"], line);
            assert_eq!(node["creationLocation"]["name"], "Greeting");
            assert_eq!(node["createdByLocalProject"], true);
        });
    }

    /// Every widget names the line of the caller that made it, through the paths a tree is
    /// built by: a child passed to a setter, a child passed to a constructor, a sliver list
    /// built from its builder, and a widget that is its own tree node.
    #[test]
    fn each_widget_names_the_line_that_made_it() {
        use waft_embedder::TextDirection;
        use waft_painting::EdgeInsetsGeometry;

        use crate::{
            CustomScrollView, Directionality, IntoWidget, LayoutBuilder, SliverList,
            SliverToBoxAdapter,
        };

        let mut tester = WidgetTester::new();
        let setter_key = GlobalKey::new();
        let constructor_key = GlobalKey::new();
        let builder_key = GlobalKey::new();
        let tree_node_key = GlobalKey::new();

        let setter = Padding::new(EdgeInsetsGeometry::all(1.0))
            .child(SizedBox::new())
            .key(setter_key.clone().into());
        let setter_line = line!() + 1;
        let setter = setter.into_widget();

        let constructor_line = line!() + 1;
        let constructor = Directionality::new(
            TextDirection::Ltr,
            Center::new().key(constructor_key.clone().into()),
        )
        .into_widget();

        let builder = SliverList::builder(|_app, _context, index| {
            (index < 1).then(|| SizedBox::new().height(10.0).into_widget())
        })
        .item_count(1)
        .key(builder_key.clone().into());
        let builder_line = line!() + 1;
        let builder = builder.into_widget();

        let tree_node =
            LayoutBuilder::new(|_app, _context, _constraints| SizedBox::new().into_widget())
                .key(tree_node_key.clone().into());
        let tree_node_line = line!() + 1;
        let tree_node = tree_node.into_widget();

        tester.pump_widget(Directionality::new(
            TextDirection::Ltr,
            CustomScrollView::new().slivers([
                SliverToBoxAdapter::new().child(setter).into_widget(),
                SliverToBoxAdapter::new().child(constructor).into_widget(),
                builder,
                SliverToBoxAdapter::new().child(tree_node).into_widget(),
            ]),
        ));

        for (key, line) in [
            (setter_key, setter_line),
            (constructor_key, constructor_line),
            (builder_key, builder_line),
            (tree_node_key, tree_node_line),
        ] {
            let app = tester.cell.borrow();
            let context = key
                .current_context(&app)
                .expect("the widget is in the tree");
            let location = context
                .widget(&app)
                .creation_location()
                .expect("a creation location");
            assert_eq!(location.file(), file!());
            assert_eq!(location.line(), line);
        }
    }

    /// A file Cargo names by a path relative to the workspace is the app's own; a dependency's,
    /// from its registry or a checkout, has an absolute one.
    #[test]
    fn only_the_workspaces_files_are_the_apps_own() {
        assert!(crate::framework::is_local_file(
            "crates/waos-design/src/sketch/home.rs"
        ));
        assert!(!crate::framework::is_local_file(
            "/Users/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/waft-widgets-0.9.1/src/widgets/basic.rs"
        ));
    }

    /// The root's node names the root, and its id pictures the whole view.
    #[test]
    fn the_roots_id_pictures_the_whole_view() {
        let mut tester = WidgetTester::with_platform(TestPlatform::new().with_gpu());
        tester.pump_widget(ColoredBox::new(GREEN));
        let root = tester.update(|app| {
            answered_now(
                app,
                "ext.waft.inspector.getRootWidget",
                &[("objectGroup", "g")],
            )
        });
        assert_eq!(root["result"]["description"], "[root]");
        let id = root["result"]["valueId"].as_str().expect("the root's id");
        // The view in its physical pixels, as Flutter's root render object paints its bounds
        // at the device pixel ratio: the 800 by 600 test view at 3.
        assert_eq!(png_size(&mut tester, id), Some((2400, 1800)));
    }

    /// A running app's root holds its views, a window's each (`[root]`, a `ViewCollection`, each
    /// `View`), so the root alone pictures nothing; each view is a node of the root's details,
    /// and its id pictures that window whole, as `cargo waft ext screenshot` takes it.
    #[test]
    fn a_window_is_pictured_by_its_views_id_under_a_root_of_views() {
        let mut tester = WidgetTester::with_platform(TestPlatform::new().with_gpu());
        tester.pump_widget(SizedBox::new());
        let view = Rc::clone(tester.view()) as ViewRef;
        tester.update(|app| {
            let views =
                ViewCollection::new(vec![View::new(view, ColoredBox::new(GREEN)).into_widget()]);
            WidgetsBinding::instance(app).attach_root_widget(app, views.into_widget());
        });
        tester.pump();
        let details = tester.update(|app| {
            let root = answered_now(
                app,
                "ext.waft.inspector.getRootWidget",
                &[("objectGroup", "g")],
            );
            let root = root["result"]["valueId"]
                .as_str()
                .expect("the root's id")
                .to_owned();
            answered_now(
                app,
                "ext.waft.inspector.getDetailsSubtree",
                &[
                    ("arg", root.as_str()),
                    ("objectGroup", "g"),
                    ("subtreeDepth", "4"),
                ],
            )
        });
        let root = &details["result"];
        assert_eq!(
            png_size(&mut tester, root["valueId"].as_str().unwrap()),
            None
        );
        let collection = &root["children"][0];
        assert_eq!(collection["widgetRuntimeType"], "ViewCollection");
        let view = &collection["children"][0];
        assert_eq!(view["widgetRuntimeType"], "View");
        let id = view["valueId"].as_str().expect("the view's id");
        assert_eq!(png_size(&mut tester, id), Some((2400, 1800)));
    }

    /// The layout explorer's node of a widget: its size, its constraints and where its parent
    /// placed it; a flexible child's flex factor and fit instead of its offset.
    #[test]
    fn a_widgets_layout_is_its_size_constraints_and_place() {
        let mut tester = WidgetTester::new();
        let boxed = GlobalKey::new();
        let flexible = GlobalKey::new();
        tester.pump_widget(crate::Column::new().children(vec![
                Center::new()
                    .child(SizedBox::new().width(40.0).height(20.0).key(boxed.clone().into()))
                    .into_widget(),
                crate::Expanded::new(SizedBox::new().key(flexible.clone().into())).into_widget(),
            ]));
        tester.update(|app| {
            let id = inspector_id(boxed.current_context(app).expect("mounted").id());
            let node = answered_now(
                app,
                "ext.waft.inspector.getLayoutExplorerNode",
                &[
                    ("id", id.as_str()),
                    ("groupName", "g"),
                    ("subtreeDepth", "0"),
                ],
            );
            let node = &node["result"];
            assert_eq!(
                node["size"],
                serde_json::json!({ "width": "40.0", "height": "20.0" })
            );
            assert_eq!(node["isBox"], true);
            assert_eq!(node["constraints"]["maxWidth"], "800.0");
            assert_eq!(node["constraints"]["minWidth"], "0.0");
            assert_eq!(node["parentData"]["offsetX"], "380.0");
            assert!(
                node["renderObject"]["description"]
                    .as_str()
                    .is_some_and(|text| text.starts_with("RenderConstrainedBox"))
            );

            let id = inspector_id(flexible.current_context(app).expect("mounted").id());
            let node = answered_now(
                app,
                "ext.waft.inspector.getLayoutExplorerNode",
                &[("id", id.as_str()), ("subtreeDepth", "0")],
            );
            assert_eq!(node["result"]["flexFactor"], 1);
            assert_eq!(node["result"]["flexFit"], "tight");
        });
    }

    /// A widget waiting to repaint, as one is while its window is out of sight, is pictured by
    /// repainting the boundary above it, as Dart's `toImage` does, not refused.
    #[test]
    fn a_widget_waiting_to_repaint_is_pictured() {
        let mut tester = WidgetTester::with_platform(TestPlatform::new().with_gpu());
        let green = GlobalKey::new();
        tester.pump_widget(
            Center::new().child(
                SizedBox::new()
                    .width(40.0)
                    .height(40.0)
                    .key(green.clone().into())
                    .child(ColoredBox::new(GREEN)),
            ),
        );
        let id = tester.update(|app| {
            let element = green.current_context(app).expect("mounted");
            let render = element.find_render_object(app).expect("a render object");
            render.mark_needs_paint(app);
            inspector_id(element.id())
        });
        assert_eq!(png_size(&mut tester, &id), Some((40, 40)));
    }

    /// The width and height of the PNG `id`'s screenshot answers, read back by the next pump, or
    /// `None` where it answers none.
    fn png_size(tester: &mut WidgetTester, id: &str) -> Option<(u32, u32)> {
        let params = ServiceExtensionParams::new([
            ("id".to_owned(), id.to_owned()),
            ("width".to_owned(), "100000".to_owned()),
            ("height".to_owned(), "100000".to_owned()),
        ]);
        let mut task = tester
            .update(|app| ServiceExtensions::call(app, "ext.waft.inspector.screenshot", params));
        tester.pump();
        let answer =
            match std::pin::Pin::new(&mut task).poll(&mut Context::from_waker(Waker::noop())) {
                Poll::Ready(answer) => answer.expect("answered"),
                Poll::Pending => panic!("the screenshot is read back by the next pump"),
            };
        let png = base64::engine::general_purpose::STANDARD
            .decode(answer["result"].as_str()?)
            .expect("base64");
        // A PNG's width and height follow its signature and the header chunk's name.
        let size = |at: usize| u32::from_be_bytes(png[at..at + 4].try_into().unwrap());
        Some((size(16), size(20)))
    }

    #[test]
    fn the_details_of_an_id_that_names_nothing_are_null() {
        let mut tester = WidgetTester::new();
        tester.pump_widget(SizedBox::new());
        tester.update(|app| {
            let details = answered_now(
                app,
                "ext.waft.inspector.getDetailsSubtree",
                &[("arg", "inspector-1"), ("objectGroup", "g")],
            );
            assert_eq!(details, serde_json::json!({ "result": null }));
        });
    }

    /// An id that names nothing answers no picture, as Dart's does for a gone object.
    #[test]
    fn a_screenshot_of_nothing_answers_null() {
        let mut tester = WidgetTester::new();
        tester.pump_widget(SizedBox::new());
        let mut task = tester.update(|app| {
            let params = ServiceExtensionParams::new([
                ("id".to_owned(), "inspector-1".to_owned()),
                ("width".to_owned(), "10".to_owned()),
                ("height".to_owned(), "10".to_owned()),
            ]);
            ServiceExtensions::call(app, "ext.waft.inspector.screenshot", params)
        });
        let answer =
            match std::pin::Pin::new(&mut task).poll(&mut Context::from_waker(Waker::noop())) {
                Poll::Ready(answer) => answer.expect("answered"),
                Poll::Pending => panic!("answered at once"),
            };
        assert_eq!(answer, serde_json::json!({ "result": null }));
    }

    #[test]
    fn an_inspector_id_names_its_object_back() {
        let cell = waft_foundation::AppCell::new();
        let mut app = cell.borrow_mut();
        let object = app.create(()).id();
        assert_eq!(from_inspector_id(&inspector_id(object)), Some(object));
        assert_eq!(from_inspector_id("inspector-x"), None);
        assert_eq!(from_inspector_id("e12"), None);
    }
}