use crate::chart::Chart;
use crate::drawing::{DrawingData, DrawingTool};
use crate::error::{Error, Result};
use crate::frame::Invalidation;
use crate::geom::Css;
use crate::interaction::{CrosshairMode, Drag};
use crate::price_scale::PriceScaleMode;
pub const STATE_VERSION: u32 = 1;
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChartState {
pub version: u32,
pub bar_spacing: Css,
pub right_offset: f64,
pub crosshair_mode: CrosshairMode,
pub panes: Vec<PaneState>,
pub drawings: Vec<SavedDrawing>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PaneState {
pub stretch: f32,
pub price_scale: PriceScaleState,
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PriceScaleState {
pub mode: PriceScaleMode,
pub inverted: bool,
pub margins: (f32, f32),
pub range: Option<(f64, f64)>,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SavedDrawing {
pub pane: usize,
pub data: DrawingData,
pub visible: bool,
pub locked: bool,
}
impl Chart {
pub fn save_state(&self) -> ChartState {
let panes = self
.panes
.iter()
.map(|p| {
let s = &p.price_scale;
PaneState {
stretch: p.stretch,
price_scale: PriceScaleState {
mode: s.mode(),
inverted: s.inverted(),
margins: s.margins(),
range: (!s.auto_scale()).then(|| s.range()),
},
}
})
.collect();
let drawings = self
.drawings
.entries
.iter()
.filter(|e| self.drawings.creating.is_none_or(|c| c.id != e.id))
.filter_map(|e| {
Some(SavedDrawing {
pane: self.panes.iter().position(|p| p.id == e.pane)?,
data: e.tool.save(),
visible: e.visible,
locked: e.locked,
})
})
.collect();
ChartState {
version: STATE_VERSION,
bar_spacing: Css((self.time_scale.bar_spacing() / f64::from(self.dpr)) as f32),
right_offset: self.time_scale.right_offset(),
crosshair_mode: self.input.crosshair,
panes,
drawings,
}
}
pub fn load_state(&mut self, s: ChartState) -> Result<()> {
if s.version > STATE_VERSION {
return Err(Error::InvalidArgument(
"state version is newer than supported",
));
}
if s.panes.len() != self.panes.len() {
return Err(Error::InvalidArgument(
"state has a different number of panes",
));
}
if !(s.bar_spacing.0.is_finite() && s.bar_spacing.0 > 0.0 && s.right_offset.is_finite()) {
return Err(Error::InvalidArgument(
"invalid bar spacing or right offset",
));
}
for p in &s.panes {
let ps = &p.price_scale;
let margin_ok = |m: f32| (0.0..1.0).contains(&m);
let (top, bottom) = ps.margins;
let range_ok = ps.range.is_none_or(|(lo, hi)| {
lo.is_finite()
&& hi.is_finite()
&& lo < hi
&& (ps.mode != PriceScaleMode::Logarithmic || lo > 0.0)
});
if !(margin_ok(top) && margin_ok(bottom) && top + bottom < 1.0 && range_ok) {
return Err(Error::InvalidArgument("invalid price scale state"));
}
}
let mut tools: Vec<(_, Box<dyn DrawingTool>, bool, bool)> =
Vec::with_capacity(s.drawings.len());
for d in s.drawings {
let pane = self
.panes
.get(d.pane)
.ok_or(Error::InvalidArgument("drawing on a missing pane"))?
.id;
tools.push((
pane,
self.drawings.build_saved(&d.data)?,
d.visible,
d.locked,
));
}
let ts = &mut self.time_scale;
ts.set_bar_spacing(f64::from(s.bar_spacing.to_px(self.dpr).0));
ts.set_right_offset(s.right_offset);
self.input.crosshair = s.crosshair_mode;
self.input.kinetic = None;
if matches!(self.input.drag, Drag::EditingDrawing { .. }) {
self.input.drag = Drag::Idle;
}
for (pane, p) in self.panes.iter_mut().zip(&s.panes) {
pane.stretch = if p.stretch.is_finite() && p.stretch > 0.0 {
p.stretch
} else {
1.0
};
let ps = &mut pane.price_scale;
let st = p.price_scale;
let _ = ps.set_mode(st.mode);
let _ = ps.set_margins(st.margins.0, st.margins.1);
ps.set_inverted(st.inverted);
match st.range {
Some((lo, hi)) => {
let _ = ps.set_range(lo, hi);
}
None => ps.set_auto_scale(true),
}
}
self.drawings.replace_all(tools);
self.invalidation = Invalidation::Full;
Ok(())
}
}