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, Hash)]
115#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
116pub enum ColorSpec {
117 Role(ColorRole),
119 Custom(Argb),
121}
122
123impl ColorSpec {
124 pub const fn resolve(self, scheme: &ColorScheme) -> Argb {
126 match self {
127 Self::Role(role) => scheme.color(role),
128 Self::Custom(argb) => argb,
129 }
130 }
131}
132
133impl From<ColorRole> for ColorSpec {
134 fn from(role: ColorRole) -> Self {
135 Self::Role(role)
136 }
137}
138
139impl From<Argb> for ColorSpec {
140 fn from(argb: Argb) -> Self {
141 Self::Custom(argb)
142 }
143}
144
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub struct ColorPair {
148 pub foreground: Argb,
150 pub background: Argb,
152}
153
154#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct ColorScheme {
157 appearance: Appearance,
158 colors: [Argb; ColorRole::ALL.len()],
159}
160
161#[cfg(feature = "serde")]
162impl serde::Serialize for ColorScheme {
163 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
164 #[derive(serde::Serialize)]
165 #[serde(rename = "ColorScheme")]
166 struct SerializedColorScheme {
167 appearance: Appearance,
168 overrides: std::collections::BTreeMap<ColorRole, Argb>,
169 }
170
171 let mut overrides = std::collections::BTreeMap::new();
172 for role in ColorRole::ALL {
173 let color = self.colors[role as usize];
174 if color != self.baseline_color(role) {
175 overrides.insert(role, color);
176 }
177 }
178 SerializedColorScheme {
179 appearance: self.appearance,
180 overrides,
181 }
182 .serialize(serializer)
183 }
184}
185
186#[cfg(feature = "serde")]
187impl<'de> serde::Deserialize<'de> for ColorScheme {
188 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
189 #[derive(serde::Deserialize)]
190 #[serde(rename = "ColorScheme")]
191 struct SerializedColorScheme {
192 appearance: Appearance,
193 #[serde(default)]
195 overrides: std::collections::BTreeMap<ColorRole, Argb>,
196 }
197
198 let raw = SerializedColorScheme::deserialize(deserializer)?;
199 let mut scheme = Self::baseline(raw.appearance);
200 for (role, color) in raw.overrides {
201 scheme.set_color(role, color);
202 }
203 Ok(scheme)
204 }
205}
206
207impl Default for ColorScheme {
208 fn default() -> Self {
209 Self::baseline(Appearance::Light)
210 }
211}
212
213impl ColorScheme {
214 pub const fn baseline(appearance: Appearance) -> Self {
216 Self {
217 appearance,
218 colors: match appearance {
219 Appearance::Light => LIGHT,
220 Appearance::Dark => DARK,
221 },
222 }
223 }
224
225 pub const fn appearance(&self) -> Appearance {
227 self.appearance
228 }
229
230 pub const fn color(&self, role: ColorRole) -> Argb {
232 self.colors[role as usize]
233 }
234
235 pub fn set_color(&mut self, role: ColorRole, color: Argb) {
237 self.colors[role as usize] = color;
238 }
239
240 pub fn with_color(mut self, role: ColorRole, color: Argb) -> Self {
242 self.set_color(role, color);
243 self
244 }
245
246 #[cfg(feature = "serde")]
247 const fn baseline_color(&self, role: ColorRole) -> Argb {
248 match self.appearance {
249 Appearance::Light => LIGHT[role as usize],
250 Appearance::Dark => DARK[role as usize],
251 }
252 }
253
254 pub fn pair(&self, background: ColorRole) -> Option<ColorPair> {
256 let foreground = background.on_role()?;
257 Some(ColorPair {
258 foreground: self.color(foreground),
259 background: self.color(background),
260 })
261 }
262
263 pub fn blend(&self, target: &Self, t: f32) -> Self {
266 if t.is_nan() || t <= 0.0 || self == target {
267 return self.clone();
268 }
269 if t >= 1.0 {
270 return target.clone();
271 }
272 let appearance = if t < 0.5 {
273 self.appearance
274 } else {
275 target.appearance
276 };
277 let colors = std::array::from_fn(|index| {
278 let from = self.colors[index].channels();
279 let to = target.colors[index].channels();
280 let channels = std::array::from_fn(|i| {
281 let start = f32::from(from[i]);
282 (start + (f32::from(to[i]) - start) * t).round() as u8
283 });
284 Argb::from_u32(u32::from_be_bytes(channels))
285 });
286 Self { appearance, colors }
287 }
288
289 pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
291 let surface = self.color(ColorRole::Surface);
292 let dp = elevation.dp();
293 if dp == 0.0 {
294 return surface;
295 }
296
297 let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
298 let [alpha, r, g, b] = surface.channels();
299 let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
300 let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
301 let alpha = overlay_alpha + under_alpha;
302 let composite = |under, over| {
303 ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
304 as u8
305 };
306 Argb::from_u32(u32::from_be_bytes([
307 (alpha * 255.0).round() as u8,
308 composite(r, tint_r),
309 composite(g, tint_g),
310 composite(b, tint_b),
311 ]))
312 }
313
314 #[cfg(feature = "dynamic-color")]
317 pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
318 Self::from_seed_with(
319 seed,
320 appearance,
321 contrast,
322 crate::DynamicVariant::TonalSpot,
323 crate::SpecVersion::Spec2021,
324 )
325 }
326}
327
328#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
330pub enum Elevation {
331 #[default]
333 Level0,
334 Level1,
336 Level2,
338 Level3,
340 Level4,
342 Level5,
344}
345
346impl Elevation {
347 pub const fn dp(self) -> f32 {
349 match self {
350 Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
351 Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
352 Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
353 Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
354 Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
355 Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
356 }
357 }
358}
359
360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
362pub enum StateLayer {
363 Hover,
365 Focus,
367 Pressed,
369 Dragged,
371}
372
373impl StateLayer {
374 pub const fn opacity(self) -> f32 {
376 match self {
377 Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
378 Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
379 Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
380 Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
381 }
382 }
383}
384#[cfg(feature = "dynamic-color")]
387pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
388 use material_color_utils::contrast::contrast_utils::Contrast;
389
390 if first.is_nan() || second.is_nan() {
391 return None;
392 }
393 Some(Contrast::ratio_of_tones(
394 first.clamp(0.0, 100.0),
395 second.clamp(0.0, 100.0),
396 ))
397}