1use crate::{ColorRole, generated::*};
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6#[cfg_attr(feature = "serde", serde(transparent))]
7pub struct Argb(u32);
8
9impl Argb {
10 pub const fn from_u32(argb: u32) -> Self {
12 Self(argb)
13 }
14
15 pub const fn from_rgb(red: u8, green: u8, blue: u8) -> Self {
17 Self(u32::from_be_bytes([255, red, green, blue]))
18 }
19
20 pub const fn from_rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
22 Self(u32::from_be_bytes([alpha, red, green, blue]))
23 }
24
25 pub const fn with_alpha(self, alpha: u8) -> Self {
27 let [_, red, green, blue] = self.channels();
28 Self::from_rgba(red, green, blue, alpha)
29 }
30
31 pub const fn to_u32(self) -> u32 {
33 self.0
34 }
35
36 pub const fn channels(self) -> [u8; 4] {
38 self.0.to_be_bytes()
39 }
40
41 pub const fn alpha(self) -> u8 {
43 self.channels()[0]
44 }
45
46 pub const fn red(self) -> u8 {
48 self.channels()[1]
49 }
50
51 pub const fn green(self) -> u8 {
53 self.channels()[2]
54 }
55
56 pub const fn blue(self) -> u8 {
58 self.channels()[3]
59 }
60}
61
62impl ColorRole {
63 pub const fn on_role(self) -> Option<Self> {
66 use ColorRole::*;
67
68 Some(match self {
69 Background => OnBackground,
70 Error => OnError,
71 ErrorContainer => OnErrorContainer,
72 Info => OnInfo,
73 InfoContainer => OnInfoContainer,
74 InverseSurface => InverseOnSurface,
75 Primary => OnPrimary,
76 PrimaryContainer => OnPrimaryContainer,
77 PrimaryFixed | PrimaryFixedDim => OnPrimaryFixed,
78 Secondary => OnSecondary,
79 SecondaryContainer => OnSecondaryContainer,
80 SecondaryFixed | SecondaryFixedDim => OnSecondaryFixed,
81 Success => OnSuccess,
82 SuccessContainer => OnSuccessContainer,
83 Surface
84 | SurfaceBright
85 | SurfaceDim
86 | SurfaceContainerLowest
87 | SurfaceContainerLow
88 | SurfaceContainer
89 | SurfaceContainerHigh
90 | SurfaceContainerHighest => OnSurface,
91 SurfaceVariant => OnSurfaceVariant,
92 Tertiary => OnTertiary,
93 TertiaryContainer => OnTertiaryContainer,
94 TertiaryFixed | TertiaryFixedDim => OnTertiaryFixed,
95 Warning => OnWarning,
96 WarningContainer => OnWarningContainer,
97 _ => return None,
98 })
99 }
100}
101
102#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
105pub enum Appearance {
106 #[default]
108 Light,
109 Dark,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct ColorPair {
116 pub foreground: Argb,
118 pub background: Argb,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct ColorScheme {
125 appearance: Appearance,
126 colors: [Argb; ColorRole::ALL.len()],
127}
128
129#[cfg(feature = "serde")]
130impl serde::Serialize for ColorScheme {
131 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
132 #[derive(serde::Serialize)]
133 #[serde(rename = "ColorScheme")]
134 struct SerializedColorScheme {
135 appearance: Appearance,
136 overrides: std::collections::BTreeMap<ColorRole, Argb>,
137 }
138
139 let mut overrides = std::collections::BTreeMap::new();
140 for role in ColorRole::ALL {
141 let color = self.colors[role as usize];
142 if color != self.baseline_color(role) {
143 overrides.insert(role, color);
144 }
145 }
146 SerializedColorScheme {
147 appearance: self.appearance,
148 overrides,
149 }
150 .serialize(serializer)
151 }
152}
153
154#[cfg(feature = "serde")]
155impl<'de> serde::Deserialize<'de> for ColorScheme {
156 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
157 #[derive(serde::Deserialize)]
158 #[serde(rename = "ColorScheme")]
159 struct SerializedColorScheme {
160 appearance: Appearance,
161 #[serde(default)]
163 overrides: std::collections::BTreeMap<ColorRole, Argb>,
164 }
165
166 let raw = SerializedColorScheme::deserialize(deserializer)?;
167 let mut scheme = Self::baseline(raw.appearance);
168 for (role, color) in raw.overrides {
169 scheme.set_color(role, color);
170 }
171 Ok(scheme)
172 }
173}
174
175impl Default for ColorScheme {
176 fn default() -> Self {
177 Self::baseline(Appearance::Light)
178 }
179}
180
181impl ColorScheme {
182 pub const fn baseline(appearance: Appearance) -> Self {
184 Self {
185 appearance,
186 colors: match appearance {
187 Appearance::Light => LIGHT,
188 Appearance::Dark => DARK,
189 },
190 }
191 }
192
193 pub const fn appearance(&self) -> Appearance {
195 self.appearance
196 }
197
198 pub const fn color(&self, role: ColorRole) -> Argb {
200 self.colors[role as usize]
201 }
202
203 pub fn set_color(&mut self, role: ColorRole, color: Argb) {
205 self.colors[role as usize] = color;
206 }
207
208 pub fn with_color(mut self, role: ColorRole, color: Argb) -> Self {
210 self.set_color(role, color);
211 self
212 }
213
214 #[cfg(feature = "serde")]
215 const fn baseline_color(&self, role: ColorRole) -> Argb {
216 match self.appearance {
217 Appearance::Light => LIGHT[role as usize],
218 Appearance::Dark => DARK[role as usize],
219 }
220 }
221
222 pub fn pair(&self, background: ColorRole) -> Option<ColorPair> {
224 let foreground = background.on_role()?;
225 Some(ColorPair {
226 foreground: self.color(foreground),
227 background: self.color(background),
228 })
229 }
230
231 pub fn blend(&self, target: &Self, t: f32) -> Self {
234 if t.is_nan() || t <= 0.0 || self == target {
235 return self.clone();
236 }
237 if t >= 1.0 {
238 return target.clone();
239 }
240 let appearance = if t < 0.5 {
241 self.appearance
242 } else {
243 target.appearance
244 };
245 let colors = std::array::from_fn(|index| {
246 let from = self.colors[index].channels();
247 let to = target.colors[index].channels();
248 let channels = std::array::from_fn(|i| {
249 let start = f32::from(from[i]);
250 (start + (f32::from(to[i]) - start) * t).round() as u8
251 });
252 Argb::from_u32(u32::from_be_bytes(channels))
253 });
254 Self { appearance, colors }
255 }
256
257 pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
259 let surface = self.color(ColorRole::Surface);
260 let dp = elevation.dp();
261 if dp == 0.0 {
262 return surface;
263 }
264
265 let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
266 let [alpha, r, g, b] = surface.channels();
267 let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
268 let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
269 let alpha = overlay_alpha + under_alpha;
270 let composite = |under, over| {
271 ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
272 as u8
273 };
274 Argb::from_u32(u32::from_be_bytes([
275 (alpha * 255.0).round() as u8,
276 composite(r, tint_r),
277 composite(g, tint_g),
278 composite(b, tint_b),
279 ]))
280 }
281
282 #[cfg(feature = "dynamic-color")]
285 pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
286 Self::from_seed_with(
287 seed,
288 appearance,
289 contrast,
290 crate::DynamicVariant::TonalSpot,
291 crate::SpecVersion::Spec2021,
292 )
293 }
294}
295
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
298pub enum Elevation {
299 #[default]
301 Level0,
302 Level1,
304 Level2,
306 Level3,
308 Level4,
310 Level5,
312}
313
314impl Elevation {
315 pub const fn dp(self) -> f32 {
317 match self {
318 Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
319 Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
320 Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
321 Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
322 Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
323 Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
324 }
325 }
326}
327
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330pub enum StateLayer {
331 Hover,
333 Focus,
335 Pressed,
337 Dragged,
339}
340
341impl StateLayer {
342 pub const fn opacity(self) -> f32 {
344 match self {
345 Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
346 Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
347 Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
348 Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
349 }
350 }
351}
352#[cfg(feature = "dynamic-color")]
355pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
356 use material_color_utils::contrast::contrast_utils::Contrast;
357
358 if first.is_nan() || second.is_nan() {
359 return None;
360 }
361 Some(Contrast::ratio_of_tones(
362 first.clamp(0.0, 100.0),
363 second.clamp(0.0, 100.0),
364 ))
365}