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)]
385pub enum ContinuousScaleKind {
386 Sequential,
388 Diverging,
390}
391
392#[derive(Debug, Clone, PartialEq, Eq)]
414pub struct ContinuousColorScale {
415 selection: ContinuousSelection,
416 domain: Option<ColorDomain>,
417}
418#[derive(Debug, Clone, PartialEq)]
419enum ContinuousSelection {
420 Sequential(Option<SequentialGradient>),
421 Diverging {
422 center: f64,
423 gradient: Option<DivergingGradient>,
424 },
425}
426impl Eq for ContinuousSelection {}
427
428impl ContinuousColorScale {
429 pub fn sequential(
431 gradient: Option<SequentialGradient>,
432 domain: Option<ColorDomain>,
433 ) -> Result<Self> {
434 Ok(Self {
435 selection: ContinuousSelection::Sequential(gradient),
436 domain,
437 })
438 }
439 pub fn diverging(
441 center: f64,
442 gradient: Option<DivergingGradient>,
443 domain: Option<ColorDomain>,
444 ) -> Result<Self> {
445 let value = Self {
446 selection: ContinuousSelection::Diverging {
447 center: zero(center),
448 gradient,
449 },
450 domain,
451 };
452 value.validate()?;
453 Ok(value)
454 }
455 fn validate(&self) -> Result<()> {
456 if let Some(center) = self.get_center() {
457 if !center.is_finite()
458 || self
459 .domain
460 .as_ref()
461 .is_some_and(|domain| center < domain.minimum || center > domain.maximum)
462 {
463 return Err(invalid(
464 "diverging center must be finite and the exact domain must contain center",
465 ));
466 }
467 }
468 Ok(())
469 }
470 pub fn kind(&self) -> ContinuousScaleKind {
472 match self.selection {
473 ContinuousSelection::Sequential(_) => ContinuousScaleKind::Sequential,
474 ContinuousSelection::Diverging { .. } => ContinuousScaleKind::Diverging,
475 }
476 }
477 pub fn get_center(&self) -> Option<f64> {
479 match self.selection {
480 ContinuousSelection::Sequential(_) => None,
481 ContinuousSelection::Diverging { center, .. } => Some(center),
482 }
483 }
484 pub fn get_domain(&self) -> Option<&ColorDomain> {
486 self.domain.as_ref()
487 }
488 pub fn get_sequential_gradient(&self) -> Option<&SequentialGradient> {
490 match &self.selection {
491 ContinuousSelection::Sequential(gradient) => gradient.as_ref(),
492 ContinuousSelection::Diverging { .. } => None,
493 }
494 }
495 pub fn get_diverging_gradient(&self) -> Option<&DivergingGradient> {
497 match &self.selection {
498 ContinuousSelection::Diverging { gradient, .. } => gradient.as_ref(),
499 ContinuousSelection::Sequential(_) => None,
500 }
501 }
502 pub fn domain(mut self, domain: Option<ColorDomain>) -> Result<Self> {
504 self.domain = domain;
505 self.validate()?;
506 Ok(self)
507 }
508 pub fn center(mut self, value: f64) -> Result<Self> {
510 let ContinuousSelection::Diverging { center, .. } = &mut self.selection else {
511 return Err(invalid("sequential scale has no center"));
512 };
513 *center = zero(value);
514 self.validate()?;
515 Ok(self)
516 }
517 pub fn sequential_gradient(mut self, value: Option<SequentialGradient>) -> Result<Self> {
519 let ContinuousSelection::Sequential(gradient) = &mut self.selection else {
520 return Err(invalid("diverging scale cannot take a sequential gradient"));
521 };
522 *gradient = value;
523 self.validate()?;
524 Ok(self)
525 }
526 pub fn diverging_gradient(mut self, value: Option<DivergingGradient>) -> Result<Self> {
528 let ContinuousSelection::Diverging { gradient, .. } = &mut self.selection else {
529 return Err(invalid("sequential scale cannot take a diverging gradient"));
530 };
531 *gradient = value;
532 self.validate()?;
533 Ok(self)
534 }
535 pub(crate) fn stops(&self) -> Result<&[ColorStop]> {
536 match &self.selection {
537 ContinuousSelection::Sequential(Some(gradient)) => Ok(gradient.stops()),
538 ContinuousSelection::Diverging {
539 gradient: Some(gradient),
540 ..
541 } => Ok(gradient.stops()),
542 _ => Err(Error::Render(
543 "prepared continuous selection has no retained gradient".into(),
544 )),
545 }
546 }
547}
548
549#[cfg(test)]
550mod tests;