frus-widgets 0.2.1

frus — declarative widget tree
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
//! The **transparent wrapper**: one macro, so that a wrapper cannot forget a hook.
//!
//! A transparent wrapper *is* its child. It exists to add something the tree needs — a
//! stable identity ([`crate::Keyed`]), a theme for a subtree ([`crate::Themed`]) — and
//! must otherwise be indistinguishable from the widget it holds: the same style, the same
//! children, the same paint, and above all the same answers to the **structural**
//! questions the walk asks before it looks at a widget at all.
//!
//! Those answers are where this goes wrong. A wrapper that forwards `style` and
//! `children` and stops there looks correct in every test, until someone wraps a
//! [`crate::Stack`] in it and the layers lay out in flow, or wraps a scrollable and the
//! scrolling stops. That bug has been found on a device here once already, which is why
//! there is a macro rather than a convention: a wrapper written by hand forwards what its
//! author remembered.
//!
//! ```ignore
//! forward_transparent!(Keyed {
//!     fn key(&self) -> Option<u64> {
//!         Some(self.key)                            // what this wrapper adds
//!     }
//!     fn theme_override(&self, inherited: &Theme) -> Option<Box<Theme>> {
//!         self.inner.theme_override(inherited)      // and what it passes through
//!     }
//! });
//! ```
//!
//! The type must have an `inner: Box<dyn Widget<Msg>>` field. The hooks above are the
//! ones a transparent wrapper can have a reason to claim, so the macro leaves them **all**
//! to the caller: whichever one this wrapper is not for is then visibly forwarded rather
//! than quietly defaulted. [`crate::Widget::positioned`] is the third — a
//! [`crate::Positioned`] claims it, and a wrapper that forgot to forward it would make
//! `Keyed(Positioned(…))` silently lose its place in the stack.
//!
//! ## The third hook: `restyle`
//!
//! [`crate::Expanded`] is transparent in every respect but one — it alters the flex item
//! its child *is*. So the **box** is the third thing a wrapper may legitimately claim,
//! and the macro asks for it the same way: an inherent method every wrapper writes, so
//! that the one which does not change the box has to say so.
//!
//! ```ignore
//! impl<Msg> Expanded<Msg> {
//!     fn restyle(&self, base: Style) -> Style {
//!         Style { flex_grow: self.flex, ..base }
//!     }
//! }
//! ```
//!
//! It is applied to `style` **and** `style_themed`, so a themed child keeps its themed
//! sizing and the two cannot drift apart.

/// Implements `Widget<Msg>` for a `{ inner: Box<dyn Widget<Msg>>, … }` wrapper by
/// delegating every hook to `inner`, except [`Widget::key`] and
/// [`Widget::theme_override`](crate::Widget::theme_override) — the two a wrapper may
/// legitimately answer for itself, which the caller therefore states, claimed or
/// forwarded.
macro_rules! forward_transparent {
    ($ty:ident { $($extra:item)* }) => {
        impl<Msg> $crate::widget::Widget<Msg> for $ty<Msg> {
            $($extra)*

            // Both go through `restyle`, the wrapper's own inherent method, so a themed
            // child keeps its themed sizing and the two cannot drift apart.
            fn style(&self) -> frus_layout::Style {
                self.restyle(self.inner.style())
            }

            fn style_themed(&self, theme: &$crate::theme::Theme) -> frus_layout::Style {
                self.restyle(self.inner.style_themed(theme))
            }

            fn build_themed(&self, theme: &$crate::theme::Theme) {
                // A deferred subtree inside a wrapper still has to be composed: without
                // this, a `ThemeBuilder` behind a `Keyed` never builds and the wrapper
                // reports a node with no children.
                self.inner.build_themed(theme)
            }

            fn build_in(
                &self,
                id: $crate::interaction::WidgetId,
                runtime: &$crate::runtime::Runtime,
                theme: &$crate::theme::Theme,
            ) {
                // The same identity: a wrapper has none of its own. Without this an
                // `AnimatedSwitcher` behind a `Keyed` is built by `build_themed` and never
                // finds what it was showing.
                self.inner.build_in(id, runtime, theme)
            }

            fn expand(
                &self,
                id: $crate::interaction::WidgetId,
                runtime: &$crate::runtime::Runtime,
                theme: &$crate::theme::Theme,
            ) {
                // Also with the identity untouched: what a component built is where the
                // component is.
                self.inner.expand(id, runtime, theme)
            }

            fn switches(&self) -> bool {
                self.inner.switches()
            }

            fn system_ui_style(&self) -> Option<$crate::SystemUiOverlayStyle> {
                self.inner.system_ui_style()
            }

            fn debug_name(&self) -> &'static str {
                // A transparent wrapper: the inspector shows the wrapped widget.
                self.inner.debug_name()
            }

            fn semantics(&self) -> Option<frus_core::SemanticsProperties> {
                self.inner.semantics()
            }
            fn describes(&self) -> Option<$crate::semantics::Description> {
                self.inner.describes()
            }

            fn children(&self) -> &[Box<dyn $crate::widget::Widget<Msg>>] {
                self.inner.children()
            }

            fn paint(
                &self,
                bounds: frus_core::Rect,
                status: $crate::interaction::Status,
                theme: &$crate::theme::Theme,
                scene: &mut frus_core::Scene,
            ) {
                self.inner.paint(bounds, status, theme, scene);
            }

            fn ink(&self, theme: &$crate::theme::Theme) -> Option<$crate::ink::InkStyle> {
                self.inner.ink(theme)
            }

            fn foreground(
                &self,
                theme: &$crate::theme::Theme,
            ) -> Option<frus_core::BoxDecoration> {
                self.inner.foreground(theme)
            }

            fn on_click(&self) -> Option<Msg> {
                self.inner.on_click()
            }
            fn opaque(&self) -> bool {
                self.inner.opaque()
            }

            fn positional_click(
                &self,
                local_x: f32,
                local_y: f32,
                width: f32,
                height: f32,
            ) -> Option<Msg> {
                self.inner.positional_click(local_x, local_y, width, height)
            }

            fn cursor_icon(
                &self,
                local_x: f32,
                local_y: f32,
                width: f32,
                height: f32,
            ) -> Option<$crate::interaction::Cursor> {
                self.inner.cursor_icon(local_x, local_y, width, height)
            }

            fn on_edit(
                &self,
                edit: &mut $crate::runtime::Edit,
                key: &$crate::interaction::Key,
            ) -> Option<Msg> {
                self.inner.on_edit(edit, key)
            }

            fn cursor_at(
                &self,
                local_x: f32,
                local_y: f32,
                width: f32,
                scroll_cursor: usize,
            ) -> Option<usize> {
                self.inner.cursor_at(local_x, local_y, width, scroll_cursor)
            }

            fn text_metrics(&self, width: f32, cursor: usize) -> Option<(f32, f32, f32, f32)> {
                self.inner.text_metrics(width, cursor)
            }

            fn text_viewport(&self, rect: frus_core::Rect) -> Option<frus_core::Rect> {
                self.inner.text_viewport(rect)
            }

            fn caret_vertical(
                &self,
                width: f32,
                cursor: usize,
                down: bool,
                page: bool,
                goal_x: Option<f32>,
            ) -> Option<(usize, f32)> {
                self.inner
                    .caret_vertical(width, cursor, down, page, goal_x)
            }

            fn selected_text(&self, edit: &$crate::runtime::Edit) -> Option<String> {
                self.inner.selected_text(edit)
            }

            fn text_value(&self) -> Option<&str> {
                self.inner.text_value()
            }

            fn replace_value(&self, value: String) -> Option<Msg> {
                self.inner.replace_value(value)
            }

            fn word_at(&self, index: usize) -> Option<(usize, usize)> {
                self.inner.word_at(index)
            }

            fn selection_handles(
                &self,
                width: f32,
                edit: &$crate::runtime::Edit,
                scroll_y: f32,
            ) -> Option<[$crate::SelectionHandle; 2]> {
                self.inner.selection_handles(width, edit, scroll_y)
            }

            fn autofill_hints(&self) -> &[$crate::AutofillHint] {
                self.inner.autofill_hints()
            }

            fn focusable(&self) -> bool {
                self.inner.focusable()
            }

            fn shortcut_bindings(
                &self,
            ) -> &[($crate::shortcuts::KeyStroke, $crate::shortcuts::Intent)] {
                self.inner.shortcut_bindings()
            }

            fn shortcut_callbacks(&self) -> &[($crate::shortcuts::KeyStroke, Msg)] {
                self.inner.shortcut_callbacks()
            }

            fn action_bindings(&self) -> &[($crate::shortcuts::Intent, Msg)] {
                self.inner.action_bindings()
            }

            fn action_listeners(&self) -> &[($crate::shortcuts::Intent, Msg)] {
                self.inner.action_listeners()
            }

            fn on_keystroke(
                &self,
            ) -> Option<std::rc::Rc<dyn Fn($crate::shortcuts::KeyStroke) -> Option<Msg>>> {
                self.inner.on_keystroke()
            }

            fn descendants_focusable(&self) -> bool {
                self.inner.descendants_focusable()
            }

            fn focus_skip_traversal(&self) -> bool {
                self.inner.focus_skip_traversal()
            }

            fn focus_order(&self) -> Option<f32> {
                self.inner.focus_order()
            }

            fn focus_group(&self) -> bool {
                self.inner.focus_group()
            }

            // The **structural** questions the walk and the layout ask before they look
            // at a widget's children. A transparent wrapper that answered these for
            // itself would change how its content is laid out — a keyed stack would have
            // its layers put in flow instead of on top of one another — which is exactly
            // what a wrapper that claims to be transparent must not do.
            fn stack(&self) -> bool {
                self.inner.stack()
            }

            fn continuous(&self) -> bool {
                self.inner.continuous()
            }

            fn draws_own_focus(&self) -> bool {
                self.inner.draws_own_focus()
            }

            fn repaint_boundary(&self) -> bool {
                self.inner.repaint_boundary()
            }

            fn draggable(&self) -> bool {
                self.inner.draggable()
            }

            fn on_drag(&self, fraction: f32) -> Option<Msg> {
                self.inner.on_drag(fraction)
            }

            fn on_drag_start(&self, fraction: f32) -> Option<Msg> {
                self.inner.on_drag_start(fraction)
            }

            fn on_drag_end(&self, fraction: f32) -> Option<Msg> {
                self.inner.on_drag_end(fraction)
            }

            fn on_drag_delta(&self, dx: f32) -> Option<Msg> {
                self.inner.on_drag_delta(dx)
            }

            fn reorder_index(&self) -> Option<usize> {
                self.inner.reorder_index()
            }

            fn on_reorder(&self, to: usize) -> Option<Msg> {
                self.inner.on_reorder(to)
            }

            fn reorder_axis(&self) -> $crate::widget::ReorderAxis {
                self.inner.reorder_axis()
            }

            fn reorder_inserts(&self) -> bool {
                self.inner.reorder_inserts()
            }

            fn reorder_draggable(&self) -> bool {
                self.inner.reorder_draggable()
            }

            fn reorder_droppable(&self) -> bool {
                self.inner.reorder_droppable()
            }

            fn reorder_announcement(&self, to: usize) -> Option<String> {
                self.inner.reorder_announcement(to)
            }

            fn announce(&self) -> Option<String> {
                self.inner.announce()
            }

            fn scroll_content(&self) -> Option<&dyn $crate::widget::Widget<Msg>> {
                self.inner.scroll_content()
            }

            fn virtual_list(
                &self,
                viewport: frus_core::Size,
            ) -> Option<$crate::list::VirtualList<'_, Msg>> {
                self.inner.virtual_list(viewport)
            }

            fn page_view(&self) -> Option<$crate::pageview::PagedView<'_, Msg>> {
                self.inner.page_view()
            }

            fn intrinsic(&self) -> Option<($crate::constraints::IntrinsicAxis, Option<f32>)> {
                self.inner.intrinsic()
            }

            fn overflow_box(&self) -> Option<$crate::constraints::Overflow> {
                self.inner.overflow_box()
            }

            fn constraints_transform(
                &self,
            ) -> Option<$crate::constraints::ConstraintsTransform> {
                self.inner.constraints_transform()
            }

            fn hero_tag(&self) -> Option<u64> {
                self.inner.hero_tag()
            }

            fn drag_payload(&self) -> Option<u64> {
                self.inner.drag_payload()
            }

            fn drag_needs_long_press(&self) -> bool {
                self.inner.drag_needs_long_press()
            }

            fn drag_ghost_opacity(&self) -> f32 {
                self.inner.drag_ghost_opacity()
            }

            fn on_dropped(&self, accepted: bool) -> Option<Msg> {
                self.inner.on_dropped(accepted)
            }

            fn drop_zone(&self) -> bool {
                self.inner.drop_zone()
            }

            fn accepts_drag(&self, payload: u64) -> bool {
                self.inner.accepts_drag(payload)
            }

            fn on_drop(&self, payload: u64) -> Option<Msg> {
                self.inner.on_drop(payload)
            }

            fn on_page_changed(&self, page: usize) -> Option<Msg> {
                self.inner.on_page_changed(page)
            }

            fn on_scroll(
                &self,
                position: $crate::scrollposition::ScrollPosition,
            ) -> Option<Msg> {
                self.inner.on_scroll(position)
            }

            fn scroll_grain(&self) -> f32 {
                self.inner.scroll_grain()
            }

            fn layout_builder(
                &self,
            ) -> Option<&dyn Fn(frus_core::Size) -> Box<dyn $crate::widget::Widget<Msg>>> {
                self.inner.layout_builder()
            }

            fn scroll_overlay(
                &self,
            ) -> Option<&$crate::scrolloverlay::OverlayBuilder<Msg>> {
                self.inner.scroll_overlay()
            }

            fn scroll_axis(&self) -> $crate::scroll::Axis {
                self.inner.scroll_axis()
            }

            fn scrollbars(&self) -> Option<$crate::physics::Scrollbars> {
                self.inner.scrollbars()
            }

            fn thumb_visibility(&self) -> Option<bool> {
                self.inner.thumb_visibility()
            }

            fn scroll_physics(&self) -> Option<$crate::physics::ScrollPhysics> {
                self.inner.scroll_physics()
            }

            fn ime(&self) -> $crate::ime::Ime {
                self.inner.ime()
            }

            fn overlay(
                &self,
            ) -> Option<(&dyn $crate::widget::Widget<Msg>, $crate::portal::Placement)> {
                self.inner.overlay()
            }

            fn overlay_dismiss(&self) -> Option<Msg> {
                self.inner.overlay_dismiss()
            }

            fn overlay_scrim(
                &self,
                theme: &$crate::theme::Theme,
            ) -> Option<frus_core::Color> {
                self.inner.overlay_scrim(theme)
            }

            fn overlay_traps_focus(&self) -> bool {
                self.inner.overlay_traps_focus()
            }

            fn anim_target(&self) -> Option<f32> {
                self.inner.anim_target()
            }

            fn anim_duration(&self) -> f32 {
                self.inner.anim_duration()
            }

            fn anim_curve(&self) -> frus_core::Curve {
                self.inner.anim_curve()
            }

            fn opacity_group(&self) -> Option<f32> {
                self.inner.opacity_group()
            }

            fn anim_color(&self) -> Option<frus_core::Color> {
                self.inner.anim_color()
            }

            fn anim_size(&self) -> Option<frus_core::Size> {
                self.inner.anim_size()
            }

            fn anim_radius(&self) -> Option<frus_core::BorderRadius> {
                self.inner.anim_radius()
            }

            fn anim_padding(&self) -> Option<frus_core::Insets> {
                self.inner.anim_padding()
            }

            fn anim_offset(&self) -> Option<(f32, f32)> {
                self.inner.anim_offset()
            }

            fn anim_pins(&self) -> Option<$crate::positioned::Positioning> {
                self.inner.anim_pins()
            }

            fn anim_fractions(&self) -> Option<(Option<f32>, Option<f32>)> {
                self.inner.anim_fractions()
            }
            fn anim_text_style(&self) -> Option<frus_core::TextStyle> {
                self.inner.anim_text_style()
            }

            fn anim_transform(&self) -> Option<$crate::runtime::TransformValues> {
                self.inner.anim_transform()
            }

            fn alignment_geometry(&self) -> Option<frus_core::AlignmentGeometry> {
                self.inner.alignment_geometry()
            }

            fn transform_translate(&self) -> Option<(f32, f32)> {
                self.inner.transform_translate()
            }

            fn translate_fraction(&self) -> Option<(f32, f32)> {
                self.inner.translate_fraction()
            }

            fn transform_scale(&self) -> Option<(f32, f32, frus_core::Alignment)> {
                self.inner.transform_scale()
            }

            fn transform_rotate(&self) -> Option<(f32, frus_core::Alignment)> {
                self.inner.transform_rotate()
            }

            fn clip_shape(&self) -> Option<frus_core::ClipShape> {
                self.inner.clip_shape()
            }

            fn clip_path(&self) -> Option<&frus_core::Path> {
                self.inner.clip_path()
            }

            fn layer_filter(
                &self,
                cx: $crate::widget::FilterContext,
            ) -> Option<frus_core::LayerFilter> {
                self.inner.layer_filter(cx)
            }

            fn backdrop_group(&self) -> bool {
                self.inner.backdrop_group()
            }

            fn text_baseline(&self, theme: &$crate::theme::Theme) -> Option<f32> {
                self.inner.text_baseline(theme)
            }

            fn ignores_baseline(&self) -> bool {
                self.inner.ignores_baseline()
            }

            fn baseline_target(&self) -> Option<f32> {
                self.inner.baseline_target()
            }

            fn fill_axes(&self, theme: &$crate::theme::Theme) -> $crate::widget::FillAxes {
                self.inner.fill_axes(theme)
            }

            fn main_axis_floor(&self, theme: &$crate::theme::Theme) -> Option<f32> {
                self.inner.main_axis_floor(theme)
            }

            fn stack_loose(&self) -> bool {
                self.inner.stack_loose()
            }

            fn stack_visible(&self) -> Option<usize> {
                self.inner.stack_visible()
            }

            fn scroll_reverse(&self) -> bool {
                self.inner.scroll_reverse()
            }

            fn keep_visible(
                &self,
                size: $crate::Size,
                theme: &$crate::theme::Theme,
            ) -> Option<$crate::ui::KeepVisible> {
                self.inner.keep_visible(size, theme)
            }

            fn scroll_padding(&self) -> frus_core::Insets {
                self.inner.scroll_padding()
            }

            fn tile_shape(&self) -> Option<f32> {
                self.inner.tile_shape()
            }

            fn barrier(&self) -> Option<$crate::barrier::ModalBarrier> {
                self.inner.barrier()
            }

            fn dismissible(&self) -> Option<$crate::dismiss::DismissSpec> {
                self.inner.dismissible()
            }

            fn on_dismissed(
                &self,
                direction: $crate::dismiss::DismissDirection,
            ) -> Option<Msg> {
                self.inner.on_dismissed(direction)
            }

            fn sheet(&self) -> Option<&$crate::sheet::SheetSpec> {
                self.inner.sheet()
            }

            fn on_sheet_dismissed(&self) -> Option<Msg> {
                self.inner.on_sheet_dismissed()
            }

            fn refresh(&self) -> Option<$crate::refresh::RefreshSpec> {
                self.inner.refresh()
            }

            fn on_refresh(&self) -> Option<Msg> {
                self.inner.on_refresh()
            }

            fn interactive(&self) -> Option<(f32, f32)> {
                self.inner.interactive()
            }

            fn fitted(&self) -> Option<frus_core::BoxFit> {
                self.inner.fitted()
            }

            fn rotated_quarter_turns(&self) -> Option<i32> {
                self.inner.rotated_quarter_turns()
            }

            fn navigator_clips(&self) -> bool {
                self.inner.navigator_clips()
            }
            fn navigator(&self) -> Option<(f32, bool)> {
                self.inner.navigator()
            }
            fn navigator_retained(&self) -> usize {
                self.inner.navigator_retained()
            }

            fn measure(&self, theme: &$crate::theme::Theme) -> Option<frus_layout::MeasureFn<'_>> {
                self.inner.measure(theme)
            }

            fn measure_key(&self, theme: &$crate::theme::Theme) -> Option<u64> {
                self.inner.measure_key(theme)
            }

            fn on_long_press(&self) -> Option<Msg> {
                self.inner.on_long_press()
            }

            fn on_key(
                &self,
                key: &$crate::interaction::Key,
            ) -> $crate::interaction::KeyResponse<Msg> {
                self.inner.on_key(key)
            }
        }
    };
}

pub(crate) use forward_transparent;

/// A widget held by a **shared pointer**, so that a builder which rebuilds its subtree can
/// hand the same caller-supplied child to each build.
///
/// The framework's children are `Box<dyn Widget<Msg>>`, which cannot be cloned. That is
/// the right default — a widget tree is built once and consumed — and it collides with the
/// one shape several controls here have: a builder that **rebuilds** on every setting, so
/// that the order the settings are written in does not matter. `PopupMenuButton` and
/// `DropdownButton` are both that shape, and both let a caller supply a whole widget as one
/// of their rows.
///
/// It is a transparent wrapper and nothing else: the sharing is the whole of it, and
/// [`Widget::opaque`](crate::Widget::opaque) and every other hook come straight from the
/// child.
pub(crate) struct Shared<Msg> {
    inner: std::rc::Rc<dyn crate::widget::Widget<Msg>>,
}

impl<Msg> Shared<Msg> {
    pub(crate) fn new(inner: std::rc::Rc<dyn crate::widget::Widget<Msg>>) -> Self {
        Self { inner }
    }

    /// It changes nothing about the box: it *is* its child.
    fn restyle(&self, base: frus_layout::Style) -> frus_layout::Style {
        base
    }
}

forward_transparent!(Shared {
    /// Every one of these is **forwarded**: holding a widget by a shared pointer is not an
    /// identity, not a place, not a theme and not a surface.
    fn key(&self) -> Option<u64> {
        self.inner.key()
    }
    fn positioned(&self) -> Option<crate::positioned::Positioning> {
        self.inner.positioned()
    }
    fn theme_override(
        &self,
        inherited: &crate::theme::Theme,
    ) -> Option<Box<crate::theme::Theme>> {
        self.inner.theme_override(inherited)
    }
    fn media_override(&self, inherited: crate::MediaQuery) -> Option<crate::MediaQuery> {
        self.inner.media_override(inherited)
    }
    fn scaffold_override(&self) -> Option<crate::ScaffoldInfo> {
        self.inner.scaffold_override()
    }
});

#[cfg(test)]
mod tests {
    use crate::widget::Widget;

    /// Reads one of this crate's own source files, with its line endings normalised.
    ///
    /// A checkout on Windows hands these files back with CRLF — git's `core.autocrlf` is
    /// on there, and it is on the CI runner — while the patterns below are written with
    /// `\n`: rustc normalises line endings inside a string literal, so a newline written
    /// in *this* file is an LF whatever the checkout did. Without this the two tripwires
    /// below fail to find the end of the trait and report that, rather than what they
    /// exist to measure.
    fn read_source(relative: &str) -> String {
        let path = format!("{}{relative}", env!("CARGO_MANIFEST_DIR"));
        std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("reading {path}: {e}"))
            .replace("\r\n", "\n")
    }

    /// Every hook the trait has, forwarded — checked against the trait itself rather
    /// than against a list someone kept up to date by hand. A hook added to `Widget`
    /// and not to the macro is a wrapper that silently answers for itself.
    #[test]
    fn the_macro_forwards_every_hook_the_trait_declares() {
        let widget = read_source("/src/widget.rs");
        let macro_src = read_source("/src/transparent.rs");
        // The trait's own declarations stop at its closing brace (the blanket impl for
        // `Box<dyn Widget>` follows and repeats every name).
        let trait_body = widget
            .split_once("pub trait Widget")
            .expect("the trait")
            .1
            .split_once("\n}\n")
            .expect("its end")
            .0;
        let names = |src: &str| -> Vec<String> {
            src.lines()
                .filter_map(|l| l.trim().strip_prefix("fn "))
                .filter_map(|l| l.split(['(', '<']).next())
                .map(str::to_owned)
                .collect()
        };
        // The two the macro deliberately leaves to its callers; each wrapper states both.
        let claimable = [
            "key",
            "theme_override",
            "media_override",
            "scaffold_override",
            // A wrapper that *is* a form says so; every other one forwards it (512).
            "autofill_group",
        ];
        let missing: Vec<String> = names(trait_body)
            .into_iter()
            .filter(|n| !claimable.contains(&n.as_str()))
            .filter(|n| !macro_src.contains(&format!("fn {n}(")))
            .collect();
        assert!(
            missing.is_empty(),
            "a transparent wrapper would answer these for itself: {missing:?}"
        );
    }

    /// The **same instrument, second target**: `Box<dyn Widget>` also claims to be the
    /// widget it holds, through a hand-written blanket impl with no macro behind it.
    ///
    /// Milestone 324 found it two hooks short — `build_themed` and `repaint_boundary` —
    /// so a boxed `ThemeBuilder` asked to build would quietly do nothing and a boxed
    /// repaint boundary would report that it was not one. Neither was reachable, because
    /// every walk in the framework takes `&dyn Widget` and dispatches virtually; both were
    /// waiting for the first caller to hold a `Box` instead. That is exactly the shape of
    /// bug this module exists to prevent, and the blanket impl had no guard at all.
    #[test]
    fn the_boxed_widget_forwards_every_hook_the_trait_declares() {
        let src = read_source("/src/widget.rs");
        let trait_body = src
            .split_once("pub trait Widget")
            .expect("the trait")
            .1
            .split_once("\n}\n")
            .expect("its end")
            .0;
        let blanket = src
            .split_once("impl<Msg> Widget<Msg> for Box<dyn Widget<Msg>>")
            .expect("the blanket impl")
            .1;
        let names = |src: &str| -> Vec<String> {
            src.lines()
                .filter_map(|l| l.trim().strip_prefix("fn "))
                .filter_map(|l| l.split(['(', '<']).next())
                .map(str::to_owned)
                .collect()
        };
        let forwarded = names(blanket);
        let missing: Vec<String> = names(trait_body)
            .into_iter()
            .filter(|n| !forwarded.contains(n))
            .collect();
        assert!(
            missing.is_empty(),
            "a boxed widget answers these for itself: {missing:?}"
        );
    }

    /// And every wrapper states the two the macro left out — forwarding one of them by
    /// forgetting it is the same silence this module exists to prevent.
    #[test]
    fn every_wrapper_states_the_hooks_the_macro_leaves_out() {
        // Found, not listed: a wrapper added to the crate is covered the day it is
        // written, which a hand-kept array is not.
        let mut checked = 0;
        for entry in std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src"))
            .expect("the source directory")
        {
            let path = entry.expect("a directory entry").path();
            let file = path
                .file_name()
                .expect("a name")
                .to_string_lossy()
                .to_string();
            // `src` holds directories too (a module with children); only a `.rs` file
            // can carry a wrapper, and reading a directory is an error, not an empty
            // string.
            if file == "transparent.rs" || path.extension().is_none_or(|e| e != "rs") {
                continue;
            }
            let src = std::fs::read_to_string(&path).expect("the wrapper's source");
            if !src.contains("forward_transparent!(") {
                continue;
            }
            checked += 1;
            for hook in [
                "fn key(",
                "fn theme_override(",
                "fn media_override(",
                "fn scaffold_override(",
                "fn restyle(",
                "fn positioned(",
                "fn autofill_group(",
            ] {
                assert!(src.contains(hook), "{file} says nothing about `{hook}`");
            }
        }
        assert!(
            checked >= 3,
            "only {checked} wrappers found — did the search break?"
        );
    }

    #[test]
    fn a_wrapped_widget_keeps_its_structure() {
        let stack = crate::Stack::<()>::new()
            .width(100.0)
            .height(50.0)
            .layer(crate::Container::new());
        let wrapped = crate::Keyed::new(1u64, stack);
        assert!(
            Widget::<()>::stack(&wrapped),
            "a wrapped stack is still a stack"
        );
    }
}