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
//! A visual container widget.

use std::ops::Div;

use figures::units::{Lp, Px, UPx};
use figures::{Abs, Angle, IntoSigned, IntoUnsigned, Point, Rect, Round, ScreenScale, Size, Zero};
use kludgine::shapes::{CornerRadii, PathBuilder, Shape};
use kludgine::Color;

use crate::context::{EventContext, GraphicsContext, LayoutContext, WidgetContext};
use crate::styles::components::{CornerRadius, IntrinsicPadding, Opacity, SurfaceColor};
use crate::styles::{Component, ContainerLevel, Dimension, Edges, RequireInvalidation, Styles};
use crate::value::{Dynamic, IntoValue, Source, Value};
use crate::widget::{MakeWidget, RootBehavior, Widget, WidgetInstance, WidgetRef};
use crate::ConstraintLimit;

/// A visual container widget, optionally applying padding and a background
/// color.
///
/// # Background Color Selection
///
/// This widget has three different modes for coloring its background:
///
/// - [`ContainerBackground::Auto`]: The background color is automatically
///   selected by using the [next](ContainerLevel::next) level from the next
///   parent container in the hierarchy.
///
///   If the previous container is [`ContainerLevel::Highest`] or the previous
///   parent container uses a color instead of a level,
///   [`ContainerLevel::Lowest`] will be used.
/// - [`ContainerBackground::Color`]: The specified color will be drawn.
/// - [`ContainerBackground::Level`]: The
///   [`SurfaceTheme`](crate::styles::SurfaceTheme) container color associated
///   with the given level will be used.
#[derive(Debug)]
pub struct Container {
    /// The configured background selection.
    pub background: Value<ContainerBackground>,
    /// Padding to surround the contained widget.
    ///
    /// If this is None, a uniform surround of [`IntrinsicPadding`] will be
    /// applied.
    pub padding: Option<Value<Edges<Dimension>>>,
    /// The shadow to apply behind the container's background.
    pub shadow: Value<ContainerShadow>,
    child: WidgetRef,
    applied_background: Option<EffectiveBackground>,
}

/// A strategy of applying a background to a [`Container`].
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub enum ContainerBackground {
    /// Automatically select a [`ContainerLevel`] by picking the
    /// [next](ContainerLevel::next) level after the previous parent
    /// [`Container`].
    ///
    /// If no parent container is found or a parent container is found with a
    /// [color](Self::Color) background, [`ContainerLevel::Lowest`] will be
    /// used. See [`Self::Level`] for more information.
    #[default]
    Auto,
    /// Fills the background with the specified color.
    Color(Color),
    /// Applies the [`SurfaceTheme`][st] color
    /// corresponding with the given level.
    ///
    /// | [`ContainerLevel`] | [`SurfaceTheme`][st] property |
    /// |--------------------|-------------------------------|
    /// | [`Lowest`][ll]     | [`lowest_container`][llc]     |
    /// | [`Low`][lo]        | [`low_container`][loc]        |
    /// | [`Low`][mi]        | [`container`][mic]            |
    /// | [`High`][hi]       | [`high_container`][hic]       |
    /// | [`Highest`][hh]    | [`highest_container`][hhc]    |
    ///
    /// [st]: crate::styles::SurfaceTheme
    /// [ll]: ContainerLevel::Lowest
    /// [llc]: crate::styles::SurfaceTheme::lowest_container
    /// [lo]: ContainerLevel::Low
    /// [loc]: crate::styles::SurfaceTheme::low_container
    /// [mi]: ContainerLevel::Mid
    /// [mic]: crate::styles::SurfaceTheme::container
    /// [hi]: ContainerLevel::High
    /// [hic]: crate::styles::SurfaceTheme::high_container
    /// [hh]: ContainerLevel::Highest
    /// [hhc]: crate::styles::SurfaceTheme::highest_container
    Level(ContainerLevel),
}

impl From<ContainerLevel> for ContainerBackground {
    fn from(value: ContainerLevel) -> Self {
        Self::Level(value)
    }
}

impl From<Color> for ContainerBackground {
    fn from(value: Color) -> Self {
        Self::Color(value)
    }
}

impl Container {
    /// Returns a new container wrapping `child` with default padding and a
    /// background color automatically selected by the theme.
    ///
    /// See [`ContainerBackground::Auto`] for more information about automatic
    /// coloring.
    #[must_use]
    pub fn new(child: impl MakeWidget) -> Self {
        Self {
            padding: None,
            applied_background: None,
            background: Value::default(),
            shadow: Value::default(),
            child: WidgetRef::new(child),
        }
    }

    /// Pads the contained widget with `padding`, returning the updated
    /// container.
    #[must_use]
    pub fn pad_by(mut self, padding: impl IntoValue<Edges<Dimension>>) -> Self {
        self.padding = Some(padding.into_value());
        self
    }

    /// Sets this container to render no background color, and then returns the
    /// updated container.
    #[must_use]
    pub fn transparent(mut self) -> Self {
        self.background = Value::Constant(ContainerBackground::Color(Color::CLEAR_WHITE));
        self
    }

    /// Sets this container to use the specific container level, and then
    /// returns the updated container.
    #[must_use]
    pub fn contain_level(mut self, level: impl IntoValue<ContainerLevel>) -> Container {
        self.background = level
            .into_value()
            .map_each(|level| ContainerBackground::from(*level));
        self
    }

    /// Sets this container to render the specified `color` background, and then
    /// returns the updated container.
    #[must_use]
    pub fn background_color(mut self, color: impl IntoValue<Color>) -> Self {
        self.background = color
            .into_value()
            .map_each(|color| ContainerBackground::from(*color));
        self
    }

    /// Renders `shadow` behind the container's background.
    #[must_use]
    pub fn shadow(mut self, shadow: impl IntoValue<ContainerShadow>) -> Self {
        self.shadow = shadow.into_value();
        self
    }

    fn padding(&self, context: &GraphicsContext<'_, '_, '_, '_>) -> Edges<Px> {
        match &self.padding {
            Some(padding) => padding.get(),
            None => Edges::from(context.get(&IntrinsicPadding)),
        }
        .map(|dim| dim.into_px(context.gfx.scale()).round())
    }

    fn effective_background_color(&mut self, context: &WidgetContext<'_>) -> kludgine::Color {
        let background = match self.background.get() {
            ContainerBackground::Color(color) => EffectiveBackground::Color(color),
            ContainerBackground::Level(level) => EffectiveBackground::Level(level),
            ContainerBackground::Auto => {
                EffectiveBackground::Level(match context.get(&CurrentContainerBackground) {
                    EffectiveBackground::Color(_) => ContainerLevel::default(),
                    EffectiveBackground::Level(level) => level.next().unwrap_or_default(),
                })
            }
        };

        if self.applied_background != Some(background) {
            context.attach_styles(Styles::new().with(&CurrentContainerBackground, background));
            self.applied_background = Some(background);
        }

        match background {
            EffectiveBackground::Color(color) => color,
            EffectiveBackground::Level(level) => match level {
                ContainerLevel::Lowest => context.theme().surface.lowest_container,
                ContainerLevel::Low => context.theme().surface.low_container,
                ContainerLevel::Mid => context.theme().surface.container,
                ContainerLevel::High => context.theme().surface.high_container,
                ContainerLevel::Highest => context.theme().surface.highest_container,
            },
        }
    }
}

impl Widget for Container {
    fn summarize(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_struct("Container")
            .field("background", &self.background)
            .field("padding", &self.padding)
            .field("shadow", &self.shadow)
            .field("child", &self.child)
            .finish()
    }

    fn unmounted(&mut self, context: &mut EventContext<'_>) {
        self.child.unmount_in(context);
    }

    fn full_control_redraw(&self) -> bool {
        true
    }

    #[allow(clippy::too_many_lines)]
    fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_>) {
        let opacity = context.get(&Opacity);

        let background = self.effective_background_color(context);
        let background = background.with_alpha_f32(background.alpha_f32() * *opacity);
        if background.alpha() > 0 {
            let shadow = self
                .shadow
                .get_tracking_invalidate(context)
                .into_px(context.gfx.scale());

            let child_shadow_offset = shadow.offset.min(Point::ZERO).abs();
            let child_size = context.gfx.region().size - shadow.spread * 2 - shadow.offset.abs();
            let child_area = Rect::new(child_shadow_offset + shadow.spread, child_size);

            let corner_radii = context.get(&CornerRadius).into_px(context.gfx.scale());

            // check if the shadow would be obscured before we try to draw it.
            if child_area.origin != Point::ZERO || child_size != context.gfx.region().size {
                render_shadow(&child_area, corner_radii, &shadow, background, context);
            }

            context.gfx.draw_shape(&Shape::filled_round_rect(
                child_area,
                corner_radii,
                background,
            ));
        }

        let child = self.child.mounted(context);
        context.for_other(&child).redraw();
    }

    fn layout(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Size<UPx> {
        let child = self.child.mounted(context);

        let corner_radii = context.get(&CornerRadius).into_upx(context.gfx.scale());

        let max_space = available_space.map(ConstraintLimit::max);
        let min_dimension = max_space.width.min(max_space.height);
        let max_corner_radii = min_dimension / 2;

        let corner_radii = corner_radii.map(|r| r.min(max_corner_radii));

        let mut padding = self.padding(context).into_upx(context.gfx.scale());
        padding.left = padding
            .left
            .max(corner_radii.top_left / std::f32::consts::PI)
            .max(corner_radii.bottom_left / std::f32::consts::PI);
        padding.right = padding
            .right
            .max(corner_radii.top_right / std::f32::consts::PI)
            .max(corner_radii.bottom_right / std::f32::consts::PI);
        padding.top = padding
            .top
            .max(corner_radii.top_right / std::f32::consts::PI)
            .max(corner_radii.top_left / std::f32::consts::PI);
        padding.bottom = padding
            .bottom
            .max(corner_radii.bottom_right / std::f32::consts::PI)
            .max(corner_radii.bottom_left / std::f32::consts::PI);
        let padding_amount = padding.size();

        let shadow = self
            .shadow
            .get_tracking_invalidate(context)
            .into_px(context.gfx.scale());
        let shadow_spread = shadow.spread.into_unsigned();

        let child_shadow_offset_amount = shadow.offset.abs().into_unsigned();
        let child_size = context.for_other(&child).layout(
            available_space - padding_amount - child_shadow_offset_amount - shadow_spread * 2,
        );

        let child_shadow_offset = shadow.offset.min(Point::ZERO).abs().into_unsigned();
        context.set_child_layout(
            &child,
            Rect::new(
                Point::new(padding.left, padding.top) + child_shadow_offset + shadow_spread,
                child_size,
            )
            .into_signed(),
        );

        child_size + padding_amount + child_shadow_offset_amount + shadow_spread * 2
    }

    fn root_behavior(
        &mut self,
        context: &mut EventContext<'_>,
    ) -> Option<(RootBehavior, WidgetInstance)> {
        let mut padding = self
            .padding
            .as_ref()
            .map(|padding| padding.get().into_px(context.kludgine.scale()))
            .unwrap_or_default();
        let shadow = self
            .shadow
            .get_tracking_invalidate(context)
            .into_px(context.kludgine.scale());

        if shadow.offset.x >= 0 {
            padding.right += shadow.offset.x;
        } else {
            padding.left += shadow.offset.x.abs();
        }

        if shadow.spread > 0 {
            padding += Edges::from(shadow.spread);
        }

        let behavior = if padding.is_zero() {
            RootBehavior::PassThrough
        } else {
            RootBehavior::Pad(padding.map(Dimension::from))
        };
        Some((behavior, self.child.widget().clone()))
    }
}

#[allow(clippy::too_many_lines)]
pub(crate) fn render_shadow(
    child_area: &Rect<Px>,
    mut corner_radii: CornerRadii<Px>,
    shadow: &ContainerShadow<Px>,
    background: Color,
    context: &mut GraphicsContext<'_, '_, '_, '_>,
) {
    let shadow_color = shadow.color.unwrap_or_else(|| context.theme_pair().shadow);
    let shadow_color =
        shadow_color.with_alpha_f32(shadow_color.alpha_f32() * background.alpha_f32());

    let min_dimension = child_area.size.width.min(child_area.size.height);
    let max_corner_radii = min_dimension / 2;

    corner_radii = corner_radii.map(|r| r.min(max_corner_radii));

    let max_corner = corner_radii
        .top_left
        .max(corner_radii.top_right)
        .max(corner_radii.bottom_left)
        .max(corner_radii.bottom_right);

    let max_blur = min_dimension / 2 - max_corner;
    let blur = shadow.blur_radius.min(max_blur).max(Px::ZERO);
    let gradient_size = shadow.spread + blur;

    if gradient_size > 0 {
        let mut solid_area = Rect::new(Point::squared(gradient_size), child_area.size - blur * 2);
        solid_area.origin += shadow.offset.max(Point::ZERO);

        let transparent = shadow_color.with_alpha(0);
        let solid_left = solid_area.origin.x;
        let solid_right = solid_area.origin.x + solid_area.size.width;
        let solid_top = solid_area.origin.y;
        let solid_bottom = solid_area.origin.y + solid_area.size.height;

        let solid_left_at_top = solid_area.origin.x + corner_radii.top_left;
        let solid_left_at_bottom = solid_area.origin.x + corner_radii.bottom_left;
        let solid_right_at_top =
            solid_area.origin.x + solid_area.size.width - corner_radii.top_right;
        let solid_right_at_bottom =
            solid_area.origin.x + solid_area.size.width - corner_radii.bottom_right;

        let solid_top_at_left = solid_area.origin.y + corner_radii.top_left;
        let solid_bottom_at_left =
            solid_area.origin.y + solid_area.size.height - corner_radii.bottom_left;
        let solid_top_at_right = solid_area.origin.y + corner_radii.top_right;
        let solid_bottom_at_right =
            solid_area.origin.y + solid_area.size.height - corner_radii.bottom_right;

        // Top
        if solid_left_at_top < solid_right_at_top {
            context.gfx.draw_shape(
                &PathBuilder::new((
                    Point::new(solid_left_at_top, solid_top_at_left),
                    shadow_color,
                ))
                .line_to((Point::new(solid_left_at_top, solid_top), shadow_color))
                .line_to((
                    Point::new(solid_left_at_top, solid_top - gradient_size),
                    transparent,
                ))
                .line_to((
                    Point::new(solid_right_at_top, solid_top - gradient_size),
                    transparent,
                ))
                .line_to((Point::new(solid_right_at_top, solid_top), shadow_color))
                .line_to((
                    Point::new(solid_right_at_top, solid_top_at_right),
                    shadow_color,
                ))
                .close()
                .filled(),
            );
        }
        // Right
        context.gfx.draw_shape(
            &PathBuilder::new((Point::new(solid_right, solid_top_at_right), shadow_color))
                .line_to((
                    Point::new(solid_right + gradient_size, solid_top_at_right),
                    transparent,
                ))
                .line_to((
                    Point::new(solid_right + gradient_size, solid_bottom_at_right),
                    transparent,
                ))
                .line_to((Point::new(solid_right, solid_bottom_at_right), shadow_color))
                .close()
                .filled(),
        );
        context.gfx.draw_shape(
            &PathBuilder::new((
                Point::new(solid_right_at_top, solid_top_at_right),
                shadow_color,
            ))
            .line_to((Point::new(solid_right, solid_top_at_right), shadow_color))
            .line_to((Point::new(solid_right, solid_bottom_at_right), shadow_color))
            .line_to((
                Point::new(solid_right_at_bottom, solid_bottom_at_right),
                shadow_color,
            ))
            .close()
            .filled(),
        );

        // Bottom
        context.gfx.draw_shape(
            &PathBuilder::new((
                Point::new(solid_left_at_bottom, solid_bottom_at_left),
                shadow_color,
            ))
            .line_to((Point::new(solid_left_at_bottom, solid_bottom), shadow_color))
            .line_to((
                Point::new(solid_left_at_bottom, solid_bottom + gradient_size),
                transparent,
            ))
            .line_to((
                Point::new(solid_right_at_bottom, solid_bottom + gradient_size),
                transparent,
            ))
            .line_to((
                Point::new(solid_right_at_bottom, solid_bottom),
                shadow_color,
            ))
            .line_to((
                Point::new(solid_right_at_bottom, solid_bottom_at_right),
                shadow_color,
            ))
            .close()
            .filled(),
        );

        // Left
        context.gfx.draw_shape(
            &PathBuilder::new((
                Point::new(solid_left - gradient_size, solid_top_at_left),
                transparent,
            ))
            .line_to((Point::new(solid_left, solid_top_at_left), shadow_color))
            .line_to((Point::new(solid_left, solid_bottom_at_left), shadow_color))
            .line_to((
                Point::new(solid_left - gradient_size, solid_bottom_at_left),
                transparent,
            ))
            .close()
            .filled(),
        );
        context.gfx.draw_shape(
            &PathBuilder::new((Point::new(solid_left, solid_top_at_left), shadow_color))
                .line_to((
                    Point::new(solid_left_at_top, solid_top_at_left),
                    shadow_color,
                ))
                .line_to((
                    Point::new(solid_left_at_bottom, solid_bottom_at_left),
                    shadow_color,
                ))
                .line_to((Point::new(solid_left, solid_bottom_at_left), shadow_color))
                .close()
                .filled(),
        );

        // Top Right
        shadow_arc(
            Point::new(solid_right_at_top, solid_top_at_right),
            corner_radii.top_right,
            gradient_size,
            shadow_color,
            transparent,
            Angle::degrees(270),
            context,
        );

        // Bottom Right
        shadow_arc(
            Point::new(solid_right_at_bottom, solid_bottom_at_right),
            corner_radii.bottom_right,
            gradient_size,
            shadow_color,
            transparent,
            Angle::degrees(0),
            context,
        );

        // Bottom Left
        shadow_arc(
            Point::new(solid_left_at_bottom, solid_bottom_at_left),
            corner_radii.bottom_left,
            gradient_size,
            shadow_color,
            transparent,
            Angle::degrees(90),
            context,
        );

        // Top Left
        shadow_arc(
            Point::new(solid_left_at_top, solid_top_at_left),
            corner_radii.top_left,
            gradient_size,
            shadow_color,
            transparent,
            Angle::degrees(180),
            context,
        );

        // Center
        context.gfx.draw_shape(
            &PathBuilder::new((
                Point::new(solid_left_at_top, solid_top_at_left),
                shadow_color,
            ))
            .line_to((
                Point::new(solid_right_at_top, solid_top_at_right),
                shadow_color,
            ))
            .line_to((
                Point::new(solid_right_at_bottom, solid_bottom_at_right),
                shadow_color,
            ))
            .line_to((
                Point::new(solid_left_at_bottom, solid_bottom_at_left),
                shadow_color,
            ))
            .close()
            .filled(),
        );
    } else {
        context.gfx.draw_shape(&Shape::filled_round_rect(
            Rect::new(shadow.offset.max(Point::ZERO), child_area.size),
            corner_radii,
            shadow_color,
        ));
    }
}

/// Draws a gradiented arc, quantized into sections to compensate for
/// `lyon_geom` having directional fill tesselator. If a single pair of arcs
/// joined by line segements is tesselated, the gradient "leans" in the
/// orientation of `FillOptions::sweep_orientation` and doesn't look properly
/// circular.
fn shadow_arc(
    origin: Point<Px>,
    radius: Px,
    gradient: Px,
    solid_color: Color,
    transparent_color: Color,
    start_angle: Angle,
    context: &mut GraphicsContext<'_, '_, '_, '_>,
) {
    let full_radius = radius + gradient;
    let mut current_outer_arc = origin + Point::new(full_radius, Px::ZERO).rotate_by(start_angle);

    let mut current_inner_arc = origin + Point::new(radius, Px::ZERO).rotate_by(start_angle);
    let mut angle = Angle::degrees(0);

    while angle < Angle::degrees(90) {
        angle += Angle::degrees(5);

        let outer_arc = origin + Point::new(full_radius, Px::ZERO).rotate_by(start_angle + angle);
        if outer_arc == current_outer_arc {
            continue;
        }

        let inner_arc = origin + Point::new(radius, Px::ZERO).rotate_by(start_angle + angle);

        let mut path = PathBuilder::new((current_inner_arc, solid_color));
        path = path
            .line_to((current_outer_arc, transparent_color))
            .line_to((outer_arc, transparent_color))
            .line_to((inner_arc, solid_color));
        if inner_arc != current_inner_arc {
            path = path.line_to((current_inner_arc, solid_color));
        }
        context.gfx.draw_shape(&path.close().filled());

        if inner_arc != current_inner_arc {
            let mut path = PathBuilder::new((origin, solid_color));
            path = path
                .line_to((current_inner_arc, solid_color))
                .line_to((inner_arc, solid_color))
                .line_to((origin, solid_color));
            context.gfx.draw_shape(&path.close().filled());
        }

        current_outer_arc = outer_arc;
        current_inner_arc = inner_arc;
    }
}

/// The selected background configuration of a [`Container`].
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum EffectiveBackground {
    /// The container rendered using the specified level's theme color.
    Level(ContainerLevel),
    /// The container rendered using the specified color.
    Color(Color),
}

impl TryFrom<Component> for EffectiveBackground {
    type Error = Component;

    fn try_from(value: Component) -> Result<Self, Self::Error> {
        match value {
            Component::Color(color) => Ok(EffectiveBackground::Color(color)),
            Component::ContainerLevel(level) => Ok(EffectiveBackground::Level(level)),
            other => Err(other),
        }
    }
}

impl From<EffectiveBackground> for Component {
    fn from(value: EffectiveBackground) -> Self {
        match value {
            EffectiveBackground::Level(level) => Self::ContainerLevel(level),
            EffectiveBackground::Color(color) => Self::Color(color),
        }
    }
}

impl RequireInvalidation for EffectiveBackground {
    fn requires_invalidation(&self) -> bool {
        false
    }
}

define_components! {
    Container {
        /// The container background behind the current widget.
        CurrentContainerBackground(EffectiveBackground, "background", |context| EffectiveBackground::Color(context.get(&SurfaceColor)))
    }
}

/// A shadow for a [`Container`].
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct ContainerShadow<Unit = Dimension> {
    /// The color of the shadow to use for the solid area.
    ///
    /// This color will be faded to transparent if there is any blur on the
    /// shadow.
    pub color: Option<Color>,
    /// The offset of the shadow.
    pub offset: Point<Unit>,
    /// The radius of the blur.
    pub blur_radius: Unit,
    /// An additional amount of space the blur should be expanded across in all
    /// directions. This increases the physical space of the shadow.
    pub spread: Unit,
}

impl<Unit> ContainerShadow<Unit> {
    /// Returns a new shadow that is offset underneath its contents.
    pub fn new(offset: Point<Unit>) -> Self
    where
        Unit: Default,
    {
        Self {
            color: None,
            offset,
            blur_radius: Unit::default(),
            spread: Unit::default(),
        }
    }

    /// Returns a drop shadow placed `distance` below.
    pub fn drop(distance: Unit) -> Self
    where
        Unit: Zero + Div<i32, Output = Unit> + Default + Copy,
    {
        Self::new(Point::new(Unit::ZERO, distance))
            .blur_radius(distance)
            .spread(distance / 2)
    }

    /// Sets the shadow color and returns self.
    #[must_use]
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Sets the blur radius and returns self.
    #[must_use]
    pub fn blur_radius(mut self, radius: Unit) -> Self {
        self.blur_radius = radius;
        self
    }

    /// Sets the spread radius and returns self.
    #[must_use]
    pub fn spread(mut self, spread: Unit) -> Self {
        self.spread = spread;
        self
    }
}

impl<Unit> ScreenScale for ContainerShadow<Unit>
where
    Unit: ScreenScale<Lp = Lp, Px = Px, UPx = UPx>,
{
    type Lp = ContainerShadow<Lp>;
    type Px = ContainerShadow<Px>;
    type UPx = ContainerShadow<UPx>;

    fn into_px(self, scale: figures::Fraction) -> Self::Px {
        ContainerShadow {
            color: self.color,
            offset: self.offset.into_px(scale),
            blur_radius: self.blur_radius.into_px(scale),
            spread: self.spread.into_px(scale),
        }
    }

    fn from_px(px: Self::Px, scale: figures::Fraction) -> Self {
        Self {
            color: px.color,
            offset: Point::from_px(px.offset, scale),
            blur_radius: Unit::from_px(px.blur_radius, scale),
            spread: Unit::from_px(px.spread, scale),
        }
    }

    fn into_upx(self, scale: figures::Fraction) -> Self::UPx {
        ContainerShadow {
            color: self.color,
            offset: self.offset.into_upx(scale),
            blur_radius: self.blur_radius.into_upx(scale),
            spread: self.spread.into_upx(scale),
        }
    }

    fn from_upx(px: Self::UPx, scale: figures::Fraction) -> Self {
        Self {
            color: px.color,
            offset: Point::from_upx(px.offset, scale),
            blur_radius: Unit::from_upx(px.blur_radius, scale),
            spread: Unit::from_upx(px.spread, scale),
        }
    }

    fn into_lp(self, scale: figures::Fraction) -> Self::Lp {
        ContainerShadow {
            color: self.color,
            offset: self.offset.into_lp(scale),
            blur_radius: self.blur_radius.into_lp(scale),
            spread: self.spread.into_lp(scale),
        }
    }

    fn from_lp(lp: Self::Lp, scale: figures::Fraction) -> Self {
        Self {
            color: lp.color,
            offset: Point::from_lp(lp.offset, scale),
            blur_radius: Unit::from_lp(lp.blur_radius, scale),
            spread: Unit::from_lp(lp.spread, scale),
        }
    }
}

impl From<Px> for ContainerShadow {
    fn from(value: Px) -> Self {
        Self::from(Dimension::from(value))
    }
}

impl From<Lp> for ContainerShadow {
    fn from(value: Lp) -> Self {
        Self::from(Dimension::from(value))
    }
}

impl From<Dimension> for ContainerShadow {
    fn from(spread: Dimension) -> Self {
        Self::default().spread(spread)
    }
}

impl From<Point<Lp>> for ContainerShadow {
    fn from(offset: Point<Lp>) -> Self {
        Self::from(offset.map(Dimension::from))
    }
}

impl From<Point<Px>> for ContainerShadow {
    fn from(offset: Point<Px>) -> Self {
        Self::from(offset.map(Dimension::from))
    }
}

impl From<Point<Dimension>> for ContainerShadow {
    fn from(size: Point<Dimension>) -> Self {
        Self::new(size)
    }
}

impl IntoValue<ContainerShadow> for Dimension {
    fn into_value(self) -> Value<ContainerShadow> {
        ContainerShadow::from(self).into_value()
    }
}

impl IntoValue<ContainerShadow> for Point<Px> {
    fn into_value(self) -> Value<ContainerShadow> {
        ContainerShadow::from(self).into_value()
    }
}

impl IntoValue<ContainerShadow> for Point<Lp> {
    fn into_value(self) -> Value<ContainerShadow> {
        ContainerShadow::from(self).into_value()
    }
}

impl IntoValue<ContainerShadow> for Point<Dimension> {
    fn into_value(self) -> Value<ContainerShadow> {
        ContainerShadow::from(self).into_value()
    }
}

impl IntoValue<ContainerShadow> for ContainerShadow<Px> {
    fn into_value(self) -> Value<ContainerShadow> {
        ContainerShadow {
            color: self.color,
            offset: self.offset.map(Dimension::from),
            blur_radius: Dimension::from(self.blur_radius),
            spread: Dimension::from(self.spread),
        }
        .into_value()
    }
}

impl From<ContainerShadow<Lp>> for ContainerShadow {
    fn from(value: ContainerShadow<Lp>) -> Self {
        ContainerShadow {
            color: value.color,
            offset: value.offset.map(Dimension::from),
            blur_radius: Dimension::from(value.blur_radius),
            spread: Dimension::from(value.spread),
        }
    }
}

impl From<ContainerShadow<Px>> for ContainerShadow {
    fn from(value: ContainerShadow<Px>) -> Self {
        ContainerShadow {
            color: value.color,
            offset: value.offset.map(Dimension::from),
            blur_radius: Dimension::from(value.blur_radius),
            spread: Dimension::from(value.spread),
        }
    }
}

impl IntoValue<ContainerShadow> for ContainerShadow<Lp> {
    fn into_value(self) -> Value<ContainerShadow> {
        ContainerShadow::<Dimension>::from(self).into_value()
    }
}

impl IntoValue<ContainerShadow> for Dynamic<ContainerShadow<Px>> {
    fn into_value(self) -> Value<ContainerShadow> {
        Value::Dynamic(self.map_each_cloned(ContainerShadow::<Dimension>::from))
    }
}

impl IntoValue<ContainerShadow> for Dynamic<ContainerShadow<Lp>> {
    fn into_value(self) -> Value<ContainerShadow> {
        Value::Dynamic(self.map_each_cloned(ContainerShadow::<Dimension>::from))
    }
}