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