Skip to main content

ferrochart_core/plugin/
custom.rs

1//! Custom series: a plugin that owns its data, gives
2//! core its times and range extremes, and writes immediate primitives for the
3//! visible points.
4
5use core::any::Any;
6use core::fmt;
7
8use crate::data::{ChangeLog, SeriesMapping, TimeIndex, Timestamp};
9use crate::drawing::{DrawingCtx, FrameBuilder, index_of_time, time_of_index};
10use crate::error::{Error, Result};
11use crate::frame::SeriesStyle;
12use crate::geom::Px;
13
14/// How a custom series is placed on the time axis.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub enum AxisMode {
17    /// Each point's time is a slot of the time axis, like the points of a
18    /// built-in series (e.g. footprint columns sharing the candles' slots).
19    Slots,
20    /// Points are placed between the existing slots by interpolating their
21    /// times and add no slots (e.g. 1 s heatmap columns on a 1 min chart).
22    Overlay,
23}
24
25/// A series that owns its data.
26///
27/// Core asks it for its times and extremes and lets it draw the visible
28/// points; the data is changed through [`crate::Chart::update_custom`], which
29/// tells core what changed. Point `i` is element `i` of
30/// [`times`](Self::times).
31///
32/// # Examples
33///
34/// ```
35/// use ferrochart_core::data::{DataChange, Timestamp};
36/// use ferrochart_core::drawing::FrameBuilder;
37/// use ferrochart_core::geom::RectPx;
38/// use ferrochart_core::plugin::{AxisMode, CustomSeries, MinMaxIndex, SeriesCtx};
39/// use ferrochart_core::chart::SeriesOptions;
40/// use ferrochart_core::testing::MonoMeasurer;
41/// use ferrochart_core::{Chart, ChartOptions};
42///
43/// /// A vertical bar from `lo` to `hi` per point.
44/// #[derive(Default)]
45/// struct Ranges {
46///     time: Vec<Timestamp>,
47///     range: Vec<(f64, f64)>,
48///     index: MinMaxIndex,
49/// }
50///
51/// impl Ranges {
52///     fn push(&mut self, t: Timestamp, lo: f64, hi: f64) -> DataChange {
53///         self.time.push(t);
54///         self.range.push((lo, hi));
55///         let _ = self.index.push(lo, hi);
56///         DataChange::Append { count: 1 }
57///     }
58/// }
59///
60/// impl CustomSeries for Ranges {
61///     fn kind(&self) -> &'static str {
62///         "example.ranges"
63///     }
64///     fn axis_mode(&self) -> AxisMode {
65///         AxisMode::Slots
66///     }
67///     fn times(&self) -> &[Timestamp] {
68///         &self.time
69///     }
70///     fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
71///         self.index.query(from, to)
72///     }
73///     fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
74///         let w = (ctx.bar_spacing().0 * 0.6).max(1.0);
75///         for i in from..to {
76///             let (lo, hi) = self.range[i];
77///             let (Some(x), Some(y0), Some(y1)) =
78///                 (ctx.x_of_point(i), ctx.coords().y_of(hi), ctx.coords().y_of(lo))
79///             else {
80///                 continue;
81///             };
82///             let rect = RectPx { x: x - w / 2.0, y: y0, w, h: (y1 - y0).max(1.0) };
83///             out.rect(rect, ctx.style().up);
84///         }
85///     }
86/// }
87///
88/// let mut chart = Chart::new(ChartOptions::default());
89/// let id = chart.add_custom_series(
90///     chart.main_pane(),
91///     Box::new(Ranges::default()),
92///     SeriesOptions::default(),
93/// )?;
94/// chart.update_custom(id, |r: &mut Ranges| r.push(60_000, 1.0, 2.0))?;
95/// chart.update_custom(id, |r: &mut Ranges| r.push(120_000, 1.5, 3.0))?;
96/// assert_eq!(chart.custom_series::<Ranges>(id).map(|r| r.time.len()), Some(2));
97/// chart.build_frame(0.0, &MonoMeasurer);
98/// # Ok::<(), ferrochart_core::Error>(())
99/// ```
100pub trait CustomSeries: Send + Any {
101    /// Kind name, e.g. `"orderflow.heatmap"`; renderers that draw it natively
102    /// declare this name.
103    fn kind(&self) -> &'static str;
104    /// How the points are placed on the time axis; read once, when added.
105    fn axis_mode(&self) -> AxisMode;
106    /// Times of the points, strictly increasing.
107    fn times(&self) -> &[Timestamp];
108    /// Price extremes of points `from..to`, for auto scaling. Called every
109    /// frame, so it must be O(log n) (see [`crate::plugin::MinMaxIndex`]).
110    fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)>;
111    /// Portable path: writes the primitives of points `from..to` (the
112    /// visible ones and one more on each side). Must not allocate once
113    /// warmed up.
114    fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>);
115    /// Value of the last-value label; `None` hides it.
116    fn last_value(&self) -> Option<f64> {
117        None
118    }
119    /// Value of point `point` for the crosshair and magnet.
120    fn crosshair_value(&self, point: usize) -> Option<f64> {
121        let _ = point;
122        None
123    }
124    /// Parameters of the native GPU path, e.g. a color-scale range.
125    fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
126        let _ = (ctx, params);
127    }
128}
129
130/// What a [`CustomSeries`] knows about the chart while it draws.
131pub struct SeriesCtx<'a> {
132    pub(crate) coords: DrawingCtx<'a>,
133    pub(crate) store: &'a CustomStore,
134    /// `SeriesOptions::shift` in bars.
135    pub(crate) shift: f64,
136    pub(crate) visible: (usize, usize),
137    pub(crate) style: SeriesStyle,
138}
139
140impl<'a> SeriesCtx<'a> {
141    /// Time/price conversions of the pane, with this series' price map (on
142    /// relative scales each series has its own), fonts and price
143    /// formatting.
144    pub fn coords(&self) -> &DrawingCtx<'a> {
145        &self.coords
146    }
147
148    /// x of point `i` (the center of its slot); `None` if it has none.
149    pub fn x_of_point(&self, i: usize) -> Option<f32> {
150        let index = self.store.x_index(self.coords.index, i)? + self.shift;
151        let x = f64::from(self.coords.plot.x) + self.coords.time_scale.index_to_x_f64(index);
152        x.is_finite().then_some(x as f32)
153    }
154
155    /// The points being drawn, `from..to` (the visible ones and one more on
156    /// each side).
157    pub fn visible(&self) -> (usize, usize) {
158        self.visible
159    }
160
161    /// Distance between two slots of the time axis.
162    pub fn bar_spacing(&self) -> Px {
163        Px(self.coords.time_scale.bar_spacing() as f32)
164    }
165
166    /// Colors and line settings resolved from the series options and the
167    /// theme (`up`/`down` are `color`/`down_color` or the theme's).
168    pub fn style(&self) -> &SeriesStyle {
169        &self.style
170    }
171}
172
173/// A custom series in the chart: the plugin and where its points are.
174pub(crate) struct CustomStore {
175    pub(crate) plugin: Box<dyn CustomSeries>,
176    pub(crate) kind: &'static str,
177    pub(crate) mode: AxisMode,
178    /// `Slots`: logical index of each point (`Mapped` has `len` offsets).
179    mapping: SeriesMapping,
180    /// Points core has accepted (the plugin's data may be longer only
181    /// between a change and its sync).
182    len: usize,
183    /// Times of the first and last accepted point.
184    bounds: Option<(Timestamp, Timestamp)>,
185    /// Changes by point number (`CustomDraw::points` is in point numbers).
186    pub(crate) log: ChangeLog,
187}
188
189impl fmt::Debug for CustomStore {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.debug_struct("CustomStore")
192            .field("kind", &self.kind)
193            .field("mode", &self.mode)
194            .field("len", &self.len)
195            .finish_non_exhaustive()
196    }
197}
198
199/// How `Chart::update_custom` applies a change after checking it.
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub(crate) enum CustomChange {
202    /// Nothing to do.
203    None,
204    UpdateLast,
205    Append,
206    Prepend {
207        count: usize,
208    },
209    Replace,
210}
211
212impl CustomStore {
213    pub(crate) fn new(plugin: Box<dyn CustomSeries>) -> Self {
214        Self {
215            kind: plugin.kind(),
216            mode: plugin.axis_mode(),
217            plugin,
218            mapping: SeriesMapping::Aligned { first: 0 },
219            len: 0,
220            bounds: None,
221            log: ChangeLog::new(),
222        }
223    }
224
225    pub(crate) fn len(&self) -> usize {
226        self.len
227    }
228
229    /// The accepted times.
230    pub(crate) fn times(&self) -> &[Timestamp] {
231        let t = self.plugin.times();
232        t.get(..self.len).unwrap_or(t)
233    }
234
235    pub(crate) fn heap_bytes(&self) -> usize {
236        match &self.mapping {
237            SeriesMapping::Aligned { .. } => 0,
238            SeriesMapping::Mapped { offsets, .. } => offsets.capacity() * 4,
239        }
240    }
241
242    /// Logical index of point `i` (`Slots`).
243    fn logical(&self, i: usize) -> Option<i64> {
244        if i >= self.len {
245            return None;
246        }
247        self.mapping.logical_index(i)
248    }
249
250    /// Logical indices `first..end` the points cover (`Slots` only).
251    pub(crate) fn span(&self) -> Option<(i64, i64)> {
252        if self.mode != AxisMode::Slots || self.len == 0 {
253            return None;
254        }
255        Some((self.logical(0)?, self.logical(self.len - 1)? + 1))
256    }
257
258    /// The point in slot `j` (`Slots` only).
259    pub(crate) fn point_at(&self, j: i64) -> Option<usize> {
260        if self.mode != AxisMode::Slots {
261            return None;
262        }
263        match &self.mapping {
264            SeriesMapping::Aligned { first } => {
265                let p = usize::try_from(j.checked_sub(*first)?).ok()?;
266                (p < self.len).then_some(p)
267            }
268            SeriesMapping::Mapped { first, offsets } => {
269                let off = u32::try_from(j.checked_sub(*first)?).ok()?;
270                offsets.get(..self.len)?.binary_search(&off).ok()
271            }
272        }
273    }
274
275    /// Fractional logical index of point `i`.
276    pub(crate) fn x_index(&self, index: &TimeIndex, i: usize) -> Option<f64> {
277        match self.mode {
278            AxisMode::Slots => self.logical(i).map(|j| j as f64),
279            AxisMode::Overlay => index_of_time(index, *self.times().get(i)?),
280        }
281    }
282
283    /// Points in slots `from..to` (`Slots`).
284    fn slot_points(&self, from: i64, to: i64) -> (usize, usize) {
285        let n = self.len;
286        let (a, b) = match &self.mapping {
287            SeriesMapping::Aligned { first } => {
288                let rel = |j: i64| {
289                    usize::try_from(j.saturating_sub(*first).max(0))
290                        .unwrap_or(n)
291                        .min(n)
292                };
293                (rel(from), rel(to))
294            }
295            SeriesMapping::Mapped { first, offsets } => {
296                let offsets = offsets.get(..n).unwrap_or(offsets);
297                let (lo, hi) = (from.saturating_sub(*first), to.saturating_sub(*first));
298                (
299                    offsets.partition_point(|&o| i64::from(o) < lo),
300                    offsets.partition_point(|&o| i64::from(o) < hi),
301                )
302            }
303        };
304        (a, b.max(a))
305    }
306
307    /// Points in time range `t0..=t1` (`Overlay`).
308    fn time_points(&self, t0: Timestamp, t1: Timestamp) -> (usize, usize) {
309        let times = self.times();
310        let a = times.partition_point(|&t| t < t0);
311        (a, times.partition_point(|&t| t <= t1).max(a))
312    }
313
314    /// Exact points positioned in logical range `from..=to`.
315    fn points_between(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
316        if self.len == 0 || from.partial_cmp(&to).is_none_or(core::cmp::Ordering::is_gt) {
317            return (0, 0);
318        }
319        match self.mode {
320            AxisMode::Slots => self.slot_points(from.ceil() as i64, to.floor() as i64 + 1),
321            AxisMode::Overlay => match (time_of_index(index, from), time_of_index(index, to)) {
322                (Some(t0), Some(t1)) => self.time_points(t0, t1),
323                _ => (0, 0),
324            },
325        }
326    }
327
328    /// Points positioned in logical range `from..=to`, plus one on each side.
329    pub(crate) fn points_in(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
330        if self.len == 0 {
331            return (0, 0);
332        }
333        let (a, b) = self.points_between(index, from, to);
334        (a.saturating_sub(1), (b + 1).min(self.len))
335    }
336
337    /// Extremes of the points in logical range `from..to`.
338    pub(crate) fn extremes(&self, index: &TimeIndex, from: i64, to: i64) -> Option<(f64, f64)> {
339        let (a, b) = self.points_between(index, from as f64, (to - 1) as f64);
340        if a >= b {
341            return None;
342        }
343        self.plugin.extremes(a, b)
344    }
345
346    /// The crosshair value at slot `j`.
347    pub(crate) fn value_at(&self, j: i64) -> Option<f64> {
348        let v = self.plugin.crosshair_value(self.point_at(j)?)?;
349        v.is_finite().then_some(v)
350    }
351
352    /// Checks the plugin's data after `change` and says how to apply it. A
353    /// change that does not match the data (wrong count, the last time moved)
354    /// is applied as a `Replace`.
355    pub(crate) fn classify(&self, change: crate::data::DataChange) -> Result<CustomChange> {
356        use crate::data::DataChange as D;
357        let times = self.plugin.times();
358        let (n, old) = (times.len(), self.len);
359        let change = match (change, self.bounds) {
360            (D::UpdateLast, Some((_, last))) if n == old && times.last() == Some(&last) => {
361                CustomChange::UpdateLast
362            }
363            (D::Append { count: 0 } | D::Prepend { count: 0 }, _) if n == old => CustomChange::None,
364            (D::Append { count }, Some((_, last))) if n == old + count => {
365                if times.get(old - 1) == Some(&last) {
366                    check_increasing(&times[old - 1..], old - 1)?;
367                    CustomChange::Append
368                } else {
369                    CustomChange::Replace
370                }
371            }
372            (D::Prepend { count }, Some((first, _))) if n == old + count => {
373                if times.get(count) == Some(&first) {
374                    check_increasing(&times[..=count], 0)?;
375                    CustomChange::Prepend { count }
376                } else {
377                    CustomChange::Replace
378                }
379            }
380            _ => CustomChange::Replace,
381        };
382        if change == CustomChange::Replace {
383            check_increasing(times, 0)?;
384        }
385        Ok(change)
386    }
387
388    /// Accepts all of the plugin's points, with `mapping` (`Slots`).
389    pub(crate) fn accept(&mut self, mapping: SeriesMapping) {
390        self.mapping = mapping;
391        self.take_all();
392    }
393
394    /// Accepts all of the plugin's points with the current mapping.
395    fn take_all(&mut self) {
396        let times = self.plugin.times();
397        self.len = times.len();
398        self.bounds = times.first().copied().zip(times.last().copied());
399    }
400
401    /// Maps all points onto `index` (`Slots`) and accepts them.
402    ///
403    /// # Errors
404    ///
405    /// [`Error::InvalidArgument`] if a time is not a slot of `index`;
406    /// [`Error::OutOfMemory`].
407    pub(crate) fn map_onto(&mut self, index: &TimeIndex) -> Result<()> {
408        let mapping = if self.mode == AxisMode::Slots {
409            index
410                .map_series(self.plugin.times())?
411                .ok_or(Error::InvalidArgument(
412                    "custom series times are not on the axis",
413                ))?
414        } else {
415            SeriesMapping::Aligned { first: 0 }
416        };
417        self.accept(mapping);
418        Ok(())
419    }
420
421    /// Maps the points after the accepted ones onto `index` (whose slots
422    /// they already are) and accepts them.
423    pub(crate) fn extend_onto(&mut self, index: &TimeIndex) -> Result<()> {
424        if self.mode == AxisMode::Slots {
425            let times = self.plugin.times();
426            let new = times.get(self.len..).unwrap_or(&[]);
427            for (p, &t) in (self.len..).zip(new) {
428                let j = index.index_of(t).ok_or(Error::InvalidArgument(
429                    "custom series times are not on the axis",
430                ))?;
431                match &mut self.mapping {
432                    SeriesMapping::Aligned { first } if p == 0 => *first = j,
433                    SeriesMapping::Aligned { first }
434                        if Some(j) == first.checked_add(i64::try_from(p).unwrap_or(i64::MAX)) => {}
435                    SeriesMapping::Aligned { first } => {
436                        let first = *first;
437                        let mut offsets = Vec::new();
438                        offsets.try_reserve(p + 1).map_err(|_| Error::OutOfMemory)?;
439                        offsets.extend((0..p).filter_map(|o| u32::try_from(o).ok()));
440                        offsets.push(offset(first, j)?);
441                        self.mapping = SeriesMapping::Mapped { first, offsets };
442                    }
443                    SeriesMapping::Mapped { first, offsets } => {
444                        let o = offset(*first, j)?;
445                        offsets.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
446                        offsets.push(o);
447                    }
448                }
449            }
450        }
451        self.take_all();
452        Ok(())
453    }
454
455    /// Drops all points (after invalid data): nothing is drawn until the
456    /// next valid change.
457    pub(crate) fn clear(&mut self) {
458        self.len = 0;
459        self.bounds = None;
460        self.mapping = SeriesMapping::Aligned { first: 0 };
461        self.log.replace();
462    }
463}
464
465fn offset(first: i64, j: i64) -> Result<u32> {
466    j.checked_sub(first)
467        .and_then(|o| u32::try_from(o).ok())
468        .ok_or(Error::InvalidArgument(
469            "mapped series spans more than u32::MAX slots",
470        ))
471}
472
473/// `Err(TimeNotIncreasing)` with the index in the plugin's data (`times`
474/// starts at point `base`).
475fn check_increasing(times: &[Timestamp], base: usize) -> Result<()> {
476    match times.windows(2).position(|w| w[1] <= w[0]) {
477        Some(k) => Err(Error::TimeNotIncreasing {
478            index: base + k + 1,
479        }),
480        None => Ok(()),
481    }
482}