carnelian/scene/
scene.rs

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

use super::facets::{
    FacetEntry, FacetId, FacetMap, FacetPtr, RectangleFacet, SpacingFacet, TextFacet,
    TextFacetOptions,
};
use super::group::{GroupId, GroupMap, GroupMember, GroupMemberData};
use super::layout::{ArrangerPtr, Axis, Flex, FlexBuilder, StackBuilder};
use super::{raster_for_corner_knockouts, BlendMode, FillRule, LayerGroup, Rendering};
use crate::color::Color;
use crate::drawing::{path_for_cursor, FontFace};
use crate::render::generic::{GenericOrder, OrderError};
use crate::render::{
    Composition, Context as RenderContext, Fill, Layer, Order, PreClear, Raster, RenderExt, Style,
};
use crate::{Coord, IntPoint, Point, Rect, Size, ViewAssistantContext};
use anyhow::{bail, Error};
use euclid::{size2, vec2};
use fuchsia_trace::duration;
use std::any::Any;
use std::collections::{BTreeMap, HashMap};
use std::fmt::{self, Debug};
use zx::{AsHandleRef, Event, Signals};

// Maximum order supported by scene. 3 layers are reserved for
/// scene features such as rounded corners.
pub const MAX_ORDER: usize = (Order::MAX.as_u32() - 3) as usize;

/// Scene order
pub type SceneOrder = GenericOrder<MAX_ORDER>;

impl TryFrom<SceneOrder> for Order {
    type Error = OrderError;

    fn try_from(order: SceneOrder) -> Result<Self, OrderError> {
        Self::try_from(order.as_u32())
    }
}

struct DirectLayerGroup<'a>(&'a mut Composition);

impl LayerGroup for DirectLayerGroup<'_> {
    fn clear(&mut self) {
        self.0.clear();
    }
    fn insert(&mut self, order: SceneOrder, layer: Layer) {
        self.0.insert(Order::try_from(order).unwrap_or_else(|e| panic!("{}", e)), layer);
    }
    fn remove(&mut self, order: SceneOrder) {
        self.0.remove(Order::try_from(order).unwrap_or_else(|e| panic!("{}", e)));
    }
}

struct SimpleLayerGroup<'a>(&'a mut BTreeMap<SceneOrder, Layer>);

impl LayerGroup for SimpleLayerGroup<'_> {
    fn clear(&mut self) {
        self.0.clear();
    }
    fn insert(&mut self, order: SceneOrder, layer: Layer) {
        self.0.insert(order, layer);
    }
    fn remove(&mut self, order: SceneOrder) {
        self.0.remove(&order);
    }
}

fn create_mouse_cursor_raster(render_context: &mut RenderContext) -> Raster {
    let path = path_for_cursor(Point::zero(), 20.0, render_context);
    let mut raster_builder = render_context.raster_builder().expect("raster_builder");
    raster_builder.add(&path, None);
    raster_builder.build()
}

fn cursor_layer(cursor_raster: &Raster, position: IntPoint, color: &Color) -> Layer {
    Layer {
        raster: cursor_raster.clone().translate(position.to_vector()),
        clip: None,
        style: Style {
            fill_rule: FillRule::NonZero,
            fill: Fill::Solid(*color),
            blend_mode: BlendMode::Over,
        },
    }
}

fn cursor_layer_pair(cursor_raster: &Raster, position: IntPoint) -> (Layer, Layer) {
    let black_pos = position + vec2(-1, -1);
    (
        cursor_layer(cursor_raster, position, &Color::fuchsia()),
        cursor_layer(cursor_raster, black_pos, &Color::new()),
    )
}

type LayerMap = BTreeMap<FacetId, BTreeMap<SceneOrder, Layer>>;

/// Options for creating a scene.
pub struct SceneOptions {
    /// Background color.
    pub background_color: Color,
    /// True if, when running without Scenic, if the scene
    /// should round the corners of the screen to match the
    /// presentation that sometimes occurs with Scenic.
    pub round_scene_corners: bool,
    /// True if, when running without Scenic, the mouse cursor should
    /// be drawn.
    pub enable_mouse_cursor: bool,
    /// Option arranger for the root group.
    pub root_arranger: Option<ArrangerPtr>,
    /// True if the scene should be mutable. If the scene is not going
    /// to change, setting this to false can provide some important
    /// performance benefits.
    pub mutable: bool,
    /// True if the scene is animated in a way that requires a render
    /// on every frame, for example, Spinning Square.
    pub animated: bool,
}

impl SceneOptions {
    /// Create the default scene options with a specified background color.
    pub fn with_background_color(background_color: Color) -> Self {
        Self { background_color, ..Self::default() }
    }
}

impl Default for SceneOptions {
    fn default() -> Self {
        Self {
            background_color: Color::new(),
            round_scene_corners: false,
            enable_mouse_cursor: true,
            root_arranger: None,
            mutable: true,
            animated: false,
        }
    }
}

/// A Carnelian scene is responsible for turning a collection of facets and groups
/// into rendered pixels.
pub struct Scene {
    renderings: HashMap<u64, Rendering>,
    mouse_cursor_raster: Option<Raster>,
    corner_knockouts_raster: Option<Raster>,
    facets: FacetMap,
    facet_order: Vec<FacetId>,
    groups: GroupMap,
    layers: LayerMap,
    composition: Composition,
    options: SceneOptions,
}

impl Scene {
    fn new_from_builder(options: SceneOptions, facets: FacetMap, groups: GroupMap) -> Self {
        let facet_order: Vec<FacetId> = facets.iter().map(|(facet_id, _)| *facet_id).collect();
        Self {
            renderings: HashMap::new(),
            mouse_cursor_raster: None,
            corner_knockouts_raster: None,
            facets,
            facet_order,
            groups,
            layers: LayerMap::new(),
            composition: Composition::new(options.background_color),
            options,
        }
    }

    /// Set the option to round scene corners.
    pub fn round_scene_corners(&mut self, round_scene_corners: bool) {
        self.options.round_scene_corners = round_scene_corners;
        if !round_scene_corners {
            self.corner_knockouts_raster = None;
        }
    }

    /// Add a facet to the scene, returning its ID.
    pub fn add_facet(&mut self, mut facet: FacetPtr) -> FacetId {
        assert_eq!(self.options.mutable, true);
        let facet_id = FacetId::new();
        facet.associate_facet_id(facet_id);
        self.facets
            .insert(facet_id, FacetEntry { facet, location: Point::zero(), size: Size::zero() });
        self.facet_order.push(facet_id);
        facet_id
    }

    /// Remove a particular facet from the scene.
    pub fn remove_facet(&mut self, facet_id: FacetId) -> Result<(), Error> {
        assert_eq!(self.options.mutable, true);
        if let Some(_) = self.facets.remove(&facet_id).as_mut() {
            self.layers.remove(&facet_id);
            self.facet_order.retain(|fid| facet_id != *fid);
            Ok(())
        } else {
            bail!("Tried to remove non-existant facet")
        }
    }

    /// Move a facet forward in the facet order list.
    pub fn move_facet_forward(&mut self, facet_id: FacetId) -> Result<(), Error> {
        assert_eq!(self.options.mutable, true);
        if let Some(index) = self.facet_order.iter().position(|fid| *fid == facet_id) {
            if index > 0 {
                let new_index = index - 1;
                self.facet_order.swap(new_index, index)
            }
            Ok(())
        } else {
            bail!("Tried to move_facet_forward non-existant facet")
        }
    }

    /// Move a facet backwards in the facet order list.
    pub fn move_facet_backward(&mut self, facet_id: FacetId) -> Result<(), Error> {
        assert_eq!(self.options.mutable, true);
        if let Some(index) = self.facet_order.iter().position(|fid| *fid == facet_id) {
            if index < self.facet_order.len() - 1 {
                let new_index = index + 1;
                self.facet_order.swap(new_index, index)
            }
            Ok(())
        } else {
            bail!("Tried to move_facet_backward non-existant facet")
        }
    }

    /// Create a new group.
    pub fn new_group(&mut self) -> GroupId {
        GroupId::new()
    }

    /// Add a facet to a group, removing it from any group it might already belong to.
    pub fn add_facet_to_group(
        &mut self,
        facet_id: FacetId,
        group_id: GroupId,
        member_data: Option<GroupMemberData>,
    ) {
        self.groups.add_facet_to_group(facet_id, group_id, member_data);
    }

    /// Remove a facet from a group.
    pub fn remove_facet_from_group(&mut self, facet_id: FacetId, group_id: GroupId) {
        self.groups.remove_facet_from_group(facet_id, group_id);
    }

    /// Set the arranger for a group. No change in facet position will occur until layout
    /// is called.
    pub fn set_group_arranger(&mut self, group_id: GroupId, arranger: ArrangerPtr) {
        self.groups.set_group_arranger(group_id, arranger);
    }

    pub(crate) fn update_scene_layers(
        &mut self,
        render_context: &mut RenderContext,
        view_context: &ViewAssistantContext,
    ) {
        duration!(c"gfx", c"Scene::update_scene_layers");

        for (facet_id, facet_entry) in &mut self.facets {
            let facet_layers = self.layers.entry(*facet_id).or_insert_with(|| BTreeMap::new());
            let mut layer_group = SimpleLayerGroup(facet_layers);
            facet_entry
                .facet
                .update_layers(facet_entry.size, &mut layer_group, render_context, view_context)
                .expect("update_layers");
        }
    }

    fn create_or_update_rendering(
        renderings: &mut HashMap<u64, Rendering>,
        background_color: Color,
        context: &ViewAssistantContext,
    ) -> Option<PreClear> {
        let image_id = context.image_id;
        let size_rendering = renderings.entry(image_id).or_insert_with(|| Rendering::new());
        let size = context.size;
        if size != size_rendering.size {
            size_rendering.size = context.size;
            Some(PreClear { color: background_color })
        } else {
            None
        }
    }

    fn update_composition(
        layers: impl IntoIterator<Item = (SceneOrder, Layer)>,
        mouse_position: &Option<IntPoint>,
        mouse_cursor_raster: &Option<Raster>,
        corner_knockouts: &Option<Raster>,
        composition: &mut Composition,
    ) {
        duration!(c"gfx", c"Scene::update_composition");

        for (order, layer) in layers.into_iter() {
            composition.insert(Order::try_from(order).unwrap_or_else(|e| panic!("{}", e)), layer);
        }

        const CORNER_KOCKOUTS_ORDER: u32 = Order::MAX.as_u32();
        const MOUSE_CURSOR_LAYER_0_ORDER: u32 = Order::MAX.as_u32() - 1;
        const MOUSE_CURSOR_LAYER_1_ORDER: u32 = Order::MAX.as_u32() - 2;

        if let Some(position) = mouse_position {
            if let Some(raster) = mouse_cursor_raster {
                let (layer0, layer1) = cursor_layer_pair(raster, *position);
                composition.insert(
                    Order::try_from(MOUSE_CURSOR_LAYER_0_ORDER).unwrap_or_else(|e| panic!("{}", e)),
                    layer0,
                );
                composition.insert(
                    Order::try_from(MOUSE_CURSOR_LAYER_1_ORDER).unwrap_or_else(|e| panic!("{}", e)),
                    layer1,
                );
            }
        }

        if let Some(raster) = corner_knockouts {
            composition.insert(
                Order::try_from(CORNER_KOCKOUTS_ORDER).unwrap_or_else(|e| panic!("{}", e)),
                Layer {
                    raster: raster.clone(),
                    clip: None,
                    style: Style {
                        fill_rule: FillRule::NonZero,
                        fill: Fill::Solid(Color::new()),
                        blend_mode: BlendMode::Over,
                    },
                },
            );
        }
    }

    fn is_immutable_single_facet_scene_at_origin(&self) -> bool {
        !self.options.mutable
            && self.facets.len() == 1
            && self.facets.iter().next().expect("first facet").1.location == Point::zero()
    }

    /// Render the scene. Expected to be called from the view assistant's render method.
    pub fn render(
        &mut self,
        render_context: &mut RenderContext,
        ready_event: Event,
        context: &ViewAssistantContext,
    ) -> Result<(), Error> {
        let image = render_context.get_current_image(context);
        let background_color = self.options.background_color;
        let pre_clear =
            Self::create_or_update_rendering(&mut self.renderings, background_color, context);
        let size = context.size;

        let ext = RenderExt { pre_clear, ..Default::default() };

        const CORNER_KNOCKOUTS_SIZE: f32 = 10.0;

        if self.options.round_scene_corners && self.corner_knockouts_raster.is_none() {
            self.corner_knockouts_raster = Some(raster_for_corner_knockouts(
                &Rect::from_size(size),
                CORNER_KNOCKOUTS_SIZE,
                render_context,
            ));
        }

        let mouse_cursor_position = if self.options.enable_mouse_cursor {
            if context.mouse_cursor_position.is_some() && self.mouse_cursor_raster.is_none() {
                self.mouse_cursor_raster = Some(create_mouse_cursor_raster(render_context));
            }
            &context.mouse_cursor_position
        } else {
            &None
        };

        // Allow immutable single facet scenes at origin to mutate the composition directly
        // for optimal performance.
        if self.is_immutable_single_facet_scene_at_origin() {
            let (_, facet_entry) = self.facets.iter_mut().next().expect("first facet");
            let composition = &mut self.composition;
            let mut layer_group = DirectLayerGroup(composition);
            facet_entry
                .facet
                .update_layers(size, &mut layer_group, render_context, context)
                .expect("update_layers");

            Self::update_composition(
                std::iter::empty(),
                mouse_cursor_position,
                &self.mouse_cursor_raster,
                &self.corner_knockouts_raster,
                composition,
            );
        } else {
            self.update_scene_layers(render_context, context);

            let composition = &mut self.composition;
            let facet_order = &self.facet_order;
            let facets = &self.facets;
            let layers = &self.layers;

            // Clear composition and generate a completely new set of layers.
            composition.clear();

            let mut next_origin: u32 = 0;
            let layers = facet_order.iter().rev().flat_map(|facet_id| {
                let facet_entry = facets.get(facet_id).expect("facets");
                let facet_translation = facet_entry.location.to_vector().to_i32();
                let facet_layers = layers.get(facet_id).expect("layers");
                let facet_origin = next_origin;

                // Advance origin for next facet.
                next_origin += facet_layers.keys().next_back().map(|o| o.as_u32() + 1).unwrap_or(0);

                facet_layers.iter().map(move |(order, layer)| {
                    (
                        SceneOrder::try_from(facet_origin + order.as_u32())
                            .unwrap_or_else(|e| panic!("{}", e)),
                        Layer {
                            raster: layer.raster.clone().translate(facet_translation),
                            clip: layer.clip.clone().map(|c| c.translate(facet_translation)),
                            style: layer.style.clone(),
                        },
                    )
                })
            });

            Self::update_composition(
                layers,
                mouse_cursor_position,
                &self.mouse_cursor_raster,
                &self.corner_knockouts_raster,
                composition,
            );
        }

        render_context.render(&mut self.composition, None, image, &ext);
        ready_event.as_handle_ref().signal(Signals::NONE, Signals::EVENT_SIGNALED)?;

        Ok(())
    }

    /// Send a message to a facet.
    pub fn send_message(&mut self, target: &FacetId, msg: Box<dyn Any>) {
        if let Some(facet_entry) = self.facets.get_mut(target) {
            facet_entry.facet.handle_message(msg);
        }
    }

    /// Set the absolute position of a facet.
    pub fn set_facet_location(&mut self, target: &FacetId, location: Point) {
        assert_eq!(self.options.mutable, true);
        if let Some(facet_entry) = self.facets.get_mut(target) {
            facet_entry.location = location;
        }
    }

    /// Set the size of a facet.
    pub fn set_facet_size(&mut self, target: &FacetId, size: Size) {
        assert_eq!(self.options.mutable, true);
        if let Some(facet_entry) = self.facets.get_mut(target) {
            facet_entry.size = size;
        }
    }

    /// Get the absolute position of a facet.
    pub fn get_facet_location(&self, target: &FacetId) -> Point {
        self.facets
            .get(target)
            .and_then(|facet_entry| Some(facet_entry.location))
            .unwrap_or_else(Point::zero)
    }

    /// Get the size of a facet.
    pub fn get_facet_size(&self, target: &FacetId) -> Size {
        self.facets
            .get(target)
            .and_then(|facet_entry| Some(facet_entry.size))
            .expect("get_facet_size")
    }

    pub(crate) fn calculate_facet_size(&self, target: &FacetId, available: Size) -> Size {
        self.facets
            .get(target)
            .and_then(|facet_entry| Some(facet_entry.facet.calculate_size(available)))
            .expect("calculate_facet_size")
    }

    /// Get a rectangle created from the absolute position and size of a facet.
    pub fn get_facet_bounds(&self, target: &FacetId) -> Rect {
        Rect::new(self.get_facet_location(target), self.get_facet_size(target))
    }

    fn position_group(
        &mut self,
        origin: Point,
        group_id: GroupId,
        size_map: &HashMap<GroupMember, Size>,
    ) {
        let members = self.groups.group_members(group_id);
        let group_size = size_map.get(&GroupMember::Group(group_id)).expect("group size");
        let sizes: Vec<_> =
            members.iter().map(|member| *size_map.get(member).expect("members size")).collect();
        if let Some(arranger) = self.groups.group_arranger(group_id) {
            let member_data = self.groups.group_member_data(group_id);
            let positions = arranger.arrange(*group_size, &sizes, &member_data);
            let member_ids = self.groups.group_members(group_id);
            for (pos, member_id) in positions.iter().zip(member_ids.iter()) {
                match member_id {
                    GroupMember::Facet(facet_id) => {
                        let size =
                            size_map.get(member_id).map_or_else(|| size2(10.0, 10.0), |size| *size);
                        self.set_facet_size(facet_id, size);
                        self.set_facet_location(facet_id, *pos + origin.to_vector())
                    }
                    GroupMember::Group(member_group_id) => {
                        self.position_group(*pos + origin.to_vector(), *member_group_id, size_map)
                    }
                }
            }
        } else {
            println!("no arranger");
        }
    }

    /// Run the layout process, positioning groups and facets.
    pub fn layout(&mut self, target_size: Size) {
        let size_map = self.groups.calculate_size_map(target_size, self);
        self.position_group(Point::zero(), self.groups.get_root_group_id(), &size_map);
    }

    /// Return the bounds of all facets.
    pub fn all_facet_bounds(&self) -> Vec<Rect> {
        self.facet_order
            .iter()
            .filter_map(|facet_id| {
                self.facets
                    .get(facet_id)
                    .and_then(|facet_entry| Some(Rect::new(facet_entry.location, facet_entry.size)))
            })
            .collect()
    }

    pub(crate) fn is_animated(&self) -> bool {
        self.options.animated
    }
}

impl Debug for Scene {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Scene").field("groups", &self.groups).finish()
    }
}

/// Fluent builder for facet groups
pub struct GroupBuilder<'a> {
    pub(crate) builder: &'a mut SceneBuilder,
    label: String,
    pub(crate) arranger: Option<ArrangerPtr>,
}

impl<'a> GroupBuilder<'a> {
    pub(crate) fn new(builder: &'a mut SceneBuilder) -> Self {
        Self { builder, label: String::from(""), arranger: None }
    }

    /// Set the debugging label for a group.
    pub fn label(mut self, label: &str) -> Self {
        self.label = String::from(label);
        self
    }

    /// Create a row-oriented flex builder with member data.
    pub fn row_with_member_data(self, member_data: Option<GroupMemberData>) -> FlexBuilder<'a> {
        FlexBuilder::new(self, Axis::Horizontal, member_data)
    }

    /// Create a row-oriented flex builder.
    pub fn row(self) -> FlexBuilder<'a> {
        self.row_with_member_data(None)
    }

    /// Create a column-oriented flex builder with member data.
    pub fn column_with_member_data(self, member_data: Option<GroupMemberData>) -> FlexBuilder<'a> {
        FlexBuilder::new(self, Axis::Vertical, member_data)
    }

    /// Create a column-oriented flex builder.
    pub fn column(self) -> FlexBuilder<'a> {
        self.column_with_member_data(None)
    }

    /// Create a stack builder.
    pub fn stack(self) -> StackBuilder<'a> {
        StackBuilder::new(self)
    }

    /// Create the stack group, with contents provided by
    /// `f`.
    pub fn contents<F>(self, mut f: F) -> GroupId
    where
        F: FnMut(&mut SceneBuilder),
    {
        self.builder.start_group(&self.label, self.arranger.unwrap_or_else(Flex::new_ptr));
        f(self.builder);
        self.builder.end_group()
    }

    /// Create the stack group, with contents provided by
    /// `f` and member data for the group
    pub fn contents_with_member_data<F>(
        self,
        member_data: Option<GroupMemberData>,
        mut f: F,
    ) -> GroupId
    where
        F: FnMut(&mut SceneBuilder),
    {
        self.builder.start_group_with_member_data(
            &self.label,
            self.arranger.unwrap_or_else(Flex::new_ptr),
            member_data,
        );
        f(self.builder);
        self.builder.end_group()
    }
}

/// Fluent builder for scenes.
pub struct SceneBuilder {
    options: SceneOptions,
    facets: FacetMap,
    groups: GroupMap,
    group_stack: Vec<GroupId>,
}

impl SceneBuilder {
    /// Create a new fluent builder for building Scenes.
    pub fn new() -> Self {
        Self {
            options: SceneOptions::default(),
            facets: FacetMap::new(),
            groups: GroupMap::new(),
            group_stack: vec![],
        }
    }

    /// True if, when running without Scenic, if the scene
    /// should round the corners of the screen to match the
    /// presentation that sometimes occurs with Scenic.
    pub fn round_scene_corners(mut self, round: bool) -> Self {
        self.options.round_scene_corners = round;
        self
    }

    /// If true, when running without Scenic, the mouse cursor should
    /// be drawn.
    pub fn enable_mouse_cursor(mut self, enable: bool) -> Self {
        self.options.enable_mouse_cursor = enable;
        self
    }

    /// Set the color to use for the background of a scene.
    pub fn background_color(mut self, background_color: Color) -> Self {
        self.options.background_color = background_color;
        self
    }

    /// If true, the scene can be mutated after being built.
    pub fn mutable(mut self, mutable: bool) -> Self {
        self.options.mutable = mutable;
        self
    }

    /// If true, the scene should be rendered on every frame.
    pub fn animated(mut self, animated: bool) -> Self {
        self.options.animated = animated;
        self
    }

    fn allocate_facet_id(&mut self) -> FacetId {
        FacetId::new()
    }

    fn push_facet(
        &mut self,
        mut facet: FacetPtr,
        location: Point,
        member_data: Option<GroupMemberData>,
    ) -> FacetId {
        let facet_id = self.allocate_facet_id();
        facet.associate_facet_id(facet_id);
        self.facets.insert(facet_id.clone(), FacetEntry { facet, location, size: Size::zero() });
        if let Some(group_id) = self.group_stack.last() {
            self.groups.add_facet_to_group(facet_id, *group_id, member_data);
        }
        facet_id
    }

    /// Add a rectangle facet of size and color to the scene.
    pub fn rectangle(&mut self, size: Size, color: Color) -> FacetId {
        self.push_facet(RectangleFacet::new(size, color), Point::zero(), None)
    }

    /// Add a rounded rectangle facet of size, corner radius and color to the scene.
    pub fn rounded_rectangle(&mut self, size: Size, corner: Coord, color: Color) -> FacetId {
        self.push_facet(RectangleFacet::new_rounded(size, corner, color), Point::zero(), None)
    }

    /// Add a spacing facet of size.
    pub fn space(&mut self, size: Size) -> FacetId {
        self.push_facet(Box::new(SpacingFacet::new(size)), Point::zero(), None)
    }

    /// Add a horizontal line to the scene.
    pub fn h_line(
        &mut self,
        width: Coord,
        thickness: Coord,
        color: Color,
        location: Option<Point>,
    ) -> FacetId {
        self.h_line_with_data(width, thickness, color, location, None)
    }

    /// Add a horizontal line to the scene with member data
    pub fn h_line_with_data(
        &mut self,
        width: Coord,
        thickness: Coord,
        color: Color,
        location: Option<Point>,
        member_data: Option<GroupMemberData>,
    ) -> FacetId {
        self.push_facet(
            RectangleFacet::h_line(width, thickness, color),
            location.unwrap_or_else(Point::zero),
            member_data,
        )
    }

    /// Add a vertical line to the scene.
    pub fn v_line(
        &mut self,
        height: Coord,
        thickness: Coord,
        color: Color,
        location: Option<Point>,
    ) -> FacetId {
        self.v_line_with_data(height, thickness, color, location, None)
    }

    /// Add a vertical line to the scene with member data.
    pub fn v_line_with_data(
        &mut self,
        height: Coord,
        thickness: Coord,
        color: Color,
        location: Option<Point>,
        member_data: Option<GroupMemberData>,
    ) -> FacetId {
        self.push_facet(
            RectangleFacet::v_line(height, thickness, color),
            location.unwrap_or_else(Point::zero),
            member_data,
        )
    }

    /// Add a text facet to the scene.
    pub fn text(
        &mut self,
        face: FontFace,
        text: &str,
        size: f32,
        location: Point,
        options: TextFacetOptions,
    ) -> FacetId {
        self.text_with_data(face, text, size, location, options, None)
    }

    /// Add a text facet to the scene along with
    /// some data for the group arranger.
    pub fn text_with_data(
        &mut self,
        face: FontFace,
        text: &str,
        size: f32,
        location: Point,
        options: TextFacetOptions,
        member_data: Option<GroupMemberData>,
    ) -> FacetId {
        self.push_facet(TextFacet::with_options(face, text, size, options), location, member_data)
    }

    /// Add an object that implements the Facet trait to the scene, along with
    /// some data for the group arranger.
    pub fn facet_with_data(
        &mut self,
        facet: FacetPtr,
        member_data: Option<GroupMemberData>,
    ) -> FacetId {
        self.push_facet(facet, Point::zero(), member_data)
    }

    /// Add an object that implements the Facet trait to the scene.
    pub fn facet(&mut self, facet: FacetPtr) -> FacetId {
        self.push_facet(facet, Point::zero(), None)
    }

    /// Add an object that implements the Facet trait to the scene and set
    /// its location.
    pub fn facet_at_location(&mut self, facet: FacetPtr, location: Point) -> FacetId {
        self.push_facet(facet, location, None)
    }

    /// Start a facet group with member data. Any facets added to the scene or
    // groups started will become members of this group.
    pub fn start_group_with_member_data(
        &mut self,
        label: &str,
        arranger: ArrangerPtr,
        member_data: Option<GroupMemberData>,
    ) {
        let group_id = GroupId::new();
        self.groups.start_group(group_id, label, arranger, self.group_stack.last(), member_data);
        self.group_stack.push(group_id);
    }

    /// Start a facet group. Any facets added to the scene or groups started will become
    // members of this group.
    pub fn start_group(&mut self, label: &str, arranger: ArrangerPtr) {
        self.start_group_with_member_data(label, arranger, None);
    }

    /// End the current group, returning its group ID.
    pub fn end_group(&mut self) -> GroupId {
        self.group_stack.pop().expect("group stack to always have a group ID")
    }

    /// Create a group builder.
    pub fn group(&mut self) -> GroupBuilder<'_> {
        GroupBuilder::new(self)
    }

    /// Consume this builder and build the scene.
    pub fn build(mut self) -> Scene {
        while self.group_stack.len() > 0 {
            self.end_group();
        }
        Scene::new_from_builder(self.options, self.facets, self.groups)
    }
}