Skip to main content

ferrochart_core/
pane.rs

1//! Panes: plot areas stacked vertically that share the time scale, each with
2//! its own price scale.
3//!
4//! Heights follow the panes' stretch factors; panes are separated by a
5//! 1-physical-px separator that can be dragged (hit area ±4 CSS px). The price
6//! axis has the same width in every pane (the widest labels win) and the time
7//! axis sits below the last pane.
8//!
9
10use crate::data::PaneId;
11use crate::format::NumberFormat;
12use crate::geom::RectPx;
13use crate::price_scale::PriceScale;
14
15/// Options of a new pane.
16///
17/// # Examples
18///
19/// ```
20/// use ferrochart_core::{Chart, ChartOptions};
21/// use ferrochart_core::pane::PaneOptions;
22///
23/// let mut chart = Chart::new(ChartOptions::default());
24/// // An indicator pane a third as tall as the main pane.
25/// let pane = chart.add_pane(PaneOptions { stretch_factor: 1.0 / 3.0 });
26/// assert_eq!(chart.panes().count(), 2);
27/// assert_eq!(chart.pane_stretch(pane), Some(1.0 / 3.0));
28/// ```
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct PaneOptions {
31    /// Share of the height relative to the other panes' factors. Values that
32    /// are not finite and positive are replaced by 1.
33    pub stretch_factor: f32,
34}
35
36impl Default for PaneOptions {
37    fn default() -> Self {
38        Self {
39            stretch_factor: 1.0,
40        }
41    }
42}
43
44/// Rectangles of one pane in the last built layout, in physical pixels.
45#[derive(Clone, Copy, Debug, Default, PartialEq)]
46pub struct PaneLayout {
47    /// The plot area.
48    pub plot: RectPx,
49    /// The pane's part of the right price axis.
50    pub price_axis: RectPx,
51}
52
53/// A pane of a chart.
54#[derive(Clone, Debug)]
55pub(crate) struct Pane {
56    pub(crate) id: PaneId,
57    pub(crate) stretch: f32,
58    /// The right price scale.
59    pub(crate) price_scale: PriceScale,
60    /// Overlay scale of a volume series sharing the pane with candles.
61    pub(crate) volume_scale: PriceScale,
62    /// Price ticks of the last frame (capacity reserved, reused).
63    pub(crate) ticks: Vec<f64>,
64    /// Plot rectangle of the last layout.
65    pub(crate) plot: RectPx,
66    pub(crate) labels: NumberFormat,
67    /// Whether the pane had data to scale in the last frame.
68    pub(crate) has_content: bool,
69}
70
71/// Volume occupies the bottom quarter of a pane it shares with candles.
72pub(crate) const VOLUME_MARGINS: (f32, f32) = (0.75, 0.0);
73/// Price series leave room above and below.
74pub(crate) const PRICE_MARGINS: (f32, f32) = (0.1, 0.1);
75/// Separator thickness in physical px.
76pub(crate) const SEPARATOR_PX: f32 = 1.0;
77/// Separator hit area on each side, in CSS px.
78pub(crate) const SEPARATOR_HIT_CSS: f32 = 4.0;
79/// Dragging a separator keeps both panes at least this tall (CSS px).
80pub(crate) const MIN_PANE_CSS: f32 = 24.0;
81
82/// Replaces stretch factors that are not finite and positive by 1.
83pub(crate) fn sanitize_stretch(s: f32) -> f32 {
84    if s.is_finite() && s > 0.0 { s } else { 1.0 }
85}
86
87impl Pane {
88    pub(crate) fn new(id: PaneId, stretch: f32) -> Self {
89        Self {
90            id,
91            stretch: sanitize_stretch(stretch),
92            price_scale: PriceScale::new(PRICE_MARGINS),
93            volume_scale: PriceScale::new(VOLUME_MARGINS),
94            ticks: Vec::with_capacity(256),
95            plot: RectPx::default(),
96            labels: NumberFormat::Auto(2),
97            has_content: false,
98        }
99    }
100}
101
102/// Stacks `panes` from `top` down over `total` px (separators included) with
103/// plot width `width`. Edges are rounded to whole pixels cumulatively, so the
104/// panes tile the area exactly.
105pub(crate) fn stack(panes: &mut [Pane], top: f32, total: f32, width: f32) {
106    let n = panes.len();
107    if n == 0 {
108        return;
109    }
110    let separators = SEPARATOR_PX * (n - 1) as f32;
111    let avail = f64::from((total - separators).max(0.0));
112    let sum: f64 = panes.iter().map(|p| f64::from(p.stretch)).sum();
113    let mut acc = 0.0;
114    for (i, pane) in panes.iter_mut().enumerate() {
115        let gap = SEPARATOR_PX * i as f32;
116        let y0 = top + (avail * acc / sum).round() as f32 + gap;
117        acc += f64::from(pane.stretch);
118        let y1 = top + (avail * acc / sum).round() as f32 + gap;
119        pane.plot = RectPx {
120            x: 0.0,
121            y: y0,
122            w: width,
123            h: (y1 - y0).max(0.0),
124        };
125    }
126}
127
128/// New stretch factors of two adjacent panes after their separator moved so
129/// that the upper pane is `upper_h` and the lower pane `lower_h` px tall; the
130/// sum of the two factors is kept.
131pub(crate) fn split_stretch(sum: f32, upper_h: f32, lower_h: f32) -> Option<(f32, f32)> {
132    let total = upper_h + lower_h;
133    if !(total > 0.0 && sum.is_finite() && sum > 0.0) {
134        return None;
135    }
136    let upper = (sum * upper_h / total).max(sum * 1e-3);
137    let lower = (sum - upper).max(sum * 1e-3);
138    Some((upper, lower))
139}
140
141#[cfg(test)]
142#[allow(clippy::float_cmp)] // pixel edges are whole numbers
143mod tests {
144    use super::*;
145
146    fn panes(stretches: &[f32]) -> Vec<Pane> {
147        stretches
148            .iter()
149            .enumerate()
150            .map(|(i, &s)| Pane::new(PaneId(i as u32), s))
151            .collect()
152    }
153
154    #[test]
155    fn panes_tile_the_area() {
156        let mut p = panes(&[3.0, 1.0, 1.0]);
157        stack(&mut p, 0.0, 502.0, 700.0);
158        assert_eq!(p[0].plot.y, 0.0);
159        assert_eq!(p[0].plot.h, 300.0);
160        assert_eq!(p[1].plot.y, 301.0);
161        assert_eq!(p[1].plot.h, 100.0);
162        assert_eq!(p[2].plot.y, 402.0);
163        assert_eq!(p[2].plot.bottom(), 502.0);
164        for w in p.windows(2) {
165            assert_eq!(w[0].plot.bottom() + SEPARATOR_PX, w[1].plot.y);
166        }
167    }
168
169    #[test]
170    fn invalid_stretch_is_one() {
171        assert_eq!(sanitize_stretch(f32::NAN), 1.0);
172        assert_eq!(sanitize_stretch(-2.0), 1.0);
173        assert_eq!(sanitize_stretch(0.5), 0.5);
174    }
175
176    #[test]
177    fn split_keeps_the_sum() {
178        let (a, b) = split_stretch(2.0, 150.0, 50.0).unwrap();
179        assert!((a - 1.5).abs() < 1e-6 && (b - 0.5).abs() < 1e-6);
180        assert!(split_stretch(2.0, 0.0, 0.0).is_none());
181    }
182}