1use std::sync::Arc;
4
5use crate::spec::CategoricalColorMap;
6use crate::{Error, Result};
7
8use super::OpaqueColor;
9
10fn invalid(message: &str) -> Error {
11 Error::Data(message.into())
12}
13
14fn retain<T>(values: impl IntoIterator<Item = T>) -> Result<Arc<Vec<T>>> {
16 let values = values.into_iter();
17 let (minimum, maximum) = values.size_hint();
18 let mut retained = Vec::new();
19 if maximum == Some(minimum) && minimum > 0 {
20 reserve_input(&mut retained, minimum)?;
21 }
22 for value in values {
23 let next = retained
24 .len()
25 .checked_add(1)
26 .ok_or_else(|| invalid("scale input length overflow"))?;
27
28 if next > retained.capacity() {
29 let capacity = retained
30 .capacity()
31 .checked_mul(2)
32 .ok_or_else(|| invalid("scale input capacity overflow"))?
33 .max(next);
34 reserve_input(&mut retained, capacity)?;
35 }
36 retained.push(value);
37 }
38 if retained.is_empty() {
39 return Err(invalid("scale input must be nonempty"));
40 }
41 Ok(Arc::new(retained))
42}
43
44fn reserve_input<T>(values: &mut Vec<T>, capacity: usize) -> Result<()> {
45 values
46 .try_reserve_exact(capacity - values.len())
47 .map_err(|_| invalid("cannot reserve scale input"))
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PaletteCapacity {
53 Fixed,
55 Extendable,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct QualitativePalette {
62 colors: Arc<Vec<OpaqueColor>>,
63 capacity: PaletteCapacity,
64}
65
66impl QualitativePalette {
67 pub fn fixed(colors: impl IntoIterator<Item = OpaqueColor>) -> Result<Self> {
69 Ok(Self {
70 colors: retain(colors)?,
71 capacity: PaletteCapacity::Fixed,
72 })
73 }
74 pub fn extendable(colors: impl IntoIterator<Item = OpaqueColor>) -> Result<Self> {
76 Ok(Self {
77 colors: retain(colors)?,
78 capacity: PaletteCapacity::Extendable,
79 })
80 }
81 pub fn colors(&self) -> &[OpaqueColor] {
83 &self.colors
84 }
85 pub fn capacity(&self) -> PaletteCapacity {
87 self.capacity
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct AccentPalette {
94 seeds: Arc<Vec<OpaqueColor>>,
95}
96
97impl AccentPalette {
98 pub fn new(seeds: impl IntoIterator<Item = OpaqueColor>) -> Result<Self> {
100 Ok(Self {
101 seeds: retain(seeds)?,
102 })
103 }
104 pub fn seeds(&self) -> &[OpaqueColor] {
106 &self.seeds
107 }
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct CategoricalColorScale {
133 source: CategoricalSource,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137enum CategoricalSource {
138 Palette(QualitativePalette),
139 Map(CategoricalColorMap),
140}
141
142impl CategoricalColorScale {
143 pub fn from_palette(palette: QualitativePalette) -> Self {
145 Self {
146 source: CategoricalSource::Palette(palette),
147 }
148 }
149 pub fn from_map(map: CategoricalColorMap) -> Self {
151 Self {
152 source: CategoricalSource::Map(map),
153 }
154 }
155 pub fn palette(&self) -> Option<&QualitativePalette> {
157 match &self.source {
158 CategoricalSource::Palette(palette) => Some(palette),
159 CategoricalSource::Map(_) => None,
160 }
161 }
162 pub fn map(&self) -> Option<&CategoricalColorMap> {
164 match &self.source {
165 CategoricalSource::Map(map) => Some(map),
166 CategoricalSource::Palette(_) => None,
167 }
168 }
169}
170
171#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct ColorStop {
174 offset: f64,
175 color: OpaqueColor,
176}
177impl Eq for ColorStop {}
178
179impl ColorStop {
180 pub fn new(offset: f64, color: OpaqueColor) -> Result<Self> {
182 if !offset.is_finite() || !(0.0..=1.0).contains(&offset) {
183 return Err(invalid("gradient offset must be finite in 0..=1"));
184 }
185 Ok(Self {
186 offset: zero(offset),
187 color,
188 })
189 }
190 const fn builtin(offset: f64, color: OpaqueColor) -> Self {
191 assert!(offset.is_finite() && offset >= 0.0 && offset <= 1.0);
192 Self {
193 offset: if offset == 0.0 { 0.0 } else { offset },
194 color,
195 }
196 }
197 pub fn offset(&self) -> f64 {
199 self.offset
200 }
201 pub fn color(&self) -> OpaqueColor {
203 self.color
204 }
205 pub(crate) fn backend_stop(&self) -> crate::render::backend::GradientStop {
206 crate::render::backend::GradientStop::new(self.offset(), self.color().as_rgb())
207 }
208}
209
210pub(crate) const HEATMAP_SEQUENTIAL_STOPS: [ColorStop; 2] = [
211 ColorStop::builtin(0.0, OpaqueColor::rgb(247, 251, 255)),
212 ColorStop::builtin(1.0, OpaqueColor::rgb(8, 48, 107)),
213];
214pub(crate) const HEATMAP_DIVERGING_STOPS: [ColorStop; 3] = [
215 ColorStop::builtin(0.0, OpaqueColor::rgb(49, 130, 189)),
216 ColorStop::builtin(0.5, OpaqueColor::rgb(247, 247, 247)),
217 ColorStop::builtin(1.0, OpaqueColor::rgb(222, 45, 38)),
218];
219
220fn validate_stops(stops: &[ColorStop], diverging: bool) -> Result<()> {
221 if stops.len() < if diverging { 3 } else { 2 }
222 || stops.first().is_none_or(|s| s.offset.to_bits() != 0)
223 || stops
224 .last()
225 .is_none_or(|s| s.offset.to_bits() != 1.0_f64.to_bits())
226 || stops
227 .windows(2)
228 .any(|pair| pair[0].offset >= pair[1].offset)
229 || (diverging
230 && !stops
231 .iter()
232 .any(|s| s.offset.to_bits() == 0.5_f64.to_bits()))
233 {
234 return Err(invalid("gradient must increase strictly from exactly 0 to 1 with an explicit diverging neutral center stop at 0.5"));
235 }
236 Ok(())
237}
238
239macro_rules! gradient {
240 ($name:ident, $diverging:expr) => {
241 #[derive(Debug, Clone, PartialEq, Eq)]
242 #[doc = concat!("Complete strictly ordered opaque `", stringify!($name), "` with exact zero/one endpoints.")]
243 pub struct $name {
244 stops: Arc<Vec<ColorStop>>,
245 }
246 impl $name {
247 pub fn new(stops: impl IntoIterator<Item = ColorStop>) -> Result<Self> {
250 let stops = retain(stops)?;
251 validate_stops(&stops, $diverging)?;
252 Ok(Self { stops })
253 }
254 pub fn stops(&self) -> &[ColorStop] {
256 &self.stops
257 }
258 }
259 };
260}
261gradient!(SequentialGradient, false);
262gradient!(DivergingGradient, true);
263
264impl SequentialGradient {
265 pub(crate) fn same_in(&self, other: &Self) -> bool {
268 if Arc::ptr_eq(&self.stops, &other.stops) {
269 return true;
270 }
271 if self.stops.len() != other.stops.len() {
272 return false;
273 }
274 for (left, right) in self.stops.iter().zip(other.stops.iter()) {
275 if left != right {
276 return false;
277 }
278 }
279 true
280 }
281}
282
283impl DivergingGradient {
284 pub fn neutral(&self) -> OpaqueColor {
286 self.stops()
287 .iter()
288 .find(|s| s.offset.to_bits() == 0.5_f64.to_bits())
289 .expect("validated neutral stop")
290 .color()
291 }
292}
293
294#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct ColorScales {
297 qualitative: QualitativePalette,
298 sequential: SequentialGradient,
299 diverging: DivergingGradient,
300}
301
302impl ColorScales {
303 pub fn new(
305 qualitative: QualitativePalette,
306 sequential: SequentialGradient,
307 diverging: DivergingGradient,
308 ) -> Result<Self> {
309 Ok(Self {
310 qualitative,
311 sequential,
312 diverging,
313 })
314 }
315 pub fn get_qualitative(&self) -> &QualitativePalette {
317 &self.qualitative
318 }
319 pub fn get_sequential(&self) -> &SequentialGradient {
321 &self.sequential
322 }
323 pub fn get_diverging(&self) -> &DivergingGradient {
325 &self.diverging
326 }
327 pub fn qualitative(self, value: QualitativePalette) -> Result<Self> {
329 Self::new(value, self.sequential, self.diverging)
330 }
331 pub fn sequential(self, value: SequentialGradient) -> Result<Self> {
333 Self::new(self.qualitative, value, self.diverging)
334 }
335 pub fn diverging(self, value: DivergingGradient) -> Result<Self> {
337 Self::new(self.qualitative, self.sequential, value)
338 }
339}
340
341fn zero(value: f64) -> f64 {
342 if value == 0.0 {
343 0.0
344 } else {
345 value
346 }
347}
348
349#[derive(Debug, Clone, PartialEq)]
351pub struct ColorDomain {
352 minimum: f64,
353 maximum: f64,
354}
355impl Eq for ColorDomain {}
356
357impl ColorDomain {
358 pub fn exact(minimum: f64, maximum: f64) -> Result<Self> {
360 if !minimum.is_finite() || !maximum.is_finite() || maximum < minimum {
361 return Err(invalid(
362 "color domain must be finite and ascending, including a constant domain",
363 ));
364 }
365 Ok(Self {
366 minimum: zero(minimum),
367 maximum: zero(maximum),
368 })
369 }
370 pub fn minimum(&self) -> f64 {
372 self.minimum
373 }
374 pub fn maximum(&self) -> f64 {
376 self.maximum
377 }
378 pub(crate) fn as_pair(&self) -> (f64, f64) {
379 (self.minimum(), self.maximum())
380 }
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385#[non_exhaustive]
386pub enum ContinuousScaleKind {
387 Sequential,
389 Diverging,
391}
392
393#[derive(Debug, Clone, PartialEq, Eq)]
417pub struct ContinuousColorScale {
418 selection: ContinuousSelection,
419 domain: Option<ColorDomain>,
420}
421#[derive(Debug, Clone, PartialEq)]
422enum ContinuousSelection {
423 Sequential(Option<SequentialGradient>),
424 Diverging {
425 center: f64,
426 gradient: Option<DivergingGradient>,
427 },
428}
429impl Eq for ContinuousSelection {}
430
431impl ContinuousColorScale {
432 pub fn sequential(
434 gradient: Option<SequentialGradient>,
435 domain: Option<ColorDomain>,
436 ) -> Result<Self> {
437 Ok(Self {
438 selection: ContinuousSelection::Sequential(gradient),
439 domain,
440 })
441 }
442 pub fn diverging(
444 center: f64,
445 gradient: Option<DivergingGradient>,
446 domain: Option<ColorDomain>,
447 ) -> Result<Self> {
448 let value = Self {
449 selection: ContinuousSelection::Diverging {
450 center: zero(center),
451 gradient,
452 },
453 domain,
454 };
455 value.validate()?;
456 Ok(value)
457 }
458 fn validate(&self) -> Result<()> {
459 if let Some(center) = self.get_center() {
460 if !center.is_finite()
461 || self
462 .domain
463 .as_ref()
464 .is_some_and(|domain| center < domain.minimum || center > domain.maximum)
465 {
466 return Err(invalid(
467 "diverging center must be finite and the exact domain must contain center",
468 ));
469 }
470 }
471 Ok(())
472 }
473 pub fn kind(&self) -> ContinuousScaleKind {
475 match self.selection {
476 ContinuousSelection::Sequential(_) => ContinuousScaleKind::Sequential,
477 ContinuousSelection::Diverging { .. } => ContinuousScaleKind::Diverging,
478 }
479 }
480 pub fn get_center(&self) -> Option<f64> {
482 match self.selection {
483 ContinuousSelection::Sequential(_) => None,
484 ContinuousSelection::Diverging { center, .. } => Some(center),
485 }
486 }
487 pub fn get_domain(&self) -> Option<&ColorDomain> {
489 self.domain.as_ref()
490 }
491 pub fn get_sequential_gradient(&self) -> Option<&SequentialGradient> {
493 match &self.selection {
494 ContinuousSelection::Sequential(gradient) => gradient.as_ref(),
495 ContinuousSelection::Diverging { .. } => None,
496 }
497 }
498 pub fn get_diverging_gradient(&self) -> Option<&DivergingGradient> {
500 match &self.selection {
501 ContinuousSelection::Diverging { gradient, .. } => gradient.as_ref(),
502 ContinuousSelection::Sequential(_) => None,
503 }
504 }
505 pub fn domain(mut self, domain: Option<ColorDomain>) -> Result<Self> {
507 self.domain = domain;
508 self.validate()?;
509 Ok(self)
510 }
511 pub fn center(mut self, value: f64) -> Result<Self> {
513 let ContinuousSelection::Diverging { center, .. } = &mut self.selection else {
514 return Err(invalid("sequential scale has no center"));
515 };
516 *center = zero(value);
517 self.validate()?;
518 Ok(self)
519 }
520 pub fn sequential_gradient(mut self, value: Option<SequentialGradient>) -> Result<Self> {
522 let ContinuousSelection::Sequential(gradient) = &mut self.selection else {
523 return Err(invalid("diverging scale cannot take a sequential gradient"));
524 };
525 *gradient = value;
526 self.validate()?;
527 Ok(self)
528 }
529 pub fn diverging_gradient(mut self, value: Option<DivergingGradient>) -> Result<Self> {
531 let ContinuousSelection::Diverging { gradient, .. } = &mut self.selection else {
532 return Err(invalid("sequential scale cannot take a diverging gradient"));
533 };
534 *gradient = value;
535 self.validate()?;
536 Ok(self)
537 }
538 pub(crate) fn stops(&self) -> Result<&[ColorStop]> {
539 match &self.selection {
540 ContinuousSelection::Sequential(Some(gradient)) => Ok(gradient.stops()),
541 ContinuousSelection::Diverging {
542 gradient: Some(gradient),
543 ..
544 } => Ok(gradient.stops()),
545 _ => Err(Error::Render(
546 "prepared continuous selection has no retained gradient".into(),
547 )),
548 }
549 }
550}
551
552#[cfg(test)]
553mod tests;