ferrochart_core/state.rs
1//! Saving and loading the state of a chart.
2//!
3//! [`ChartState`] is plain data: the view (bar spacing, right offset), the
4//! crosshair mode, each pane's height and price scale, and the drawings. It
5//! does not contain data, series or indicators, which the host creates (a
6//! state is loaded into a chart the host has set up the same way). With the
7//! `serde` feature every type derives `Serialize`/`Deserialize`; the format
8//! is the host's choice (core does not depend on `serde_json`).
9
10use crate::chart::Chart;
11use crate::drawing::{DrawingData, DrawingTool};
12use crate::error::{Error, Result};
13use crate::frame::Invalidation;
14use crate::geom::Css;
15use crate::interaction::{CrosshairMode, Drag};
16use crate::price_scale::PriceScaleMode;
17
18/// Version written by [`Chart::save_state`]; [`Chart::load_state`] refuses
19/// newer ones.
20pub const STATE_VERSION: u32 = 1;
21
22/// Saved view, layout and drawings of a chart.
23///
24/// # Examples
25///
26/// ```
27/// use ferrochart_core::chart::{SeriesData, SeriesOptions};
28/// use ferrochart_core::drawing::{Anchor, DrawingData};
29/// use ferrochart_core::frame::SeriesKind;
30/// use ferrochart_core::testing::random_walk;
31/// use ferrochart_core::{Chart, ChartOptions};
32///
33/// // The host sets up a chart: series and data.
34/// let setup = || -> Result<Chart, ferrochart_core::Error> {
35/// let mut chart = Chart::new(ChartOptions::default());
36/// let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
37/// chart.set_data(id, SeriesData::Ohlc(random_walk(1, 100, 0, 60_000)?))?;
38/// Ok(chart)
39/// };
40/// let mut chart = setup()?;
41/// let pane = chart.main_pane();
42/// chart.drawings().add(pane, &DrawingData::new("horizontal_line", vec![Anchor { time: 0, price: 100.0 }]))?;
43/// chart.time_scale().set_bar_spacing(12.0);
44/// let state = chart.save_state();
45///
46/// // Later: the same setup, then the saved state.
47/// let mut restored = setup()?;
48/// restored.load_state(state.clone())?;
49/// assert_eq!(restored.save_state(), state);
50/// # Ok::<(), ferrochart_core::Error>(())
51/// ```
52#[derive(Clone, Debug, PartialEq)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54pub struct ChartState {
55 /// Format version ([`STATE_VERSION`]).
56 pub version: u32,
57 /// Bar spacing.
58 pub bar_spacing: Css,
59 /// Empty space right of the last bar, in bars.
60 pub right_offset: f64,
61 /// Crosshair mode.
62 pub crosshair_mode: CrosshairMode,
63 /// Panes, top to bottom.
64 pub panes: Vec<PaneState>,
65 /// Drawings, bottom to top.
66 pub drawings: Vec<SavedDrawing>,
67}
68
69/// Saved state of a pane.
70#[derive(Clone, Copy, Debug, PartialEq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72pub struct PaneState {
73 /// Relative height.
74 pub stretch: f32,
75 /// The right price scale.
76 pub price_scale: PriceScaleState,
77}
78
79/// Saved state of a price scale.
80#[derive(Clone, Copy, Debug, PartialEq)]
81#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
82pub struct PriceScaleState {
83 /// Mode.
84 pub mode: PriceScaleMode,
85 /// Whether higher prices are drawn lower.
86 pub inverted: bool,
87 /// Top and bottom margins.
88 pub margins: (f32, f32),
89 /// The range set by the user `(low, high)`; `None` while auto-scaling
90 /// (the range then follows the data and is not saved).
91 pub range: Option<(f64, f64)>,
92}
93
94/// A saved drawing.
95#[derive(Clone, Debug, PartialEq)]
96#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
97pub struct SavedDrawing {
98 /// Index of its pane (top to bottom).
99 pub pane: usize,
100 /// Kind, anchors, style and parameters.
101 pub data: DrawingData,
102 /// Shown.
103 pub visible: bool,
104 /// Locked against editing.
105 pub locked: bool,
106}
107
108impl Chart {
109 /// Saves the view, layout and drawings.
110 pub fn save_state(&self) -> ChartState {
111 let panes = self
112 .panes
113 .iter()
114 .map(|p| {
115 let s = &p.price_scale;
116 PaneState {
117 stretch: p.stretch,
118 price_scale: PriceScaleState {
119 mode: s.mode(),
120 inverted: s.inverted(),
121 margins: s.margins(),
122 range: (!s.auto_scale()).then(|| s.range()),
123 },
124 }
125 })
126 .collect();
127 let drawings = self
128 .drawings
129 .entries
130 .iter()
131 // The drawing being created is not finished yet.
132 .filter(|e| self.drawings.creating.is_none_or(|c| c.id != e.id))
133 .filter_map(|e| {
134 Some(SavedDrawing {
135 pane: self.panes.iter().position(|p| p.id == e.pane)?,
136 data: e.tool.save(),
137 visible: e.visible,
138 locked: e.locked,
139 })
140 })
141 .collect();
142 ChartState {
143 version: STATE_VERSION,
144 bar_spacing: Css((self.time_scale.bar_spacing() / f64::from(self.dpr)) as f32),
145 right_offset: self.time_scale.right_offset(),
146 crosshair_mode: self.input.crosshair,
147 panes,
148 drawings,
149 }
150 }
151
152 /// Loads a state saved by [`save_state`](Self::save_state) into a chart
153 /// with the same number of panes. The drawings replace the current ones
154 /// (with `DrawingRemoved`/`DrawingCreated` events and new ids); the undo
155 /// history is cleared.
156 ///
157 /// # Errors
158 ///
159 /// [`Error::InvalidArgument`], with the chart unchanged, for a newer
160 /// version, a different number of panes, a non-finite or non-positive
161 /// spacing or offset, invalid margins or range, or a drawing that
162 /// [`DrawingManager::add`](crate::drawing::DrawingManager::add) would
163 /// refuse.
164 pub fn load_state(&mut self, s: ChartState) -> Result<()> {
165 if s.version > STATE_VERSION {
166 return Err(Error::InvalidArgument(
167 "state version is newer than supported",
168 ));
169 }
170 if s.panes.len() != self.panes.len() {
171 return Err(Error::InvalidArgument(
172 "state has a different number of panes",
173 ));
174 }
175 if !(s.bar_spacing.0.is_finite() && s.bar_spacing.0 > 0.0 && s.right_offset.is_finite()) {
176 return Err(Error::InvalidArgument(
177 "invalid bar spacing or right offset",
178 ));
179 }
180 for p in &s.panes {
181 let ps = &p.price_scale;
182 let margin_ok = |m: f32| (0.0..1.0).contains(&m);
183 let (top, bottom) = ps.margins;
184 let range_ok = ps.range.is_none_or(|(lo, hi)| {
185 lo.is_finite()
186 && hi.is_finite()
187 && lo < hi
188 && (ps.mode != PriceScaleMode::Logarithmic || lo > 0.0)
189 });
190 if !(margin_ok(top) && margin_ok(bottom) && top + bottom < 1.0 && range_ok) {
191 return Err(Error::InvalidArgument("invalid price scale state"));
192 }
193 }
194 let mut tools: Vec<(_, Box<dyn DrawingTool>, bool, bool)> =
195 Vec::with_capacity(s.drawings.len());
196 for d in s.drawings {
197 let pane = self
198 .panes
199 .get(d.pane)
200 .ok_or(Error::InvalidArgument("drawing on a missing pane"))?
201 .id;
202 tools.push((
203 pane,
204 self.drawings.build_saved(&d.data)?,
205 d.visible,
206 d.locked,
207 ));
208 }
209
210 // Valid: apply.
211 let ts = &mut self.time_scale;
212 ts.set_bar_spacing(f64::from(s.bar_spacing.to_px(self.dpr).0));
213 ts.set_right_offset(s.right_offset);
214 self.input.crosshair = s.crosshair_mode;
215 self.input.kinetic = None;
216 if matches!(self.input.drag, Drag::EditingDrawing { .. }) {
217 self.input.drag = Drag::Idle;
218 }
219 for (pane, p) in self.panes.iter_mut().zip(&s.panes) {
220 pane.stretch = if p.stretch.is_finite() && p.stretch > 0.0 {
221 p.stretch
222 } else {
223 1.0
224 };
225 let ps = &mut pane.price_scale;
226 let st = p.price_scale;
227 // Checked above, so these cannot fail.
228 let _ = ps.set_mode(st.mode);
229 let _ = ps.set_margins(st.margins.0, st.margins.1);
230 ps.set_inverted(st.inverted);
231 match st.range {
232 Some((lo, hi)) => {
233 let _ = ps.set_range(lo, hi);
234 }
235 None => ps.set_auto_scale(true),
236 }
237 }
238 self.drawings.replace_all(tools);
239 self.invalidation = Invalidation::Full;
240 Ok(())
241 }
242}