Skip to main content

ferrochart_core/
chart.rs

1//! `Chart`: the public object that owns data, scales and layout and builds frames.
2//!
3//! Scope so far: any number of panes holding series of the built-in
4//! kinds. All series share one time axis, the union of their times;
5//! volume series read the volume column of an OHLC series.
6//!
7//! `build_frame` is a hot path: once the frame pools and scratch buffers have
8//! warmed up, panning, zooming and real-time updates do not allocate.
9//!
10
11use crate::data::lod::{bucket_of, bucket_start};
12use core::any::Any;
13
14use crate::data::{
15    BandId, BarUpdate, ChangeLog, Column, DataChange, DataDelta, DrawingId, IdxSpan, IndicatorId,
16    LayerPluginId, LogicalIndex, OhlcLevelView, PaneId, PriceLineId, SeriesId, TimeIndex,
17    Timestamp, ValidationMode,
18};
19use crate::drawing::{DrawingCtx, DrawingManager, FrameBuilder};
20use crate::error::{Error, Result};
21use crate::format::NumberFormat;
22use crate::format::auto_decimals;
23use crate::frame::{
24    CustomDraw, DrawCmd, FontId, FontStyleRef, Frame, Invalidation, LabelBg, LayerId, LineDash,
25    LineInst, Reveal, SeriesDraw, SeriesKind, SeriesStyle, StrokeStyle, TextAlign, TextRun,
26    XTransform,
27};
28use crate::geom::{Css, PointCss, PointPx, Px, RectPx, Rgba, SizeCss, SizePx, Span};
29use crate::interaction::{CrosshairMode, Drag, Interaction};
30use crate::pane::{PRICE_MARGINS, Pane, PaneLayout, PaneOptions, SEPARATOR_PX, stack};
31use crate::plugin::{
32    AxisMode, CustomChange, CustomSeries, CustomStore, Indicator, IndicatorInput, IndicatorOutputs,
33    LayerCtx, LayerPlugin, LayerPosition, OutputKind, Placement, SeriesCtx, SeriesTransform,
34};
35use crate::price_scale::{Normalize, PriceScale, ScaleSide};
36use crate::series::{Op, Store, is_ohlc_kind, is_value_kind};
37use crate::sync::{SyncMessage, SyncState};
38use crate::text::{StackStr, TextMeasurer, text_width};
39use crate::theme::Theme;
40use crate::time_scale::{
41    TimeScale, TimeTick, TimeZoneProvider, Utc, collect_ticks, format_crosshair_time, format_tick,
42};
43use crate::transform::store::{TransformStore, input_columns};
44
45/// Options of a new chart.
46///
47/// # Examples
48///
49/// ```
50/// use ferrochart_core::{Chart, ChartOptions};
51/// use ferrochart_core::theme::Theme;
52///
53/// let chart = Chart::new(ChartOptions { theme: Theme::dark(), ..ChartOptions::default() });
54/// # let _ = chart;
55/// ```
56pub struct ChartOptions {
57    /// Colors and sizes.
58    pub theme: Theme,
59    /// Time zone for time labels.
60    pub time_zone: Box<dyn TimeZoneProvider>,
61    /// Handling of bars that violate the OHLC constraints.
62    pub ohlc_validation: ValidationMode,
63    /// Initial bar spacing.
64    pub bar_spacing: Css,
65    /// Lower bound of the bar spacing (further limited by the data size).
66    pub min_bar_spacing: Css,
67    /// Upper bound of the bar spacing.
68    pub max_bar_spacing: Css,
69    /// Initial empty space right of the last bar, in bars.
70    pub right_offset: f64,
71}
72
73impl Default for ChartOptions {
74    fn default() -> Self {
75        Self {
76            theme: Theme::light(),
77            time_zone: Box::new(Utc),
78            ohlc_validation: ValidationMode::Reject,
79            bar_spacing: Css(6.0),
80            min_bar_spacing: Css(0.5),
81            max_bar_spacing: Css(50.0),
82            right_offset: 3.0,
83        }
84    }
85}
86
87pub use crate::series::SeriesData;
88
89/// Options of a series. Colors left at `None` come from the theme.
90///
91/// # Examples
92///
93/// ```
94/// use ferrochart_core::chart::SeriesOptions;
95/// use ferrochart_core::data::SeriesId;
96/// use ferrochart_core::geom::{Css, Rgba};
97///
98/// let opts = SeriesOptions::volume_of(SeriesId(0));
99/// assert_eq!(opts.source, Some(SeriesId(0)));
100///
101/// let line = SeriesOptions {
102///     color: Some(Rgba::hex(0x00FF_6D00)),
103///     line_width: Css(1.0),
104///     ..SeriesOptions::default()
105/// };
106/// # let _ = line;
107/// ```
108#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct SeriesOptions {
110    /// Decimal places of price labels; `None` (the default) is automatic:
111    /// at least 2 decimals and 4 significant digits of the visible values,
112    /// with a subscript count of zeros for small prices (`0.0₄1234`).
113    pub price_precision: Option<u8>,
114    /// For `SeriesKind::Volume`: the OHLC series whose volume is drawn.
115    pub source: Option<SeriesId>,
116    /// Main color: the line of `Line`/`Area`, the bars of `Histogram`, up
117    /// candles and bars, the line of `Baseline` above its base.
118    pub color: Option<Rgba>,
119    /// Down candles and bars; the line of `Baseline` below its base.
120    pub down_color: Option<Rgba>,
121    /// Fill at the top of an `Area`; fill above the base of a `Baseline`.
122    pub top_fill: Option<Rgba>,
123    /// Fill at the bottom of an `Area`; fill below the base of a `Baseline`.
124    pub bottom_fill: Option<Rgba>,
125    /// Line width of `Line`, `Area` and `Baseline`.
126    pub line_width: Css,
127    /// Dash pattern of the line.
128    pub line_style: LineDash,
129    /// Step line: horizontal to the next point's time, then vertical.
130    pub step: bool,
131    /// Base value of `Baseline` (fill boundary) and `Histogram` (bar base).
132    pub base_value: f64,
133    /// Label with the last value on the price axis. Not drawn for
134    /// volume series.
135    pub last_value_visible: bool,
136    /// Dotted horizontal line at the last value. Not drawn for volume
137    /// series.
138    pub price_line_visible: bool,
139    /// Display shift in bars: the point at logical index `j` is drawn at
140    /// `j + shift` (Ichimoku's leading spans and lagging line).
141    /// Autoscale and the crosshair follow the drawn positions.
142    pub shift: i32,
143}
144
145impl Default for SeriesOptions {
146    fn default() -> Self {
147        Self {
148            price_precision: None,
149            source: None,
150            color: None,
151            down_color: None,
152            top_fill: None,
153            bottom_fill: None,
154            line_width: Css(2.0),
155            line_style: LineDash::Solid,
156            step: false,
157            base_value: 0.0,
158            last_value_visible: true,
159            price_line_visible: true,
160            shift: 0,
161        }
162    }
163}
164
165/// Colors of a band between two series.
166///
167/// # Examples
168///
169/// ```
170/// use ferrochart_core::chart::{BandOptions, SeriesData, SeriesOptions};
171/// use ferrochart_core::data::ValueColumns;
172/// use ferrochart_core::frame::SeriesKind;
173/// use ferrochart_core::geom::Rgba;
174/// use ferrochart_core::{Chart, ChartOptions};
175///
176/// let mut chart = Chart::new(ChartOptions::default());
177/// let pane = chart.main_pane();
178/// let a = chart.add_series(pane, SeriesKind::Line, SeriesOptions::default())?;
179/// let b = chart.add_series(pane, SeriesKind::Line, SeriesOptions::default())?;
180/// let line = |v: Vec<f64>| SeriesData::Value(ValueColumns { time: vec![0, 60_000, 120_000], value: v, color: None });
181/// chart.set_data(a, line(vec![2.0, 3.0, 1.0]))?;
182/// chart.set_data(b, line(vec![1.0, 1.0, 2.0]))?;
183/// // Green where a is above b, red where it is below.
184/// let band = chart.add_band(a, b, BandOptions {
185///     fill: Some(Rgba::hex(0x0026_A69A).with_alpha(0x40)),
186///     fill_crossed: Some(Rgba::hex(0x00EF_5350).with_alpha(0x40)),
187/// })?;
188/// assert!(chart.band_options(band).is_some());
189/// chart.remove_band(band)?;
190/// # Ok::<(), ferrochart_core::Error>(())
191/// ```
192#[derive(Clone, Copy, Debug, Default, PartialEq)]
193pub struct BandOptions {
194    /// Fill where the upper series is at or above the lower one; `None`: the
195    /// upper series' color at 15% opacity.
196    pub fill: Option<Rgba>,
197    /// Fill where the upper series is below the lower one; `None`: as `fill`.
198    pub fill_crossed: Option<Rgba>,
199}
200
201/// Whether a series is drawn on the pane's volume scale: volume series and
202/// lines placed with `Placement::Volume`.
203fn volume_like(e: &SeriesEntry) -> bool {
204    e.kind == SeriesKind::Volume || e.volume_scale
205}
206
207/// A marker drawn in the last frame, for click hit tests.
208#[derive(Clone, Copy, Debug)]
209struct MarkerHit {
210    series: SeriesId,
211    index: usize,
212    pane: PaneId,
213    pos: PointPx,
214    radius: f32,
215}
216
217/// Hit tolerance of lines (CSS px).
218const HIT_TOLERANCE: f32 = 4.0;
219
220/// Distance from `p` to the segment `a`–`b`.
221fn segment_distance(p: PointPx, a: PointPx, b: PointPx) -> f32 {
222    let (dx, dy) = (b.x - a.x, b.y - a.y);
223    let len2 = dx * dx + dy * dy;
224    let t = if len2 > 0.0 {
225        (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0)
226    } else {
227        0.0
228    };
229    (p.x - (a.x + dx * t)).hypot(p.y - (a.y + dy * t))
230}
231
232/// A band.
233#[derive(Clone, Copy, Debug)]
234struct BandEntry {
235    id: BandId,
236    upper: SeriesId,
237    lower: SeriesId,
238    opts: BandOptions,
239}
240
241/// A horizontal line at a price of a series, with an optional label on the
242/// price axis.
243///
244/// # Examples
245///
246/// ```
247/// use ferrochart_core::chart::{PriceLineOptions, SeriesOptions};
248/// use ferrochart_core::frame::SeriesKind;
249/// use ferrochart_core::{Chart, ChartOptions};
250///
251/// let mut chart = Chart::new(ChartOptions::default());
252/// let id = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
253/// let stop = chart.create_price_line(id, PriceLineOptions {
254///     price: 95.0,
255///     title: "stop".into(),
256///     ..PriceLineOptions::default()
257/// })?;
258/// chart.remove_price_line(stop)?;
259/// # Ok::<(), ferrochart_core::Error>(())
260/// ```
261#[derive(Clone, Debug, PartialEq)]
262pub struct PriceLineOptions {
263    /// Price, in the series' units.
264    pub price: f64,
265    /// Line and label color; `None` uses the series' main color.
266    pub color: Option<Rgba>,
267    /// Line width.
268    pub line_width: Css,
269    /// Dash pattern.
270    pub line_style: LineDash,
271    /// Whether the price is labelled on the price axis.
272    pub axis_label_visible: bool,
273    /// Text drawn above the line at the right edge of the plot; empty for none.
274    pub title: String,
275}
276
277impl Default for PriceLineOptions {
278    fn default() -> Self {
279        Self {
280            price: 0.0,
281            color: None,
282            line_width: Css(1.0),
283            line_style: LineDash::Dashed,
284            axis_label_visible: true,
285            title: String::new(),
286        }
287    }
288}
289
290/// Where a [`Marker`] sits relative to its bar.
291#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
292pub enum MarkerPosition {
293    /// Above the bar's high (above the value for single-value series).
294    #[default]
295    AboveBar,
296    /// Below the bar's low.
297    BelowBar,
298}
299
300/// Shape of a [`Marker`].
301#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
302pub enum MarkerShape {
303    /// Filled circle.
304    #[default]
305    Circle,
306    /// Filled square.
307    Square,
308    /// Arrow pointing up.
309    ArrowUp,
310    /// Arrow pointing down.
311    ArrowDown,
312}
313
314impl MarkerShape {
315    fn icon(self) -> u16 {
316        use crate::transform_helpers::{ICON_ARROW_DOWN, ICON_ARROW_UP, ICON_CIRCLE, ICON_SQUARE};
317        match self {
318            Self::Circle => ICON_CIRCLE,
319            Self::Square => ICON_SQUARE,
320            Self::ArrowUp => ICON_ARROW_UP,
321            Self::ArrowDown => ICON_ARROW_DOWN,
322        }
323    }
324}
325
326/// An icon with optional text above or below a bar, e.g. a buy or sell
327/// signal. Anchored by time; markers on the same bar
328/// and side stack away from it in the order given.
329///
330/// # Examples
331///
332/// ```
333/// use ferrochart_core::chart::{Marker, MarkerPosition, MarkerShape, SeriesOptions};
334/// use ferrochart_core::frame::SeriesKind;
335/// use ferrochart_core::{Chart, ChartOptions};
336///
337/// let mut chart = Chart::new(ChartOptions::default());
338/// let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
339/// chart.set_markers(id, vec![Marker {
340///     time: 1_700_000_000_000,
341///     position: MarkerPosition::BelowBar,
342///     shape: MarkerShape::ArrowUp,
343///     text: "buy".into(),
344///     ..Marker::default()
345/// }])?;
346/// assert_eq!(chart.markers(id).map(<[Marker]>::len), Some(1));
347/// # Ok::<(), ferrochart_core::Error>(())
348/// ```
349#[derive(Clone, Debug, Default, PartialEq)]
350pub struct Marker {
351    /// Time of the bar. A time that is not on the time axis snaps to the next
352    /// bar (the last one for times after the end).
353    pub time: Timestamp,
354    /// Above or below the bar.
355    pub position: MarkerPosition,
356    /// Icon.
357    pub shape: MarkerShape,
358    /// Icon and text color; `None` uses the series' main color.
359    pub color: Option<Rgba>,
360    /// Text next to the icon, on the side away from the bar; empty for none.
361    pub text: String,
362}
363
364/// Marker icon size and gap to the bar or the next marker, in CSS pixels.
365const MARKER_SIZE: f32 = 10.0;
366const MARKER_GAP: f32 = 4.0;
367
368#[derive(Clone, Debug)]
369struct PriceLineEntry {
370    id: PriceLineId,
371    series: SeriesId,
372    opts: PriceLineOptions,
373}
374
375/// A label on the price axis (last values, price lines).
376#[derive(Clone, Copy, Debug)]
377struct AxisLabel {
378    /// Wanted center y.
379    want: f32,
380    /// Placed center y.
381    at: f32,
382    text: Span,
383    bg: Rgba,
384    fg: Rgba,
385}
386
387impl SeriesOptions {
388    /// Options of a volume series that draws `source`'s volume column.
389    pub fn volume_of(source: SeriesId) -> Self {
390        Self {
391            source: Some(source),
392            ..Self::default()
393        }
394    }
395}
396
397/// Non-fatal problems reported through [`ChartEvent::Warning`].
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399#[non_exhaustive]
400pub enum WarningKind {
401    /// `ValidationMode::Repair` widened high/low of `bars` bars.
402    OhlcRepaired {
403        /// The series.
404        series: SeriesId,
405        /// Number of repaired bars.
406        bars: usize,
407    },
408    /// Times of `series` fell between bars of the time axis, so the axis was
409    /// rebuilt as the union of all series' times and the logical
410    /// indices after the first inserted bar moved.
411    TimeAxisMerged {
412        /// The series whose data was added.
413        series: SeriesId,
414        /// Number of bars inserted between existing ones.
415        slots: usize,
416    },
417    /// The data of `series` could not be moved onto a rebuilt time axis (out
418    /// of memory) and was cleared.
419    DataDropped {
420        /// The series.
421        series: SeriesId,
422    },
423}
424
425/// OHLCV values of one bar.
426#[derive(Clone, Copy, Debug, PartialEq)]
427pub struct BarValues {
428    /// Open.
429    pub open: f64,
430    /// High.
431    pub high: f64,
432    /// Low.
433    pub low: f64,
434    /// Close.
435    pub close: f64,
436    /// Volume, if the series has one.
437    pub volume: Option<f64>,
438}
439
440/// Where the crosshair points.
441#[derive(Clone, Copy, Debug, PartialEq)]
442pub struct CrosshairPoint {
443    /// Logical index of the bar under the crosshair (may be outside the data).
444    pub logical_index: i64,
445    /// Time of that bar, `None` in the empty space beyond the data.
446    pub time: Option<Timestamp>,
447    /// The pane under the pointer.
448    pub pane: PaneId,
449    /// Price at the crosshair's y, on that pane's price scale.
450    pub price: f64,
451    /// Values of the first OHLC series that has a bar there.
452    pub bar: Option<BarValues>,
453}
454
455/// What a click hit: the first in priority order (drawing, marker, series).
456#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457#[non_exhaustive]
458pub enum ClickTarget {
459    /// A drawing (its body or a handle).
460    Drawing(DrawingId),
461    /// Marker `index` of `series`, in the time order [`Chart::markers`]
462    /// returns them.
463    Marker {
464        /// The series the marker belongs to.
465        series: SeriesId,
466        /// Its index in [`Chart::markers`].
467        index: usize,
468    },
469    /// A series: a candle's body or wick, within 4 CSS px of a line, inside
470    /// a histogram bar, or on a dot.
471    Series(SeriesId),
472}
473
474/// Events for the host, pulled with [`Chart::drain_events`].
475///
476/// Pending `CrosshairMove` and `VisibleRangeChanged` events are coalesced: if
477/// the host has not drained the previous one, it is replaced, so the queue
478/// does not grow (and does not allocate) while the user interacts.
479#[derive(Clone, Copy, Debug, PartialEq)]
480#[non_exhaustive]
481pub enum ChartEvent {
482    /// The crosshair moved; `None` when it left the plot or is hidden.
483    CrosshairMove {
484        /// The new position.
485        point: Option<CrosshairPoint>,
486    },
487    /// A press and release in a plot without moving more than the drag
488    /// threshold (3 CSS px); not sent while a drawing is being created.
489    Click {
490        /// Where, in CSS pixels from the chart's top left.
491        pos: PointCss,
492        /// The pane clicked.
493        pane: PaneId,
494        /// Logical index at `pos` (fractional).
495        logical_index: f64,
496        /// Time of the bar nearest to `logical_index`; `None` beyond the data.
497        time: Option<Timestamp>,
498        /// Price at `pos`, on the pane's price scale.
499        price: f64,
500        /// What was clicked; `None` for empty space.
501        target: Option<ClickTarget>,
502    },
503    /// The visible logical range changed.
504    VisibleRangeChanged {
505        /// Left edge.
506        from: LogicalIndex,
507        /// Right edge.
508        to: LogicalIndex,
509    },
510    /// The left edge of the view is within one screen of the first bar: the
511    /// host should `prepend` older data. Sent once per first-bar position.
512    NeedMoreHistory {
513        /// Bars between the first bar and the left edge (negative when the
514        /// view already shows empty space before the data).
515        bars_before_start: i64,
516    },
517    /// A drawing was created (by the user, `DrawingManager::add`, or an
518    /// undo/redo that brought it back).
519    DrawingCreated(DrawingId),
520    /// A drawing was moved or restyled.
521    DrawingModified(DrawingId),
522    /// A drawing was removed.
523    DrawingRemoved(DrawingId),
524    /// The selection changed.
525    DrawingSelected(Option<DrawingId>),
526    /// A non-fatal problem.
527    Warning(WarningKind),
528    /// The chart posted a message to its sync group. Hosts that sync
529    /// charts across workers forward it with [`Chart::apply_sync`]; charts
530    /// in the same [`SyncGroup`](crate::sync::SyncGroup) need nothing.
531    Sync(SyncMessage),
532    /// The chart sent drawing sync operations; hosts that forward
533    /// them to charts in other workers take them with
534    /// [`Chart::take_drawing_sync_ops`]. Reported once until they are taken.
535    DrawingSync,
536}
537
538/// Rectangles of the last built layout, in physical pixels. Per-pane
539/// rectangles are available from [`Chart::pane_layout`].
540#[derive(Clone, Copy, Debug, Default, PartialEq)]
541pub struct Layout {
542    /// The plot area of the main (top) pane.
543    pub plot: RectPx,
544    /// The right price axis, over all panes.
545    pub price_axis: RectPx,
546    /// The time axis at the bottom.
547    pub time_axis: RectPx,
548}
549
550#[derive(Debug)]
551struct SeriesEntry {
552    id: SeriesId,
553    pane: PaneId,
554    kind: SeriesKind,
555    opts: SeriesOptions,
556    store: Store,
557    /// Price-to-display map of the last frame (relative price scales);
558    /// `None` when the series has no usable base value.
559    norm: Option<Normalize>,
560    /// Markers, sorted by time.
561    markers: Vec<Marker>,
562    /// An output of an indicator: follows its source, so it is left
563    /// out of the time-axis union and recomputed after a rebuild.
564    derived: bool,
565    /// Drawn on the pane's volume scale (`Placement::Volume`).
566    volume_scale: bool,
567    /// Decimals of automatic precision from the last visible values.
568    auto_decimals: u8,
569}
570
571/// The new data of the series being rebuilt.
572enum Target<'a> {
573    Data(SeriesData),
574    /// A custom series, taken out of its entry: its plugin has the data.
575    Custom(&'a mut CustomStore),
576}
577
578impl Target<'_> {
579    fn times(&self) -> &[Timestamp] {
580        match self {
581            Self::Data(d) => d.times(),
582            Self::Custom(c) => c.plugin.times(),
583        }
584    }
585}
586
587/// Segments of a Point & Figure O.
588const CIRCLE_SEGMENTS: u16 = 16;
589
590const NOT_CUSTOM: Error = Error::InvalidArgument("not a custom series");
591const NEXT_TO_TRANSFORM: Error =
592    Error::InvalidArgument("a transform series cannot share the chart with other series");
593
594/// A layer plugin attached to the chart.
595struct LayerEntry {
596    id: LayerPluginId,
597    /// `None`: the whole chart.
598    pane: Option<PaneId>,
599    position: LayerPosition,
600    plugin: Box<dyn LayerPlugin>,
601}
602
603/// An indicator attached to the chart.
604struct IndicatorEntry {
605    id: IndicatorId,
606    source: SeriesId,
607    ind: Box<dyn Indicator>,
608    /// The output series, in the order of `Indicator::outputs`.
609    series: Vec<SeriesId>,
610    /// The pane `add_indicator` created, removed with the indicator if empty.
611    own_pane: Option<PaneId>,
612    /// Bands of `OutputSpec::fill_to`.
613    bands: Vec<BandId>,
614}
615
616/// Runs the indicator of `entry` for `change` into `out` (reads only the
617/// chart, so several can run in parallel). Returns the change actually
618/// computed (`Replace` when an incremental one does not fit) and the first
619/// slot written.
620fn compute_indicator(
621    entry: &mut IndicatorEntry,
622    source: crate::series::Source<'_>,
623    index: &crate::data::TimeIndex,
624    change: DataChange,
625    out: &mut IndicatorOutputs,
626) -> (DataChange, usize) {
627    let input = IndicatorInput::new(source, index);
628    let len = input.len();
629    let change = match change {
630        DataChange::Append { count } if count <= len => change,
631        DataChange::UpdateLast if len > 0 => change,
632        _ => DataChange::Replace,
633    };
634    let start = match change {
635        DataChange::Append { count } => len - count,
636        DataChange::UpdateLast => len - 1,
637        _ => 0,
638    };
639    out.reset(entry.ind.outputs().len(), start, len);
640    entry.ind.update(&input, change, out);
641    (change, start)
642}
643
644/// Colors of indicator outputs without a default color.
645const INDICATOR_PALETTE: [u32; 6] = [
646    0x0029_62FF,
647    0x00FF_9800,
648    0x009C_27B0,
649    0x0000_BCD4,
650    0x00E9_1E63,
651    0x0079_5548,
652];
653
654/// A placed time label.
655#[derive(Clone, Copy, Debug)]
656struct PlacedTick {
657    x: f32,
658    width: f32,
659    tick: TimeTick,
660}
661
662/// A financial chart.
663///
664/// # Examples
665///
666/// ```
667/// use ferrochart_core::{Chart, ChartOptions};
668/// use ferrochart_core::chart::{SeriesData, SeriesOptions};
669/// use ferrochart_core::frame::{Invalidation, SeriesKind};
670/// use ferrochart_core::geom::SizeCss;
671/// use ferrochart_core::testing::{random_walk, MonoMeasurer};
672///
673/// let mut chart = Chart::new(ChartOptions::default());
674/// chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
675/// let pane = chart.main_pane();
676/// let candles = chart.add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())?;
677/// chart.add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(candles))?;
678/// chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 500, 0, 60_000)?))?;
679///
680/// assert_ne!(chart.needs_redraw(), Invalidation::None);
681/// chart.build_frame(0.0, &MonoMeasurer);
682/// assert!(!chart.frame().layers[1].cmds.is_empty());
683/// assert_eq!(chart.needs_redraw(), Invalidation::None);
684/// # Ok::<(), ferrochart_core::Error>(())
685/// ```
686pub struct Chart {
687    theme: Theme,
688    tz: Box<dyn TimeZoneProvider>,
689    validation: ValidationMode,
690    default_right_offset: f64,
691    pub(crate) default_bar_spacing: Css,
692    size: SizeCss,
693    pub(crate) dpr: f32,
694    pub(crate) panes: Vec<Pane>,
695    next_pane: u32,
696    pub(crate) time_index: TimeIndex,
697    series: Vec<SeriesEntry>,
698    next_id: u32,
699    pub(crate) time_scale: TimeScale,
700    pub(crate) invalidation: Invalidation,
701    revisions: [u64; 3],
702    frame: Frame,
703    pub(crate) layout: Layout,
704    pub(crate) input: Interaction,
705    last_range: (f64, f64),
706    last_crosshair: Option<CrosshairPoint>,
707    history_requested: Option<i64>,
708    axis_width: f32,
709    events: Vec<ChartEvent>,
710    price_lines: Vec<PriceLineEntry>,
711    indicators: Vec<IndicatorEntry>,
712    next_indicator: u32,
713    /// Colors handed out to indicator outputs so far.
714    palette_next: usize,
715    /// Scratch of indicator updates (kept small between full updates, so the
716    /// real-time path does not allocate).
717    ind_out: IndicatorOutputs,
718    /// Set by `rebuild`: every indicator must be recomputed.
719    axis_rebuilt: bool,
720    next_price_line: u32,
721    /// Axis labels of the pane being built (scratch).
722    axis_labels: Vec<AxisLabel>,
723    time_ticks: Vec<TimeTick>,
724    placed: Vec<PlacedTick>,
725    pub(crate) drawings: DrawingManager,
726    /// Text metrics of the last frame, for hit tests between frames.
727    pub(crate) text_cache: CachedText,
728    /// Handles of the selected drawing (reused: no allocation per frame or
729    /// hit test).
730    pub(crate) handle_buf: core::cell::RefCell<Vec<PointPx>>,
731    /// Multi-chart sync.
732    pub(crate) sync: SyncState,
733    /// Layer plugins, in the order they were added.
734    layer_plugins: Vec<LayerEntry>,
735    next_layer: u32,
736    /// Custom series kinds the renderer draws natively.
737    native_kinds: Vec<&'static str>,
738    /// Bands between two series, drawn in this order.
739    bands: Vec<BandEntry>,
740    next_band: u32,
741    /// Markers of the last frame (click hit tests).
742    marker_hits: Vec<MarkerHit>,
743    /// Gradual display of the data; `None`: everything.
744    reveal: Option<Reveal>,
745}
746
747/// The ASCII and subscript advances and line height of the last frame's
748/// font: hit tests of drawings run between frames, without the host's
749/// measurer.
750#[derive(Clone, Copy, Debug)]
751pub(crate) struct CachedText {
752    advances: [f32; 128],
753    subscripts: [f32; 10],
754    /// Line height per px of font size.
755    line: f32,
756}
757
758impl Default for CachedText {
759    fn default() -> Self {
760        Self {
761            advances: [0.6; 128],
762            subscripts: [0.6; 10],
763            line: 1.2,
764        }
765    }
766}
767
768impl TextMeasurer for CachedText {
769    fn ascii_advances(&self, _: FontStyleRef) -> &[f32; 128] {
770        &self.advances
771    }
772
773    fn subscript_advances(&self, _: FontStyleRef) -> Option<&[f32; 10]> {
774        Some(&self.subscripts)
775    }
776
777    fn measure(&self, text: &str, style: FontStyleRef) -> SizePx {
778        SizePx {
779            w: text.chars().count() as f32 * 0.6 * style.size,
780            h: self.line * style.size,
781        }
782    }
783
784    fn line_height(&self, style: FontStyleRef) -> f32 {
785        self.line * style.size
786    }
787}
788
789/// Diameter of drawing handles (CSS px).
790pub(crate) const HANDLE_CSS: f32 = 9.0;
791
792/// Pool lengths before a drawing is built: what it adds is its bounds.
793#[derive(Clone, Copy)]
794struct PoolMark {
795    lines: usize,
796    rects: usize,
797    points: usize,
798    runs: usize,
799}
800
801impl PoolMark {
802    fn of(frame: &Frame) -> Self {
803        let p = &frame.pools;
804        Self {
805            lines: p.lines.len(),
806            rects: p.rects.len(),
807            points: p.points.len(),
808            runs: p.text_runs.len(),
809        }
810    }
811
812    /// Bounds of everything added since the mark (empty if nothing).
813    fn bounds(self, frame: &Frame, ctx: &DrawingCtx<'_>) -> RectPx {
814        let p = &frame.pools;
815        let (mut x0, mut y0, mut x1, mut y1) = (
816            f32::INFINITY,
817            f32::INFINITY,
818            f32::NEG_INFINITY,
819            f32::NEG_INFINITY,
820        );
821        let mut add = |x: f32, y: f32| {
822            x0 = x0.min(x);
823            y0 = y0.min(y);
824            x1 = x1.max(x);
825            y1 = y1.max(y);
826        };
827        for l in p.lines.get(self.lines..).unwrap_or(&[]) {
828            add(l.from.x, l.from.y);
829            add(l.to.x, l.to.y);
830        }
831        for r in p.rects.get(self.rects..).unwrap_or(&[]) {
832            add(r.rect.x, r.rect.y);
833            add(r.rect.right(), r.rect.bottom());
834        }
835        for q in p.points.get(self.points..).unwrap_or(&[]) {
836            add(q.x, q.y);
837        }
838        for run in p.text_runs.get(self.runs..).unwrap_or(&[]) {
839            let w = ctx.text_width(p.text_of(run.text), run.style);
840            let h = ctx.line_height(run.style) * 0.5 + run.bg.map_or(0.0, |b| b.padding.0);
841            let x = match run.align {
842                TextAlign::Left => run.pos.x,
843                TextAlign::Center => run.pos.x - w * 0.5,
844                TextAlign::Right => run.pos.x - w,
845            };
846            add(x - h, run.pos.y - h);
847            add(x + w + h, run.pos.y + h);
848        }
849        if x0 > x1 {
850            return RectPx::default();
851        }
852        RectPx {
853            x: x0,
854            y: y0,
855            w: x1 - x0,
856            h: y1 - y0,
857        }
858    }
859}
860
861/// Time tick candidates are sampled at least this far apart (physical px).
862const TICK_SAMPLE_PX: f64 = 8.0;
863
864impl Chart {
865    /// Creates an empty chart with one pane.
866    pub fn new(options: ChartOptions) -> Self {
867        let dpr = 1.0;
868        let mut frame = Frame::default();
869        frame.reserve();
870        Self {
871            theme: options.theme,
872            tz: options.time_zone,
873            validation: options.ohlc_validation,
874            default_right_offset: options.right_offset,
875            default_bar_spacing: options.bar_spacing,
876            size: SizeCss::default(),
877            dpr,
878            panes: vec![Pane::new(PaneId(0), 1.0)],
879            next_pane: 1,
880            time_index: TimeIndex::new(),
881            series: Vec::new(),
882            next_id: 0,
883            time_scale: TimeScale::new(
884                f64::from(options.bar_spacing.to_px(dpr).0),
885                options.right_offset,
886                f64::from(options.min_bar_spacing.to_px(dpr).0),
887                f64::from(options.max_bar_spacing.to_px(dpr).0),
888            ),
889            invalidation: Invalidation::Full,
890            revisions: [0; 3],
891            frame,
892            layout: Layout::default(),
893            input: Interaction::default(),
894            last_range: (f64::NAN, f64::NAN),
895            last_crosshair: None,
896            history_requested: None,
897            axis_width: 0.0,
898            events: Vec::with_capacity(64),
899            price_lines: Vec::new(),
900            indicators: Vec::new(),
901            next_indicator: 0,
902            palette_next: 0,
903            ind_out: IndicatorOutputs::default(),
904            axis_rebuilt: false,
905            next_price_line: 0,
906            axis_labels: Vec::with_capacity(64),
907            time_ticks: Vec::with_capacity(2048),
908            placed: Vec::with_capacity(256),
909            drawings: DrawingManager::new(PaneId(0)),
910            text_cache: CachedText::default(),
911            handle_buf: core::cell::RefCell::new(Vec::new()),
912            sync: SyncState::default(),
913            layer_plugins: Vec::new(),
914            next_layer: 0,
915            bands: Vec::new(),
916            next_band: 0,
917            marker_hits: Vec::new(),
918            reveal: None,
919            native_kinds: Vec::new(),
920        }
921    }
922
923    /// Sets the size in CSS pixels and the device pixel ratio. All geometry is
924    /// computed in physical pixels (`size × dpr`). Non-finite or non-positive
925    /// values are ignored.
926    pub fn resize(&mut self, size: SizeCss, dpr: f32) {
927        let finite = size.w.is_finite() && size.h.is_finite() && dpr.is_finite();
928        if !finite || dpr <= 0.0 || size.w < 0.0 || size.h < 0.0 {
929            return;
930        }
931        if (dpr - self.dpr).abs() > f32::EPSILON {
932            self.time_scale.rescale(f64::from(dpr / self.dpr));
933            self.dpr = dpr;
934        }
935        self.size = size;
936        self.invalidation = Invalidation::Full;
937    }
938
939    /// The top pane (the pane every chart starts with, unless it was removed).
940    pub fn main_pane(&self) -> PaneId {
941        self.panes.first().map_or(PaneId(0), |p| p.id)
942    }
943
944    /// Adds a pane below the existing ones.
945    ///
946    /// # Examples
947    ///
948    /// ```
949    /// use ferrochart_core::{Chart, ChartOptions};
950    /// use ferrochart_core::chart::{SeriesData, SeriesOptions};
951    /// use ferrochart_core::frame::SeriesKind;
952    /// use ferrochart_core::geom::SizeCss;
953    /// use ferrochart_core::pane::PaneOptions;
954    /// use ferrochart_core::testing::{random_walk, MonoMeasurer};
955    ///
956    /// let mut chart = Chart::new(ChartOptions::default());
957    /// chart.resize(SizeCss { w: 800.0, h: 600.0 }, 1.0);
958    /// let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
959    /// // Volume in its own pane, a quarter of the height of the main pane.
960    /// let below = chart.add_pane(PaneOptions { stretch_factor: 0.25 });
961    /// chart.add_series(below, SeriesKind::Volume, SeriesOptions::volume_of(candles))?;
962    /// chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 500, 0, 60_000)?))?;
963    /// chart.build_frame(0.0, &MonoMeasurer);
964    ///
965    /// let main = chart.pane_layout(chart.main_pane()).unwrap();
966    /// let vol = chart.pane_layout(below).unwrap();
967    /// assert!(vol.plot.y > main.plot.bottom());
968    /// assert!((main.plot.h / vol.plot.h - 4.0).abs() < 0.1);
969    /// # Ok::<(), ferrochart_core::Error>(())
970    /// ```
971    pub fn add_pane(&mut self, opts: PaneOptions) -> PaneId {
972        let id = PaneId(self.next_pane);
973        self.next_pane = self.next_pane.wrapping_add(1);
974        self.panes.push(Pane::new(id, opts.stretch_factor));
975        self.drawings.pane_added(id);
976        self.invalidation = Invalidation::Full;
977        id
978    }
979
980    /// Removes a pane and the series in it (removing the candlestick series
981    /// also removes its volume series, wherever it is).
982    ///
983    /// # Errors
984    ///
985    /// [`Error::UnknownId`] if the pane does not exist,
986    /// [`Error::InvalidArgument`] for the last remaining pane.
987    pub fn remove_pane(&mut self, id: PaneId) -> Result<()> {
988        let i = self.pane_index(id).ok_or(Error::UnknownId)?;
989        if self.panes.len() == 1 {
990            return Err(Error::InvalidArgument("a chart keeps at least one pane"));
991        }
992        while let Some(sid) = self.series.iter().find(|e| e.pane == id).map(|e| e.id) {
993            self.remove_series(sid)?;
994        }
995        self.panes.remove(i);
996        self.drawings.pane_removed(id);
997        self.layer_plugins.retain(|l| l.pane != Some(id));
998        if self.input.drag.involves(id) {
999            self.input.drag = Drag::Idle;
1000        }
1001        self.invalidation = Invalidation::Full;
1002        Ok(())
1003    }
1004
1005    /// The panes from top to bottom.
1006    pub fn panes(&self) -> impl Iterator<Item = PaneId> + '_ {
1007        self.panes.iter().map(|p| p.id)
1008    }
1009
1010    /// Rectangles of a pane in the last built layout; `None` for unknown ids.
1011    pub fn pane_layout(&self, id: PaneId) -> Option<PaneLayout> {
1012        let pane = self.panes.get(self.pane_index(id)?)?;
1013        Some(PaneLayout {
1014            plot: pane.plot,
1015            price_axis: RectPx {
1016                x: self.layout.price_axis.x,
1017                y: pane.plot.y,
1018                w: self.layout.price_axis.w,
1019                h: pane.plot.h,
1020            },
1021        })
1022    }
1023
1024    /// The stretch factor of a pane; `None` for unknown ids.
1025    pub fn pane_stretch(&self, id: PaneId) -> Option<f32> {
1026        Some(self.panes.get(self.pane_index(id)?)?.stretch)
1027    }
1028
1029    /// Sets the stretch factor of a pane (dragging a separator changes the
1030    /// factors of the two panes next to it).
1031    ///
1032    /// # Errors
1033    ///
1034    /// [`Error::UnknownId`] if the pane does not exist,
1035    /// [`Error::InvalidArgument`] if `stretch` is not finite and positive.
1036    pub fn set_pane_stretch(&mut self, id: PaneId, stretch: f32) -> Result<()> {
1037        let i = self.pane_index(id).ok_or(Error::UnknownId)?;
1038        if !(stretch.is_finite() && stretch > 0.0) {
1039            return Err(Error::InvalidArgument(
1040                "a stretch factor must be finite and positive",
1041            ));
1042        }
1043        if let Some(p) = self.panes.get_mut(i) {
1044            p.stretch = stretch;
1045        }
1046        self.invalidation = Invalidation::Full;
1047        Ok(())
1048    }
1049
1050    /// Prices at the bottom and the top of pane `id`'s plot area in the last
1051    /// built layout (display values in the relative modes); `None` for an
1052    /// unknown pane or before the first frame. Hosts copy it to a
1053    /// `ferrochart-plot` side panel that shares the price axis.
1054    ///
1055    /// ```
1056    /// use ferrochart_core::chart::{SeriesData, SeriesOptions};
1057    /// use ferrochart_core::frame::SeriesKind;
1058    /// use ferrochart_core::geom::SizeCss;
1059    /// use ferrochart_core::testing::{random_walk, MonoMeasurer};
1060    /// use ferrochart_core::{Chart, ChartOptions};
1061    ///
1062    /// let mut chart = Chart::new(ChartOptions::default());
1063    /// let pane = chart.main_pane();
1064    /// assert_eq!(chart.visible_price_range(pane), None);
1065    /// let id = chart.add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())?;
1066    /// chart.set_data(id, SeriesData::Ohlc(random_walk(1, 100, 0, 60_000)?))?;
1067    /// chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
1068    /// chart.build_frame(0.0, &MonoMeasurer);
1069    /// let (lo, hi) = chart.visible_price_range(pane).unwrap();
1070    /// assert!(lo < hi);
1071    /// # Ok::<(), ferrochart_core::Error>(())
1072    /// ```
1073    pub fn visible_price_range(&self, id: PaneId) -> Option<(f64, f64)> {
1074        let pane = self.panes.get(self.pane_index(id)?)?;
1075        let h = f64::from(pane.plot.h);
1076        if !(pane.has_content && h > 0.0) {
1077            return None;
1078        }
1079        let a = pane.price_scale.y_to_price(h, 0.0, h);
1080        let b = pane.price_scale.y_to_price(0.0, 0.0, h);
1081        (a.is_finite() && b.is_finite()).then_some((a.min(b), a.max(b)))
1082    }
1083
1084    pub(crate) fn pane_index(&self, id: PaneId) -> Option<usize> {
1085        self.panes.iter().position(|p| p.id == id)
1086    }
1087
1088    pub(crate) fn pane_mut(&mut self, id: PaneId) -> Option<&mut Pane> {
1089        self.panes.iter_mut().find(|p| p.id == id)
1090    }
1091
1092    fn entry(&self, id: SeriesId) -> Result<&SeriesEntry> {
1093        self.series
1094            .iter()
1095            .find(|e| e.id == id)
1096            .ok_or(Error::UnknownId)
1097    }
1098
1099    fn entry_index(&self, id: SeriesId) -> Result<usize> {
1100        self.series
1101            .iter()
1102            .position(|e| e.id == id)
1103            .ok_or(Error::UnknownId)
1104    }
1105
1106    /// Adds a candlestick series on the main pane with the default options:
1107    /// `add_series(main_pane(), SeriesKind::Candlestick, SeriesOptions::default())`.
1108    ///
1109    /// # Errors
1110    ///
1111    /// As [`Chart::add_series`].
1112    ///
1113    /// # Examples
1114    ///
1115    /// ```
1116    /// use ferrochart_core::testing::random_walk;
1117    /// use ferrochart_core::{Chart, ChartOptions};
1118    ///
1119    /// let mut chart = Chart::new(ChartOptions::default());
1120    /// let candles = chart.add_candlestick()?;
1121    /// chart.add_volume(candles)?;
1122    /// chart.set_data(candles, random_walk(1, 500, 0, 60_000)?)?;
1123    /// # Ok::<(), ferrochart_core::Error>(())
1124    /// ```
1125    pub fn add_candlestick(&mut self) -> Result<SeriesId> {
1126        self.add_series(
1127            self.main_pane(),
1128            SeriesKind::Candlestick,
1129            SeriesOptions::default(),
1130        )
1131    }
1132
1133    /// Adds a volume histogram of `source`'s volume column on the main pane:
1134    /// `add_series(main_pane(), SeriesKind::Volume, SeriesOptions::volume_of(source))`.
1135    ///
1136    /// # Errors
1137    ///
1138    /// As [`Chart::add_series`] ([`Error::UnknownId`] if `source` does not
1139    /// exist).
1140    pub fn add_volume(&mut self, source: SeriesId) -> Result<SeriesId> {
1141        self.add_series(
1142            self.main_pane(),
1143            SeriesKind::Volume,
1144            SeriesOptions::volume_of(source),
1145        )
1146    }
1147
1148    /// Adds a series to a pane.
1149    ///
1150    /// All series share one time axis, the union of their times. A
1151    /// series that skips bars of the axis is drawn across them (line-like
1152    /// series) or leaves gaps (histograms, OHLC series).
1153    ///
1154    /// # Errors
1155    ///
1156    /// - [`Error::UnknownId`] if `pane` does not exist;
1157    /// - [`Error::InvalidArgument`] for a volume series whose `opts.source` is
1158    ///   not an OHLC or transform series of this chart, for `Custom`, `Kagi`
1159    ///   and `PointFigure` (added with their own methods), and for any
1160    ///   series but volume when the chart has a transform series.
1161    ///
1162    /// # Examples
1163    ///
1164    /// ```
1165    /// use ferrochart_core::{Chart, ChartOptions};
1166    /// use ferrochart_core::chart::SeriesOptions;
1167    /// use ferrochart_core::data::ValueColumns;
1168    /// use ferrochart_core::chart::SeriesData;
1169    /// use ferrochart_core::frame::SeriesKind;
1170    ///
1171    /// let mut chart = Chart::new(ChartOptions::default());
1172    /// let line = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
1173    /// chart.set_data(line, SeriesData::Value(ValueColumns {
1174    ///     time: vec![0, 60_000, 120_000],
1175    ///     value: vec![1.0, f64::NAN, 3.0], // NaN: a gap
1176    ///     color: None,
1177    /// }))?;
1178    /// # Ok::<(), ferrochart_core::Error>(())
1179    /// ```
1180    pub fn add_series(
1181        &mut self,
1182        pane: PaneId,
1183        kind: SeriesKind,
1184        opts: SeriesOptions,
1185    ) -> Result<SeriesId> {
1186        if self.transform_entry().is_some() && kind != SeriesKind::Volume {
1187            return Err(NEXT_TO_TRANSFORM);
1188        }
1189        self.insert_series(pane, kind, opts)
1190    }
1191
1192    /// `add_series` without the transform-series check (indicator outputs).
1193    fn insert_series(
1194        &mut self,
1195        pane: PaneId,
1196        kind: SeriesKind,
1197        opts: SeriesOptions,
1198    ) -> Result<SeriesId> {
1199        if self.pane_index(pane).is_none() {
1200            return Err(Error::UnknownId);
1201        }
1202        if kind == SeriesKind::Custom {
1203            return Err(Error::InvalidArgument(
1204                "custom series are added with add_custom_series",
1205            ));
1206        }
1207        if matches!(kind, SeriesKind::Kagi | SeriesKind::PointFigure) {
1208            return Err(Error::InvalidArgument(
1209                "Kagi and Point & Figure series are added with add_transform_series",
1210            ));
1211        }
1212        if kind == SeriesKind::Band {
1213            return Err(Error::InvalidArgument("bands are added with add_band"));
1214        }
1215        if kind == SeriesKind::Volume {
1216            let source_ok = opts
1217                .source
1218                .and_then(|s| self.entry(s).ok())
1219                .is_some_and(|e| is_ohlc_kind(e.kind) || e.store.transform().is_some());
1220            if !source_ok {
1221                return Err(Error::InvalidArgument(
1222                    "a volume series needs an OHLC series of this chart as its source",
1223                ));
1224            }
1225            if !self.series.iter().any(|e| e.pane == pane)
1226                && let Some(p) = self.pane_mut(pane)
1227            {
1228                // Bars stand on the bottom of a pane of their own.
1229                let _ = p.price_scale.set_margins(PRICE_MARGINS.0, 0.0);
1230            }
1231        }
1232        let id = SeriesId(self.next_id);
1233        self.next_id = self.next_id.checked_add(1).ok_or(Error::OutOfMemory)?;
1234        self.series.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
1235        self.series.push(SeriesEntry {
1236            id,
1237            pane,
1238            kind,
1239            opts,
1240            store: Store::for_kind(kind),
1241            norm: None,
1242            markers: Vec::new(),
1243            derived: false,
1244            volume_scale: false,
1245            auto_decimals: 2,
1246        });
1247        self.invalidation = Invalidation::Full;
1248        Ok(id)
1249    }
1250
1251    /// The options of a series; `None` for an unknown id.
1252    pub fn series_options(&self, id: SeriesId) -> Option<&SeriesOptions> {
1253        self.entry(id).ok().map(|e| &e.opts)
1254    }
1255
1256    /// The kind of a series; `None` for an unknown id.
1257    pub fn series_kind(&self, id: SeriesId) -> Option<SeriesKind> {
1258        self.entry(id).ok().map(|e| e.kind)
1259    }
1260
1261    /// The pane of a series; `None` for an unknown id.
1262    pub fn series_pane(&self, id: SeriesId) -> Option<PaneId> {
1263        self.entry(id).ok().map(|e| e.pane)
1264    }
1265
1266    /// Changes the options of a series (colors, line style, labels, shift,
1267    /// …), e.g. for `applyOptions` of the lightweight-charts compatibility
1268    /// layer. The data is kept.
1269    ///
1270    /// # Errors
1271    ///
1272    /// - [`Error::UnknownId`] if the series does not exist;
1273    /// - [`Error::InvalidArgument`] if `opts.source` differs from the
1274    ///   series' source (the source of a volume series is fixed).
1275    ///
1276    /// # Examples
1277    ///
1278    /// ```
1279    /// use ferrochart_core::chart::SeriesOptions;
1280    /// use ferrochart_core::frame::SeriesKind;
1281    /// use ferrochart_core::geom::Rgba;
1282    /// use ferrochart_core::{Chart, ChartOptions};
1283    ///
1284    /// let mut chart = Chart::new(ChartOptions::default());
1285    /// let line = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
1286    /// let mut opts = *chart.series_options(line).unwrap();
1287    /// opts.color = Some(Rgba::hex(0x00FF_6D00));
1288    /// chart.set_series_options(line, opts)?;
1289    /// assert_eq!(chart.series_options(line).unwrap().color, Some(Rgba::hex(0x00FF_6D00)));
1290    /// # Ok::<(), ferrochart_core::Error>(())
1291    /// ```
1292    pub fn set_series_options(&mut self, id: SeriesId, opts: SeriesOptions) -> Result<()> {
1293        let k = self.entry_index(id)?;
1294        if opts.source != self.series[k].opts.source {
1295            return Err(Error::InvalidArgument(
1296                "the source of a series cannot change",
1297            ));
1298        }
1299        self.series[k].opts = opts;
1300        self.invalidation = Invalidation::Full;
1301        Ok(())
1302    }
1303
1304    /// Removes a series and its data. Removing an OHLC series also removes the
1305    /// volume series that read it.
1306    ///
1307    /// # Errors
1308    ///
1309    /// [`Error::UnknownId`] if the series does not exist.
1310    pub fn remove_series(&mut self, id: SeriesId) -> Result<()> {
1311        if self.entry(id)?.derived {
1312            return Err(Error::InvalidArgument(
1313                "an indicator output; remove the indicator instead",
1314            ));
1315        }
1316        self.drop_indicators_of(id);
1317        self.series
1318            .retain(|e| e.id != id && e.opts.source != Some(id));
1319        self.price_lines
1320            .retain(|l| self.series.iter().any(|e| e.id == l.series));
1321        self.prune_bands();
1322        // The other series keep the time axis; without data it is reset.
1323        if self.series.iter().all(|e| e.store.is_empty()) {
1324            self.time_index = TimeIndex::new();
1325            self.time_scale.set_extent(0, 0);
1326        }
1327        self.invalidation = Invalidation::Full;
1328        Ok(())
1329    }
1330
1331    fn after_change(&mut self, id: SeriesId, repaired: usize) {
1332        self.time_scale
1333            .set_extent(self.time_index.first_index(), self.time_index.end_index());
1334        self.invalidation = self.invalidation.max(Invalidation::Data);
1335        if repaired > 0 {
1336            self.events
1337                .push(ChartEvent::Warning(WarningKind::OhlcRepaired {
1338                    series: id,
1339                    bars: repaired,
1340                }));
1341        }
1342    }
1343
1344    /// Index of series `id`, which must take data of its own.
1345    fn data_entry(&self, id: SeriesId) -> Result<usize> {
1346        let k = self.entry_index(id)?;
1347        if self.series[k].store.takes_data() {
1348            Ok(k)
1349        } else if self.series[k].kind == SeriesKind::Custom {
1350            Err(Error::InvalidArgument(
1351                "a custom series owns its data; use update_custom",
1352            ))
1353        } else {
1354            Err(Error::InvalidArgument(
1355                "this series has no data of its own; use its source series",
1356            ))
1357        }
1358    }
1359
1360    /// Runs a data operation on series `k` with the current time axis. If it
1361    /// fails, the `(front, back)` slots `cover` added are removed again.
1362    fn run_op<T>(
1363        &mut self,
1364        k: usize,
1365        added: (usize, usize),
1366        f: impl FnOnce(&Op<'_>, &mut Store) -> Result<T>,
1367    ) -> Result<T> {
1368        let entry = &mut self.series[k];
1369        let op = Op {
1370            kind: entry.kind,
1371            index: &self.time_index,
1372            mode: self.validation,
1373        };
1374        let out = f(&op, &mut entry.store);
1375        if out.is_err() {
1376            self.time_index.truncate_ends(added.0, added.1);
1377        }
1378        out
1379    }
1380
1381    /// Makes `times` slots of the time axis where that keeps every logical
1382    /// index: times before the first slot are prepended, times after
1383    /// the last appended. Returns the `(front, back)` numbers added, or `None`
1384    /// if a time falls between existing slots (the axis must be rebuilt).
1385    fn cover(&mut self, times: &[Timestamp]) -> Result<Option<(usize, usize)>> {
1386        let index = &mut self.time_index;
1387        let (Some(&t0), Some(&tn)) = (times.first(), times.last()) else {
1388            return Ok(Some((0, 0)));
1389        };
1390        let (Some(&first), Some(&last)) = (index.times().first(), index.times().last()) else {
1391            index.append(times)?;
1392            return Ok(Some((0, times.len())));
1393        };
1394        if t0 > last {
1395            index.append(times)?;
1396            return Ok(Some((0, times.len())));
1397        }
1398        if tn < first {
1399            index.prepend(times)?;
1400            return Ok(Some((times.len(), 0)));
1401        }
1402        if let [t] = times {
1403            // The real-time path: no allocation.
1404            return Ok(index.index_of(*t).map(|_| (0, 0)));
1405        }
1406        let head = times.partition_point(|&t| t < first);
1407        let body_end = times.partition_point(|&t| t <= last).max(head);
1408        if index.map_series(&times[head..body_end])?.is_none() {
1409            return Ok(None);
1410        }
1411        index.prepend(&times[..head])?;
1412        if let Err(e) = index.append(&times[body_end..]) {
1413            index.truncate_ends(head, 0);
1414            return Err(e);
1415        }
1416        Ok(Some((head, times.len() - body_end)))
1417    }
1418
1419    /// Logical-index spans of the series other than `k` that have data,
1420    /// sorted and merged.
1421    fn other_spans(&self, k: usize) -> Vec<(i64, i64)> {
1422        let mut spans: Vec<(i64, i64)> = self
1423            .series
1424            .iter()
1425            .enumerate()
1426            .filter(|&(j, e)| j != k && !e.derived)
1427            .filter_map(|(_, e)| e.store.span())
1428            .collect();
1429        spans.sort_unstable();
1430        let mut merged: Vec<(i64, i64)> = Vec::with_capacity(spans.len());
1431        for (a, b) in spans {
1432            match merged.last_mut() {
1433                Some(last) if a <= last.1 => last.1 = last.1.max(b),
1434                _ => merged.push((a, b)),
1435            }
1436        }
1437        merged
1438    }
1439
1440    /// Whether a slot of the axis outside `others` (sorted, disjoint spans)
1441    /// is not one of `times` (which are all slots of the axis): such a slot
1442    /// would belong to no series after the operation.
1443    fn has_orphans(&self, others: &[(i64, i64)], times: &[Timestamp]) -> bool {
1444        let index = &self.time_index;
1445        let end = index.end_index();
1446        let mut at = index.first_index();
1447        for &(a, b) in others.iter().chain(core::iter::once(&(end, end))) {
1448            if at < a {
1449                let (Some(ta), Some(tb)) = (index.time_at(at), index.time_at(a - 1)) else {
1450                    return true;
1451                };
1452                let lo = times.partition_point(|&t| t < ta);
1453                let hi = times.partition_point(|&t| t <= tb);
1454                if i64::try_from(hi - lo).ok() != Some(a - at) {
1455                    return true;
1456                }
1457            }
1458            at = at.max(b);
1459        }
1460        false
1461    }
1462
1463    /// Rebuilds the time axis as the union of `target`'s times (the complete
1464    /// new data of series `k`) and the slots the `others` spans cover, then
1465    /// sets every series' data on it. Logical indices are kept for the
1466    /// first slot the old and new axis share. Reports a
1467    /// [`WarningKind::TimeAxisMerged`] if times were inserted between
1468    /// existing slots. The chart is unchanged if `target` is invalid.
1469    fn rebuild(&mut self, k: usize, target: Target<'_>, others: &[(i64, i64)]) -> Result<usize> {
1470        let old = &self.time_index;
1471        let mut kept = Vec::new();
1472        for &(a, b) in others {
1473            let from = usize::try_from(a - old.first_index()).unwrap_or(0);
1474            let to = usize::try_from(b - old.first_index()).unwrap_or(0);
1475            kept.extend_from_slice(old.times().get(from..to).unwrap_or(&[]));
1476        }
1477        let mut index = TimeIndex::from_times(kept)?;
1478        index.merge(target.times())?;
1479        let inserted = match (old.times().first(), old.times().last()) {
1480            (Some(&first), Some(&last)) => target
1481                .times()
1482                .iter()
1483                .filter(|&&t| t > first && t < last && old.index_of(t).is_none())
1484                .count(),
1485            _ => 0,
1486        };
1487        let shared = index
1488            .times()
1489            .iter()
1490            .enumerate()
1491            .find_map(|(p, &t)| Some((old.index_of(t)?, p)));
1492        if let Some((j, p)) = shared
1493            && let Some(first) = j.checked_sub(i64::try_from(p).unwrap_or(i64::MAX))
1494        {
1495            index.rebase(first);
1496        }
1497        let snapshots: Vec<(usize, SeriesData)> = self
1498            .series
1499            .iter()
1500            .enumerate()
1501            .filter(|&(j, e)| j != k && !e.store.is_empty() && !e.derived)
1502            .filter_map(|(j, e)| Some((j, e.store.snapshot(old)?)))
1503            .collect();
1504        // The target first: its errors leave the chart unchanged.
1505        let entry = &mut self.series[k];
1506        let repaired = match target {
1507            Target::Data(data) => Op {
1508                kind: entry.kind,
1509                index: &index,
1510                mode: self.validation,
1511            }
1512            .set(&mut entry.store, data)?,
1513            Target::Custom(c) => {
1514                c.map_onto(&index)?;
1515                c.log.replace();
1516                0
1517            }
1518        };
1519        let id = entry.id;
1520        for (j, snap) in snapshots {
1521            let entry = &mut self.series[j];
1522            let op = Op {
1523                kind: entry.kind,
1524                index: &index,
1525                mode: ValidationMode::Repair,
1526            };
1527            // Only an allocation failure can make a snapshot not fit.
1528            if op.set(&mut entry.store, snap).is_err() {
1529                entry.store = Store::for_kind(entry.kind);
1530                self.events
1531                    .push(ChartEvent::Warning(WarningKind::DataDropped {
1532                        series: entry.id,
1533                    }));
1534            }
1535        }
1536        // Custom series are re-mapped from their own times.
1537        for e in &mut self.series {
1538            if let Store::Custom(c) = &mut e.store
1539                && c.mode == AxisMode::Slots
1540                && c.len() > 0
1541            {
1542                c.log.replace();
1543                if c.map_onto(&index).is_err() {
1544                    c.clear();
1545                    self.events
1546                        .push(ChartEvent::Warning(WarningKind::DataDropped {
1547                            series: e.id,
1548                        }));
1549                }
1550            }
1551        }
1552        // Indicator outputs are recomputed on the new axis (`after_data`).
1553        for e in self.series.iter_mut().filter(|e| e.derived) {
1554            e.store = Store::for_kind(e.kind);
1555        }
1556        self.axis_rebuilt = true;
1557        self.time_index = index;
1558        self.time_index.shrink_to_fit();
1559        if inserted > 0 {
1560            self.events
1561                .push(ChartEvent::Warning(WarningKind::TimeAxisMerged {
1562                    series: id,
1563                    slots: inserted,
1564                }));
1565        }
1566        Ok(repaired)
1567    }
1568
1569    /// The complete data of series `k` after adding `new` before (`prepend`)
1570    /// or after its current points, for a rebuild.
1571    fn combined(&self, k: usize, new: SeriesData, prepend: bool) -> Result<SeriesData> {
1572        let store = &self.series[k].store;
1573        let Some(old) = store
1574            .snapshot(&self.time_index)
1575            .filter(|_| !store.is_empty())
1576        else {
1577            return Ok(new);
1578        };
1579        let (Some(&new_first), Some(&new_last)) = (new.times().first(), new.times().last()) else {
1580            return Ok(old);
1581        };
1582        let (Some(&old_first), Some(&old_last)) = (old.times().first(), old.times().last()) else {
1583            return Ok(new);
1584        };
1585        if prepend {
1586            if new_last >= old_first {
1587                return Err(Error::TimeNotIncreasing {
1588                    index: new.times().len() - 1,
1589                });
1590            }
1591            new.concat(old)
1592        } else {
1593            if new_first <= old_last {
1594                return Err(Error::TimeNotIncreasing { index: 0 });
1595            }
1596            old.concat(new)
1597        }
1598    }
1599
1600    /// Replaces all data of a series.
1601    ///
1602    /// The time axis becomes the union of the new times and the times of the
1603    /// other series: times the other series do not have are added (a
1604    /// time between existing bars rebuilds the axis and reports
1605    /// [`WarningKind::TimeAxisMerged`]), and bars only this series had are
1606    /// removed.
1607    ///
1608    /// # Errors
1609    ///
1610    /// [`Error::UnknownId`], [`Error::InvalidArgument`] (wrong series or data
1611    /// kind), and the data validation errors
1612    /// ([`Error::LengthMismatch`], [`Error::InvalidOhlc`],
1613    /// [`Error::TimeNotIncreasing`]). The chart is unchanged on error.
1614    pub fn set_data(&mut self, id: SeriesId, data: impl Into<SeriesData>) -> Result<()> {
1615        self.set_data_data(id, data.into())
1616    }
1617
1618    fn set_data_data(&mut self, id: SeriesId, data: SeriesData) -> Result<()> {
1619        let k = self.data_entry(id)?;
1620        if self.series[k].store.transform().is_some() {
1621            let (input, repaired) = input_columns(data, self.validation)?;
1622            self.run_transform(k, repaired, |t, index| {
1623                t.set(index, input).map(|()| Some(DataChange::Replace))
1624            })?;
1625            return Ok(());
1626        }
1627        let others = self.other_spans(k);
1628        let repaired = if others.is_empty() {
1629            // The only series with data: its times are the axis.
1630            let (times, data) = data.take_times()?;
1631            let index = TimeIndex::from_times(times)?;
1632            let entry = &mut self.series[k];
1633            let repaired = Op {
1634                kind: entry.kind,
1635                index: &index,
1636                mode: self.validation,
1637            }
1638            .set_aligned(&mut entry.store, index.first_index(), data)?;
1639            self.time_index = index;
1640            self.time_index.shrink_to_fit();
1641            // A new axis: indicator outputs are recomputed on it.
1642            self.axis_rebuilt = true;
1643            repaired
1644        } else if self.time_index.map_series(data.times())?.is_some()
1645            && !self.has_orphans(&others, data.times())
1646        {
1647            self.run_op(k, (0, 0), |op, store| op.set(store, data))?
1648        } else {
1649            self.rebuild(k, Target::Data(data), &others)?
1650        };
1651        self.after_change(id, repaired);
1652        self.after_data(id, DataChange::Replace);
1653        Ok(())
1654    }
1655
1656    /// Appends points after the last one. Times the axis does not have yet
1657    /// are added to it.
1658    ///
1659    /// # Errors
1660    ///
1661    /// As [`set_data`](Self::set_data); additionally the times must come after
1662    /// the last point, and volume must be present exactly when the series has it.
1663    pub fn append(&mut self, id: SeriesId, data: impl Into<SeriesData>) -> Result<()> {
1664        self.append_data(id, data.into())
1665    }
1666
1667    fn append_data(&mut self, id: SeriesId, data: SeriesData) -> Result<()> {
1668        let k = self.data_entry(id)?;
1669        if self.series[k].store.transform().is_some() {
1670            let (input, repaired) = input_columns(data, self.validation)?;
1671            self.run_transform(k, repaired, |t, index| t.append(index, input))?;
1672            return Ok(());
1673        }
1674        let old_end = self.series[k].store.span().map(|(_, e)| e);
1675        let repaired = if let Some(added) = self.cover(data.times())? {
1676            self.run_op(k, added, |op, store| op.append(store, data))?
1677        } else {
1678            let all = self.combined(k, data, false)?;
1679            let others = self.other_spans(k);
1680            self.rebuild(k, Target::Data(all), &others)?
1681        };
1682        self.after_change(id, repaired);
1683        let change = match (old_end, self.series[k].store.span()) {
1684            (Some(old), Some((_, end))) => DataChange::Append {
1685                count: usize::try_from(end - old).unwrap_or(0),
1686            },
1687            _ => DataChange::Replace,
1688        };
1689        self.after_data(id, change);
1690        Ok(())
1691    }
1692
1693    /// Inserts older points before the first one (history loading). Existing
1694    /// points keep their logical indices unless a time falls between
1695    /// existing bars of the axis.
1696    ///
1697    /// # Errors
1698    ///
1699    /// As [`append`](Self::append), with times before the first point.
1700    pub fn prepend(&mut self, id: SeriesId, data: impl Into<SeriesData>) -> Result<()> {
1701        self.prepend_data(id, data.into())
1702    }
1703
1704    fn prepend_data(&mut self, id: SeriesId, data: SeriesData) -> Result<()> {
1705        let k = self.data_entry(id)?;
1706        if self.series[k].store.transform().is_some() {
1707            let (input, repaired) = input_columns(data, self.validation)?;
1708            self.run_transform(k, repaired, |t, index| {
1709                t.prepend(index, input).map(|()| Some(DataChange::Replace))
1710            })?;
1711            return Ok(());
1712        }
1713        let repaired = if let Some(added) = self.cover(data.times())? {
1714            self.run_op(k, added, |op, store| op.prepend(store, data))?
1715        } else {
1716            let all = self.combined(k, data, true)?;
1717            let others = self.other_spans(k);
1718            self.rebuild(k, Target::Data(all), &others)?
1719        };
1720        self.after_change(id, repaired);
1721        self.after_data(id, DataChange::Replace);
1722        Ok(())
1723    }
1724
1725    /// Real-time update. Replaces the last point if `bar.time` equals its time
1726    /// (no allocation), appends one if it is later. Returns the applied change.
1727    /// Value series (line, area, baseline, histogram) take `bar.close` as the
1728    /// value and ignore the other fields. For a transform series `bar` is an
1729    /// input and the result is the change of the output (`Append { count: 0
1730    /// }` if the output did not change); replacing the last input does not
1731    /// allocate while the number of forming elements stays the same.
1732    ///
1733    /// # Errors
1734    ///
1735    /// [`Error::UnknownId`], [`Error::InvalidArgument`] (a volume series),
1736    /// [`Error::TimeNotIncreasing`] (time before the last point), and the
1737    /// validation errors.
1738    pub fn update_last(&mut self, id: SeriesId, bar: BarUpdate) -> Result<DataChange> {
1739        let k = self.data_entry(id)?;
1740        if self.series[k].store.transform().is_some() {
1741            let (bar, repaired) = crate::data::ohlc::OhlcStore::check_one(bar, self.validation)?;
1742            return self.run_transform(k, repaired, |t, index| t.update_last(index, bar));
1743        }
1744        let (change, repaired) = if let Some(added) = self.cover(&[bar.time])? {
1745            self.run_op(k, added, |op, store| op.update_last(store, bar))?
1746        } else {
1747            let point = SeriesData::point(self.series[k].kind, bar);
1748            let all = self.combined(k, point, false)?;
1749            let others = self.other_spans(k);
1750            (
1751                DataChange::Append { count: 1 },
1752                self.rebuild(k, Target::Data(all), &others)?,
1753            )
1754        };
1755        if change == DataChange::UpdateLast {
1756            self.invalidation = self.invalidation.max(Invalidation::Data);
1757            if repaired > 0 {
1758                self.after_change(id, repaired);
1759            }
1760        } else {
1761            self.after_change(id, repaired);
1762        }
1763        self.after_data(id, change);
1764        Ok(change)
1765    }
1766
1767    /// Adds a transform series to a pane: the data given to it
1768    /// with [`set_data`](Self::set_data), [`append`](Self::append),
1769    /// [`prepend`](Self::prepend) and [`update_last`](Self::update_last) is
1770    /// its input, and its output elements, at synthetic times, are the time
1771    /// axis. See [`crate::transform`] for the built-in transforms.
1772    ///
1773    /// # Errors
1774    ///
1775    /// - [`Error::UnknownId`] if `pane` does not exist;
1776    /// - [`Error::InvalidArgument`] if the chart already has a series other
1777    ///   than volume (a chart has at most one transform series and no
1778    ///   time-based series next to it), if the output kind is not
1779    ///   `Candlestick`, `OhlcBar`, `Kagi` or `PointFigure`, or if a
1780    ///   `PointFigure` transform has no positive box size.
1781    ///
1782    /// # Examples
1783    ///
1784    /// ```
1785    /// use ferrochart_core::chart::{SeriesData, SeriesOptions};
1786    /// use ferrochart_core::data::BarUpdate;
1787    /// use ferrochart_core::frame::SeriesKind;
1788    /// use ferrochart_core::testing::{random_walk, MonoMeasurer};
1789    /// use ferrochart_core::transform::{Kagi, Reversal};
1790    /// use ferrochart_core::{Chart, ChartOptions};
1791    ///
1792    /// let mut chart = Chart::new(ChartOptions::default());
1793    /// let pane = chart.main_pane();
1794    /// let kagi = chart.add_transform_series(
1795    ///     pane,
1796    ///     Box::new(Kagi::new(Reversal::Percent(2.0))?),
1797    ///     SeriesOptions::default(),
1798    /// )?;
1799    /// let bars = random_walk(1, 5_000, 0, 60_000)?;
1800    /// let last = *bars.time.last().unwrap();
1801    /// chart.set_data(kagi, SeriesData::Ohlc(bars))?;
1802    /// // Far fewer lines than input bars.
1803    /// assert!(chart.data_view().time_index().len() < 1_000);
1804    /// // Real-time input.
1805    /// let tick = BarUpdate { time: last + 60_000, open: 100.0, high: 100.0, low: 100.0, close: 100.0, volume: Some(1.0) };
1806    /// chart.update_last(kagi, tick)?;
1807    /// // No time-based series next to it.
1808    /// assert!(chart.add_series(pane, SeriesKind::Line, SeriesOptions::default()).is_err());
1809    /// chart.build_frame(0.0, &MonoMeasurer);
1810    /// # Ok::<(), ferrochart_core::Error>(())
1811    /// ```
1812    pub fn add_transform_series(
1813        &mut self,
1814        pane: PaneId,
1815        t: Box<dyn SeriesTransform>,
1816        opts: SeriesOptions,
1817    ) -> Result<SeriesId> {
1818        if self.pane_index(pane).is_none() {
1819            return Err(Error::UnknownId);
1820        }
1821        if self
1822            .series
1823            .iter()
1824            .any(|e| !e.derived && e.kind != SeriesKind::Volume)
1825        {
1826            return Err(NEXT_TO_TRANSFORM);
1827        }
1828        let kind = t.output_kind();
1829        if !matches!(
1830            kind,
1831            SeriesKind::Candlestick
1832                | SeriesKind::OhlcBar
1833                | SeriesKind::Kagi
1834                | SeriesKind::PointFigure
1835        ) {
1836            return Err(Error::InvalidArgument(
1837                "a transform is drawn as candlesticks, OHLC bars, Kagi or Point & Figure",
1838            ));
1839        }
1840        if kind == SeriesKind::PointFigure
1841            && !t.box_size().is_some_and(|b| b.is_finite() && b > 0.0)
1842        {
1843            return Err(Error::InvalidArgument(
1844                "a Point & Figure transform needs a positive box size",
1845            ));
1846        }
1847        let id = SeriesId(self.next_id);
1848        self.next_id = self.next_id.checked_add(1).ok_or(Error::OutOfMemory)?;
1849        self.series.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
1850        self.series.push(SeriesEntry {
1851            id,
1852            pane,
1853            kind,
1854            opts,
1855            store: Store::Transform(Box::new(TransformStore::new(t))),
1856            norm: None,
1857            markers: Vec::new(),
1858            derived: false,
1859            volume_scale: false,
1860            auto_decimals: 2,
1861        });
1862        self.invalidation = Invalidation::Full;
1863        Ok(id)
1864    }
1865
1866    /// The transform series, if the chart has one.
1867    fn transform_entry(&self) -> Option<usize> {
1868        self.series
1869            .iter()
1870            .position(|e| e.store.transform().is_some())
1871    }
1872
1873    /// Runs a data operation on transform series `k`, whose output is the
1874    /// whole time axis, and passes the output's change on.
1875    fn run_transform(
1876        &mut self,
1877        k: usize,
1878        repaired: usize,
1879        f: impl FnOnce(&mut TransformStore, &mut TimeIndex) -> Result<Option<DataChange>>,
1880    ) -> Result<DataChange> {
1881        let Store::Transform(t) = &mut self.series[k].store else {
1882            return Err(Error::InvalidArgument("not a transform series"));
1883        };
1884        let out = f(t, &mut self.time_index);
1885        let id = self.series[k].id;
1886        let change = match out {
1887            Ok(c) => c,
1888            Err(e) => {
1889                // The output may have been cleared.
1890                self.after_change(id, 0);
1891                self.after_data(id, DataChange::Replace);
1892                return Err(e);
1893            }
1894        };
1895        match change {
1896            None => {
1897                if repaired > 0 {
1898                    self.after_change(id, repaired);
1899                }
1900                Ok(DataChange::Append { count: 0 })
1901            }
1902            Some(DataChange::UpdateLast) => {
1903                self.invalidation = self.invalidation.max(Invalidation::Data);
1904                if repaired > 0 {
1905                    self.after_change(id, repaired);
1906                }
1907                self.after_data(id, DataChange::UpdateLast);
1908                Ok(DataChange::UpdateLast)
1909            }
1910            Some(change) => {
1911                self.after_change(id, repaired);
1912                self.after_data(id, change);
1913                Ok(change)
1914            }
1915        }
1916    }
1917
1918    /// Adds a custom series to a pane. Its current data is taken as a
1919    /// `Replace`; later changes go through [`update_custom`](Self::update_custom).
1920    /// See [`CustomSeries`] for an example.
1921    ///
1922    /// # Errors
1923    ///
1924    /// [`Error::UnknownId`] if `pane` does not exist;
1925    /// [`Error::InvalidArgument`] if the chart has a transform series;
1926    /// [`Error::TimeNotIncreasing`] if the plugin's times are not strictly
1927    /// increasing (the series is not added); [`Error::OutOfMemory`].
1928    pub fn add_custom_series(
1929        &mut self,
1930        pane: PaneId,
1931        series: Box<dyn CustomSeries>,
1932        opts: SeriesOptions,
1933    ) -> Result<SeriesId> {
1934        if self.pane_index(pane).is_none() {
1935            return Err(Error::UnknownId);
1936        }
1937        if self.transform_entry().is_some() {
1938            return Err(NEXT_TO_TRANSFORM);
1939        }
1940        let id = SeriesId(self.next_id);
1941        let next = self.next_id.checked_add(1).ok_or(Error::OutOfMemory)?;
1942        self.series.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
1943        let has_data = !series.times().is_empty();
1944        self.series.push(SeriesEntry {
1945            id,
1946            pane,
1947            kind: SeriesKind::Custom,
1948            opts,
1949            store: Store::Custom(Box::new(CustomStore::new(series))),
1950            norm: None,
1951            markers: Vec::new(),
1952            derived: false,
1953            volume_scale: false,
1954            auto_decimals: 2,
1955        });
1956        self.next_id = next;
1957        self.invalidation = Invalidation::Full;
1958        if has_data && let Err(e) = self.change_custom(id, |_| Ok(DataChange::Replace)) {
1959            self.series.pop();
1960            return Err(e);
1961        }
1962        Ok(id)
1963    }
1964
1965    /// The plugin of custom series `id` as `T`; `None` for an unknown id,
1966    /// another kind of series or another type.
1967    pub fn custom_series<T: CustomSeries>(&self, id: SeriesId) -> Option<&T> {
1968        let any: &dyn Any = self.entry(id).ok()?.store.custom()?.plugin.as_ref();
1969        any.downcast_ref::<T>()
1970    }
1971
1972    /// Changes the data of custom series `id`: `f` modifies the plugin and
1973    /// returns what changed, and core updates the time axis, generation and
1974    /// change log. `DataChange::UpdateLast` keeping the last time does
1975    /// not allocate. A change that does not match the data (wrong count, the
1976    /// last time moved) is applied as a `Replace`.
1977    ///
1978    /// # Errors
1979    ///
1980    /// - [`Error::UnknownId`];
1981    /// - [`Error::InvalidArgument`] if it is not a custom series or its plugin
1982    ///   is not a `T` (`f` is not called);
1983    /// - [`Error::TimeNotIncreasing`] if the times are no longer strictly
1984    ///   increasing: the series then shows nothing until a valid change;
1985    /// - [`Error::OutOfMemory`].
1986    pub fn update_custom<T: CustomSeries>(
1987        &mut self,
1988        id: SeriesId,
1989        f: impl FnOnce(&mut T) -> DataChange,
1990    ) -> Result<()> {
1991        self.change_custom(id, |c| {
1992            let any: &mut dyn Any = c.plugin.as_mut();
1993            let t = any.downcast_mut::<T>().ok_or(Error::InvalidArgument(
1994                "the custom series is of another type",
1995            ))?;
1996            Ok(f(t))
1997        })
1998    }
1999
2000    /// Takes custom series `id` out of its entry, lets `modify` change the
2001    /// plugin and say what changed, and applies the change.
2002    fn change_custom(
2003        &mut self,
2004        id: SeriesId,
2005        modify: impl FnOnce(&mut CustomStore) -> Result<DataChange>,
2006    ) -> Result<()> {
2007        let k = self.entry_index(id)?;
2008        let store = core::mem::replace(&mut self.series[k].store, Store::None);
2009        let Store::Custom(mut c) = store else {
2010            self.series[k].store = store;
2011            return Err(NOT_CUSTOM);
2012        };
2013        let out = modify(&mut c).and_then(|change| {
2014            let applied = c
2015                .classify(change)
2016                .and_then(|kind| self.apply_custom(k, &mut c, kind));
2017            if applied.is_err() {
2018                c.clear();
2019                self.invalidation = Invalidation::Full;
2020            }
2021            applied
2022        });
2023        self.series[k].store = Store::Custom(c);
2024        match out? {
2025            None => {}
2026            Some(DataChange::UpdateLast) => {
2027                self.invalidation = self.invalidation.max(Invalidation::Data);
2028                self.after_data(id, DataChange::UpdateLast);
2029            }
2030            Some(change) => {
2031                self.after_change(id, 0);
2032                self.after_data(id, change);
2033            }
2034        }
2035        Ok(())
2036    }
2037
2038    /// Brings the time axis and the mapping of custom series `k` (taken out
2039    /// of its entry as `c`) up to the plugin's data.
2040    fn apply_custom(
2041        &mut self,
2042        k: usize,
2043        c: &mut CustomStore,
2044        kind: CustomChange,
2045    ) -> Result<Option<DataChange>> {
2046        let old = c.len();
2047        let n = c.plugin.times().len();
2048        let span = |a: usize, b: usize| IdxSpan {
2049            start: i64::try_from(a).unwrap_or(i64::MAX),
2050            end: i64::try_from(b).unwrap_or(i64::MAX),
2051        };
2052        let change = match kind {
2053            CustomChange::None => return Ok(None),
2054            CustomChange::UpdateLast => {
2055                // The real-time path: no allocation.
2056                c.log.record(span(old.saturating_sub(1), old));
2057                return Ok(Some(DataChange::UpdateLast));
2058            }
2059            CustomChange::Append => DataChange::Append { count: n - old },
2060            CustomChange::Prepend { count } => DataChange::Prepend { count },
2061            CustomChange::Replace => DataChange::Replace,
2062        };
2063        if c.mode == AxisMode::Overlay {
2064            c.map_onto(&self.time_index)?;
2065            if kind == CustomChange::Append {
2066                c.log.record(span(old, n));
2067            } else {
2068                c.log.replace();
2069            }
2070            return Ok(Some(change));
2071        }
2072        match kind {
2073            CustomChange::Append | CustomChange::Prepend { .. } => {
2074                let times = c.plugin.times();
2075                let new = match kind {
2076                    CustomChange::Prepend { count } => times.get(..count),
2077                    _ => times.get(old..),
2078                };
2079                if let Some(added) = self.cover(new.unwrap_or(&[]))? {
2080                    let mapped = if kind == CustomChange::Append {
2081                        c.extend_onto(&self.time_index)
2082                    } else {
2083                        c.map_onto(&self.time_index)
2084                    };
2085                    if let Err(e) = mapped {
2086                        self.time_index.truncate_ends(added.0, added.1);
2087                        return Err(e);
2088                    }
2089                    if kind == CustomChange::Append {
2090                        c.log.record(span(old, n));
2091                    } else {
2092                        // Every point number moved.
2093                        c.log.replace();
2094                    }
2095                } else {
2096                    let others = self.other_spans(k);
2097                    self.rebuild(k, Target::Custom(c), &others)?;
2098                }
2099            }
2100            _ => {
2101                let others = self.other_spans(k);
2102                let times = c.plugin.times();
2103                if others.is_empty() {
2104                    // The only series with data: its times are the axis.
2105                    let mut own = Vec::new();
2106                    own.try_reserve_exact(times.len())
2107                        .map_err(|_| Error::OutOfMemory)?;
2108                    own.extend_from_slice(times);
2109                    let index = TimeIndex::from_times(own)?;
2110                    c.map_onto(&index)?;
2111                    self.time_index = index;
2112                    self.axis_rebuilt = true;
2113                } else if let Some(m) = self.time_index.map_series(times)?
2114                    && !self.has_orphans(&others, times)
2115                {
2116                    c.accept(m);
2117                } else {
2118                    self.rebuild(k, Target::Custom(c), &others)?;
2119                }
2120                c.log.replace();
2121            }
2122        }
2123        Ok(Some(change))
2124    }
2125
2126    /// Adds a price line to a series. Its price is in the series'
2127    /// units, so on a relative scale it moves with the series.
2128    ///
2129    /// # Errors
2130    ///
2131    /// [`Error::UnknownId`] if the series does not exist;
2132    /// [`Error::InvalidArgument`] for a volume series or a price that is not
2133    /// finite.
2134    ///
2135    /// # Examples
2136    ///
2137    /// See [`PriceLineOptions`].
2138    pub fn create_price_line(
2139        &mut self,
2140        series: SeriesId,
2141        opts: PriceLineOptions,
2142    ) -> Result<PriceLineId> {
2143        let e = self.entry(series)?;
2144        if e.kind == SeriesKind::Volume {
2145            return Err(Error::InvalidArgument("volume series have no price lines"));
2146        }
2147        if !opts.price.is_finite() {
2148            return Err(Error::InvalidArgument("the price must be finite"));
2149        }
2150        let id = PriceLineId(self.next_price_line);
2151        self.next_price_line += 1;
2152        self.price_lines.push(PriceLineEntry { id, series, opts });
2153        self.invalidation = self.invalidation.max(Invalidation::Data);
2154        Ok(id)
2155    }
2156
2157    /// Replaces the options of a price line.
2158    ///
2159    /// # Errors
2160    ///
2161    /// [`Error::UnknownId`] if the price line does not exist;
2162    /// [`Error::InvalidArgument`] for a price that is not finite.
2163    ///
2164    /// # Examples
2165    ///
2166    /// ```
2167    /// use ferrochart_core::chart::{PriceLineOptions, SeriesOptions};
2168    /// use ferrochart_core::frame::SeriesKind;
2169    /// use ferrochart_core::{Chart, ChartOptions};
2170    ///
2171    /// let mut chart = Chart::new(ChartOptions::default());
2172    /// let id = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
2173    /// let line = chart.create_price_line(id, PriceLineOptions { price: 1.0, ..Default::default() })?;
2174    /// chart.update_price_line(line, PriceLineOptions { price: 2.0, ..Default::default() })?;
2175    /// assert_eq!(chart.price_line(line).map(|o| o.price), Some(2.0));
2176    /// # Ok::<(), ferrochart_core::Error>(())
2177    /// ```
2178    pub fn update_price_line(&mut self, id: PriceLineId, opts: PriceLineOptions) -> Result<()> {
2179        if !opts.price.is_finite() {
2180            return Err(Error::InvalidArgument("the price must be finite"));
2181        }
2182        let line = self
2183            .price_lines
2184            .iter_mut()
2185            .find(|l| l.id == id)
2186            .ok_or(Error::UnknownId)?;
2187        line.opts = opts;
2188        self.invalidation = self.invalidation.max(Invalidation::Data);
2189        Ok(())
2190    }
2191
2192    /// Options of a price line; `None` if it does not exist.
2193    pub fn price_line(&self, id: PriceLineId) -> Option<&PriceLineOptions> {
2194        self.price_lines
2195            .iter()
2196            .find(|l| l.id == id)
2197            .map(|l| &l.opts)
2198    }
2199
2200    /// Removes a price line.
2201    ///
2202    /// # Errors
2203    ///
2204    /// [`Error::UnknownId`] if it does not exist.
2205    pub fn remove_price_line(&mut self, id: PriceLineId) -> Result<()> {
2206        let n = self.price_lines.len();
2207        self.price_lines.retain(|l| l.id != id);
2208        if self.price_lines.len() == n {
2209            return Err(Error::UnknownId);
2210        }
2211        self.invalidation = self.invalidation.max(Invalidation::Data);
2212        Ok(())
2213    }
2214
2215    /// Attaches an indicator to `source`. Each output becomes a value
2216    /// series ([`indicator_series`](Self::indicator_series)) on the pane
2217    /// `placement` names; the chart keeps them up to date as the source
2218    /// changes, incrementally for `append` and `update_last`.
2219    ///
2220    /// # Errors
2221    ///
2222    /// [`Error::UnknownId`] for an unknown source or pane;
2223    /// [`Error::InvalidArgument`] for a volume source, an indicator without
2224    /// outputs, or one that needs volume on a source without it.
2225    ///
2226    /// # Examples
2227    ///
2228    /// A minimal indicator: the close, doubled.
2229    ///
2230    /// ```
2231    /// use ferrochart_core::chart::SeriesOptions;
2232    /// use ferrochart_core::data::DataChange;
2233    /// use ferrochart_core::frame::SeriesKind;
2234    /// use ferrochart_core::plugin::{
2235    ///     Indicator, IndicatorInput, IndicatorOutputs, OutputSpec, Placement,
2236    /// };
2237    /// use ferrochart_core::testing::random_walk;
2238    /// use ferrochart_core::chart::SeriesData;
2239    /// use ferrochart_core::{Chart, ChartOptions};
2240    ///
2241    /// struct Double;
2242    /// impl Indicator for Double {
2243    ///     fn name(&self) -> &str { "double" }
2244    ///     fn outputs(&self) -> &[OutputSpec] {
2245    ///         const OUT: [OutputSpec; 1] = [OutputSpec::line("double")];
2246    ///         &OUT
2247    ///     }
2248    ///     fn default_placement(&self) -> Placement { Placement::NewPane }
2249    ///     fn warmup(&self) -> usize { 0 }
2250    ///     fn update(&mut self, input: &IndicatorInput<'_>, _: DataChange, out: &mut IndicatorOutputs) {
2251    ///         let start = out.start();
2252    ///         for (i, v) in out.column(0).iter_mut().enumerate() {
2253    ///             if let Some(b) = input.bar(start + i) {
2254    ///                 *v = 2.0 * b.close;
2255    ///             }
2256    ///         }
2257    ///     }
2258    /// }
2259    ///
2260    /// let mut chart = Chart::new(ChartOptions::default());
2261    /// let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
2262    /// chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 50, 0, 60_000)?))?;
2263    /// let id = chart.add_indicator(candles, Box::new(Double), Placement::NewPane)?;
2264    /// assert_eq!(chart.indicator_series(id).map(<[_]>::len), Some(1));
2265    /// assert_eq!(chart.panes().count(), 2);
2266    /// # Ok::<(), ferrochart_core::Error>(())
2267    /// ```
2268    pub fn add_indicator(
2269        &mut self,
2270        source: SeriesId,
2271        ind: Box<dyn Indicator>,
2272        placement: Placement,
2273    ) -> Result<IndicatorId> {
2274        let src = self.entry(source)?;
2275        if src.kind == SeriesKind::Volume {
2276            return Err(Error::InvalidArgument(
2277                "volume series have no data of their own; use the source series",
2278            ));
2279        }
2280        if src.kind == SeriesKind::Custom {
2281            return Err(Error::InvalidArgument(
2282                "indicators take built-in series as their source",
2283            ));
2284        }
2285        if ind.outputs().is_empty() {
2286            return Err(Error::InvalidArgument("the indicator has no outputs"));
2287        }
2288        let n_out = ind.outputs().len();
2289        if ind
2290            .outputs()
2291            .iter()
2292            .enumerate()
2293            .any(|(i, o)| o.fill_to.is_some_and(|(to, _)| to >= n_out || to == i))
2294        {
2295            return Err(Error::InvalidArgument(
2296                "fill_to must name another output of the indicator",
2297            ));
2298        }
2299        let has_data = !src.store.is_empty();
2300        if ind.needs_volume() && (is_value_kind(src.kind) || has_data && !src.store.has_volume()) {
2301            return Err(Error::InvalidArgument("the indicator needs volume"));
2302        }
2303        let src_pane = src.pane;
2304        let volume_pane = self
2305            .series
2306            .iter()
2307            .find(|e| e.kind == SeriesKind::Volume && e.opts.source == Some(source))
2308            .map(|e| e.pane);
2309        let on_volume = placement == Placement::Volume && volume_pane.is_some();
2310        let (pane, own_pane) = match (placement, volume_pane) {
2311            (Placement::Volume, Some(p)) => (p, None),
2312            (Placement::Overlay, _) => (src_pane, None),
2313            (Placement::Pane(p), _) => {
2314                if !self.panes.iter().any(|x| x.id == p) {
2315                    return Err(Error::UnknownId);
2316                }
2317                (p, None)
2318            }
2319            (Placement::NewPane | Placement::Volume, _) => {
2320                let p = self.add_pane(PaneOptions::default());
2321                (p, Some(p))
2322            }
2323        };
2324        let mut series = Vec::with_capacity(ind.outputs().len());
2325        for spec in ind.outputs() {
2326            let color = spec.color.unwrap_or_else(|| {
2327                let c = INDICATOR_PALETTE[self.palette_next % INDICATOR_PALETTE.len()];
2328                self.palette_next += 1;
2329                Rgba::hex(c)
2330            });
2331            let kind = match spec.kind {
2332                OutputKind::Line => SeriesKind::Line,
2333                OutputKind::Histogram => SeriesKind::Histogram,
2334                OutputKind::Points => SeriesKind::Points,
2335            };
2336            let opts = SeriesOptions {
2337                color: Some(color),
2338                // Dots are `line_width` across: 1 px would hardly show.
2339                line_width: Css(if kind == SeriesKind::Points { 3.0 } else { 1.0 }),
2340                price_line_visible: false,
2341                shift: spec.shift,
2342                ..SeriesOptions::default()
2343            };
2344            let id = self.insert_series(pane, kind, opts)?;
2345            if let Some(e) = self.series.iter_mut().find(|e| e.id == id) {
2346                e.derived = true;
2347                e.volume_scale = on_volume;
2348            }
2349            series.push(id);
2350        }
2351        let mut bands = Vec::new();
2352        for (i, spec) in ind.outputs().iter().enumerate() {
2353            if let Some((to, opts)) = spec.fill_to
2354                && let (Some(&upper), Some(&lower)) = (series.get(i), series.get(to))
2355            {
2356                bands.push(self.add_band(upper, lower, opts)?);
2357            }
2358        }
2359        let id = IndicatorId(self.next_indicator);
2360        self.next_indicator += 1;
2361        self.indicators.push(IndicatorEntry {
2362            id,
2363            source,
2364            ind,
2365            series,
2366            own_pane,
2367            bands,
2368        });
2369        self.update_indicator(self.indicators.len() - 1, DataChange::Replace);
2370        self.invalidation = Invalidation::Full;
2371        Ok(id)
2372    }
2373
2374    /// Removes an indicator, its output series, the indicators attached to
2375    /// them, and the pane `add_indicator` created for it if it is now empty.
2376    ///
2377    /// # Errors
2378    ///
2379    /// [`Error::UnknownId`] if it does not exist.
2380    pub fn remove_indicator(&mut self, id: IndicatorId) -> Result<()> {
2381        let n = self
2382            .indicators
2383            .iter()
2384            .position(|x| x.id == id)
2385            .ok_or(Error::UnknownId)?;
2386        self.drop_indicator(n);
2387        self.invalidation = Invalidation::Full;
2388        Ok(())
2389    }
2390
2391    /// The output series of an indicator, in the order of its outputs;
2392    /// `None` if it does not exist.
2393    pub fn indicator_series(&self, id: IndicatorId) -> Option<&[SeriesId]> {
2394        self.indicators
2395            .iter()
2396            .find(|x| x.id == id)
2397            .map(|x| x.series.as_slice())
2398    }
2399
2400    /// The bands an indicator's `OutputSpec::fill_to` created, e.g.
2401    /// to change their colors with [`set_band_options`](Self::set_band_options);
2402    /// `None` if it does not exist. They are removed with the indicator.
2403    ///
2404    /// # Examples
2405    ///
2406    /// ```
2407    /// use ferrochart_core::chart::{BandOptions, SeriesData, SeriesOptions};
2408    /// use ferrochart_core::frame::SeriesKind;
2409    /// use ferrochart_core::geom::Rgba;
2410    /// use ferrochart_core::plugin::{Indicator, IndicatorInput, IndicatorOutputs, OutputSpec, Placement};
2411    /// use ferrochart_core::data::DataChange;
2412    /// use ferrochart_core::testing::random_walk;
2413    /// use ferrochart_core::{Chart, ChartOptions};
2414    ///
2415    /// /// The high and the low, filled between.
2416    /// struct Range([OutputSpec; 2]);
2417    /// impl Indicator for Range {
2418    ///     fn name(&self) -> &str { "range" }
2419    ///     fn outputs(&self) -> &[OutputSpec] { &self.0 }
2420    ///     fn default_placement(&self) -> Placement { Placement::Overlay }
2421    ///     fn warmup(&self) -> usize { 0 }
2422    ///     fn update(&mut self, input: &IndicatorInput<'_>, _: DataChange, out: &mut IndicatorOutputs) {
2423    ///         let start = out.start();
2424    ///         for k in 0..2 {
2425    ///             for (i, v) in out.column(k).iter_mut().enumerate() {
2426    ///                 if let Some(b) = input.bar(start + i) {
2427    ///                     *v = if k == 0 { b.high } else { b.low };
2428    ///                 }
2429    ///             }
2430    ///         }
2431    ///     }
2432    /// }
2433    ///
2434    /// let mut chart = Chart::new(ChartOptions::default());
2435    /// let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
2436    /// chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 50, 0, 60_000)?))?;
2437    /// let high = OutputSpec { fill_to: Some((1, BandOptions::default())), ..OutputSpec::line("high") };
2438    /// let id = chart.add_indicator(candles, Box::new(Range([high, OutputSpec::line("low")])), Placement::Overlay)?;
2439    /// let band = chart.indicator_bands(id).unwrap()[0];
2440    /// chart.set_band_options(band, BandOptions { fill: Some(Rgba::hex(0x0026_A69A).with_alpha(0x30)), fill_crossed: None })?;
2441    /// # Ok::<(), ferrochart_core::Error>(())
2442    /// ```
2443    pub fn indicator_bands(&self, id: IndicatorId) -> Option<&[BandId]> {
2444        self.indicators
2445            .iter()
2446            .find(|x| x.id == id)
2447            .map(|x| x.bands.as_slice())
2448    }
2449
2450    fn drop_indicator(&mut self, n: usize) {
2451        if n >= self.indicators.len() {
2452            return;
2453        }
2454        let entry = self.indicators.remove(n);
2455        for &out in &entry.series {
2456            self.drop_indicators_of(out);
2457        }
2458        self.series.retain(|e| !entry.series.contains(&e.id));
2459        self.price_lines
2460            .retain(|l| self.series.iter().any(|e| e.id == l.series));
2461        self.prune_bands();
2462        if let Some(p) = entry.own_pane
2463            && self.panes.len() > 1
2464            && !self.series.iter().any(|e| e.pane == p)
2465        {
2466            let _ = self.remove_pane(p);
2467        }
2468    }
2469
2470    /// Drops the indicators whose source is `series`.
2471    fn drop_indicators_of(&mut self, series: SeriesId) {
2472        while let Some(n) = self.indicators.iter().position(|x| x.source == series) {
2473            self.drop_indicator(n);
2474        }
2475    }
2476
2477    /// Brings the indicators up to date after `change` to series `id`.
2478    fn after_data(&mut self, id: SeriesId, change: DataChange) {
2479        if core::mem::take(&mut self.axis_rebuilt) {
2480            // Everything, starting with the indicators on data series.
2481            let roots = (0..self.indicators.len())
2482                .filter(|&n| {
2483                    let src = self.indicators[n].source;
2484                    !self.indicators.iter().any(|x| x.series.contains(&src))
2485                })
2486                .collect();
2487            self.recompute_levels(roots);
2488        } else {
2489            self.run_indicators(id, change);
2490        }
2491    }
2492
2493    /// Updates the indicators on `source`, then those on their outputs.
2494    fn run_indicators(&mut self, source: SeriesId, change: DataChange) {
2495        if !matches!(change, DataChange::Append { .. } | DataChange::UpdateLast) {
2496            let roots = (0..self.indicators.len())
2497                .filter(|&n| self.indicators[n].source == source)
2498                .collect();
2499            self.recompute_levels(roots);
2500            return;
2501        }
2502        for n in 0..self.indicators.len() {
2503            if self.indicators[n].source == source {
2504                self.update_indicator(n, change);
2505                for o in 0..self.indicators[n].series.len() {
2506                    let out = self.indicators[n].series[o];
2507                    self.run_indicators(out, change);
2508                }
2509            }
2510        }
2511    }
2512
2513    /// Full recomputation of the indicators `level` and then, level by
2514    /// level, of the indicators on their outputs. With the `rayon`
2515    /// feature the indicators of a level are computed in parallel; outputs
2516    /// are written in order, so the result does not depend on the feature.
2517    fn recompute_levels(&mut self, mut level: Vec<usize>) {
2518        while !level.is_empty() {
2519            self.recompute_level(&level);
2520            let outs: Vec<SeriesId> = level
2521                .iter()
2522                .flat_map(|&n| self.indicators[n].series.iter().copied())
2523                .collect();
2524            level = (0..self.indicators.len())
2525                .filter(|&n| outs.contains(&self.indicators[n].source))
2526                .collect();
2527        }
2528    }
2529
2530    fn recompute_level(&mut self, level: &[usize]) {
2531        #[cfg(feature = "rayon")]
2532        if level.len() > 1 {
2533            use rayon::prelude::*;
2534            let index = &self.time_index;
2535            // Sources first: series entries hold plugins that are not `Sync`.
2536            // Plain sources only; indicators on custom series run after.
2537            let sources: Vec<Option<crate::series::PlainSource<'_>>> = (0..self.indicators.len())
2538                .map(|n| {
2539                    let src = self.indicators[n].source;
2540                    level
2541                        .contains(&n)
2542                        .then(|| self.series.iter().find(|e| e.id == src))
2543                        .flatten()
2544                        .and_then(|e| match e.store.source() {
2545                            crate::series::Source::Plain(p) => Some(p),
2546                            crate::series::Source::Custom(_) => None,
2547                        })
2548                })
2549                .collect();
2550            let results: Vec<_> = self
2551                .indicators
2552                .par_iter_mut()
2553                .zip(sources.par_iter())
2554                .enumerate()
2555                .filter_map(|(n, (entry, source))| {
2556                    let mut out = IndicatorOutputs::default();
2557                    let source = crate::series::Source::Plain((*source)?);
2558                    let done =
2559                        compute_indicator(entry, source, index, DataChange::Replace, &mut out);
2560                    Some((n, done, out))
2561                })
2562                .collect();
2563            let done: Vec<usize> = results.iter().map(|r| r.0).collect();
2564            for (n, (change, start), out) in results {
2565                self.write_indicator(n, change, start, &out);
2566            }
2567            for &n in level.iter().filter(|n| !done.contains(n)) {
2568                self.update_indicator(n, DataChange::Replace);
2569            }
2570            return;
2571        }
2572        for &n in level {
2573            self.update_indicator(n, DataChange::Replace);
2574        }
2575    }
2576
2577    /// Runs indicator `n` for `change` and writes its outputs.
2578    fn update_indicator(&mut self, n: usize, change: DataChange) {
2579        let Some(entry) = self.indicators.get_mut(n) else {
2580            return;
2581        };
2582        let Some(source) = self.series.iter().find(|e| e.id == entry.source) else {
2583            return;
2584        };
2585        let mut out = core::mem::take(&mut self.ind_out);
2586        let (change, start) = compute_indicator(
2587            entry,
2588            source.store.source(),
2589            &self.time_index,
2590            change,
2591            &mut out,
2592        );
2593        self.write_indicator(n, change, start, &out);
2594        if change == DataChange::Replace {
2595            out.shrink();
2596        }
2597        self.ind_out = out;
2598    }
2599
2600    /// Writes the outputs `out` of indicator `n` computed for `change` from
2601    /// slot `start` into its output series.
2602    fn write_indicator(
2603        &mut self,
2604        n: usize,
2605        change: DataChange,
2606        start: usize,
2607        out: &IndicatorOutputs,
2608    ) {
2609        let Some(entry) = self.indicators.get(n) else {
2610            return;
2611        };
2612        let Some(k) = self.series.iter().position(|e| e.id == entry.source) else {
2613            return;
2614        };
2615        let input = IndicatorInput::new(self.series[k].store.source(), &self.time_index);
2616        let len = input.len();
2617        let first = input.first();
2618        let outputs = out.columns().len();
2619        for o in 0..outputs.min(entry.series.len()) {
2620            let id = entry.series[o];
2621            let Some(ko) = self.series.iter().position(|e| e.id == id) else {
2622                continue;
2623            };
2624            let col = out.columns().get(o).map_or(&[][..], Vec::as_slice);
2625            let src = &self.series[k].store;
2626            let index = &self.time_index;
2627            // Points at the source's bars; gap slots are left to the value
2628            // series' rules (lines interpolate, histograms break).
2629            if change == DataChange::UpdateLast {
2630                let j = first + i64::try_from(start).unwrap_or(0);
2631                let (Some(time), Some(&v)) = (index.time_at(j), col.first()) else {
2632                    continue;
2633                };
2634                if src.bar_at(j).is_none() {
2635                    continue;
2636                }
2637                let bar = BarUpdate {
2638                    time,
2639                    open: v,
2640                    high: v,
2641                    low: v,
2642                    close: v,
2643                    volume: None,
2644                };
2645                let entry = &mut self.series[ko];
2646                let op = Op {
2647                    kind: entry.kind,
2648                    index,
2649                    mode: ValidationMode::Repair,
2650                };
2651                let _ = op.update_last(&mut entry.store, bar);
2652                continue;
2653            }
2654            let mut time = Vec::new();
2655            let mut value = Vec::new();
2656            for (i, &v) in col.iter().enumerate() {
2657                let j = first + i64::try_from(start + i).unwrap_or(0);
2658                if src.bar_at(j).is_some()
2659                    && let Some(t) = index.time_at(j)
2660                {
2661                    time.push(t);
2662                    value.push(v);
2663                }
2664            }
2665            if time.is_empty() && change != DataChange::Replace {
2666                continue;
2667            }
2668            let data = SeriesData::Value(crate::data::ValueColumns {
2669                time,
2670                value,
2671                color: None,
2672            });
2673            let entry = &mut self.series[ko];
2674            let op = Op {
2675                kind: entry.kind,
2676                index,
2677                mode: ValidationMode::Repair,
2678            };
2679            let done = if change == DataChange::Replace {
2680                if len == 0 {
2681                    entry.store = Store::for_kind(entry.kind);
2682                    Ok(0)
2683                } else {
2684                    op.set(&mut entry.store, data)
2685                }
2686            } else {
2687                op.append(&mut entry.store, data)
2688            };
2689            if done.is_err() {
2690                // Only an allocation failure: show nothing rather than stale values.
2691                entry.store = Store::for_kind(entry.kind);
2692            }
2693        }
2694    }
2695
2696    /// Replaces the markers of a series. They are kept sorted by time
2697    /// (stable, so markers on the same bar stack in the given order).
2698    ///
2699    /// # Errors
2700    ///
2701    /// [`Error::UnknownId`] if the series does not exist;
2702    /// [`Error::InvalidArgument`] for a volume series.
2703    ///
2704    /// # Examples
2705    ///
2706    /// See [`Marker`].
2707    pub fn set_markers(&mut self, series: SeriesId, mut markers: Vec<Marker>) -> Result<()> {
2708        let k = self.entry_index(series)?;
2709        if self.series[k].kind == SeriesKind::Volume {
2710            return Err(Error::InvalidArgument("volume series have no markers"));
2711        }
2712        markers.sort_by_key(|m| m.time);
2713        self.series[k].markers = markers;
2714        self.invalidation = self.invalidation.max(Invalidation::Data);
2715        Ok(())
2716    }
2717
2718    /// Markers of a series, sorted by time; `None` if it does not exist.
2719    pub fn markers(&self, series: SeriesId) -> Option<&[Marker]> {
2720        self.entry(series).ok().map(|e| e.markers.as_slice())
2721    }
2722
2723    /// The (global) time scale.
2724    pub fn time_scale(&mut self) -> &mut TimeScale {
2725        &mut self.time_scale
2726    }
2727
2728    /// A price scale of a pane; `None` if it does not exist (for now every
2729    /// pane has only its right scale).
2730    pub fn price_scale(&mut self, pane: PaneId, side: ScaleSide) -> Option<&mut PriceScale> {
2731        if side != ScaleSide::Right {
2732            return None;
2733        }
2734        self.pane_mut(pane).map(|p| &mut p.price_scale)
2735    }
2736
2737    /// Shows all bars.
2738    pub fn fit_content(&mut self) {
2739        self.time_scale.fit_content();
2740    }
2741
2742    /// Scrolls so that the last bar is visible with the configured
2743    /// [`ChartOptions::right_offset`].
2744    pub fn scroll_to_realtime(&mut self) {
2745        self.time_scale.set_right_offset(self.default_right_offset);
2746    }
2747
2748    /// What needs to be redrawn. The host only builds a frame when this is not
2749    /// `None`; without interaction or new data, nothing is redrawn.
2750    pub fn needs_redraw(&self) -> Invalidation {
2751        let mut inv = self.invalidation;
2752        if self.time_scale.changed
2753            || self.drawings.dirty
2754            || self.input.kinetic.is_some()
2755            || self.panes.iter().any(|p| p.price_scale.changed)
2756        {
2757            inv = inv.max(Invalidation::Light);
2758        }
2759        inv.max(self.sync_pending())
2760    }
2761
2762    /// The last built frame.
2763    pub fn frame(&self) -> &Frame {
2764        &self.frame
2765    }
2766
2767    /// Read-only view of the chart data for renderers.
2768    pub fn data_view(&self) -> ChartDataView<'_> {
2769        ChartDataView {
2770            series: &self.series,
2771            time_index: &self.time_index,
2772        }
2773    }
2774
2775    /// The last built layout.
2776    pub fn layout(&self) -> Layout {
2777        self.layout
2778    }
2779
2780    /// Shows the data gradually: with `Some`, series, indicators,
2781    /// bands, markers, drawings and pane plugin layers are clipped to the
2782    /// left `progress` of each pane, while grid and axes are drawn whole and
2783    /// the price scale still fits all visible data; price lines, value
2784    /// labels and the crosshair wait for progress 1. `None` (the default)
2785    /// shows everything. The host moves the progress over time.
2786    ///
2787    /// ```
2788    /// use ferrochart_core::chart::{Chart, ChartOptions};
2789    /// use ferrochart_core::frame::Reveal;
2790    ///
2791    /// let mut chart = Chart::new(ChartOptions::default());
2792    /// chart.set_reveal(Some(Reveal { progress: 0.5, pen: None }));
2793    /// assert_eq!(chart.reveal().map(|r| r.progress), Some(0.5));
2794    /// chart.set_reveal(None);
2795    /// assert!(chart.reveal().is_none());
2796    /// ```
2797    pub fn set_reveal(&mut self, reveal: Option<Reveal>) {
2798        if self.reveal != reveal {
2799            self.reveal = reveal;
2800            self.invalidation = self.invalidation.max(Invalidation::Light);
2801        }
2802    }
2803
2804    /// The gradual display set by [`set_reveal`](Self::set_reveal).
2805    pub fn reveal(&self) -> Option<Reveal> {
2806        self.reveal
2807    }
2808
2809    /// Where the data of a pane with plot area `plot` is drawn.
2810    fn data_clip(&self, plot: RectPx) -> RectPx {
2811        self.reveal.map_or(plot, |r| r.clip(plot))
2812    }
2813
2814    /// Whether a reveal is under way: price lines, value labels and the
2815    /// crosshair wait for its end.
2816    fn revealing(&self) -> bool {
2817        self.reveal.is_some_and(|r| !r.is_done())
2818    }
2819
2820    /// Heap bytes held by the chart's series data: columns, LOD pyramid and time
2821    /// index. Used by the memory benchmark (P2).
2822    pub fn heap_bytes(&self) -> usize {
2823        self.series
2824            .iter()
2825            .map(|e| e.store.heap_bytes())
2826            .sum::<usize>()
2827            + self.time_index.len() * core::mem::size_of::<i64>()
2828    }
2829
2830    /// Takes all pending events.
2831    pub fn drain_events(&mut self) -> impl Iterator<Item = ChartEvent> + '_ {
2832        self.events.append(&mut self.drawings.events);
2833        self.events.drain(..)
2834    }
2835
2836    /// Resolved colors and line settings of a series.
2837    fn style_of(&self, e: &SeriesEntry) -> SeriesStyle {
2838        let t = &self.theme;
2839        let o = &e.opts;
2840        let mut st = SeriesStyle {
2841            line_width: Px(o.line_width.to_px(self.dpr).0.round().max(1.0)),
2842            line_dash: o.line_style,
2843            step: o.step,
2844            base_value: o.base_value,
2845            ..SeriesStyle::default()
2846        };
2847        let (up, down) = match e.kind {
2848            SeriesKind::Line | SeriesKind::Area | SeriesKind::Histogram | SeriesKind::Points => {
2849                let c = o.color.unwrap_or(if e.kind == SeriesKind::Histogram {
2850                    t.up
2851                } else {
2852                    t.line
2853                });
2854                (c, c)
2855            }
2856            SeriesKind::Volume => (t.volume_up, t.volume_down),
2857            _ => (o.color.unwrap_or(t.up), o.down_color.unwrap_or(t.down)),
2858        };
2859        st.up = up;
2860        st.down = down;
2861        st.up_border = up;
2862        st.down_border = down;
2863        let themed_wicks = o.color.is_none() && o.down_color.is_none();
2864        st.up_wick = if themed_wicks { t.up_wick } else { up };
2865        st.down_wick = if themed_wicks { t.down_wick } else { down };
2866        let (top, bottom) = match e.kind {
2867            SeriesKind::Area => (up.with_alpha(0x66), up.with_alpha(0x05)),
2868            _ => (up.with_alpha(0x33), down.with_alpha(0x33)),
2869        };
2870        st.fill_top = o.top_fill.unwrap_or(top);
2871        st.fill_bottom = o.bottom_fill.unwrap_or(bottom);
2872        st
2873    }
2874
2875    /// Auto-scales every pane's price scale to the visible data of its series
2876    /// and chooses its label format.
2877    fn autoscale(&mut self) {
2878        let (from, to) = self.time_scale.visible_range();
2879        let (a, b) = (from.floor() as i64, to.ceil() as i64 + 1);
2880        let spacing = self.time_scale.bar_spacing();
2881        for i in 0..self.panes.len() {
2882            let id = self.panes[i].id;
2883            let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
2884            let mut precision = None;
2885            let mut any_price = false;
2886            let mut max_volume: Option<f64> = None;
2887            for k in 0..self.series.len() {
2888                if self.series[k].pane != id {
2889                    continue;
2890                }
2891                if self.series[k].kind == SeriesKind::Volume {
2892                    let source = self.series[k]
2893                        .opts
2894                        .source
2895                        .and_then(|s| self.series.iter().find(|e| e.id == s));
2896                    if let Some(src) = source
2897                        && src.store.has_volume()
2898                    {
2899                        let level = lod_level(src.store.lod(), spacing);
2900                        if let Some(view) = src.store.level_view(level) {
2901                            let span = visible_span(&view, from, to);
2902                            let m = max_volume_in(&view, span);
2903                            max_volume = Some(max_volume.unwrap_or(0.0).max(m));
2904                        }
2905                    }
2906                    continue;
2907                }
2908                if self.series[k].volume_scale {
2909                    // A line on the volume scale (`Placement::Volume`).
2910                    let e = &mut self.series[k];
2911                    e.norm = Some(Normalize::IDENTITY);
2912                    let s = i64::from(e.opts.shift);
2913                    if let Some((_, h)) = e.store.extremes(a - s, b - s) {
2914                        max_volume = Some(max_volume.unwrap_or(0.0).max(h));
2915                    }
2916                    continue;
2917                }
2918                let mode = self.panes[i].price_scale.mode();
2919                let e = &mut self.series[k];
2920                precision.get_or_insert(e.opts.price_precision);
2921                if e.store.is_empty() {
2922                    e.norm = None;
2923                    continue;
2924                }
2925                any_price = true;
2926                let s = i64::from(e.opts.shift);
2927                let (a, b) = (a - s, b - s);
2928                let base = mode
2929                    .is_relative()
2930                    .then(|| first_value(&e.store, a, b))
2931                    .flatten();
2932                e.norm = Normalize::new(mode, base);
2933                let Some(norm) = e.norm else { continue };
2934                let extremes = match e.store.custom() {
2935                    Some(c) => c.extremes(&self.time_index, a, b),
2936                    None => e.store.extremes(a, b),
2937                };
2938                if let Some((l, h)) = extremes {
2939                    e.auto_decimals = auto_decimals(l.abs().max(h.abs()));
2940                    // k > 0: the order is kept.
2941                    lo = lo.min(norm.apply(l));
2942                    hi = hi.max(norm.apply(h));
2943                    if e.kind == SeriesKind::Histogram {
2944                        let base = norm.apply(e.opts.base_value);
2945                        lo = lo.min(base);
2946                        hi = hi.max(base);
2947                    }
2948                }
2949            }
2950            let pane = &mut self.panes[i];
2951            pane.has_content = any_price || max_volume.is_some();
2952            pane.labels = match pane.price_scale.mode() {
2953                _ if !any_price && max_volume.is_some() => NumberFormat::Compact,
2954                crate::price_scale::PriceScaleMode::Percentage => NumberFormat::Percent(2),
2955                crate::price_scale::PriceScaleMode::IndexedTo100 => NumberFormat::Fixed(2),
2956                _ => match precision.flatten() {
2957                    Some(p) => NumberFormat::Fixed(p),
2958                    None if lo <= hi => NumberFormat::Auto(auto_decimals(lo.abs().max(hi.abs()))),
2959                    None => NumberFormat::Auto(2),
2960                },
2961            };
2962            if any_price && lo <= hi {
2963                pane.price_scale.fit(lo, hi);
2964            }
2965            if let Some(m) = max_volume {
2966                if any_price {
2967                    pane.volume_scale.fit(0.0, m);
2968                } else {
2969                    pane.price_scale.fit(0.0, m);
2970                }
2971            }
2972        }
2973    }
2974
2975    /// Whether pane `i` has something to scale (and therefore ticks).
2976    fn pane_has_content(&self, i: usize) -> bool {
2977        self.panes.get(i).is_some_and(|p| p.has_content)
2978    }
2979
2980    /// Builds the frame for the current state. Call when
2981    /// [`needs_redraw`](Self::needs_redraw) is not `None`, then read it with
2982    /// [`frame`](Self::frame) and [`data_view`](Self::data_view).
2983    ///
2984    /// `now_ms` drives kinetic scrolling; it must use the same clock as the
2985    /// `time_ms` of input events (see [`interaction`](crate::interaction)).
2986    ///
2987    /// Every layer is always rebuilt, so the frame is complete for any
2988    /// renderer; only the revisions of layers whose content changed are bumped:
2989    /// `Cursor` bumps only the overlay.
2990    pub fn build_frame(&mut self, now_ms: f64, text: &dyn TextMeasurer) {
2991        self.step_kinetic(now_ms);
2992        self.pull_sync();
2993        let inv = self.needs_redraw();
2994        if inv >= Invalidation::Light {
2995            self.revisions[LayerId::Background as usize] += 1;
2996            self.revisions[LayerId::Main as usize] += 1;
2997        }
2998        if inv >= Invalidation::Cursor {
2999            self.revisions[LayerId::Overlay as usize] += 1;
3000        }
3001        let w = (self.size.w * self.dpr).round();
3002        let h = (self.size.h * self.dpr).round();
3003        self.frame
3004            .begin(SizePx { w, h }, self.theme.background, inv);
3005        for (layer, rev) in self.frame.layers.iter_mut().zip(self.revisions) {
3006            layer.revision = rev;
3007        }
3008        self.invalidation = Invalidation::None;
3009        self.time_scale.changed = false;
3010        self.drawings.dirty = false;
3011        for pane in &mut self.panes {
3012            pane.price_scale.changed = false;
3013        }
3014        if w < 1.0 || h < 1.0 {
3015            return;
3016        }
3017
3018        let font = FontStyleRef {
3019            font: FontId(0),
3020            size: self.theme.font_size.to_px(self.dpr).0,
3021        };
3022        let line_h = text.line_height(font);
3023        if font.size > 0.0 {
3024            self.text_cache = CachedText {
3025                advances: *text.ascii_advances(font),
3026                subscripts: text.subscript_advances(font).copied().unwrap_or([0.6; 10]),
3027                line: line_h / font.size,
3028            };
3029        }
3030        let pad = self.theme.axis_padding.to_px(self.dpr).0.round();
3031        let time_h = (line_h + 2.0 * pad).ceil().min(h);
3032        let panes_h = (h - time_h).max(0.0);
3033
3034        // The price axis width (shared by all panes) depends on the labels,
3035        // which depend on the visible range, which depends on the plot width:
3036        // iterate (at most twice).
3037        for _ in 0..2 {
3038            let plot_w = (w - self.axis_width).max(0.0);
3039            self.time_scale.set_width(f64::from(plot_w));
3040            stack(&mut self.panes, 0.0, panes_h, plot_w);
3041            self.autoscale();
3042            let mut widest: f32 = 0.0;
3043            for i in 0..self.panes.len() {
3044                let has_content = self.pane_has_content(i);
3045                let pane = &mut self.panes[i];
3046                if has_content {
3047                    pane.price_scale.ticks(
3048                        f64::from(pane.plot.h),
3049                        f64::from(line_h) * 2.5,
3050                        &mut pane.ticks,
3051                    );
3052                } else {
3053                    pane.ticks.clear();
3054                }
3055                let labels = pane.labels.for_ticks(&pane.ticks);
3056                for &p in &pane.ticks {
3057                    let mut s = StackStr::<64>::new();
3058                    write_label(&mut s, p, labels);
3059                    widest = widest.max(text_width(text, s.as_str(), font));
3060                }
3061            }
3062            let required = (widest + 2.0 * pad).ceil().min(w);
3063            if required > self.axis_width || required < self.axis_width * 0.75 {
3064                self.axis_width = required;
3065            } else {
3066                break;
3067            }
3068        }
3069        let plot_w = (w - self.axis_width).max(0.0);
3070        self.time_scale.set_width(f64::from(plot_w));
3071        self.time_scale.settle();
3072        stack(&mut self.panes, 0.0, panes_h, plot_w);
3073        self.layout = Layout {
3074            plot: self.panes.first().map_or(RectPx::default(), |p| p.plot),
3075            price_axis: RectPx {
3076                x: plot_w,
3077                y: 0.0,
3078                w: w - plot_w,
3079                h: panes_h,
3080            },
3081            time_axis: RectPx {
3082                x: 0.0,
3083                y: panes_h,
3084                w,
3085                h: h - panes_h,
3086            },
3087        };
3088
3089        self.place_time_ticks(text, font);
3090        self.emit_layers(None, LayerPosition::BelowSeries, text);
3091        self.marker_hits.clear();
3092        for i in 0..self.panes.len() {
3093            self.emit_grid(i);
3094            self.emit_layers(Some(i), LayerPosition::Background, text);
3095            self.emit_layers(Some(i), LayerPosition::BelowSeries, text);
3096            self.emit_series(i, text);
3097            self.emit_markers(i, line_h, font);
3098            self.emit_layers(Some(i), LayerPosition::AboveSeries, text);
3099            self.emit_drawings(i, text);
3100            self.emit_marks(i, line_h, pad, font);
3101            self.emit_price_labels(i, line_h, pad, font);
3102        }
3103        self.emit_layers(None, LayerPosition::Background, text);
3104        self.emit_layers(None, LayerPosition::AboveSeries, text);
3105        self.emit_axes(time_h, font);
3106        for i in 0..self.panes.len() {
3107            self.emit_layers(Some(i), LayerPosition::Overlay, text);
3108        }
3109        self.emit_layers(None, LayerPosition::Overlay, text);
3110        if let Some(r) = self.reveal {
3111            for pane in &self.panes {
3112                r.push_pen(&mut self.frame, LayerId::Overlay, pane.plot, self.dpr);
3113            }
3114        }
3115        let local_crosshair = self.emit_crosshair(time_h, pad, font);
3116        self.emit_view_events();
3117        self.push_sync(local_crosshair.map(|i| i as f64));
3118    }
3119
3120    /// The drawings.
3121    pub fn drawings(&mut self) -> &mut DrawingManager {
3122        &mut self.drawings
3123    }
3124
3125    /// Adds a band: the area between two single-value series of the same
3126    /// pane, filled with `opts.fill` where `upper` is at or above `lower`
3127    /// and `opts.fill_crossed` where it is below. Bands are drawn
3128    /// after the volume and before the other series of the pane, and are
3129    /// removed with either series. See [`BandOptions`] for an example.
3130    ///
3131    /// # Errors
3132    ///
3133    /// [`Error::UnknownId`] if a series does not exist;
3134    /// [`Error::InvalidArgument`] unless both are single-value series
3135    /// (line, area, baseline, histogram, points) on the same pane and
3136    /// different.
3137    pub fn add_band(
3138        &mut self,
3139        upper: SeriesId,
3140        lower: SeriesId,
3141        opts: BandOptions,
3142    ) -> Result<BandId> {
3143        let (u, l) = (self.entry(upper)?, self.entry(lower)?);
3144        if !is_value_kind(u.kind) || !is_value_kind(l.kind) {
3145            return Err(Error::InvalidArgument(
3146                "a band is between two single-value series",
3147            ));
3148        }
3149        if u.pane != l.pane || upper == lower {
3150            return Err(Error::InvalidArgument(
3151                "a band is between two different series of the same pane",
3152            ));
3153        }
3154        let id = BandId(self.next_band);
3155        self.next_band += 1;
3156        self.bands.push(BandEntry {
3157            id,
3158            upper,
3159            lower,
3160            opts,
3161        });
3162        self.invalidation = Invalidation::Full;
3163        Ok(id)
3164    }
3165
3166    /// Changes the colors of a band.
3167    ///
3168    /// # Errors
3169    ///
3170    /// [`Error::UnknownId`] if it does not exist.
3171    pub fn set_band_options(&mut self, id: BandId, opts: BandOptions) -> Result<()> {
3172        let b = self
3173            .bands
3174            .iter_mut()
3175            .find(|b| b.id == id)
3176            .ok_or(Error::UnknownId)?;
3177        b.opts = opts;
3178        self.invalidation = Invalidation::Full;
3179        Ok(())
3180    }
3181
3182    /// The colors of a band; `None` if it does not exist.
3183    pub fn band_options(&self, id: BandId) -> Option<&BandOptions> {
3184        self.bands.iter().find(|b| b.id == id).map(|b| &b.opts)
3185    }
3186
3187    /// Removes a band.
3188    ///
3189    /// # Errors
3190    ///
3191    /// [`Error::UnknownId`] if it does not exist.
3192    pub fn remove_band(&mut self, id: BandId) -> Result<()> {
3193        let n = self
3194            .bands
3195            .iter()
3196            .position(|b| b.id == id)
3197            .ok_or(Error::UnknownId)?;
3198        self.bands.remove(n);
3199        self.invalidation = Invalidation::Full;
3200        Ok(())
3201    }
3202
3203    /// Reports a click at `p` in `pane`; `drawing` is the drawing
3204    /// pressed, if any.
3205    pub(crate) fn emit_click(&mut self, pane: PaneId, p: PointPx, drawing: Option<DrawingId>) {
3206        let Some(pn) = self.pane_index(pane).and_then(|i| self.panes.get(i)) else {
3207            return;
3208        };
3209        let plot = pn.plot;
3210        let logical_index = self.time_scale.x_to_index(Px(p.x - plot.x));
3211        let price = pn
3212            .price_scale
3213            .y_to_price(f64::from(p.y), f64::from(plot.y), f64::from(plot.h));
3214        let time = self.time_index.time_at(logical_index.round() as i64);
3215        let target = drawing
3216            .or_else(|| self.hit_drawing(pane, p).map(|(d, _)| d))
3217            .map(ClickTarget::Drawing)
3218            .or_else(|| self.hit_marker(pane, p))
3219            .or_else(|| self.hit_series(pane, p).map(ClickTarget::Series));
3220        self.events.push(ChartEvent::Click {
3221            pos: PointCss {
3222                x: p.x / self.dpr,
3223                y: p.y / self.dpr,
3224            },
3225            pane,
3226            logical_index,
3227            time,
3228            price,
3229            target,
3230        });
3231    }
3232
3233    /// The marker of `pane` under `p` in the last frame.
3234    fn hit_marker(&self, pane: PaneId, p: PointPx) -> Option<ClickTarget> {
3235        let tol = HIT_TOLERANCE * 0.5 * self.dpr;
3236        self.marker_hits
3237            .iter()
3238            .rev()
3239            .find(|m| m.pane == pane && (p.x - m.pos.x).hypot(p.y - m.pos.y) <= m.radius + tol)
3240            .map(|m| ClickTarget::Marker {
3241                series: m.series,
3242                index: m.index,
3243            })
3244    }
3245
3246    /// The topmost series of `pane` under `p`: on a candle's body or
3247    /// wick, within the tolerance of a line, inside a bar, on a dot.
3248    fn hit_series(&self, pane: PaneId, p: PointPx) -> Option<SeriesId> {
3249        let pn = self.panes.get(self.pane_index(pane)?)?;
3250        let plot = pn.plot;
3251        let (top, height) = (f64::from(plot.y), f64::from(plot.h));
3252        let has_price = self
3253            .series
3254            .iter()
3255            .any(|e| e.pane == pane && !volume_like(e) && !e.store.is_empty());
3256        let tol = HIT_TOLERANCE * self.dpr;
3257        let m = crate::transform_helpers::bar_metrics(self.time_scale.bar_spacing() as f32);
3258        let half_bar = (m.body * 0.5).max(tol * 0.5);
3259        let center = self.time_scale.x_to_index(Px(p.x - plot.x)).round() as i64;
3260        let within = |a: f32, b: f32| p.y >= a.min(b) - 1.0 && p.y <= a.max(b) + 1.0;
3261        for e in self.series.iter().rev().filter(|e| e.pane == pane) {
3262            let (store, shift) = if e.kind == SeriesKind::Volume {
3263                let src = e
3264                    .opts
3265                    .source
3266                    .and_then(|s| self.series.iter().find(|x| x.id == s));
3267                let Some(src) = src else { continue };
3268                (&src.store, 0)
3269            } else {
3270                (&e.store, i64::from(e.opts.shift))
3271            };
3272            let x_of = |j: i64| plot.x + self.time_scale.index_to_x((j + shift) as f64).0;
3273            let y_of = |v: f64| -> Option<f32> {
3274                let y = if volume_like(e) {
3275                    let scale = if has_price {
3276                        &pn.volume_scale
3277                    } else {
3278                        &pn.price_scale
3279                    };
3280                    scale.price_to_y(v, top, height)
3281                } else {
3282                    pn.price_scale.price_to_y(e.norm?.apply(v), top, height)
3283                };
3284                y.is_finite().then_some(y as f32)
3285            };
3286            let point = |j: i64| -> Option<PointPx> {
3287                let v = store.bar_at(j)?[3];
3288                Some(PointPx {
3289                    x: x_of(j),
3290                    y: y_of(v)?,
3291                })
3292            };
3293            let j = center - shift;
3294            let hit = match e.kind {
3295                k if is_ohlc_kind(k) => (|| {
3296                    let [o, h, l, c] = store.bar_at(j)?;
3297                    let dx = (p.x - x_of(j)).abs();
3298                    let (yo, yh, yl, yc) = (y_of(o)?, y_of(h)?, y_of(l)?, y_of(c)?);
3299                    Some(
3300                        (dx <= tol * 0.5 && within(yh, yl))
3301                            || (dx <= m.body * 0.5 && within(yo, yc)),
3302                    )
3303                })(),
3304                SeriesKind::Volume | SeriesKind::Histogram => (|| {
3305                    let (v, base) = if e.kind == SeriesKind::Volume {
3306                        (store.volume_at(j)?, 0.0)
3307                    } else {
3308                        (store.bar_at(j)?[3], e.opts.base_value)
3309                    };
3310                    let dx = (p.x - x_of(j)).abs();
3311                    Some(dx <= half_bar && within(y_of(v)?, y_of(base)?))
3312                })(),
3313                SeriesKind::Points => point(j).map(|c| {
3314                    let r = e.opts.line_width.to_px(self.dpr).0 * 0.5;
3315                    (p.x - c.x).hypot(p.y - c.y) <= r + tol * 0.5
3316                }),
3317                SeriesKind::Line | SeriesKind::Area | SeriesKind::Baseline => point(j).map(|c| {
3318                    [point(j - 1), point(j + 1)]
3319                        .into_iter()
3320                        .map(|n| {
3321                            n.map_or_else(
3322                                || (p.x - c.x).hypot(p.y - c.y),
3323                                |n| segment_distance(p, c, n),
3324                            )
3325                        })
3326                        .fold(f32::INFINITY, f32::min)
3327                        <= tol
3328                }),
3329                _ => None,
3330            };
3331            if hit == Some(true) {
3332                return Some(e.id);
3333            }
3334        }
3335        None
3336    }
3337
3338    /// Drops the bands of removed series.
3339    fn prune_bands(&mut self) {
3340        let series = &self.series;
3341        self.bands.retain(|b| {
3342            series.iter().any(|e| e.id == b.upper) && series.iter().any(|e| e.id == b.lower)
3343        });
3344    }
3345
3346    /// Adds a layer plugin to a pane, or to the whole chart (`pane: None`),
3347    /// drawn after the plugins added before it. See
3348    /// [`LayerPlugin`] for an example.
3349    ///
3350    /// # Errors
3351    ///
3352    /// [`Error::UnknownId`] if the pane does not exist;
3353    /// [`Error::OutOfMemory`].
3354    pub fn add_layer(
3355        &mut self,
3356        pane: Option<PaneId>,
3357        plugin: Box<dyn LayerPlugin>,
3358    ) -> Result<LayerPluginId> {
3359        if pane.is_some_and(|p| self.pane_index(p).is_none()) {
3360            return Err(Error::UnknownId);
3361        }
3362        let id = LayerPluginId(self.next_layer);
3363        self.next_layer = self.next_layer.checked_add(1).ok_or(Error::OutOfMemory)?;
3364        self.layer_plugins
3365            .try_reserve(1)
3366            .map_err(|_| Error::OutOfMemory)?;
3367        self.layer_plugins.push(LayerEntry {
3368            id,
3369            pane,
3370            position: plugin.position(),
3371            plugin,
3372        });
3373        self.invalidation = self.invalidation.max(Invalidation::Light);
3374        Ok(id)
3375    }
3376
3377    /// Removes a layer plugin. Plugins of a pane are also removed with the
3378    /// pane.
3379    ///
3380    /// # Errors
3381    ///
3382    /// [`Error::UnknownId`] if it does not exist.
3383    pub fn remove_layer(&mut self, id: LayerPluginId) -> Result<()> {
3384        let n = self
3385            .layer_plugins
3386            .iter()
3387            .position(|l| l.id == id)
3388            .ok_or(Error::UnknownId)?;
3389        self.layer_plugins.remove(n);
3390        self.invalidation = self.invalidation.max(Invalidation::Light);
3391        Ok(())
3392    }
3393
3394    /// Requests a redraw after a layer plugin's own content changed.
3395    ///
3396    /// # Errors
3397    ///
3398    /// [`Error::UnknownId`] if it does not exist.
3399    pub fn invalidate_layer(&mut self, id: LayerPluginId) -> Result<()> {
3400        if !self.layer_plugins.iter().any(|l| l.id == id) {
3401            return Err(Error::UnknownId);
3402        }
3403        self.invalidation = self.invalidation.max(Invalidation::Light);
3404        Ok(())
3405    }
3406
3407    /// Layer plugins of pane `i` (or chart-wide ones, `None`) at `position`.
3408    fn emit_layers(
3409        &mut self,
3410        pane: Option<usize>,
3411        position: LayerPosition,
3412        text: &dyn TextMeasurer,
3413    ) {
3414        let pane_id = match pane {
3415            Some(i) => match self.panes.get(i) {
3416                Some(p) => Some(p.id),
3417                None => return,
3418            },
3419            None => None,
3420        };
3421        if !self
3422            .layer_plugins
3423            .iter()
3424            .any(|l| l.pane == pane_id && l.position == position)
3425        {
3426            return;
3427        }
3428        let norm = pane.and_then(|i| self.drawing_norm(i));
3429        let (rect, coords) = match pane {
3430            Some(i) => {
3431                let p = &self.panes[i];
3432                let coords = (!self.time_index.is_empty() && p.has_content)
3433                    .then_some(norm)
3434                    .flatten()
3435                    .map(|norm| DrawingCtx {
3436                        index: &self.time_index,
3437                        time_scale: &self.time_scale,
3438                        price_scale: &p.price_scale,
3439                        norm,
3440                        plot: p.plot,
3441                        dpr: self.dpr,
3442                        labels: p.labels,
3443                        text,
3444                    });
3445                (p.plot, coords)
3446            }
3447            None => (
3448                RectPx {
3449                    x: 0.0,
3450                    y: 0.0,
3451                    w: self.layout.price_axis.x,
3452                    h: self.layout.price_axis.h,
3453                },
3454                None,
3455            ),
3456        };
3457        let ctx = LayerCtx {
3458            rect,
3459            dpr: self.dpr,
3460            text,
3461            coords,
3462        };
3463        let layer = match position {
3464            LayerPosition::Background => LayerId::Background,
3465            LayerPosition::BelowSeries | LayerPosition::AboveSeries => LayerId::Main,
3466            LayerPosition::Overlay => LayerId::Overlay,
3467        };
3468        // Pane layers next to the series are revealed with them.
3469        let clip = match (pane, position) {
3470            (Some(_), LayerPosition::BelowSeries | LayerPosition::AboveSeries) => {
3471                self.data_clip(rect)
3472            }
3473            _ => rect,
3474        };
3475        let frame = &mut self.frame;
3476        frame.push_cmd(layer, DrawCmd::PushClip(clip));
3477        for l in &self.layer_plugins {
3478            if l.pane == pane_id && l.position == position {
3479                l.plugin.build(
3480                    &ctx,
3481                    &mut FrameBuilder {
3482                        frame: &mut *frame,
3483                        layer,
3484                    },
3485                );
3486            }
3487        }
3488        frame.push_cmd(layer, DrawCmd::PopClip);
3489    }
3490
3491    /// Price map of the drawings of pane `i`: the map of the pane's first
3492    /// price series; `None` if a relative scale has no base yet.
3493    pub(crate) fn drawing_norm(&self, i: usize) -> Option<Normalize> {
3494        let pane = self.panes.get(i)?;
3495        if !pane.price_scale.mode().is_relative() {
3496            return Some(Normalize::IDENTITY);
3497        }
3498        self.series
3499            .iter()
3500            .find(|e| e.pane == pane.id && !e.derived && e.kind != SeriesKind::Volume)
3501            .and_then(|e| e.norm)
3502    }
3503
3504    /// The coordinate context of drawings on pane `i`.
3505    pub(crate) fn drawing_ctx<'a>(
3506        &'a self,
3507        i: usize,
3508        text: &'a dyn TextMeasurer,
3509    ) -> Option<DrawingCtx<'a>> {
3510        let pane = self.panes.get(i)?;
3511        if self.time_index.is_empty() || !pane.has_content {
3512            return None;
3513        }
3514        Some(DrawingCtx {
3515            index: &self.time_index,
3516            time_scale: &self.time_scale,
3517            price_scale: &pane.price_scale,
3518            norm: self.drawing_norm(i)?,
3519            plot: pane.plot,
3520            dpr: self.dpr,
3521            labels: pane.labels,
3522            text,
3523        })
3524    }
3525
3526    /// The drawings of pane `i` (main layer, above series and markers) and
3527    /// the handles of the selected one; records their screen bounds.
3528    fn emit_drawings(&mut self, i: usize, text: &dyn TextMeasurer) {
3529        let Some(pane) = self.panes.get(i) else {
3530            return;
3531        };
3532        let (id, plot) = (pane.id, pane.plot);
3533        if !self.drawings.entries.iter().any(|e| e.pane == id) {
3534            return;
3535        }
3536        let Some(norm) = self.drawing_norm(i) else {
3537            return;
3538        };
3539        if self.time_index.is_empty() || !pane.has_content {
3540            return;
3541        }
3542        let ctx = DrawingCtx {
3543            index: &self.time_index,
3544            time_scale: &self.time_scale,
3545            price_scale: &pane.price_scale,
3546            norm,
3547            plot,
3548            dpr: self.dpr,
3549            labels: pane.labels,
3550            text,
3551        };
3552        let clip = self.data_clip(plot);
3553        let frame = &mut self.frame;
3554        frame.push_cmd(LayerId::Main, DrawCmd::PushClip(clip));
3555        let selected = self.drawings.selected();
3556        let mut handles = self.handle_buf.borrow_mut();
3557        handles.clear();
3558        for e in &mut self.drawings.entries {
3559            if e.pane != id {
3560                continue;
3561            }
3562            let mark = PoolMark::of(frame);
3563            if e.visible {
3564                e.tool.build(
3565                    &ctx,
3566                    &mut FrameBuilder {
3567                        frame: &mut *frame,
3568                        layer: LayerId::Main,
3569                    },
3570                );
3571            }
3572            e.bbox = mark.bounds(frame, &ctx);
3573            if e.visible && selected == Some(e.id) {
3574                e.tool.handles(&ctx, &mut handles);
3575            }
3576        }
3577        // Handles: rings in the line color around the background color.
3578        let outer = (HANDLE_CSS * self.dpr).round();
3579        let inner = (outer - 2.0 * (1.5 * self.dpr).round()).max(2.0);
3580        let color = selected
3581            .and_then(|s| self.drawings.entry(s))
3582            .map_or(self.theme.line, |e| e.tool.style().line);
3583        for p in handles.iter() {
3584            let pos = PointPx {
3585                x: p.x.round(),
3586                y: p.y.round(),
3587            };
3588            for (size, c) in [(outer, color), (inner, self.theme.background)] {
3589                frame.push_icon(
3590                    LayerId::Main,
3591                    crate::frame::IconInst {
3592                        pos,
3593                        size: Px(size),
3594                        icon: crate::transform_helpers::ICON_CIRCLE,
3595                        color: c,
3596                    },
3597                );
3598            }
3599        }
3600        frame.push_cmd(LayerId::Main, DrawCmd::PopClip);
3601    }
3602
3603    /// Adds an event, replacing a pending one of the same kind for
3604    /// position-like events.
3605    pub(crate) fn push_event(&mut self, event: ChartEvent) {
3606        let coalesce = matches!(
3607            event,
3608            ChartEvent::CrosshairMove { .. }
3609                | ChartEvent::VisibleRangeChanged { .. }
3610                | ChartEvent::Sync(_)
3611        );
3612        let same_kind = |e: &ChartEvent| match (e, &event) {
3613            (ChartEvent::Sync(a), ChartEvent::Sync(b)) => {
3614                core::mem::discriminant(a) == core::mem::discriminant(b)
3615            }
3616            _ => core::mem::discriminant(e) == core::mem::discriminant(&event),
3617        };
3618        if coalesce && let Some(e) = self.events.iter_mut().find(|e| same_kind(e)) {
3619            *e = event;
3620            return;
3621        }
3622        self.events.push(event);
3623    }
3624
3625    fn emit_view_events(&mut self) {
3626        if self.time_index.is_empty() {
3627            return;
3628        }
3629        let (from, to) = self.time_scale.visible_range();
3630        if (from, to) != self.last_range {
3631            self.last_range = (from, to);
3632            self.push_event(ChartEvent::VisibleRangeChanged { from, to });
3633        }
3634        let first = self.time_index.first_index();
3635        let before = from.floor() as i64 - first;
3636        if (before as f64) < to - from && self.history_requested != Some(first) {
3637            self.history_requested = Some(first);
3638            self.push_event(ChartEvent::NeedMoreHistory {
3639                bars_before_start: before,
3640            });
3641        }
3642    }
3643
3644    /// Values at logical index `j` of the first OHLC series that has a bar
3645    /// there.
3646    fn bar_at(&self, j: i64) -> Option<BarValues> {
3647        let (e, [open, high, low, close]) = self
3648            .series
3649            .iter()
3650            .filter(|e| is_ohlc_kind(e.kind))
3651            .find_map(|e| Some((e, e.store.bar_at(j)?)))?;
3652        Some(BarValues {
3653            open,
3654            high,
3655            low,
3656            close,
3657            volume: e.store.volume_at(j),
3658        })
3659    }
3660
3661    /// The bar a magnet snaps to at logical index `j` of `pane`: that of the
3662    /// pane's first price series, in its own prices.
3663    pub(crate) fn magnet_bar(&self, pane: PaneId, j: i64) -> Option<[f64; 4]> {
3664        self.series
3665            .iter()
3666            .find(|e| e.pane == pane && !volume_like(e) && !e.store.is_empty())
3667            .and_then(|e| e.store.bar_at(j - i64::from(e.opts.shift)))
3668    }
3669
3670    /// Index of the pane whose plot contains `p`.
3671    pub(crate) fn pane_at(&self, p: PointPx) -> Option<usize> {
3672        self.panes.iter().position(|pane| pane.plot.contains(p))
3673    }
3674
3675    /// The crosshair in the overlay layer, and its `CrosshairMove` event.
3676    /// The vertical line crosses every pane; the horizontal line and the price
3677    /// label belong to the pane under the pointer. Without a pointer over the
3678    /// plot, a crosshair received from a synced chart is drawn as the
3679    /// vertical line and time label only. Returns the logical index under the
3680    /// pointer.
3681    fn emit_crosshair(&mut self, time_h: f32, pad: f32, font: FontStyleRef) -> Option<i64> {
3682        let hovered = self
3683            .input
3684            .pointer
3685            .filter(|_| self.input.crosshair != CrosshairMode::Hidden && !self.revealing())
3686            .and_then(|p| Some((p, self.pane_at(p)?)));
3687        let local = hovered.and_then(|(p, i)| {
3688            let pane = self.panes.get(i)?;
3689            let plot = pane.plot;
3690            let idx = self.time_scale.x_to_index(Px(p.x - plot.x)).round() as i64;
3691            let x = plot.x + self.time_scale.index_to_x_f64(idx as f64) as f32;
3692            let bar = self.bar_at(idx);
3693            let (top, height) = (f64::from(plot.y), f64::from(plot.h));
3694            let mut y = p.y;
3695            let magnet = self
3696                .series
3697                .iter()
3698                .find(|e| e.pane == pane.id && !volume_like(e) && !e.store.is_empty())
3699                .and_then(|e| Some((e.store.bar_at(idx - i64::from(e.opts.shift))?, e.norm?)));
3700            if self.input.crosshair == CrosshairMode::Magnet
3701                && let Some((b, norm)) = magnet
3702            {
3703                let mut best = f32::INFINITY;
3704                for v in b {
3705                    let vy = pane.price_scale.price_to_y(norm.apply(v), top, height) as f32;
3706                    if (vy - p.y).abs() < (best - p.y).abs() {
3707                        best = vy;
3708                    }
3709                }
3710                if best.is_finite() {
3711                    y = best.clamp(plot.y, plot.bottom() - 1.0);
3712                }
3713            }
3714            let price = pane.price_scale.y_to_price(f64::from(y), top, height);
3715            Some((
3716                Some((i, y)),
3717                x,
3718                CrosshairPoint {
3719                    logical_index: idx,
3720                    time: self.time_index.time_at(idx),
3721                    pane: pane.id,
3722                    price,
3723                    bar,
3724                },
3725            ))
3726        });
3727        let local_index = local.map(|(_, _, c)| c.logical_index);
3728        let point = local.or_else(|| {
3729            if self.input.crosshair == CrosshairMode::Hidden {
3730                return None;
3731            }
3732            let idx = self.remote_crosshair_index()?;
3733            let plot = self.panes.first()?.plot;
3734            let x = plot.x + self.time_scale.index_to_x_f64(idx as f64) as f32;
3735            Some((
3736                None,
3737                x,
3738                CrosshairPoint {
3739                    logical_index: idx,
3740                    time: self.time_index.time_at(idx),
3741                    pane: self.main_pane(),
3742                    price: f64::NAN,
3743                    bar: self.bar_at(idx),
3744                },
3745            ))
3746        });
3747        let event_point = point.map(|(_, _, c)| c);
3748        if !same_crosshair(event_point.as_ref(), self.last_crosshair.as_ref()) {
3749            self.last_crosshair = event_point;
3750            self.push_event(ChartEvent::CrosshairMove { point: event_point });
3751        }
3752        let (row, x, info) = point?;
3753        let plot0 = self.panes.first().map_or(RectPx::default(), |p| p.plot);
3754        if row.is_none() && !(x >= plot0.x && x < plot0.right()) {
3755            return local_index;
3756        }
3757        let stroke = StrokeStyle {
3758            width: Px(1.0),
3759            color: self.theme.crosshair,
3760            dash: LineDash::Dashed,
3761        };
3762        let cx = x.floor() + 0.5;
3763        for k in 0..self.panes.len() {
3764            let plot = self.panes[k].plot;
3765            let (from, to) = (
3766                PointPx { x: cx, y: plot.y },
3767                PointPx {
3768                    x: cx,
3769                    y: plot.bottom(),
3770                },
3771            );
3772            self.frame
3773                .push_line(LayerId::Overlay, LineInst { from, to, stroke });
3774        }
3775        let bg = Some(LabelBg {
3776            color: self.theme.crosshair_label_bg,
3777            padding: Px((pad * 0.5).round()),
3778        });
3779        let color = self.theme.crosshair_label_text;
3780        if let Some((i, y)) = row
3781            && let Some(pane) = self.panes.get(i)
3782        {
3783            let (plot, labels) = (pane.plot, pane.labels);
3784            let cy = y.floor() + 0.5;
3785            let (from, to) = (
3786                PointPx { x: plot.x, y: cy },
3787                PointPx {
3788                    x: plot.right(),
3789                    y: cy,
3790                },
3791            );
3792            self.frame
3793                .push_line(LayerId::Overlay, LineInst { from, to, stroke });
3794            let start = self.frame.pools.text.len();
3795            write_label(&mut self.frame.pools.text, info.price, labels);
3796            let span = Span {
3797                start: u32::try_from(start).unwrap_or(0),
3798                len: u32::try_from(self.frame.pools.text.len() - start).unwrap_or(0),
3799            };
3800            self.frame.push_text(
3801                LayerId::Overlay,
3802                TextRun {
3803                    pos: PointPx {
3804                        x: plot.right() + pad,
3805                        y: y.round(),
3806                    },
3807                    text: span,
3808                    style: font,
3809                    color,
3810                    align: TextAlign::Left,
3811                    bg,
3812                },
3813            );
3814        }
3815        if let Some(t) = info.time {
3816            let mut s = StackStr::<32>::new();
3817            if format_crosshair_time(t + self.tz.offset_ms(t), &mut s).is_ok() {
3818                let span = self.frame.push_str(s.as_str());
3819                self.frame.push_text(
3820                    LayerId::Overlay,
3821                    TextRun {
3822                        pos: PointPx {
3823                            x: x.round(),
3824                            y: (self.layout.time_axis.y + time_h * 0.5).round(),
3825                        },
3826                        text: span,
3827                        style: font,
3828                        color,
3829                        align: TextAlign::Center,
3830                        bg,
3831                    },
3832                );
3833            }
3834        }
3835        local_index
3836    }
3837
3838    /// Chooses time labels: candidates by calendar weight, highest weight first,
3839    /// keeping labels at least 1.5 label widths apart.
3840    fn place_time_ticks(&mut self, text: &dyn TextMeasurer, font: FontStyleRef) {
3841        self.placed.clear();
3842        if self.time_index.is_empty() {
3843            return;
3844        }
3845        let spacing = self.time_scale.bar_spacing();
3846        let mut shift = 0;
3847        while ((1_u64 << shift) as f64) * spacing < TICK_SAMPLE_PX && shift < 40 {
3848            shift += 1;
3849        }
3850        let (from, to) = self.time_scale.visible_range();
3851        collect_ticks(
3852            &self.time_index,
3853            self.tz.as_ref(),
3854            from.floor() as i64,
3855            to.ceil() as i64,
3856            shift,
3857            &mut self.time_ticks,
3858        );
3859        self.time_ticks
3860            .sort_unstable_by(|a, b| b.weight.cmp(&a.weight).then(a.index.cmp(&b.index)));
3861        let plot_w = self.layout.plot.w;
3862        for &tick in &self.time_ticks {
3863            let x = self.time_scale.index_to_x_f64(tick.index as f64) as f32;
3864            let Some(label) = self.tick_label(tick) else {
3865                continue;
3866            };
3867            let width = text_width(text, label.as_str(), font);
3868            if x - width * 0.5 < 0.0 || x + width * 0.5 > plot_w {
3869                continue;
3870            }
3871            let free = self
3872                .placed
3873                .iter()
3874                .all(|p| (p.x - x).abs() >= 1.5 * p.width.max(width));
3875            if free && self.placed.len() < self.placed.capacity() {
3876                self.placed.push(PlacedTick { x, width, tick });
3877            }
3878        }
3879    }
3880
3881    fn tick_label(&self, tick: TimeTick) -> Option<StackStr<32>> {
3882        let t = self.time_index.time_at(tick.index)?;
3883        let mut s = StackStr::<32>::new();
3884        format_tick(t + self.tz.offset_ms(t), tick.weight, &mut s).ok()?;
3885        Some(s)
3886    }
3887
3888    fn line(from: PointPx, to: PointPx, color: crate::geom::Rgba) -> LineInst {
3889        LineInst {
3890            from,
3891            to,
3892            stroke: StrokeStyle {
3893                width: Px(1.0),
3894                color,
3895                dash: LineDash::Solid,
3896            },
3897        }
3898    }
3899
3900    fn emit_grid(&mut self, i: usize) {
3901        let grid = self.theme.grid;
3902        let Some(plot) = self.panes.get(i).map(|p| p.plot) else {
3903            return;
3904        };
3905        for k in 0..self.panes[i].ticks.len() {
3906            let pane = &self.panes[i];
3907            let y = pane
3908                .price_scale
3909                .price_to_y(pane.ticks[k], f64::from(plot.y), f64::from(plot.h))
3910                as f32;
3911            let y = y.floor() + 0.5;
3912            if y > plot.y && y < plot.bottom() {
3913                let l = Self::line(
3914                    PointPx { x: plot.x, y },
3915                    PointPx { x: plot.right(), y },
3916                    grid,
3917                );
3918                self.frame.push_line(LayerId::Background, l);
3919            }
3920        }
3921        for k in 0..self.placed.len() {
3922            let x = self.placed[k].x.floor() + 0.5 + plot.x;
3923            let l = Self::line(
3924                PointPx { x, y: plot.y },
3925                PointPx {
3926                    x,
3927                    y: plot.bottom(),
3928                },
3929                grid,
3930            );
3931            self.frame.push_line(LayerId::Background, l);
3932        }
3933    }
3934
3935    /// Element range and x mapping of `view` for the visible range, for a
3936    /// series drawn `shift` bars later.
3937    fn draw_range(
3938        &self,
3939        view: &OhlcLevelView<'_>,
3940        plot: RectPx,
3941        shift: i32,
3942    ) -> (crate::data::IdxSpan, XTransform) {
3943        let (from, to) = self.time_scale.visible_range();
3944        let shift = f64::from(shift);
3945        let span = visible_span(view, from - shift, to - shift);
3946        let k = u32::from(view.level);
3947        let size = (1_i64 << k) as f64;
3948        let center = if k == 0 {
3949            span.start as f64
3950        } else {
3951            bucket_start(span.start, k) as f64 + (size - 1.0) * 0.5
3952        };
3953        let xt = XTransform {
3954            base: span.start,
3955            step: (self.time_scale.bar_spacing() * size) as f32,
3956            offset: (f64::from(plot.x) + self.time_scale.index_to_x_f64(center + shift)) as f32,
3957        };
3958        (span, xt)
3959    }
3960
3961    /// The series of pane `i`: volume series first, then the others in the
3962    /// order they were added.
3963    fn emit_series(&mut self, i: usize, text: &dyn TextMeasurer) {
3964        let Some(pane) = self.panes.get(i) else {
3965            return;
3966        };
3967        let (id, plot) = (pane.id, pane.plot);
3968        let clip = self.data_clip(plot);
3969        self.frame.push_cmd(LayerId::Main, DrawCmd::PushClip(clip));
3970        let has_price = self
3971            .series
3972            .iter()
3973            .any(|e| e.pane == id && !volume_like(e) && !e.store.is_empty());
3974        for volumes in [true, false] {
3975            if !volumes {
3976                for b in 0..self.bands.len() {
3977                    self.emit_band(i, b);
3978                }
3979            }
3980            for k in 0..self.series.len() {
3981                let e = &self.series[k];
3982                if e.pane == id && (e.kind == SeriesKind::Volume) == volumes {
3983                    match e.kind {
3984                        SeriesKind::Custom => self.emit_custom(i, k, text),
3985                        SeriesKind::Kagi | SeriesKind::PointFigure => self.emit_figure(i, k),
3986                        _ => self.emit_one(i, k, has_price),
3987                    }
3988                }
3989            }
3990        }
3991        self.frame.push_cmd(LayerId::Main, DrawCmd::PopClip);
3992    }
3993
3994    /// One `SeriesDraw` for series `k` in pane `i`.
3995    fn emit_one(&mut self, i: usize, k: usize, has_price: bool) {
3996        let (Some(pane), Some(e)) = (self.panes.get(i), self.series.get(k)) else {
3997            return;
3998        };
3999        let plot = pane.plot;
4000        let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4001        let (data_id, store) = if e.kind == SeriesKind::Volume {
4002            let Some(src) = e
4003                .opts
4004                .source
4005                .and_then(|s| self.series.iter().find(|x| x.id == s))
4006            else {
4007                return;
4008            };
4009            if !src.store.has_volume() {
4010                return;
4011            }
4012            (src.id, &src.store)
4013        } else {
4014            (e.id, &e.store)
4015        };
4016        let Some(log) = store.log() else { return };
4017        if store.is_empty() {
4018            return;
4019        }
4020        let level = lod_level(store.lod(), self.time_scale.bar_spacing());
4021        let Some(view) = store.level_view(level) else {
4022            return;
4023        };
4024        let shift = if e.kind == SeriesKind::Volume {
4025            0
4026        } else {
4027            e.opts.shift
4028        };
4029        let (span, xt) = self.draw_range(&view, plot, shift);
4030        let yt = if volume_like(e) {
4031            if has_price {
4032                pane.volume_scale.transform(top, height)
4033            } else {
4034                pane.price_scale.transform(top, height)
4035            }
4036        } else {
4037            // A relative scale without a base for this series: nothing to draw.
4038            let Some(norm) = e.norm else { return };
4039            pane.price_scale.series_transform(top, height, norm)
4040        };
4041        let generation = log.generation();
4042        let (kind, style) = (e.kind, self.style_of(e));
4043        let style = self.frame.push_style(style);
4044        self.frame.push_cmd(
4045            LayerId::Main,
4046            DrawCmd::Series(SeriesDraw {
4047                series: data_id,
4048                generation,
4049                style,
4050                kind,
4051                lod_level: level,
4052                index_range: span,
4053                x_transform: xt,
4054                y_transform: yt,
4055                clip: plot,
4056                pair: None,
4057            }),
4058        );
4059    }
4060
4061    /// The `SeriesDraw` of band `b` if it is in pane `i`. Not drawn when the
4062    /// two series are mapped differently (different shifts, or relative
4063    /// price scales with different bases).
4064    fn emit_band(&mut self, i: usize, b: usize) {
4065        let (Some(pane), Some(band)) = (self.panes.get(i), self.bands.get(b)) else {
4066            return;
4067        };
4068        let find = |id: SeriesId| self.series.iter().find(|e| e.id == id);
4069        let (Some(u), Some(l)) = (find(band.upper), find(band.lower)) else {
4070            return;
4071        };
4072        if u.pane != pane.id || u.store.is_empty() || l.store.is_empty() {
4073            return;
4074        }
4075        let (Some(norm), Some(lower_norm)) = (u.norm, l.norm) else {
4076            return;
4077        };
4078        if norm != lower_norm || u.opts.shift != l.opts.shift {
4079            return;
4080        }
4081        let (Some(ul), Some(ll)) = (u.store.log(), l.store.log()) else {
4082            return;
4083        };
4084        let level = lod_level(u.store.lod(), self.time_scale.bar_spacing());
4085        let (Some(view), Some(_)) = (u.store.level_view(level), l.store.level_view(level)) else {
4086            return;
4087        };
4088        let plot = pane.plot;
4089        let (span, xt) = self.draw_range(&view, plot, u.opts.shift);
4090        let yt = pane
4091            .price_scale
4092            .series_transform(f64::from(plot.y), f64::from(plot.h), norm);
4093        let generation = ul
4094            .generation()
4095            .wrapping_add(ll.generation().rotate_left(32));
4096        let fill = band
4097            .opts
4098            .fill
4099            .unwrap_or_else(|| self.style_of(u).up.with_alpha(0x26));
4100        let style = SeriesStyle {
4101            fill_top: fill,
4102            fill_bottom: band.opts.fill_crossed.unwrap_or(fill),
4103            ..SeriesStyle::default()
4104        };
4105        let (upper, lower) = (band.upper, band.lower);
4106        let style = self.frame.push_style(style);
4107        self.frame.push_cmd(
4108            LayerId::Main,
4109            DrawCmd::Series(SeriesDraw {
4110                series: upper,
4111                generation,
4112                style,
4113                kind: SeriesKind::Band,
4114                lod_level: level,
4115                index_range: span,
4116                x_transform: xt,
4117                y_transform: yt,
4118                clip: plot,
4119                pair: Some(lower),
4120            }),
4121        );
4122    }
4123
4124    /// The primitives of custom series `k` in pane `i`.
4125    fn emit_custom(&mut self, i: usize, k: usize, text: &dyn TextMeasurer) {
4126        let (Some(pane), Some(e)) = (self.panes.get(i), self.series.get(k)) else {
4127            return;
4128        };
4129        let (Some(c), Some(norm)) = (e.store.custom(), e.norm) else {
4130            return;
4131        };
4132        let shift = f64::from(e.opts.shift);
4133        let (from, to) = self.time_scale.visible_range();
4134        let visible = c.points_in(&self.time_index, from - shift, to - shift);
4135        if visible.0 >= visible.1 {
4136            return;
4137        }
4138        let ctx = SeriesCtx {
4139            coords: DrawingCtx {
4140                index: &self.time_index,
4141                time_scale: &self.time_scale,
4142                price_scale: &pane.price_scale,
4143                norm,
4144                plot: pane.plot,
4145                dpr: self.dpr,
4146                labels: pane.labels,
4147                text,
4148            },
4149            store: c,
4150            shift,
4151            visible,
4152            style: self.style_of(e),
4153        };
4154        if !self.native_kinds.contains(&c.kind) {
4155            c.plugin.build(
4156                &ctx,
4157                visible.0,
4158                visible.1,
4159                &mut FrameBuilder {
4160                    frame: &mut self.frame,
4161                    layer: LayerId::Main,
4162                },
4163            );
4164            return;
4165        }
4166        let mut params = [0.0; 8];
4167        c.plugin.native_params(&ctx, &mut params);
4168        let plot = pane.plot;
4169        let base = from.floor() as i64;
4170        let x_transform = XTransform {
4171            base,
4172            step: self.time_scale.bar_spacing() as f32,
4173            offset: (f64::from(plot.x) + self.time_scale.index_to_x_f64(base as f64 + shift))
4174                as f32,
4175        };
4176        let y_transform =
4177            pane.price_scale
4178                .series_transform(f64::from(plot.y), f64::from(plot.h), norm);
4179        let (series, generation, kind) = (e.id, c.log.generation(), c.kind);
4180        let style = self.frame.push_style(ctx.style);
4181        let points = IdxSpan {
4182            start: i64::try_from(visible.0).unwrap_or(i64::MAX),
4183            end: i64::try_from(visible.1).unwrap_or(i64::MAX),
4184        };
4185        self.frame.push_cmd(
4186            LayerId::Main,
4187            DrawCmd::Custom(CustomDraw {
4188                series,
4189                generation,
4190                kind,
4191                points,
4192                x_transform,
4193                y_transform,
4194                style,
4195                params,
4196                clip: plot,
4197            }),
4198        );
4199    }
4200
4201    /// Kagi lines or Point & Figure marks of transform series `k` in pane
4202    /// `i`, as primitives. Below 1 px per element, one min–max line
4203    /// per pixel column (from the LOD levels), so the primitives never
4204    /// outnumber the plot's pixel columns.
4205    fn emit_figure(&mut self, i: usize, k: usize) {
4206        let (Some(pane), Some(e)) = (self.panes.get(i), self.series.get(k)) else {
4207            return;
4208        };
4209        let (Some(t), Some(norm)) = (e.store.transform(), e.norm) else {
4210            return;
4211        };
4212        let style = self.style_of(e);
4213        let out = &t.out;
4214        if out.len() == 0 {
4215            return;
4216        }
4217        let plot = pane.plot;
4218        let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4219        let scale = &pane.price_scale;
4220        let ts = &self.time_scale;
4221        let y = |p: f64| -> Option<f32> {
4222            let y = scale.price_to_y(norm.apply(p), top, height);
4223            y.is_finite().then(|| y.clamp(-1e7, 1e7) as f32)
4224        };
4225        let shift = f64::from(e.opts.shift);
4226        let x = |j: f64| (f64::from(plot.x) + ts.index_to_x_f64(j + shift)) as f32;
4227        let spacing = ts.bar_spacing();
4228        let (from, to) = ts.visible_range();
4229        let mut b = FrameBuilder {
4230            frame: &mut self.frame,
4231            layer: LayerId::Main,
4232        };
4233        let thin = Px((style.line_width.0 / 2.0).max(1.0));
4234        let stroke = |flag: u8| StrokeStyle {
4235            width: if flag == 1 { style.line_width } else { thin },
4236            color: if flag == 1 { style.up } else { style.down },
4237            dash: LineDash::Solid,
4238        };
4239        if spacing < 1.0 {
4240            let level = lod_level(Some(out.lod()), spacing);
4241            let Some(view) = out.level_view(level) else {
4242                return;
4243            };
4244            let span = visible_span(&view, from - shift, to - shift);
4245            let lvl = u32::from(level);
4246            let size = (1_i64 << lvl) as f64;
4247            let one = StrokeStyle {
4248                width: Px(1.0),
4249                color: style.up,
4250                dash: LineDash::Solid,
4251            };
4252            // The current pixel column and its range of y.
4253            let mut col: Option<(f32, f32, f32)> = None;
4254            let flush = |b: &mut FrameBuilder<'_>, c: (f32, f32, f32)| {
4255                let x = c.0 + 0.5;
4256                b.line(
4257                    PointPx { x, y: c.1 },
4258                    PointPx {
4259                        x,
4260                        y: c.2.max(c.1 + 1.0),
4261                    },
4262                    one,
4263                );
4264            };
4265            for j in span.start..span.end {
4266                let center = if lvl == 0 {
4267                    j as f64
4268                } else {
4269                    bucket_start(j, lvl) as f64 + (size - 1.0) * 0.5
4270                };
4271                let (Some(hi), Some(lo)) =
4272                    (view.high.at(view.first, j), view.low.at(view.first, j))
4273                else {
4274                    continue;
4275                };
4276                let (Some(y0), Some(y1)) = (y(hi), y(lo)) else {
4277                    continue;
4278                };
4279                let px = x(center).floor();
4280                col = match col {
4281                    // Both are whole pixels.
4282                    Some(c) if (c.0 - px).abs() < 0.5 => Some((px, c.1.min(y0), c.2.max(y1))),
4283                    Some(c) => {
4284                        flush(&mut b, c);
4285                        Some((px, y0, y1))
4286                    }
4287                    None => Some((px, y0, y1)),
4288                };
4289            }
4290            if let Some(c) = col {
4291                flush(&mut b, c);
4292            }
4293            return;
4294        }
4295        let first = out.first();
4296        let a = ((from - shift).floor() as i64 - 1).max(first);
4297        let end = ((to - shift).ceil() as i64 + 2).min(out.end());
4298        let flag_at = |j: i64| {
4299            usize::try_from(j - first)
4300                .ok()
4301                .and_then(|p| t.flags.get(p).copied())
4302                .unwrap_or(0)
4303        };
4304        if e.kind == SeriesKind::Kagi {
4305            for j in a..end {
4306                let Some([open, _, _, close]) = out.bar_at(j) else {
4307                    continue;
4308                };
4309                let (Some(yo), Some(yc)) = (y(open), y(close)) else {
4310                    continue;
4311                };
4312                let xj = x(j as f64);
4313                let flag = flag_at(j);
4314                let prev = out.bar_at(j - 1);
4315                let start = if prev.is_some() { flag_at(j - 1) } else { flag };
4316                if prev.is_some() {
4317                    // The shoulder or waist joining the previous line.
4318                    let from = PointPx {
4319                        x: x((j - 1) as f64),
4320                        y: yo,
4321                    };
4322                    b.line(from, PointPx { x: xj, y: yo }, stroke(start));
4323                }
4324                match prev.and_then(|p| y(p[0])) {
4325                    // The thickness changes at the previous line's start.
4326                    Some(ys) if start != flag => {
4327                        b.line(
4328                            PointPx { x: xj, y: yo },
4329                            PointPx { x: xj, y: ys },
4330                            stroke(start),
4331                        );
4332                        b.line(
4333                            PointPx { x: xj, y: ys },
4334                            PointPx { x: xj, y: yc },
4335                            stroke(flag),
4336                        );
4337                    }
4338                    _ => b.line(
4339                        PointPx { x: xj, y: yo },
4340                        PointPx { x: xj, y: yc },
4341                        stroke(flag),
4342                    ),
4343                }
4344            }
4345            return;
4346        }
4347        // Point & Figure.
4348        let Some(size) = t.plugin.box_size().filter(|s| s.is_finite() && *s > 0.0) else {
4349            return;
4350        };
4351        let w = (spacing * 0.8) as f32;
4352        let mark = Px((style.line_width.0 * 0.75).max(1.0));
4353        for j in a..end {
4354            let Some([_, high, low, _]) = out.bar_at(j) else {
4355                continue;
4356            };
4357            let (Some(y_hi), Some(y_lo)) = (y(high), y(low)) else {
4358                continue;
4359            };
4360            let flag = flag_at(j);
4361            let color = if flag == 1 { style.up } else { style.down };
4362            let xc = x(j as f64);
4363            let boxes = ((high - low) / size).round();
4364            let box_px = (y_lo - y_hi).abs() / boxes.max(1.0) as f32;
4365            if spacing < 4.0 || box_px < 4.0 || boxes > 10_000.0 {
4366                let r = RectPx {
4367                    x: xc - w / 2.0,
4368                    y: y_hi.min(y_lo),
4369                    w: w.max(1.0),
4370                    h: (y_lo - y_hi).abs().max(1.0),
4371                };
4372                b.rect(r, color);
4373                continue;
4374            }
4375            let pen = StrokeStyle {
4376                width: mark,
4377                color,
4378                dash: LineDash::Solid,
4379            };
4380            let (l, r) = (xc - w / 2.0, xc + w / 2.0);
4381            for m in 0..boxes as i64 {
4382                let (Some(y0), Some(y1)) =
4383                    (y(low + m as f64 * size), y(low + (m + 1) as f64 * size))
4384                else {
4385                    continue;
4386                };
4387                // Inset so neighbouring boxes do not touch.
4388                let inset = (y0 - y1).abs() * 0.1;
4389                let (yb, yt) = (y0.max(y1) - inset, y0.min(y1) + inset);
4390                if flag == 1 {
4391                    b.line(PointPx { x: l, y: yt }, PointPx { x: r, y: yb }, pen);
4392                    b.line(PointPx { x: l, y: yb }, PointPx { x: r, y: yt }, pen);
4393                } else {
4394                    let (cy, rx, ry) = (f32::midpoint(yb, yt), w / 2.0, (yb - yt) / 2.0);
4395                    b.polyline(
4396                        (0..=CIRCLE_SEGMENTS).map(|s| {
4397                            let a =
4398                                f32::from(s) * core::f32::consts::TAU / f32::from(CIRCLE_SEGMENTS);
4399                            PointPx {
4400                                x: xc + rx * a.cos(),
4401                                y: cy + ry * a.sin(),
4402                            }
4403                        }),
4404                        pen,
4405                    );
4406                }
4407            }
4408        }
4409    }
4410
4411    /// Declares the custom series kinds the renderer draws natively
4412    /// ([`Renderer::native_kinds`](crate::render::Renderer::native_kinds));
4413    /// for them the frame holds a [`DrawCmd::Custom`] instead of the plugin's
4414    /// primitives. Host helpers call it before every frame; it does
4415    /// nothing (and does not allocate) when the kinds are unchanged.
4416    pub fn set_native_kinds(&mut self, kinds: &[&'static str]) {
4417        if self.native_kinds.as_slice() == kinds {
4418            return;
4419        }
4420        self.native_kinds.clear();
4421        self.native_kinds.extend_from_slice(kinds);
4422        self.invalidation = Invalidation::Full;
4423    }
4424
4425    fn push_label(&mut self, pos: PointPx, align: TextAlign, font: FontStyleRef, span: Span) {
4426        self.frame.push_text(
4427            LayerId::Main,
4428            TextRun {
4429                pos,
4430                text: span,
4431                style: font,
4432                color: self.theme.text,
4433                align,
4434                bg: None,
4435            },
4436        );
4437    }
4438
4439    /// Price labels of pane `i` on the right axis.
4440    fn emit_price_labels(&mut self, i: usize, line_h: f32, pad: f32, font: FontStyleRef) {
4441        let Some(pane) = self.panes.get(i) else {
4442            return;
4443        };
4444        let (plot, labels) = (pane.plot, pane.labels.for_ticks(&pane.ticks));
4445        for k in 0..self.panes[i].ticks.len() {
4446            let pane = &self.panes[i];
4447            let p = pane.ticks[k];
4448            let y = pane
4449                .price_scale
4450                .price_to_y(p, f64::from(plot.y), f64::from(plot.h)) as f32;
4451            if y < plot.y + line_h * 0.5 || y > plot.bottom() - line_h * 0.5 {
4452                continue;
4453            }
4454            // Value labels have priority over ticks.
4455            let label_h = line_h + pad;
4456            if self.axis_labels.iter().any(|l| (l.at - y).abs() < label_h) {
4457                continue;
4458            }
4459            let start = self.frame.pools.text.len();
4460            write_label(&mut self.frame.pools.text, p, labels);
4461            let span = Span {
4462                start: u32::try_from(start).unwrap_or(0),
4463                len: u32::try_from(self.frame.pools.text.len() - start).unwrap_or(0),
4464            };
4465            self.push_label(
4466                PointPx {
4467                    x: plot.right() + pad,
4468                    y: y.round(),
4469                },
4470                TextAlign::Left,
4471                font,
4472                span,
4473            );
4474        }
4475        // Value labels: a background over the whole axis width.
4476        let label_h = (line_h + pad).round();
4477        let axis_right = self.frame.size_px.w;
4478        for n in 0..self.axis_labels.len() {
4479            let l = self.axis_labels[n];
4480            let y = l.at.round();
4481            self.frame.push_rect(
4482                LayerId::Main,
4483                crate::frame::RectInst {
4484                    rect: RectPx {
4485                        x: plot.right() + 1.0,
4486                        y: (y - label_h * 0.5).round(),
4487                        w: (axis_right - plot.right() - 1.0).max(0.0),
4488                        h: label_h,
4489                    },
4490                    color: l.bg,
4491                },
4492            );
4493            self.frame.push_text(
4494                LayerId::Main,
4495                TextRun {
4496                    pos: PointPx {
4497                        x: plot.right() + pad,
4498                        y,
4499                    },
4500                    text: l.text,
4501                    style: font,
4502                    color: l.fg,
4503                    align: TextAlign::Left,
4504                    bg: None,
4505                },
4506            );
4507        }
4508    }
4509
4510    /// The last value of series `k` (the close of its last bar that is not a
4511    /// gap) and its color.
4512    fn last_value(&self, k: usize) -> Option<(f64, Rgba)> {
4513        let e = self.series.get(k)?;
4514        if let Some(c) = e.store.custom() {
4515            let v = c.plugin.last_value().filter(|v| v.is_finite())?;
4516            return Some((v, self.style_of(e).up));
4517        }
4518        let (first, end) = e.store.span()?;
4519        let [open, _, _, close] = (first..end).rev().find_map(|j| e.store.bar_at(j))?;
4520        let style = self.style_of(e);
4521        let up = match e.kind {
4522            SeriesKind::Baseline => close >= e.opts.base_value,
4523            k if is_ohlc_kind(k) || matches!(k, SeriesKind::Kagi | SeriesKind::PointFigure) => {
4524                close >= open
4525            }
4526            _ => true,
4527        };
4528        Some((close, if up { style.up } else { style.down }))
4529    }
4530
4531    /// Markers of the series in pane `i` (main layer, clipped to the plot). Markers on
4532    /// the same bar and side stack away from the bar.
4533    fn emit_markers(&mut self, i: usize, line_h: f32, font: FontStyleRef) {
4534        let Some(pane) = self.panes.get(i) else {
4535            return;
4536        };
4537        let (id, plot) = (pane.id, pane.plot);
4538        let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4539        if self.time_index.is_empty()
4540            || !self
4541                .series
4542                .iter()
4543                .any(|e| e.pane == id && !e.markers.is_empty())
4544        {
4545            return;
4546        }
4547        let (first, end) = (self.time_index.first_index(), self.time_index.end_index());
4548        let (a, b) = self.time_scale.visible_range();
4549        let ja = (a.floor() as i64).clamp(first, end - 1);
4550        let jb = (b.ceil() as i64).clamp(first, end - 1);
4551        let Some(t_hi) = self.time_index.time_at(jb) else {
4552            return;
4553        };
4554        // Markers snap to the next bar: those before `t_skip` land left of
4555        // the first visible bar.
4556        let t_skip = self.time_index.time_at(ja - 1).unwrap_or(i64::MIN);
4557        let size = (MARKER_SIZE * self.dpr).round().max(4.0);
4558        let gap = (MARKER_GAP * self.dpr).round();
4559        let clip = self.data_clip(plot);
4560        self.frame.push_cmd(LayerId::Main, DrawCmd::PushClip(clip));
4561        for k in 0..self.series.len() {
4562            let e = &self.series[k];
4563            let Some(norm) = e.norm.filter(|_| e.pane == id && !e.markers.is_empty()) else {
4564                continue;
4565            };
4566            let main = self.style_of(e).up;
4567            let start = e.markers.partition_point(|m| m.time <= t_skip);
4568            // (bar, offset above, offset below) of the stack being built.
4569            let mut stack = (i64::MIN, 0.0_f32, 0.0_f32);
4570            for n in start..e.markers.len() {
4571                let m = &e.markers[n];
4572                if m.time > t_hi && jb < end - 1 {
4573                    break;
4574                }
4575                let j = self.time_index.lower_bound(m.time).min(end - 1);
4576                let Some([_, high, low, _]) = e.store.bar_at(j) else {
4577                    continue;
4578                };
4579                if j != stack.0 {
4580                    stack = (j, 0.0, 0.0);
4581                }
4582                let above = m.position == MarkerPosition::AboveBar;
4583                let price = if above { high } else { low };
4584                let y_bar = self.panes[i]
4585                    .price_scale
4586                    .price_to_y(norm.apply(price), top, height) as f32;
4587                let text_h = if m.text.is_empty() { 0.0 } else { line_h };
4588                let (cy, ty) = if above {
4589                    let cy = y_bar - gap - stack.1 - size * 0.5;
4590                    stack.1 += gap + size + text_h;
4591                    (cy, cy - size * 0.5 - text_h * 0.5)
4592                } else {
4593                    let cy = y_bar + gap + stack.2 + size * 0.5;
4594                    stack.2 += gap + size + text_h;
4595                    (cy, cy + size * 0.5 + text_h * 0.5)
4596                };
4597                let shown = j + i64::from(e.opts.shift);
4598                let x = (plot.x + self.time_scale.index_to_x(shown as f64).0).round();
4599                let color = m.color.unwrap_or(main);
4600                self.marker_hits.push(MarkerHit {
4601                    series: e.id,
4602                    index: n,
4603                    pane: id,
4604                    pos: PointPx { x, y: cy.round() },
4605                    radius: size * 0.5,
4606                });
4607                self.frame.push_icon(
4608                    LayerId::Main,
4609                    crate::frame::IconInst {
4610                        pos: PointPx { x, y: cy.round() },
4611                        size: Px(size),
4612                        icon: m.shape.icon(),
4613                        color,
4614                    },
4615                );
4616                if text_h > 0.0 {
4617                    let span = self.frame.push_str(&e.markers[n].text);
4618                    self.frame.push_text(
4619                        LayerId::Main,
4620                        TextRun {
4621                            pos: PointPx { x, y: ty.round() },
4622                            text: span,
4623                            style: font,
4624                            color,
4625                            align: TextAlign::Center,
4626                            bg: None,
4627                        },
4628                    );
4629                }
4630            }
4631        }
4632        self.frame.push_cmd(LayerId::Main, DrawCmd::PopClip);
4633    }
4634
4635    /// Last-value lines and price lines of pane `i` (main layer, above the
4636    /// series), and the placement of their axis labels in `axis_labels`:
4637    /// labels are placed in priority order (series in the order
4638    /// they were added, then price lines), each at the free position nearest
4639    /// to its price.
4640    fn emit_marks(&mut self, i: usize, line_h: f32, pad: f32, font: FontStyleRef) {
4641        self.axis_labels.clear();
4642        if self.revealing() {
4643            return; // after the reveal
4644        }
4645        let Some(pane) = self.panes.get(i) else {
4646            return;
4647        };
4648        let (id, plot, labels) = (pane.id, pane.plot, pane.labels);
4649        let (top, height) = (f64::from(plot.y), f64::from(plot.h));
4650        let inside = |y: f32| y >= plot.y && y < plot.bottom();
4651        let format = |e: &SeriesEntry| match labels {
4652            NumberFormat::Fixed(_) | NumberFormat::Auto(_) => match e.opts.price_precision {
4653                Some(p) => NumberFormat::Fixed(p),
4654                None => NumberFormat::Auto(e.auto_decimals),
4655            },
4656            other => other,
4657        };
4658        for k in 0..self.series.len() {
4659            let e = &self.series[k];
4660            if e.pane != id || volume_like(e) {
4661                continue;
4662            }
4663            let (Some(norm), Some((value, color))) = (e.norm, self.last_value(k)) else {
4664                continue;
4665            };
4666            let (show_line, show_label, fmt) = (
4667                e.opts.price_line_visible,
4668                e.opts.last_value_visible,
4669                format(e),
4670            );
4671            let d = norm.apply(value);
4672            let y = self.panes[i].price_scale.price_to_y(d, top, height) as f32;
4673            if !inside(y) {
4674                continue;
4675            }
4676            if show_line {
4677                let yl = y.floor() + 0.5;
4678                self.frame.push_line(
4679                    LayerId::Main,
4680                    LineInst {
4681                        from: PointPx { x: plot.x, y: yl },
4682                        to: PointPx {
4683                            x: plot.right(),
4684                            y: yl,
4685                        },
4686                        stroke: StrokeStyle {
4687                            width: Px(1.0),
4688                            color,
4689                            dash: LineDash::Dotted,
4690                        },
4691                    },
4692                );
4693            }
4694            if show_label {
4695                self.push_axis_label(y, d, fmt, color);
4696            }
4697        }
4698        for n in 0..self.price_lines.len() {
4699            let line = &self.price_lines[n];
4700            let Some(k) = self.series.iter().position(|e| e.id == line.series) else {
4701                continue;
4702            };
4703            let e = &self.series[k];
4704            let Some(norm) = e.norm.filter(|_| e.pane == id) else {
4705                continue;
4706            };
4707            let color = line.opts.color.unwrap_or_else(|| self.style_of(e).up);
4708            let fmt = format(e);
4709            let d = norm.apply(line.opts.price);
4710            let y = self.panes[i].price_scale.price_to_y(d, top, height) as f32;
4711            if !inside(y) {
4712                continue;
4713            }
4714            let width = line.opts.line_width.to_px(self.dpr).0.round().max(1.0);
4715            let yl = if width as i32 % 2 == 1 {
4716                y.floor() + 0.5
4717            } else {
4718                y.round()
4719            };
4720            self.frame.push_line(
4721                LayerId::Main,
4722                LineInst {
4723                    from: PointPx { x: plot.x, y: yl },
4724                    to: PointPx {
4725                        x: plot.right(),
4726                        y: yl,
4727                    },
4728                    stroke: StrokeStyle {
4729                        width: Px(width),
4730                        color,
4731                        dash: line.opts.line_style,
4732                    },
4733                },
4734            );
4735            let show_label = line.opts.axis_label_visible;
4736            if !line.opts.title.is_empty() {
4737                let span = self.frame.push_str(&self.price_lines[n].opts.title);
4738                self.frame.push_text(
4739                    LayerId::Main,
4740                    TextRun {
4741                        pos: PointPx {
4742                            x: plot.right() - pad,
4743                            y: (y - line_h * 0.5 - 2.0).round(),
4744                        },
4745                        text: span,
4746                        style: font,
4747                        color,
4748                        align: TextAlign::Right,
4749                        bg: None,
4750                    },
4751                );
4752            }
4753            if show_label {
4754                self.push_axis_label(y, d, fmt, color);
4755            }
4756        }
4757        // Place in priority order: the candidate positions are the wanted
4758        // one and the slots right above and below each placed label.
4759        let h = line_h + pad;
4760        let (lo, hi) = (plot.y + h * 0.5, plot.bottom() - h * 0.5);
4761        for n in 0..self.axis_labels.len() {
4762            let want = self.axis_labels[n].want.clamp(lo, hi.max(lo));
4763            let placed = &self.axis_labels[..n];
4764            let free = |c: f32| {
4765                c >= lo - 0.01
4766                    && c <= hi + 0.01
4767                    && placed.iter().all(|p| (p.at - c).abs() >= h - 0.01)
4768            };
4769            let mut best = want;
4770            if !free(want) {
4771                let mut dist = f32::INFINITY;
4772                for p in placed {
4773                    for c in [p.at - h, p.at + h] {
4774                        if free(c) && (c - want).abs() < dist {
4775                            dist = (c - want).abs();
4776                            best = c;
4777                        }
4778                    }
4779                }
4780            }
4781            self.axis_labels[n].at = best;
4782        }
4783    }
4784
4785    /// Writes a value label's text and queues it for placement.
4786    fn push_axis_label(&mut self, want: f32, value: f64, format: NumberFormat, bg: Rgba) {
4787        let start = self.frame.pools.text.len();
4788        write_label(&mut self.frame.pools.text, value, format);
4789        let text = Span {
4790            start: u32::try_from(start).unwrap_or(0),
4791            len: u32::try_from(self.frame.pools.text.len() - start).unwrap_or(0),
4792        };
4793        if self.axis_labels.len() < self.axis_labels.capacity() {
4794            self.axis_labels.push(AxisLabel {
4795                want,
4796                at: want,
4797                text,
4798                bg,
4799                fg: contrast(bg),
4800            });
4801        }
4802    }
4803
4804    /// Axis lines, pane separators and time labels.
4805    fn emit_axes(&mut self, time_h: f32, font: FontStyleRef) {
4806        let axis = self.theme.axis_line;
4807        let (w, h) = (self.frame.size_px.w, self.frame.size_px.h);
4808        let layout = self.layout;
4809        let x = layout.price_axis.x + 0.5;
4810        let l = Self::line(
4811            PointPx { x, y: 0.0 },
4812            PointPx {
4813                x,
4814                y: layout.price_axis.bottom(),
4815            },
4816            axis,
4817        );
4818        self.frame.push_line(LayerId::Main, l);
4819        // Separators: the 1-px rows between panes, across the price axis too.
4820        for k in 1..self.panes.len() {
4821            let y = self.panes[k].plot.y - SEPARATOR_PX + 0.5;
4822            let l = Self::line(PointPx { x: 0.0, y }, PointPx { x: w, y }, axis);
4823            self.frame.push_line(LayerId::Main, l);
4824        }
4825        let y = layout.time_axis.y + 0.5;
4826        if y < h {
4827            let l = Self::line(PointPx { x: 0.0, y }, PointPx { x: w, y }, axis);
4828            self.frame.push_line(LayerId::Main, l);
4829        }
4830
4831        let y = (layout.time_axis.y + time_h * 0.5).round();
4832        for k in 0..self.placed.len() {
4833            let placed = self.placed[k];
4834            let Some(label) = self.tick_label(placed.tick) else {
4835                continue;
4836            };
4837            let span = self.frame.push_str(label.as_str());
4838            self.push_label(
4839                PointPx {
4840                    x: layout.plot.x + placed.x.round(),
4841                    y,
4842                },
4843                TextAlign::Center,
4844                font,
4845                span,
4846            );
4847        }
4848    }
4849}
4850
4851/// Read-only view of the chart data for renderers.
4852///
4853/// # Examples
4854///
4855/// ```
4856/// use ferrochart_core::{Chart, ChartOptions};
4857/// use ferrochart_core::chart::{SeriesData, SeriesOptions};
4858/// use ferrochart_core::data::DataDelta;
4859/// use ferrochart_core::frame::SeriesKind;
4860/// use ferrochart_core::testing::random_walk;
4861///
4862/// let mut chart = Chart::new(ChartOptions::default());
4863/// let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
4864/// chart.set_data(id, SeriesData::Ohlc(random_walk(1, 100, 0, 60_000)?))?;
4865///
4866/// let view = chart.data_view();
4867/// assert_eq!(view.changes_since(id, 0), DataDelta::Full); // never synced
4868/// let synced = view.generation(id).unwrap();
4869/// assert_eq!(view.changes_since(id, synced), DataDelta::None);
4870/// assert_eq!(view.ohlc(id, 0).unwrap().len(), 100);
4871/// # Ok::<(), ferrochart_core::Error>(())
4872/// ```
4873#[derive(Clone, Copy)]
4874pub struct ChartDataView<'a> {
4875    series: &'a [SeriesEntry],
4876    time_index: &'a TimeIndex,
4877}
4878
4879/// The time index of [`ChartDataView::empty`].
4880static EMPTY_TIME_INDEX: TimeIndex = TimeIndex::new();
4881
4882impl<'a> ChartDataView<'a> {
4883    /// A view without series, for frames that only hold immediate
4884    /// primitives (`ferrochart-plot`).
4885    ///
4886    /// ```
4887    /// use ferrochart_core::chart::ChartDataView;
4888    /// use ferrochart_core::data::SeriesId;
4889    ///
4890    /// let view = ChartDataView::empty();
4891    /// assert_eq!(view.generation(SeriesId(1)), None);
4892    /// assert!(view.time_index().is_empty());
4893    /// ```
4894    pub fn empty() -> ChartDataView<'static> {
4895        ChartDataView {
4896            series: &[],
4897            time_index: &EMPTY_TIME_INDEX,
4898        }
4899    }
4900
4901    /// The store holding `id`'s data (a volume series reads its source).
4902    fn store(self, id: SeriesId) -> Option<&'a Store> {
4903        let series = self.series;
4904        let e = series.iter().find(|e| e.id == id)?;
4905        match e.kind {
4906            SeriesKind::Volume => {
4907                let src = e.opts.source?;
4908                series.iter().find(|x| x.id == src).map(|x| &x.store)
4909            }
4910            _ => Some(&e.store),
4911        }
4912    }
4913
4914    /// Current data generation of a series, `None` for unknown ids.
4915    pub fn generation(&self, id: SeriesId) -> Option<u64> {
4916        self.store(id)?.log().map(ChangeLog::generation)
4917    }
4918
4919    /// What changed in a series since generation `since_gen`. Unknown ids
4920    /// give `Full`.
4921    pub fn changes_since(&self, id: SeriesId, since_gen: u64) -> DataDelta {
4922        self.store(id)
4923            .and_then(Store::log)
4924            .map_or(DataDelta::Full, |log| log.changes_since(since_gen))
4925    }
4926
4927    /// Data of one level (0 = original, `>= 2` = LOD). Value series appear as
4928    /// bars with `open == high == low == close == value` at level 0 and
4929    /// `(first, max, min, last)` per bucket at LOD levels; NaN values are gaps.
4930    pub fn ohlc(&self, id: SeriesId, level: u8) -> Option<OhlcLevelView<'a>> {
4931        self.store(id)?.level_view(level)
4932    }
4933
4934    /// Per-point colors of a value series (RGBA8, `0` = the series color) and
4935    /// the logical index of the first one. Level 0 only.
4936    pub fn point_colors(&self, id: SeriesId) -> Option<(i64, &'a [u32])> {
4937        self.store(id)?.colors()
4938    }
4939
4940    /// The plugin of a custom series, for native renderers to read its data
4941    /// (downcast with `as &dyn Any`); `None` for other series.
4942    pub fn custom(&self, id: SeriesId) -> Option<&'a dyn CustomSeries> {
4943        let e = self.series.iter().find(|e| e.id == id)?;
4944        e.store.custom().map(|c| c.plugin.as_ref())
4945    }
4946
4947    /// Fractional logical index of point `point` of custom series `id` (its
4948    /// slot, or its time interpolated between slots for `AxisMode::Overlay`),
4949    /// without `SeriesOptions::shift` (which is in [`CustomDraw::x_transform`]).
4950    pub fn custom_index(&self, id: SeriesId, point: usize) -> Option<f64> {
4951        let e = self.series.iter().find(|e| e.id == id)?;
4952        e.store.custom()?.x_index(self.time_index, point)
4953    }
4954
4955    /// The global time index.
4956    pub fn time_index(&self) -> &'a TimeIndex {
4957        self.time_index
4958    }
4959}
4960
4961/// LOD level for the current bar spacing.
4962fn lod_level(lod: Option<&crate::data::lod::Lod>, bar_spacing: f64) -> u8 {
4963    let bars_per_px = 1.0 / bar_spacing;
4964    if bars_per_px < 4.0 {
4965        return 0;
4966    }
4967    let Some(max) = lod.and_then(crate::data::lod::Lod::max_level) else {
4968        return 0;
4969    };
4970    let want = bars_per_px.log2().ceil().max(2.0).min(f64::from(max));
4971    want as u8
4972}
4973
4974/// Elements of `view` covering the visible logical range `from..to`, one
4975/// extra on each side.
4976fn visible_span(view: &OhlcLevelView<'_>, from: f64, to: f64) -> crate::data::IdxSpan {
4977    let (i0, i1) = (from.floor() as i64 - 1, to.ceil() as i64 + 1);
4978    let k = u32::from(view.level);
4979    let (start, end) = if k == 0 {
4980        (i0, i1 + 1)
4981    } else {
4982        (bucket_of(i0, k), bucket_of(i1, k) + 1)
4983    };
4984    crate::data::IdxSpan {
4985        start: start.max(view.first),
4986        end: end.min(view.end()),
4987    }
4988}
4989
4990/// Largest volume of `view` in `span`.
4991fn max_volume_in(view: &OhlcLevelView<'_>, span: crate::data::IdxSpan) -> f64 {
4992    let mut max_volume: f64 = 0.0;
4993    if let Some(col) = view.volume {
4994        for j in span.start..span.end {
4995            let p = usize::try_from(j - view.first).unwrap_or(usize::MAX);
4996            max_volume = max_volume.max(col.get(p).unwrap_or(0.0));
4997        }
4998    }
4999    max_volume
5000}
5001
5002/// Writes an axis label in the pane's format.
5003fn write_label(out: &mut impl core::fmt::Write, v: f64, format: NumberFormat) {
5004    format.write(out, v);
5005}
5006
5007/// Black or white text, whichever reads better on `bg`.
5008fn contrast(bg: Rgba) -> Rgba {
5009    let l = 0.299 * f32::from(bg.r) + 0.587 * f32::from(bg.g) + 0.114 * f32::from(bg.b);
5010    if l > 160.0 {
5011        Rgba::hex(0x0013_1722)
5012    } else {
5013        Rgba::hex(0x00FF_FFFF)
5014    }
5015}
5016
5017/// The first value (close) at logical indices `from..to` that is not a gap:
5018/// the base of relative price scales.
5019fn first_value(store: &Store, from: i64, to: i64) -> Option<f64> {
5020    let (first, end) = store.span()?;
5021    (from.max(first)..to.min(end)).find_map(|j| store.bar_at(j).map(|b| b[3]))
5022}
5023
5024impl Column<'_> {
5025    /// Value at logical index / bucket `j` of a view whose first element is `first`.
5026    pub fn at(&self, first: i64, j: i64) -> Option<f64> {
5027        self.get(usize::try_from(j - first).ok()?)
5028    }
5029}
5030
5031/// Crosshair equality with prices compared bit for bit (a synced crosshair
5032/// has a NaN price; gap bars have NaN values).
5033fn same_crosshair(a: Option<&CrosshairPoint>, b: Option<&CrosshairPoint>) -> bool {
5034    match (a, b) {
5035        (None, None) => true,
5036        (Some(a), Some(b)) => {
5037            let bits = |v: Option<BarValues>| {
5038                v.map(|v| {
5039                    [v.open, v.high, v.low, v.close, v.volume.unwrap_or(f64::NAN)].map(f64::to_bits)
5040                })
5041            };
5042            a.logical_index == b.logical_index
5043                && a.time == b.time
5044                && a.pane == b.pane
5045                && a.price.to_bits() == b.price.to_bits()
5046                && bits(a.bar) == bits(b.bar)
5047                && a.bar.map(|v| v.volume.is_some()) == b.bar.map(|v| v.volume.is_some())
5048        }
5049        _ => false,
5050    }
5051}
5052
5053#[cfg(test)]
5054mod tests {
5055    use super::*;
5056    use crate::data::{OhlcColumns, ValueColumns};
5057
5058    fn ohlc(times: &[i64], close: f64) -> SeriesData {
5059        let n = times.len();
5060        SeriesData::Ohlc(OhlcColumns {
5061            time: times.to_vec(),
5062            open: vec![close; n],
5063            high: vec![close + 1.0; n],
5064            low: vec![close - 1.0; n],
5065            close: vec![close; n],
5066            volume: Some(vec![10.0; n]),
5067        })
5068    }
5069
5070    fn values(times: &[i64], v: &[f64]) -> SeriesData {
5071        SeriesData::Value(ValueColumns {
5072            time: times.to_vec(),
5073            value: v.to_vec(),
5074            color: None,
5075        })
5076    }
5077
5078    fn two_series(a: SeriesKind, b: SeriesKind) -> (Chart, SeriesId, SeriesId) {
5079        let mut chart = Chart::new(ChartOptions::default());
5080        let pane = chart.main_pane();
5081        let x = chart.add_series(pane, a, SeriesOptions::default()).unwrap();
5082        let y = chart.add_series(pane, b, SeriesOptions::default()).unwrap();
5083        (chart, x, y)
5084    }
5085
5086    /// Value of series `id` at time `t`, through the time axis.
5087    fn at(chart: &Chart, id: SeriesId, t: i64) -> Option<f64> {
5088        let j = chart.time_index.index_of(t)?;
5089        let e = chart.series.iter().find(|e| e.id == id)?;
5090        e.store.bar_at(j).map(|b| b[3])
5091    }
5092
5093    fn merged_warnings(chart: &mut Chart) -> usize {
5094        chart
5095            .drain_events()
5096            .filter(|e| matches!(e, ChartEvent::Warning(WarningKind::TimeAxisMerged { .. })))
5097            .count()
5098    }
5099
5100    /// The axis is the union of all series' times; a time between
5101    /// existing bars rebuilds it with a warning, data stays at its times.
5102    #[test]
5103    fn time_axis_is_the_union_of_all_series() {
5104        let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Line);
5105        chart
5106            .set_data(candles, ohlc(&[10, 20, 30, 40], 5.0))
5107            .unwrap();
5108        chart.drain_events().for_each(drop);
5109        // Extending past the end keeps every logical index; no warning.
5110        chart
5111            .set_data(line, values(&[30, 40, 50, 60], &[1.0, 2.0, 3.0, 4.0]))
5112            .unwrap();
5113        assert_eq!(chart.time_index.times(), &[10, 20, 30, 40, 50, 60]);
5114        assert_eq!(chart.time_index.index_of(10), Some(0));
5115        assert_eq!(merged_warnings(&mut chart), 0);
5116        // A time between bars: rebuilt, with a warning.
5117        chart
5118            .set_data(line, values(&[15, 30, 60], &[1.0, 2.0, 4.0]))
5119            .unwrap();
5120        assert_eq!(chart.time_index.times(), &[10, 15, 20, 30, 40, 60]);
5121        assert_eq!(merged_warnings(&mut chart), 1);
5122        assert_eq!(chart.time_index.index_of(10), Some(0)); // the first shared slot keeps its index
5123        for t in [10, 20, 30, 40] {
5124            assert_eq!(at(&chart, candles, t), Some(5.0), "t = {t}");
5125        }
5126        assert_eq!(at(&chart, candles, 15), None); // a gap bar
5127        assert_eq!(at(&chart, line, 15), Some(1.0));
5128        assert_eq!(at(&chart, line, 20), Some(1.5)); // interpolated
5129        // Appending a candle between line points rebuilds again.
5130        chart.append(candles, ohlc(&[50], 6.0)).unwrap();
5131        assert_eq!(chart.time_index.times(), &[10, 15, 20, 30, 40, 50, 60]);
5132        assert_eq!(merged_warnings(&mut chart), 1);
5133        assert_eq!(at(&chart, candles, 50), Some(6.0));
5134        assert_eq!(at(&chart, line, 60), Some(4.0));
5135        // update_last past the end extends the axis without a rebuild.
5136        let bar = BarUpdate {
5137            time: 70,
5138            open: 7.0,
5139            high: 8.0,
5140            low: 6.0,
5141            close: 7.0,
5142            volume: Some(1.0),
5143        };
5144        assert_eq!(
5145            chart.update_last(candles, bar),
5146            Ok(DataChange::Append { count: 2 })
5147        );
5148        assert_eq!(at(&chart, candles, 60), None);
5149        assert_eq!(at(&chart, candles, 70), Some(7.0));
5150        assert_eq!(merged_warnings(&mut chart), 0);
5151    }
5152
5153    /// Replacing every series (e.g. another symbol) leaves no stale bars.
5154    #[test]
5155    fn replaced_data_leaves_no_stale_bars() {
5156        let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Area);
5157        chart.set_data(candles, ohlc(&[1, 2, 3], 5.0)).unwrap();
5158        chart.set_data(line, values(&[1, 2, 3], &[1.0; 3])).unwrap();
5159        chart
5160            .set_data(candles, ohlc(&[101, 102, 103], 9.0))
5161            .unwrap();
5162        // The line still has the old times.
5163        assert_eq!(chart.time_index.len(), 6);
5164        chart
5165            .set_data(line, values(&[101, 102, 103], &[2.0; 3]))
5166            .unwrap();
5167        assert_eq!(chart.time_index.times(), &[101, 102, 103]);
5168        assert_eq!(at(&chart, candles, 102), Some(9.0));
5169        assert_eq!(at(&chart, line, 103), Some(2.0));
5170    }
5171
5172    /// In relative modes every series starts at 0 % / 100 at the first
5173    /// visible bar, whatever its price level.
5174    #[test]
5175    fn relative_scales_normalize_each_series() {
5176        use crate::price_scale::PriceScaleMode;
5177        use crate::testing::MonoMeasurer;
5178        use crate::transform_helpers::y_of_price;
5179
5180        let (mut chart, a, b) = two_series(SeriesKind::Line, SeriesKind::Line);
5181        chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5182        let times: Vec<i64> = (0..50).collect();
5183        let va: Vec<f64> = (0..50).map(|i| 10.0 + f64::from(i) * 0.1).collect();
5184        let vb: Vec<f64> = (0..50).map(|i| 1000.0 - f64::from(i)).collect();
5185        chart.set_data(a, values(&times, &va)).unwrap();
5186        chart.set_data(b, values(&times, &vb)).unwrap();
5187        chart.fit_content();
5188        let pane = chart.main_pane();
5189        for (mode, start) in [
5190            (PriceScaleMode::Percentage, 0.0),
5191            (PriceScaleMode::IndexedTo100, 100.0),
5192        ] {
5193            chart
5194                .price_scale(pane, ScaleSide::Right)
5195                .unwrap()
5196                .set_mode(mode)
5197                .unwrap();
5198            chart.build_frame(0.0, &MonoMeasurer);
5199            let draws: Vec<SeriesDraw> = chart.frame().layers[LayerId::Main as usize]
5200                .cmds
5201                .iter()
5202                .filter_map(|c| match c {
5203                    DrawCmd::Series(s) => Some(*s),
5204                    _ => None,
5205                })
5206                .collect();
5207            assert_eq!(draws.len(), 2);
5208            // The base is the first bar whose index is in the visible range.
5209            let j0 = chart.time_scale.visible_range().0.floor().max(0.0) as usize;
5210            let ya = y_of_price(&draws[0].y_transform, va[j0]);
5211            let yb = y_of_price(&draws[1].y_transform, vb[j0]);
5212            assert!((ya - yb).abs() < 0.01, "{mode:?}: {ya} vs {yb}");
5213            // The scale's start value sits at the same y.
5214            let p = &chart.panes[0];
5215            let y0 = p
5216                .price_scale
5217                .price_to_y(start, f64::from(p.plot.y), f64::from(p.plot.h));
5218            assert!((y0 as f32 - ya).abs() < 0.01, "{mode:?}");
5219            // Rising and falling series end on opposite sides of the start.
5220            let (ea, eb) = (
5221                y_of_price(&draws[0].y_transform, va[49]),
5222                y_of_price(&draws[1].y_transform, vb[49]),
5223            );
5224            assert!(ea < ya && eb > yb, "{mode:?}");
5225        }
5226        // Percent labels.
5227        let text = &chart.frame().pools.text;
5228        assert!(!text.contains('%'), "indexed labels have no %");
5229        chart
5230            .price_scale(pane, ScaleSide::Right)
5231            .unwrap()
5232            .set_mode(PriceScaleMode::Percentage)
5233            .unwrap();
5234        chart.build_frame(0.0, &MonoMeasurer);
5235        assert!(chart.frame().pools.text.contains('%'));
5236    }
5237
5238    /// Errors leave the time axis and the data unchanged.
5239    #[test]
5240    fn failed_operations_leave_the_axis_unchanged() {
5241        let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Line);
5242        chart.set_data(candles, ohlc(&[10, 20, 30], 5.0)).unwrap();
5243        chart
5244            .set_data(line, values(&[10, 20, 30], &[1.0; 3]))
5245            .unwrap();
5246        let before = chart.time_index.clone();
5247        let mut bad = ohlc(&[40, 50], 5.0);
5248        if let SeriesData::Ohlc(c) = &mut bad {
5249            c.high[1] = f64::INFINITY;
5250        }
5251        assert!(chart.append(candles, bad.clone()).is_err()); // past the end
5252        assert!(matches!(
5253            chart.append(line, ohlc(&[40], 1.0)),
5254            Err(Error::InvalidArgument(_))
5255        )); // wrong kind
5256        assert_eq!(chart.time_index, before);
5257        if let SeriesData::Ohlc(c) = &mut bad {
5258            c.time = vec![15, 25];
5259        }
5260        assert!(chart.set_data(candles, bad).is_err()); // a rebuild
5261        assert_eq!(chart.time_index, before);
5262        assert_eq!(at(&chart, candles, 20), Some(5.0));
5263        assert_eq!(
5264            chart.append(line, values(&[20], &[3.0])),
5265            Err(Error::TimeNotIncreasing { index: 0 })
5266        );
5267    }
5268
5269    #[test]
5270    fn chart_is_send() {
5271        fn assert_send<T: Send>() {}
5272        assert_send::<Chart>();
5273    }
5274
5275    #[test]
5276    fn invalid_ids_are_errors() {
5277        let mut chart = Chart::new(ChartOptions::default());
5278        let pane = chart.main_pane();
5279        assert_eq!(
5280            chart.add_series(PaneId(9), SeriesKind::Candlestick, SeriesOptions::default()),
5281            Err(Error::UnknownId)
5282        );
5283        assert_eq!(chart.remove_series(SeriesId(3)), Err(Error::UnknownId));
5284        let line = chart
5285            .add_series(pane, SeriesKind::Line, SeriesOptions::default())
5286            .unwrap();
5287        // A line cannot be the source of a volume series.
5288        assert!(matches!(
5289            chart.add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(line)),
5290            Err(Error::InvalidArgument(_))
5291        ));
5292        assert!(matches!(
5293            chart.add_series(
5294                pane,
5295                SeriesKind::Volume,
5296                SeriesOptions::volume_of(SeriesId(0))
5297            ),
5298            Err(Error::InvalidArgument(_))
5299        ));
5300        assert!(chart.price_scale(pane, ScaleSide::Left).is_none());
5301        assert_eq!(
5302            chart.set_series_options(SeriesId(9), SeriesOptions::default()),
5303            Err(Error::UnknownId)
5304        );
5305        assert!(chart.series_options(SeriesId(9)).is_none());
5306        // The source cannot change.
5307        assert!(matches!(
5308            chart.set_series_options(line, SeriesOptions::volume_of(line)),
5309            Err(Error::InvalidArgument(_))
5310        ));
5311        assert_eq!(chart.series_kind(line), Some(SeriesKind::Line));
5312        assert_eq!(chart.series_pane(line), Some(pane));
5313        assert_eq!(chart.series_pane(SeriesId(9)), None);
5314    }
5315
5316    fn loaded(n: usize, options: ChartOptions) -> (Chart, SeriesId) {
5317        let mut chart = Chart::new(options);
5318        chart.resize(SizeCss { w: 800.0, h: 400.0 }, 1.0);
5319        let pane = chart.main_pane();
5320        let id = chart
5321            .add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())
5322            .unwrap();
5323        chart
5324            .add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(id))
5325            .unwrap();
5326        let data = crate::testing::random_walk(9, n, 0, 60_000).unwrap();
5327        chart.set_data(id, SeriesData::Ohlc(data)).unwrap();
5328        (chart, id)
5329    }
5330
5331    #[test]
5332    fn redraw_only_when_something_changed() {
5333        let (mut chart, _) = loaded(1000, ChartOptions::default());
5334        assert_eq!(chart.needs_redraw(), Invalidation::Full);
5335        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5336        assert_eq!(chart.needs_redraw(), Invalidation::None);
5337        chart.time_scale().scroll_by(Px(10.0));
5338        assert_eq!(chart.needs_redraw(), Invalidation::Light);
5339        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5340        assert_eq!(chart.needs_redraw(), Invalidation::None);
5341    }
5342
5343    #[test]
5344    fn prepend_keeps_the_view() {
5345        let (mut chart, id) = loaded(1000, ChartOptions::default());
5346        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5347        let before = chart.time_scale().visible_range();
5348        let older = crate::testing::random_walk(10, 500, -500 * 60_000, 60_000).unwrap();
5349        chart.prepend(id, SeriesData::Ohlc(older)).unwrap();
5350        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5351        assert_eq!(chart.time_scale().visible_range(), before);
5352        assert_eq!(chart.data_view().time_index().first_index(), -500);
5353    }
5354
5355    #[test]
5356    fn repaired_bars_produce_a_warning() {
5357        let (mut chart, id) = loaded(
5358            10,
5359            ChartOptions {
5360                ohlc_validation: ValidationMode::Repair,
5361                ..ChartOptions::default()
5362            },
5363        );
5364        let mut bad = crate::testing::random_walk(1, 2, 10 * 60_000, 60_000).unwrap();
5365        bad.high[1] = bad.low[1] - 1.0;
5366        chart.append(id, SeriesData::Ohlc(bad)).unwrap();
5367        let events: Vec<_> = chart.drain_events().collect();
5368        assert_eq!(
5369            events,
5370            [ChartEvent::Warning(WarningKind::OhlcRepaired {
5371                series: id,
5372                bars: 1
5373            })]
5374        );
5375    }
5376
5377    #[test]
5378    fn removing_candles_removes_their_volume() {
5379        let (mut chart, id) = loaded(100, ChartOptions::default());
5380        let volume = SeriesId(1);
5381        assert!(chart.data_view().ohlc(volume, 0).is_some());
5382        chart.remove_series(id).unwrap();
5383        assert_eq!(chart.remove_series(volume), Err(Error::UnknownId));
5384        assert!(chart.data_view().ohlc(id, 0).is_none());
5385        // An empty chart still builds a (background-only) frame.
5386        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5387    }
5388
5389    #[test]
5390    fn volume_series_has_no_data_of_its_own() {
5391        let (mut chart, _) = loaded(10, ChartOptions::default());
5392        let data = crate::testing::random_walk(1, 10, 0, 60_000).unwrap();
5393        assert!(matches!(
5394            chart.set_data(SeriesId(1), SeriesData::Ohlc(data)),
5395            Err(Error::InvalidArgument(_))
5396        ));
5397    }
5398
5399    /// Text runs of the main layer as `(text, y)`.
5400    fn main_texts(chart: &Chart) -> Vec<(String, f32)> {
5401        let f = chart.frame();
5402        f.layers[LayerId::Main as usize]
5403            .cmds
5404            .iter()
5405            .filter_map(|c| match c {
5406                DrawCmd::Text(s) => Some(*s),
5407                _ => None,
5408            })
5409            .flat_map(|s| f.pools.text_runs[s.start as usize..(s.start + s.len) as usize].to_vec())
5410            .map(|r| (f.pools.text_of(r.text).to_owned(), r.pos.y))
5411            .collect()
5412    }
5413
5414    /// Price lines are tied to a series, validated, and removed with it.
5415    #[test]
5416    fn price_lines_follow_their_series() {
5417        let mut chart = Chart::new(ChartOptions::default());
5418        let pane = chart.main_pane();
5419        let line = chart
5420            .add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())
5421            .unwrap();
5422        let vol = chart
5423            .add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(line))
5424            .unwrap();
5425        let opts = |price| PriceLineOptions {
5426            price,
5427            ..PriceLineOptions::default()
5428        };
5429        assert_eq!(
5430            chart.create_price_line(vol, opts(1.0)),
5431            Err(Error::InvalidArgument("volume series have no price lines"))
5432        );
5433        assert!(chart.create_price_line(line, opts(f64::NAN)).is_err());
5434        assert_eq!(
5435            chart.create_price_line(SeriesId(99), opts(1.0)),
5436            Err(Error::UnknownId)
5437        );
5438        let a = chart.create_price_line(line, opts(1.0)).unwrap();
5439        let b = chart.create_price_line(line, opts(2.0)).unwrap();
5440        assert_ne!(a, b);
5441        chart.update_price_line(a, opts(3.0)).unwrap();
5442        assert_eq!(chart.price_line(a).map(|o| o.price), Some(3.0));
5443        chart.remove_price_line(b).unwrap();
5444        assert_eq!(chart.remove_price_line(b), Err(Error::UnknownId));
5445        chart.remove_series(line).unwrap();
5446        assert!(chart.price_line(a).is_none());
5447        assert_eq!(chart.update_price_line(a, opts(1.0)), Err(Error::UnknownId));
5448    }
5449
5450    /// Automatic precision shows meme-coin prices with subscript
5451    /// zeros; a set precision is kept as it is.
5452    #[test]
5453    fn automatic_precision_reaches_tiny_prices() {
5454        use crate::testing::MonoMeasurer;
5455
5456        let (mut chart, a, _) = two_series(SeriesKind::Line, SeriesKind::Line);
5457        chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5458        let times: Vec<i64> = (0..20).collect();
5459        let v: Vec<f64> = (0..20)
5460            .map(|i| 0.000_012_34 + f64::from(i) * 1e-9)
5461            .collect();
5462        chart.set_data(a, values(&times, &v)).unwrap();
5463        chart.fit_content();
5464        chart.build_frame(0.0, &MonoMeasurer);
5465        let texts: Vec<String> = main_texts(&chart).into_iter().map(|(t, _)| t).collect();
5466        // The last value 0.000012359, and ticks widened to their step
5467        // (0.0₄12345).
5468        assert!(texts.iter().any(|t| t == "0.0₄1236"), "{texts:?}");
5469        let ticks = texts.iter().filter(|t| t.starts_with("0.0₄123")).count();
5470        assert!(ticks >= 3, "{texts:?}");
5471
5472        let k = chart.series.iter().position(|e| e.id == a).unwrap();
5473        chart.series[k].opts.price_precision = Some(2);
5474        chart.invalidation = Invalidation::Full;
5475        chart.build_frame(0.0, &MonoMeasurer);
5476        let texts: Vec<String> = main_texts(&chart).into_iter().map(|(t, _)| t).collect();
5477        assert!(texts.iter().any(|t| t == "0.00"), "{texts:?}");
5478        assert!(!texts.iter().any(|t| t.contains('₄')), "{texts:?}");
5479    }
5480
5481    /// Price ticks finer than the series precision get the decimals
5482    /// they need, so no two ticks read the same.
5483    #[test]
5484    fn fine_ticks_are_not_rounded_together() {
5485        use crate::testing::MonoMeasurer;
5486
5487        let (mut chart, a, _) = two_series(SeriesKind::Line, SeriesKind::Line);
5488        chart.resize(SizeCss { w: 400.0, h: 600.0 }, 1.0);
5489        let times: Vec<i64> = (0..20).collect();
5490        let v: Vec<f64> = (0..20).map(|i| 1.0 + f64::from(i) * 0.0002).collect();
5491        chart.set_data(a, values(&times, &v)).unwrap();
5492        chart.fit_content();
5493        chart.build_frame(0.0, &MonoMeasurer);
5494        let ticks: Vec<String> = main_texts(&chart)
5495            .into_iter()
5496            .map(|(t, _)| t)
5497            .filter(|t| t.parse::<f64>().is_ok() && t.len() > "1.00".len())
5498            .collect();
5499        assert!(ticks.len() >= 3, "{ticks:?}");
5500        let mut unique = ticks.clone();
5501        unique.dedup();
5502        assert_eq!(unique, ticks);
5503    }
5504
5505    /// Value labels never overlap, stay inside the plot, and hide the
5506    /// ticks they cover.
5507    #[test]
5508    fn axis_labels_do_not_overlap() {
5509        use crate::testing::MonoMeasurer;
5510
5511        let (mut chart, a, b) = two_series(SeriesKind::Line, SeriesKind::Line);
5512        chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5513        let times: Vec<i64> = (0..20).collect();
5514        let va: Vec<f64> = (0..20).map(f64::from).collect();
5515        let mut vb = va.clone();
5516        vb[19] = 19.01;
5517        chart.set_data(a, values(&times, &va)).unwrap();
5518        chart.set_data(b, values(&times, &vb)).unwrap();
5519        for price in [19.02, 18.99] {
5520            chart
5521                .create_price_line(
5522                    a,
5523                    PriceLineOptions {
5524                        price,
5525                        title: "t".into(),
5526                        ..PriceLineOptions::default()
5527                    },
5528                )
5529                .unwrap();
5530        }
5531        chart.fit_content();
5532        chart.build_frame(0.0, &MonoMeasurer);
5533        assert_eq!(chart.axis_labels.len(), 4);
5534        let plot = chart.panes[0].plot;
5535        let mut ys: Vec<f32> = chart.axis_labels.iter().map(|l| l.at).collect();
5536        // The first label (series a) keeps its wanted position.
5537        assert!((ys[0] - chart.axis_labels[0].want).abs() < 0.01);
5538        ys.sort_by(f32::total_cmp);
5539        let texts = main_texts(&chart);
5540        let gap = ys
5541            .windows(2)
5542            .map(|w| w[1] - w[0])
5543            .fold(f32::INFINITY, f32::min);
5544        assert!(gap >= 10.0, "labels overlap: {ys:?}");
5545        assert!(ys.iter().all(|&y| y > plot.y && y < plot.bottom()));
5546        // Titles are drawn; labels show the values.
5547        assert_eq!(texts.iter().filter(|(t, _)| t == "t").count(), 2);
5548        for v in ["19.00", "19.01", "19.02", "18.99"] {
5549            assert!(texts.iter().any(|(t, _)| t == v), "missing {v}: {texts:?}");
5550        }
5551        // Turning the marks off removes the labels.
5552        let k = chart.series.iter().position(|e| e.id == b).unwrap();
5553        chart.series[k].opts.last_value_visible = false;
5554        chart.invalidation = Invalidation::Full;
5555        chart.build_frame(0.0, &MonoMeasurer);
5556        assert_eq!(chart.axis_labels.len(), 3);
5557    }
5558
5559    /// Markers are sorted, snap to the next bar, stack away from the
5560    /// bar, and skip gap bars.
5561    #[test]
5562    fn markers_stack_and_snap() {
5563        use crate::testing::MonoMeasurer;
5564        use MarkerPosition::{AboveBar, BelowBar};
5565
5566        let (mut chart, candles, line) = two_series(SeriesKind::Candlestick, SeriesKind::Line);
5567        chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5568        chart
5569            .set_data(candles, ohlc(&[10, 20, 30, 40], 5.0))
5570            .unwrap();
5571        // Time 25 puts a gap bar into the candles.
5572        chart
5573            .set_data(line, values(&[10, 25, 40], &[5.0, 5.0, 5.0]))
5574            .unwrap();
5575        let m = |time, position, text: &str| Marker {
5576            time,
5577            position,
5578            text: text.into(),
5579            ..Marker::default()
5580        };
5581        chart
5582            .set_markers(
5583                candles,
5584                vec![
5585                    m(40, AboveBar, ""),
5586                    m(19, AboveBar, "a"), // snaps to 20
5587                    m(20, AboveBar, ""),
5588                    m(20, BelowBar, ""),
5589                    m(25, AboveBar, ""), // gap bar: not drawn
5590                ],
5591            )
5592            .unwrap();
5593        assert_eq!(
5594            chart
5595                .markers(candles)
5596                .unwrap()
5597                .iter()
5598                .map(|m| m.time)
5599                .collect::<Vec<_>>(),
5600            [19, 20, 20, 25, 40]
5601        );
5602        chart.fit_content();
5603        chart.build_frame(0.0, &MonoMeasurer);
5604        let icons = chart.frame().pools.icons.clone();
5605        assert_eq!(icons.len(), 4);
5606        let x20 = chart.panes[0].plot.x + chart.time_scale.index_to_x(1.0).0;
5607        let at20: Vec<_> = icons
5608            .iter()
5609            .filter(|i| (i.pos.x - x20.round()).abs() < 0.5)
5610            .collect();
5611        assert_eq!(at20.len(), 3);
5612        // Above the bar: the second marker sits above the first and its text.
5613        let (y_text, y1, y2, y_below) = (
5614            main_texts(&chart).iter().find(|(t, _)| t == "a").unwrap().1,
5615            at20[0].pos.y,
5616            at20[1].pos.y,
5617            at20[2].pos.y,
5618        );
5619        assert!(y2 < y_text && y_text < y1, "{y2} < {y_text} < {y1}");
5620        assert!(y_below > y1);
5621        // Errors.
5622        assert_eq!(
5623            chart.set_markers(SeriesId(99), vec![]),
5624            Err(Error::UnknownId)
5625        );
5626        let vol = chart
5627            .add_series(
5628                chart.main_pane(),
5629                SeriesKind::Volume,
5630                SeriesOptions::volume_of(candles),
5631            )
5632            .unwrap();
5633        assert!(chart.set_markers(vol, vec![]).is_err());
5634        assert!(chart.markers(SeriesId(99)).is_none());
5635    }
5636
5637    /// Draws one rectangle filling its area, and reports whether it had
5638    /// price coordinates.
5639    struct Fill(crate::plugin::LayerPosition, Rgba);
5640
5641    impl LayerPlugin for Fill {
5642        fn position(&self) -> LayerPosition {
5643            self.0
5644        }
5645        fn build(&self, ctx: &LayerCtx<'_>, out: &mut FrameBuilder<'_>) {
5646            let mut r = ctx.rect();
5647            if ctx.coords().is_some() {
5648                r.h /= 2.0;
5649            }
5650            out.rect(r, self.1);
5651        }
5652    }
5653
5654    fn rects_of(chart: &Chart, layer: LayerId) -> Vec<(Rgba, RectPx)> {
5655        let f = chart.frame();
5656        f.layers[layer as usize]
5657            .cmds
5658            .iter()
5659            .filter_map(|c| match c {
5660                DrawCmd::Rects(span) => Some(*span),
5661                _ => None,
5662            })
5663            .flat_map(|span| {
5664                let a = span.start as usize;
5665                f.pools.rects[a..a + span.len as usize]
5666                    .iter()
5667                    .map(|r| (r.color, r.rect))
5668            })
5669            .collect()
5670    }
5671
5672    #[test]
5673    fn layer_plugins_draw_in_their_layer() {
5674        let (mut chart, _) = loaded(200, ChartOptions::default());
5675        let red = Rgba::hex(0xFF_0000);
5676        let blue = Rgba::hex(0x00_00FF);
5677        let green = Rgba::hex(0x00_FF00);
5678        let pane = chart.add_pane(PaneOptions::default());
5679        let wide = chart
5680            .add_layer(None, Box::new(Fill(LayerPosition::Background, red)))
5681            .unwrap();
5682        chart
5683            .add_layer(
5684                Some(chart.main_pane()),
5685                Box::new(Fill(LayerPosition::AboveSeries, blue)),
5686            )
5687            .unwrap();
5688        chart
5689            .add_layer(Some(pane), Box::new(Fill(LayerPosition::Overlay, green)))
5690            .unwrap();
5691        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5692        let bg = rects_of(&chart, LayerId::Background);
5693        let main = rects_of(&chart, LayerId::Main);
5694        let overlay = rects_of(&chart, LayerId::Overlay);
5695        let plot = chart.layout().plot;
5696        // Chart-wide: all plots, no price coordinates.
5697        assert!(
5698            bg.iter()
5699                .any(|&(c, r)| c == red && r.y == 0.0 && r.h > plot.h)
5700        );
5701        // Main pane, with coordinates: the top half of its plot.
5702        assert!(main.iter().any(|&(c, r)| c == blue
5703            && r == RectPx {
5704                h: plot.h / 2.0,
5705                ..plot
5706            }));
5707        // The empty pane has no coordinates: its whole plot.
5708        let lower = chart.pane_layout(pane).unwrap().plot;
5709        assert!(overlay.iter().any(|&(c, r)| c == green && r == lower));
5710
5711        chart.remove_pane(pane).unwrap();
5712        chart.remove_layer(wide).unwrap();
5713        assert_eq!(chart.remove_layer(wide), Err(Error::UnknownId));
5714        assert_eq!(chart.invalidate_layer(wide), Err(Error::UnknownId));
5715        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5716        assert!(
5717            !rects_of(&chart, LayerId::Background)
5718                .iter()
5719                .any(|&(c, _)| c == red)
5720        );
5721        assert!(
5722            !rects_of(&chart, LayerId::Overlay)
5723                .iter()
5724                .any(|&(c, _)| c == green)
5725        );
5726        assert!(
5727            rects_of(&chart, LayerId::Main)
5728                .iter()
5729                .any(|&(c, _)| c == blue)
5730        );
5731        assert!(
5732            chart
5733                .add_layer(Some(pane), Box::new(Fill(LayerPosition::Overlay, green)))
5734                .is_err()
5735        );
5736    }
5737
5738    /// A custom series: a rect from `lo` to `hi` per point.
5739    #[derive(Default)]
5740    struct Ranges {
5741        mode: Option<AxisMode>,
5742        time: Vec<i64>,
5743        range: Vec<(f64, f64)>,
5744    }
5745
5746    impl Ranges {
5747        fn overlay() -> Self {
5748            Self {
5749                mode: Some(AxisMode::Overlay),
5750                ..Self::default()
5751            }
5752        }
5753
5754        fn push(&mut self, t: i64, lo: f64, hi: f64) -> DataChange {
5755            self.time.push(t);
5756            self.range.push((lo, hi));
5757            DataChange::Append { count: 1 }
5758        }
5759    }
5760
5761    impl CustomSeries for Ranges {
5762        fn kind(&self) -> &'static str {
5763            "test.ranges"
5764        }
5765        fn axis_mode(&self) -> AxisMode {
5766            self.mode.unwrap_or(AxisMode::Slots)
5767        }
5768        fn times(&self) -> &[Timestamp] {
5769            &self.time
5770        }
5771        fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> {
5772            // Linear: fine for a test.
5773            self.range[from..to]
5774                .iter()
5775                .fold(None, |acc, &(l, h)| match acc {
5776                    None => Some((l, h)),
5777                    Some((a, b)) => Some((l.min(a), h.max(b))),
5778                })
5779        }
5780        fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) {
5781            for i in from..to {
5782                let (lo, hi) = self.range[i];
5783                let (Some(x), Some(y0), Some(y1)) = (
5784                    ctx.x_of_point(i),
5785                    ctx.coords().y_of(hi),
5786                    ctx.coords().y_of(lo),
5787                ) else {
5788                    continue;
5789                };
5790                let rect = RectPx {
5791                    x: x - 1.0,
5792                    y: y0,
5793                    w: 2.0,
5794                    h: y1 - y0,
5795                };
5796                out.rect(rect, ctx.style().up);
5797            }
5798        }
5799        fn last_value(&self) -> Option<f64> {
5800            self.range.last().map(|r| r.1)
5801        }
5802        fn crosshair_value(&self, point: usize) -> Option<f64> {
5803            self.range.get(point).map(|r| r.1)
5804        }
5805        fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
5806            params[0] = ctx.visible().1 as f32;
5807        }
5808    }
5809
5810    const RED: u32 = 0x00FF_0000;
5811
5812    /// Another custom series type.
5813    struct Probe;
5814
5815    impl CustomSeries for Probe {
5816        fn kind(&self) -> &'static str {
5817            "test.probe"
5818        }
5819        fn axis_mode(&self) -> AxisMode {
5820            AxisMode::Slots
5821        }
5822        fn times(&self) -> &[Timestamp] {
5823            &[]
5824        }
5825        fn extremes(&self, _: usize, _: usize) -> Option<(f64, f64)> {
5826            None
5827        }
5828        fn build(&self, _: &SeriesCtx<'_>, _: usize, _: usize, _: &mut FrameBuilder<'_>) {}
5829    }
5830
5831    /// An indicator that computes nothing.
5832    struct Nothing;
5833
5834    impl Indicator for Nothing {
5835        fn name(&self) -> &'static str {
5836            "nothing"
5837        }
5838        fn outputs(&self) -> &[crate::plugin::OutputSpec] {
5839            const OUT: [crate::plugin::OutputSpec; 1] = [crate::plugin::OutputSpec::line("x")];
5840            &OUT
5841        }
5842        fn default_placement(&self) -> Placement {
5843            Placement::Overlay
5844        }
5845        fn warmup(&self) -> usize {
5846            0
5847        }
5848        fn update(&mut self, _: &IndicatorInput<'_>, _: DataChange, _: &mut IndicatorOutputs) {}
5849    }
5850
5851    fn custom_chart(r: Ranges) -> (Chart, SeriesId) {
5852        let mut chart = Chart::new(ChartOptions::default());
5853        chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5854        let opts = SeriesOptions {
5855            color: Some(Rgba::hex(RED)),
5856            ..SeriesOptions::default()
5857        };
5858        let id = chart
5859            .add_custom_series(chart.main_pane(), Box::new(r), opts)
5860            .unwrap();
5861        (chart, id)
5862    }
5863
5864    fn red_rects(chart: &mut Chart) -> Vec<RectPx> {
5865        chart.build_frame(0.0, &crate::testing::MonoMeasurer);
5866        // In the plot: the last-value label on the axis has the color too.
5867        let right = chart.layout().plot.right();
5868        rects_of(chart, LayerId::Main)
5869            .into_iter()
5870            .filter(|(c, r)| *c == Rgba::hex(RED) && r.x < right)
5871            .map(|(_, r)| r)
5872            .collect()
5873    }
5874
5875    #[test]
5876    fn custom_series_take_slots_and_draw() {
5877        let mut r = Ranges::default();
5878        for (n, t) in [60_000, 120_000, 180_000].into_iter().enumerate() {
5879            r.push(t, n as f64, n as f64 + 1.0);
5880        }
5881        let (mut chart, id) = custom_chart(r);
5882        assert_eq!(chart.series_kind(id), Some(SeriesKind::Custom));
5883        assert_eq!(chart.time_index.times(), &[60_000, 120_000, 180_000]);
5884        chart.fit_content();
5885        let rects = red_rects(&mut chart);
5886        assert_eq!(rects.len(), 3);
5887        assert!(rects[0].x < rects[1].x && rects[1].x < rects[2].x);
5888        // Auto scaling covers 0..3: the first rect ends low, the last starts high.
5889        let plot = chart.layout().plot;
5890        assert!(rects[0].bottom() > plot.y + plot.h * 0.7);
5891        assert!(rects[2].y < plot.y + plot.h * 0.3);
5892
5893        let view = chart.data_view();
5894        let g = view.generation(id).unwrap();
5895        let any: &dyn Any = view.custom(id).unwrap();
5896        assert_eq!(any.downcast_ref::<Ranges>().unwrap().time.len(), 3);
5897
5898        // Real time: the last point changes, then a new one.
5899        chart
5900            .update_custom(id, |r: &mut Ranges| {
5901                r.range[2].1 = 9.0;
5902                DataChange::UpdateLast
5903            })
5904            .unwrap();
5905        assert_eq!(
5906            chart.data_view().changes_since(id, g),
5907            DataDelta::Range(IdxSpan { start: 2, end: 3 })
5908        );
5909        chart
5910            .update_custom(id, |r: &mut Ranges| r.push(240_000, 1.0, 2.0))
5911            .unwrap();
5912        assert_eq!(chart.time_index.len(), 4);
5913        assert_eq!(chart.custom_series::<Ranges>(id).unwrap().time.len(), 4);
5914        assert_eq!(chart.entry(id).unwrap().store.bar_at(2), Some([9.0; 4]));
5915        assert_eq!(chart.last_value(0).map(|v| v.0), Some(2.0));
5916        chart.fit_content();
5917        assert_eq!(red_rects(&mut chart).len(), 4);
5918    }
5919
5920    #[test]
5921    fn custom_series_share_the_axis() {
5922        let mut chart = Chart::new(ChartOptions::default());
5923        chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
5924        let pane = chart.main_pane();
5925        let candles = chart
5926            .add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())
5927            .unwrap();
5928        chart.set_data(candles, ohlc(&[0, 20, 40], 10.0)).unwrap();
5929        let mut r = Ranges::default();
5930        r.push(20, 1.0, 2.0);
5931        r.push(40, 1.0, 2.0);
5932        let id = chart
5933            .add_custom_series(pane, Box::new(r), SeriesOptions::default())
5934            .unwrap();
5935        // On existing slots: nothing added.
5936        assert_eq!(chart.time_index.times(), &[0, 20, 40]);
5937        let c = |chart: &Chart| chart.entry(id).unwrap().store.span();
5938        assert_eq!(c(&chart), Some((1, 3)));
5939
5940        // A time between slots rebuilds the axis; the candles keep their bars.
5941        chart
5942            .update_custom(id, |r: &mut Ranges| {
5943                r.time.insert(1, 30);
5944                r.range.insert(1, (0.0, 1.0));
5945                DataChange::Replace
5946            })
5947            .unwrap();
5948        assert_eq!(chart.time_index.times(), &[0, 20, 30, 40]);
5949        assert_eq!(at(&chart, candles, 40), Some(10.0));
5950        assert_eq!(merged_warnings(&mut chart), 1);
5951        assert_eq!(
5952            chart.entry(id).unwrap().store.custom().unwrap().point_at(3),
5953            Some(2)
5954        );
5955
5956        // Candles rebuilding the axis re-map the custom series.
5957        chart
5958            .set_data(candles, ohlc(&[0, 10, 20, 40], 10.0))
5959            .unwrap();
5960        assert_eq!(chart.time_index.times(), &[0, 10, 20, 30, 40]);
5961        let cs = chart.entry(id).unwrap().store.custom().unwrap();
5962        assert_eq!(
5963            (cs.point_at(2), cs.point_at(3), cs.point_at(4)),
5964            (Some(0), Some(1), Some(2))
5965        );
5966
5967        // Removing the candles keeps the custom series' slots.
5968        chart.remove_series(candles).unwrap();
5969        assert!(chart.time_index.len() >= 3);
5970        assert_eq!(c(&chart).map(|(a, b)| b - a), Some(3));
5971        assert!(
5972            chart
5973                .add_indicator(id, Box::new(Nothing), Placement::Overlay)
5974                .is_err()
5975        );
5976        assert!(chart.set_data(id, values(&[0], &[1.0])).is_err());
5977        assert!(
5978            chart
5979                .add_series(pane, SeriesKind::Custom, SeriesOptions::default())
5980                .is_err()
5981        );
5982    }
5983
5984    #[test]
5985    fn overlay_custom_series_add_no_slots() {
5986        let (mut chart, id) = custom_chart(Ranges::overlay());
5987        let line = chart
5988            .add_series(
5989                chart.main_pane(),
5990                SeriesKind::Line,
5991                SeriesOptions::default(),
5992            )
5993            .unwrap();
5994        chart
5995            .set_data(line, values(&[0, 60, 120], &[0.0, 0.0, 0.0]))
5996            .unwrap();
5997        chart
5998            .update_custom(id, |r: &mut Ranges| {
5999                for t in [10, 30, 90] {
6000                    r.push(t, 1.0, 2.0);
6001                }
6002                DataChange::Replace
6003            })
6004            .unwrap();
6005        assert_eq!(chart.time_index.len(), 3);
6006        chart.fit_content();
6007        let rects = red_rects(&mut chart);
6008        assert_eq!(rects.len(), 3);
6009        // x by interpolation: 1/6, 1/2 and 3/2 of the first two slots' gap.
6010        let x = |i: f64| chart.layout().plot.x + chart.time_scale.index_to_x_f64(i) as f32 - 1.0;
6011        for (r, i) in rects.iter().zip([1.0 / 6.0, 0.5, 1.5]) {
6012            assert!((r.x - x(i)).abs() < 0.01, "{} {}", r.x, x(i));
6013        }
6014    }
6015
6016    #[test]
6017    fn invalid_custom_data_is_an_error() {
6018        let (mut chart, id) = custom_chart(Ranges::default());
6019        chart
6020            .update_custom(id, |r: &mut Ranges| r.push(60, 1.0, 2.0))
6021            .unwrap();
6022        chart
6023            .update_custom(id, |r: &mut Ranges| r.push(120, 1.0, 2.0))
6024            .unwrap();
6025        // Not increasing: an error, and nothing is drawn.
6026        assert_eq!(
6027            chart.update_custom(id, |r: &mut Ranges| r.push(90, 1.0, 2.0)),
6028            Err(Error::TimeNotIncreasing { index: 2 })
6029        );
6030        assert!(red_rects(&mut chart).is_empty());
6031        // Another type: `f` is not called.
6032        assert!(
6033            chart
6034                .update_custom(id, |_: &mut Probe| unreachable!())
6035                .is_err()
6036        );
6037        assert!(chart.custom_series::<Probe>(id).is_none());
6038        // A valid change brings it back.
6039        chart
6040            .update_custom(id, |r: &mut Ranges| {
6041                r.time[2] = 180;
6042                DataChange::Replace
6043            })
6044            .unwrap();
6045        chart.fit_content();
6046        assert_eq!(red_rects(&mut chart).len(), 3);
6047        // Duplicate times are rejected when added.
6048        let mut dup = Ranges::default();
6049        dup.push(1, 0.0, 1.0);
6050        dup.push(1, 0.0, 1.0);
6051        let pane = chart.main_pane();
6052        assert!(
6053            chart
6054                .add_custom_series(pane, Box::new(dup), SeriesOptions::default())
6055                .is_err()
6056        );
6057        assert_eq!(chart.series.len(), 1);
6058        chart.remove_series(id).unwrap();
6059        assert!(chart.custom_series::<Ranges>(id).is_none());
6060    }
6061
6062    #[test]
6063    fn native_kinds_get_a_custom_draw() {
6064        let mut r = Ranges::default();
6065        for (n, t) in [60_000, 120_000, 180_000].into_iter().enumerate() {
6066            r.push(t, n as f64, n as f64 + 1.0);
6067        }
6068        let (mut chart, id) = custom_chart(r);
6069        chart.fit_content();
6070        let portable = red_rects(&mut chart);
6071        assert_eq!(portable.len(), 3);
6072
6073        chart.set_native_kinds(&["test.ranges"]);
6074        assert_eq!(chart.needs_redraw(), Invalidation::Full);
6075        assert!(red_rects(&mut chart).is_empty());
6076        let draws: Vec<CustomDraw> = chart.frame().layers[LayerId::Main as usize]
6077            .cmds
6078            .iter()
6079            .filter_map(|c| match c {
6080                DrawCmd::Custom(d) => Some(*d),
6081                _ => None,
6082            })
6083            .collect();
6084        assert_eq!(draws.len(), 1);
6085        let d = draws[0];
6086        assert_eq!((d.series, d.kind), (id, "test.ranges"));
6087        assert_eq!(d.points, IdxSpan { start: 0, end: 3 });
6088        assert_eq!(d.clip, chart.layout().plot);
6089        assert!((d.params[0] - 3.0).abs() < f32::EPSILON);
6090        assert_eq!(Some(d.generation), chart.data_view().generation(id));
6091        assert_eq!(chart.frame().styles[d.style.0 as usize].up, Rgba::hex(RED));
6092        // The same x as the portable path.
6093        let view = chart.data_view();
6094        for (i, r) in portable.iter().enumerate() {
6095            let idx = view.custom_index(id, i).unwrap();
6096            let x = ((idx - d.x_transform.base as f64) as f32) * d.x_transform.step
6097                + d.x_transform.offset;
6098            assert!((x - (r.x + 1.0)).abs() < 1e-3, "{x} {}", r.x + 1.0);
6099        }
6100        // Unchanged kinds: nothing to redraw.
6101        chart.set_native_kinds(&["test.ranges"]);
6102        assert_eq!(chart.needs_redraw(), Invalidation::None);
6103        chart.set_native_kinds(&[]);
6104        assert_eq!(red_rects(&mut chart).len(), 3);
6105    }
6106
6107    use crate::testing::{MonoMeasurer as Mono, random_walk};
6108
6109    /// The lines of the main layer.
6110    fn main_lines(chart: &Chart) -> Vec<LineInst> {
6111        let f = chart.frame();
6112        f.layers[LayerId::Main as usize]
6113            .cmds
6114            .iter()
6115            .filter_map(|c| match c {
6116                DrawCmd::Lines(s) => f.pools.lines.get(s.range()),
6117                _ => None,
6118            })
6119            .flatten()
6120            .copied()
6121            .collect()
6122    }
6123
6124    fn transform_chart(t: Box<dyn SeriesTransform>, bars: usize) -> (Chart, SeriesId) {
6125        let mut chart = Chart::new(ChartOptions {
6126            min_bar_spacing: Css(0.01),
6127            ..ChartOptions::default()
6128        });
6129        chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
6130        let id = chart
6131            .add_transform_series(chart.main_pane(), t, SeriesOptions::default())
6132            .unwrap();
6133        let data = random_walk(5, bars, 0, 60_000).unwrap();
6134        chart.set_data(id, SeriesData::Ohlc(data)).unwrap();
6135        chart.fit_content();
6136        (chart, id)
6137    }
6138
6139    #[test]
6140    fn a_transform_series_owns_the_axis() {
6141        use crate::transform::{Kagi, Renko, Reversal};
6142        let (mut chart, renko) = transform_chart(Box::new(Renko::fixed(1.0).unwrap()), 2_000);
6143        let pane = chart.main_pane();
6144        let n = chart.time_index.len();
6145        assert!(n > 10 && n < 2_000, "{n} bricks");
6146        // Synthetic times: strictly increasing, within the input's.
6147        let times = chart.time_index.times();
6148        assert!(times.windows(2).all(|w| w[0] < w[1]));
6149        assert!(times[0] >= 0 && times[n - 1] <= 2_000 * 60_000);
6150        let opts = SeriesOptions::default;
6151        assert!(chart.add_series(pane, SeriesKind::Line, opts()).is_err());
6152        assert!(chart.add_series(pane, SeriesKind::Kagi, opts()).is_err());
6153        assert!(
6154            chart
6155                .add_transform_series(
6156                    pane,
6157                    Box::new(Kagi::new(Reversal::Fixed(1.0)).unwrap()),
6158                    opts()
6159                )
6160                .is_err()
6161        );
6162        assert!(
6163            chart
6164                .add_custom_series(pane, Box::new(Ranges::default()), opts())
6165                .is_err()
6166        );
6167        // Volume reads the bricks' volume.
6168        chart
6169            .add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(renko))
6170            .unwrap();
6171        chart.build_frame(0.0, &Mono);
6172        let kinds: Vec<SeriesKind> = chart.frame().layers[LayerId::Main as usize]
6173            .cmds
6174            .iter()
6175            .filter_map(|c| match c {
6176                DrawCmd::Series(d) => Some(d.kind),
6177                _ => None,
6178            })
6179            .collect();
6180        assert_eq!(kinds, [SeriesKind::Volume, SeriesKind::Candlestick]);
6181        // Without it, time-based series are welcome again, and the other
6182        // way round a transform series is refused.
6183        chart.remove_series(renko).unwrap();
6184        chart.add_series(pane, SeriesKind::Line, opts()).unwrap();
6185        assert!(
6186            chart
6187                .add_transform_series(pane, Box::new(Renko::fixed(1.0).unwrap()), opts())
6188                .is_err()
6189        );
6190    }
6191
6192    #[test]
6193    fn indicators_follow_a_transform_series() {
6194        use crate::transform::{Kagi, Reversal};
6195        /// The close, doubled.
6196        struct Double;
6197        impl Indicator for Double {
6198            fn name(&self) -> &'static str {
6199                "double"
6200            }
6201            fn outputs(&self) -> &[crate::plugin::OutputSpec] {
6202                const OUT: [crate::plugin::OutputSpec; 1] = [crate::plugin::OutputSpec::line("d")];
6203                &OUT
6204            }
6205            fn default_placement(&self) -> Placement {
6206                Placement::Overlay
6207            }
6208            fn warmup(&self) -> usize {
6209                0
6210            }
6211            fn update(
6212                &mut self,
6213                input: &IndicatorInput<'_>,
6214                _: DataChange,
6215                out: &mut IndicatorOutputs,
6216            ) {
6217                let start = out.start();
6218                for (i, v) in out.column(0).iter_mut().enumerate() {
6219                    if let Some(b) = input.bar(start + i) {
6220                        *v = 2.0 * b.close;
6221                    }
6222                }
6223            }
6224        }
6225        let kagi = || Box::new(Kagi::new(Reversal::Fixed(1.5)).unwrap());
6226        let (mut chart, id) = transform_chart(kagi(), 300);
6227        let ind = chart
6228            .add_indicator(id, Box::new(Double), Placement::Overlay)
6229            .unwrap();
6230        let mut all = random_walk(5, 300, 0, 60_000).unwrap();
6231        let mut bar = BarUpdate {
6232            time: *all.time.last().unwrap(),
6233            open: *all.open.last().unwrap(),
6234            high: *all.high.last().unwrap(),
6235            low: *all.low.last().unwrap(),
6236            close: *all.close.last().unwrap(),
6237            volume: all.volume.as_ref().and_then(|v| v.last().copied()),
6238        };
6239        let mut x = 7_u64;
6240        for i in 0..400 {
6241            x = x.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
6242            let mv = ((x >> 33) as f64 / f64::from(1_u32 << 31) - 0.5) * 2.0;
6243            if i % 9 == 0 {
6244                bar = BarUpdate {
6245                    time: bar.time + 60_000,
6246                    open: bar.close,
6247                    high: bar.close,
6248                    low: bar.close,
6249                    close: bar.close,
6250                    volume: Some(0.0),
6251                };
6252                all.time.push(bar.time);
6253                all.open.push(bar.open);
6254                all.high.push(bar.high);
6255                all.low.push(bar.low);
6256                all.close.push(bar.close);
6257                all.volume.as_mut().unwrap().push(0.0);
6258            }
6259            bar.close += mv;
6260            bar.high = bar.high.max(bar.close);
6261            bar.low = bar.low.min(bar.close);
6262            bar.volume = bar.volume.map(|v| v + 1.0);
6263            let p = all.time.len() - 1;
6264            all.close[p] = bar.close;
6265            all.high[p] = bar.high;
6266            all.low[p] = bar.low;
6267            all.volume.as_mut().unwrap()[p] = bar.volume.unwrap();
6268            chart.update_last(id, bar).unwrap();
6269        }
6270        let (mut fresh, fid) = transform_chart(kagi(), 1);
6271        fresh.set_data(fid, SeriesData::Ohlc(all)).unwrap();
6272        let find = fresh
6273            .add_indicator(fid, Box::new(Double), Placement::Overlay)
6274            .unwrap();
6275        assert_eq!(chart.time_index.times(), fresh.time_index.times());
6276        let values = |c: &Chart, ind: IndicatorId| -> Vec<u64> {
6277            let s = c.indicator_series(ind).unwrap()[0];
6278            let view = c.data_view().ohlc(s, 0).unwrap();
6279            (0..view.close.len())
6280                .map(|i| view.close.get(i).unwrap().to_bits())
6281                .collect()
6282        };
6283        assert_eq!(values(&chart, ind), values(&fresh, find));
6284        assert_eq!(values(&chart, ind).len(), chart.time_index.len());
6285    }
6286
6287    #[test]
6288    fn kagi_and_point_figure_are_primitives() {
6289        use crate::transform::{Kagi, PointFigure, Reversal};
6290        let theme = Theme::light();
6291        // Kagi: thick up-colored and thin down-colored lines.
6292        let (mut chart, _) =
6293            transform_chart(Box::new(Kagi::new(Reversal::Fixed(2.0)).unwrap()), 3_000);
6294        chart.time_scale().set_bar_spacing(8.0);
6295        chart.build_frame(0.0, &Mono);
6296        // The Kagi lines (the last-price line is dotted).
6297        let lines: Vec<LineInst> = main_lines(&chart)
6298            .into_iter()
6299            .filter(|l| l.stroke.dash == LineDash::Solid)
6300            .collect();
6301        let thick = lines.iter().filter(|l| l.stroke.color == theme.up).count();
6302        let thin = lines
6303            .iter()
6304            .filter(|l| l.stroke.color == theme.down)
6305            .count();
6306        assert!(thick > 10 && thin > 10, "{thick} thick, {thin} thin");
6307        assert!(
6308            lines
6309                .iter()
6310                .filter(|l| l.stroke.color == theme.up)
6311                .all(|l| l.stroke.width == Px(2.0))
6312        );
6313        assert!(
6314            lines
6315                .iter()
6316                .filter(|l| l.stroke.color == theme.down)
6317                .all(|l| l.stroke.width == Px(1.0))
6318        );
6319        // Zoomed far out: at most one line per pixel column.
6320        chart.time_scale().set_bar_spacing(0.05);
6321        chart.build_frame(0.0, &Mono);
6322        let n = main_lines(&chart).len();
6323        assert!(n > 10 && n <= 800, "{n} lines");
6324        // Point & Figure: X as crossed lines, O as closed polylines.
6325        let (mut chart, _) = transform_chart(Box::new(PointFigure::new(0.5, 3).unwrap()), 3_000);
6326        chart.time_scale().set_bar_spacing(12.0);
6327        chart.build_frame(0.0, &Mono);
6328        let xs = main_lines(&chart)
6329            .iter()
6330            .filter(|l| l.stroke.color == theme.up && l.stroke.dash == LineDash::Solid)
6331            .count();
6332        let os = chart.frame().layers[LayerId::Main as usize]
6333            .cmds
6334            .iter()
6335            .filter(|c| matches!(c, DrawCmd::Polyline { style, .. } if style.color == theme.down))
6336            .count();
6337        assert!(xs > 10 && xs % 2 == 0 && os > 5, "{xs} X lines, {os} Os");
6338        // Small boxes: one rect per column.
6339        chart.time_scale().set_bar_spacing(2.0);
6340        chart.build_frame(0.0, &Mono);
6341        let rects = rects_of(&chart, LayerId::Main)
6342            .iter()
6343            .filter(|(c, _)| *c == theme.up || *c == theme.down)
6344            .count();
6345        assert!(rects > 10, "{rects} columns");
6346    }
6347
6348    fn series_draws(chart: &Chart) -> Vec<SeriesDraw> {
6349        chart.frame().layers[LayerId::Main as usize]
6350            .cmds
6351            .iter()
6352            .filter_map(|c| match c {
6353                DrawCmd::Series(s) => Some(*s),
6354                _ => None,
6355            })
6356            .collect()
6357    }
6358
6359    /// A band is drawn before the series of its pane, with the lower
6360    /// series as `pair`, and goes away with either series.
6361    #[test]
6362    fn bands_follow_their_series() {
6363        use crate::testing::MonoMeasurer;
6364        let (mut chart, a, b) = two_series(SeriesKind::Line, SeriesKind::Line);
6365        chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
6366        let t = [0, 60_000, 120_000];
6367        chart.set_data(a, values(&t, &[2.0, 3.0, 1.0])).unwrap();
6368        chart.set_data(b, values(&t, &[1.0, 1.0, 2.0])).unwrap();
6369        let candles = chart
6370            .add_series(
6371                chart.main_pane(),
6372                SeriesKind::Candlestick,
6373                SeriesOptions::default(),
6374            )
6375            .unwrap();
6376        assert!(chart.add_band(a, candles, BandOptions::default()).is_err());
6377        assert!(chart.add_band(a, a, BandOptions::default()).is_err());
6378        assert_eq!(
6379            chart.add_band(a, SeriesId(99), BandOptions::default()),
6380            Err(Error::UnknownId)
6381        );
6382        assert!(
6383            chart
6384                .add_series(
6385                    chart.main_pane(),
6386                    SeriesKind::Band,
6387                    SeriesOptions::default()
6388                )
6389                .is_err()
6390        );
6391        let other = chart.add_pane(PaneOptions::default());
6392        let c = chart
6393            .add_series(other, SeriesKind::Line, SeriesOptions::default())
6394            .unwrap();
6395        assert!(chart.add_band(a, c, BandOptions::default()).is_err());
6396
6397        let fill = Rgba::hex(0x0011_2233);
6398        let band = chart
6399            .add_band(
6400                a,
6401                b,
6402                BandOptions {
6403                    fill: Some(fill),
6404                    fill_crossed: None,
6405                },
6406            )
6407            .unwrap();
6408        chart.build_frame(0.0, &MonoMeasurer);
6409        let draws = series_draws(&chart);
6410        let kinds: Vec<_> = draws.iter().map(|d| d.kind).collect();
6411        assert_eq!(kinds[0], SeriesKind::Band, "{kinds:?}");
6412        assert_eq!((draws[0].series, draws[0].pair), (a, Some(b)));
6413        let style = chart.frame().styles[draws[0].style.0 as usize];
6414        // `fill_crossed: None` is the same color.
6415        assert_eq!((style.fill_top, style.fill_bottom), (fill, fill));
6416        assert!(draws[1..].iter().all(|d| d.pair.is_none()));
6417
6418        // Different shifts: not drawn.
6419        let opts = SeriesOptions {
6420            shift: 2,
6421            ..*chart.series_options(b).unwrap()
6422        };
6423        chart.set_series_options(b, opts).unwrap();
6424        chart.build_frame(0.0, &MonoMeasurer);
6425        assert!(
6426            series_draws(&chart)
6427                .iter()
6428                .all(|d| d.kind != SeriesKind::Band)
6429        );
6430        let opts = SeriesOptions { shift: 0, ..opts };
6431        chart.set_series_options(b, opts).unwrap();
6432
6433        chart
6434            .set_band_options(band, BandOptions::default())
6435            .unwrap();
6436        assert_eq!(chart.band_options(band), Some(&BandOptions::default()));
6437        chart.remove_series(b).unwrap();
6438        assert_eq!(chart.band_options(band), None);
6439        assert_eq!(chart.remove_band(band), Err(Error::UnknownId));
6440        chart.build_frame(0.0, &MonoMeasurer);
6441        assert!(
6442            series_draws(&chart)
6443                .iter()
6444                .all(|d| d.kind != SeriesKind::Band)
6445        );
6446    }
6447
6448    /// `OutputSpec::fill_to` must name another output.
6449    #[test]
6450    fn fill_to_is_checked() {
6451        use crate::plugin::{IndicatorInput, IndicatorOutputs, OutputSpec};
6452        struct Bad([OutputSpec; 2]);
6453        impl Indicator for Bad {
6454            fn name(&self) -> &'static str {
6455                "bad"
6456            }
6457            fn outputs(&self) -> &[OutputSpec] {
6458                &self.0
6459            }
6460            fn default_placement(&self) -> Placement {
6461                Placement::Overlay
6462            }
6463            fn warmup(&self) -> usize {
6464                0
6465            }
6466            fn update(&mut self, _: &IndicatorInput<'_>, _: DataChange, _: &mut IndicatorOutputs) {}
6467        }
6468        let mut chart = Chart::new(ChartOptions::default());
6469        let src = chart
6470            .add_series(
6471                chart.main_pane(),
6472                SeriesKind::Line,
6473                SeriesOptions::default(),
6474            )
6475            .unwrap();
6476        for to in [0, 2] {
6477            let a = OutputSpec {
6478                fill_to: Some((to, BandOptions::default())),
6479                ..OutputSpec::line("a")
6480            };
6481            let bad = Bad([a, OutputSpec::line("b")]);
6482            assert!(
6483                chart
6484                    .add_indicator(src, Box::new(bad), Placement::Overlay)
6485                    .is_err()
6486            );
6487        }
6488        assert_eq!(chart.series.len(), 1, "nothing was added");
6489    }
6490}