rive_rs/shapes/paint/
shape_paint_mutator.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cell::{Cell, RefCell};
6use std::rc::Rc;
7
8use crate::component::Component;
9use crate::core::{Core, Object, ObjectRef, OnAdded};
10use crate::option_cell::OptionCell;
11use crate::renderer::{Gradient, PaintColor, RenderPaint};
12use crate::shapes::paint::{Fill, LinearGradient, ShapePaint, SolidColor, Stroke};
13
14#[derive(Debug)]
15pub struct ShapePaintMutator {
16    render_opacity: Cell<f32>,
17    render_paint: OptionCell<Rc<RefCell<RenderPaint>>>,
18}
19
20impl ObjectRef<'_, ShapePaintMutator> {
21    pub fn render_opacity(&self) -> f32 {
22        self.render_opacity.get()
23    }
24
25    pub fn set_render_opacity(&self, render_opacity: f32) {
26        if self.render_opacity() == render_opacity {
27            return;
28        }
29
30        self.render_opacity.set(render_opacity);
31        self.render_opacity_changed();
32    }
33}
34
35impl ObjectRef<'_, ShapePaintMutator> {
36    fn render_opacity_changed(&self) {
37        match_cast!(self, {
38            LinearGradient(linear_gradient) => linear_gradient.mark_gradient_dirty(),
39            SolidColor(solid_color) => solid_color.render_opacity_changed(),
40        })
41    }
42
43    pub fn init_paint_mutator(&self, component: Object<Component>) -> bool {
44        match_cast!(component, {
45            Fill(fill) => {
46                self.render_paint.set(fill.as_ref().init_render_paint(self.as_object()));
47                true
48            },
49            Stroke(stroke) => {
50                self.render_paint.set(stroke.as_ref().init_render_paint(self.as_object()));
51                true
52            },
53            ShapePaint(shape_paint) => {
54                self.render_paint.set(shape_paint.as_ref().init_render_paint(self.as_object()));
55                true
56            },
57            _ => false,
58        })
59    }
60
61    pub(crate) fn render_paint(&self) -> Rc<RefCell<RenderPaint>> {
62        self.render_paint.get().expect("init_paint_mutator has not been called yet")
63    }
64
65    pub(crate) fn set_gradient(&self, gradient: Gradient) {
66        self.render_paint().borrow_mut().color = PaintColor::Gradient(gradient);
67    }
68}
69
70impl Core for ShapePaintMutator {}
71
72impl OnAdded for ObjectRef<'_, ShapePaintMutator> {
73    on_added!();
74}
75
76impl Default for ShapePaintMutator {
77    fn default() -> Self {
78        Self { render_opacity: Cell::new(1.0), render_paint: OptionCell::new() }
79    }
80}