Skip to main content

ferrochart_core/drawing/
manager.rs

1//! The drawings of a chart: registry of tool factories, z order, selection,
2//! visibility, locking, and the undo/redo stack.
3
4use crate::chart::ChartEvent;
5use crate::data::{DrawingId, PaneId};
6use crate::error::{Error, Result};
7use crate::geom::RectPx;
8
9use super::{Anchor, AnchorCount, DrawingData, DrawingStyle, DrawingTool, MAX_ANCHORS, Param};
10
11/// Builds a drawing from its saved form.
12pub type DrawingFactory = fn(&DrawingData) -> Result<Box<dyn DrawingTool>>;
13
14/// Undo history length.
15const MAX_HISTORY: usize = 256;
16
17pub(crate) struct Entry {
18    pub(crate) id: DrawingId,
19    pub(crate) pane: PaneId,
20    pub(crate) tool: Box<dyn DrawingTool>,
21    pub(crate) visible: bool,
22    pub(crate) locked: bool,
23    /// Screen bounds of the last frame (empty when nothing was drawn): the
24    /// coarse hit test.
25    pub(crate) bbox: RectPx,
26}
27
28/// An undoable change.
29enum Command {
30    Add {
31        id: DrawingId,
32        pane: PaneId,
33        z: usize,
34        data: DrawingData,
35    },
36    Remove {
37        id: DrawingId,
38        pane: PaneId,
39        z: usize,
40        data: DrawingData,
41        visible: bool,
42        locked: bool,
43    },
44    Move {
45        id: DrawingId,
46        before: Vec<Anchor>,
47        after: Vec<Anchor>,
48    },
49    Restyle {
50        id: DrawingId,
51        before: DrawingData,
52        after: DrawingData,
53    },
54}
55
56/// A local change of a drawing, for drawing sync.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub(crate) enum LocalChange {
59    Added(DrawingId),
60    Modified(DrawingId),
61    Visible(DrawingId),
62    Locked(DrawingId),
63    Removed(DrawingId),
64}
65
66/// A drawing being created by clicks.
67#[derive(Clone, Copy, Debug)]
68pub(crate) struct Creating {
69    pub(crate) id: DrawingId,
70    pub(crate) pane: PaneId,
71    /// The anchor that follows the pointer.
72    pub(crate) step: usize,
73    /// Where the button went down for this step; releasing it far away
74    /// counts as a click (press-drag-release creation).
75    pub(crate) down: Option<crate::geom::PointPx>,
76    /// How the drawing is created.
77    pub(crate) count: AnchorCount,
78    /// Freehand: where the last anchor was added.
79    pub(crate) last: crate::geom::PointPx,
80}
81
82/// The drawings of a chart (`Chart::drawings`).
83///
84/// Changes made through the manager (and by the user with the mouse and
85/// keyboard) are undoable: adding, removing, moving and restyling a drawing.
86/// Selection, visibility, locking and z order are not part of the history.
87///
88/// # Examples
89///
90/// ```
91/// use ferrochart_core::chart::{SeriesData, SeriesOptions};
92/// use ferrochart_core::drawing::{Anchor, DrawingData};
93/// use ferrochart_core::frame::SeriesKind;
94/// use ferrochart_core::testing::random_walk;
95/// use ferrochart_core::{Chart, ChartOptions};
96///
97/// let mut chart = Chart::new(ChartOptions::default());
98/// let pane = chart.main_pane();
99/// let candles = chart.add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())?;
100/// chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 100, 0, 60_000)?))?;
101///
102/// let line = DrawingData::new("trend_line", vec![
103///     Anchor { time: 0, price: 100.0 },
104///     Anchor { time: 50 * 60_000, price: 110.0 },
105/// ]);
106/// let id = chart.drawings().add(pane, &line)?;
107/// assert_eq!(chart.drawings().ids().count(), 1);
108/// chart.drawings().undo();
109/// assert!(chart.drawings().data(id).is_none());
110/// chart.drawings().redo();
111/// assert!(chart.drawings().data(id).is_some());
112/// # Ok::<(), ferrochart_core::Error>(())
113/// ```
114pub struct DrawingManager {
115    factories: Vec<(&'static str, DrawingFactory)>,
116    pub(crate) entries: Vec<Entry>,
117    next_id: u64,
118    panes: Vec<PaneId>,
119    selected: Option<DrawingId>,
120    undo: Vec<Command>,
121    redo: Vec<Command>,
122    /// Kind armed by `start_tool`: the next click on a plot creates one.
123    pub(crate) armed: Option<&'static str>,
124    pub(crate) creating: Option<Creating>,
125    /// Anchors of the drawing being dragged, before the drag.
126    pub(crate) edit_before: Vec<Anchor>,
127    pub(crate) events: Vec<ChartEvent>,
128    /// Something visible changed since the last frame.
129    pub(crate) dirty: bool,
130    /// Local changes not yet sent to the sync group.
131    pub(crate) sync_log: Vec<LocalChange>,
132    /// Record `sync_log` (the chart shares drawings).
133    pub(crate) sync_log_on: bool,
134    /// Applying a received change: do not record it.
135    pub(crate) sync_mute: bool,
136}
137
138impl core::fmt::Debug for DrawingManager {
139    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140        f.debug_struct("DrawingManager")
141            .field("drawings", &self.entries.len())
142            .field("selected", &self.selected)
143            .finish_non_exhaustive()
144    }
145}
146
147impl DrawingManager {
148    pub(crate) fn new(main: PaneId) -> Self {
149        let mut m = Self {
150            factories: Vec::new(),
151            entries: Vec::new(),
152            next_id: 1,
153            panes: vec![main],
154            selected: None,
155            undo: Vec::new(),
156            redo: Vec::new(),
157            armed: None,
158            creating: None,
159            edit_before: Vec::new(),
160            events: Vec::new(),
161            dirty: false,
162            sync_log: Vec::new(),
163            sync_log_on: false,
164            sync_mute: false,
165        };
166        for kind in super::BUILTIN_KINDS {
167            m.register(kind, super::builtin);
168        }
169        m
170    }
171
172    /// Registers (or replaces) the factory of `kind`.
173    pub fn register(&mut self, kind: &'static str, factory: DrawingFactory) {
174        match self.factories.iter_mut().find(|(k, _)| *k == kind) {
175            Some((_, f)) => *f = factory,
176            None => self.factories.push((kind, factory)),
177        }
178    }
179
180    /// Registered kinds.
181    pub fn kinds(&self) -> impl Iterator<Item = &'static str> + '_ {
182        self.factories.iter().map(|(k, _)| *k)
183    }
184
185    fn factory(&self, kind: &str) -> Result<(&'static str, DrawingFactory)> {
186        self.factories
187            .iter()
188            .find(|(k, _)| *k == kind)
189            .copied()
190            .ok_or(Error::InvalidArgument("unknown drawing kind"))
191    }
192
193    fn build(&self, data: &DrawingData) -> Result<Box<dyn DrawingTool>> {
194        let (_, factory) = self.factory(&data.kind)?;
195        if data.anchors.iter().any(|a| !a.price.is_finite()) {
196            return Err(Error::InvalidArgument("anchor prices must be finite"));
197        }
198        let mut tool = factory(data)?;
199        let count = tool.anchor_count();
200        if tool.anchors().len() < count.min() {
201            return Err(Error::InvalidArgument("too few anchors"));
202        }
203        if !matches!(count, AnchorCount::Fixed(_)) && tool.anchors().len() > count.max() {
204            return Err(Error::InvalidArgument("too many anchors"));
205        }
206        tool.finish();
207        Ok(tool)
208    }
209
210    /// Builds the tool of a saved drawing (validates it like `add`).
211    pub(crate) fn build_saved(&self, data: &DrawingData) -> Result<Box<dyn DrawingTool>> {
212        self.build(data)
213    }
214
215    /// Replaces every drawing with `items` (bottom to top): `(pane, tool,
216    /// visible, locked)`. Cancels the tool in progress, clears the selection
217    /// and the history (`Chart::load_state`).
218    pub(crate) fn replace_all(&mut self, items: Vec<(PaneId, Box<dyn DrawingTool>, bool, bool)>) {
219        self.cancel_creation();
220        self.armed = None;
221        for e in core::mem::take(&mut self.entries) {
222            self.after_removal(e.id);
223        }
224        for (pane, tool, visible, locked) in items {
225            let id = DrawingId(self.next_id);
226            self.next_id += 1;
227            let z = self.entries.len();
228            self.insert(id, pane, z, tool);
229            if let Some(e) = self.entries.last_mut() {
230                e.visible = visible;
231                e.locked = locked;
232            }
233            self.emit(ChartEvent::DrawingCreated(id));
234        }
235        self.undo.clear();
236        self.redo.clear();
237        self.dirty = true;
238    }
239
240    pub(crate) fn pane_added(&mut self, pane: PaneId) {
241        self.panes.push(pane);
242    }
243
244    /// Removes the drawings of a removed pane. The history is cleared: its
245    /// commands may refer to them.
246    pub(crate) fn pane_removed(&mut self, pane: PaneId) {
247        self.panes.retain(|&p| p != pane);
248        if self.creating.is_some_and(|c| c.pane == pane) {
249            self.cancel_creation();
250        }
251        let mut removed = false;
252        let mut k = 0;
253        while k < self.entries.len() {
254            if self.entries[k].pane == pane {
255                let id = self.entries.remove(k).id;
256                self.after_removal(id);
257                removed = true;
258            } else {
259                k += 1;
260            }
261        }
262        if removed {
263            self.undo.clear();
264            self.redo.clear();
265        }
266    }
267
268    fn position(&self, id: DrawingId) -> Result<usize> {
269        self.entries
270            .iter()
271            .position(|e| e.id == id)
272            .ok_or(Error::UnknownId)
273    }
274
275    pub(crate) fn entry(&self, id: DrawingId) -> Option<&Entry> {
276        self.entries.iter().find(|e| e.id == id)
277    }
278
279    pub(crate) fn entry_mut(&mut self, id: DrawingId) -> Option<&mut Entry> {
280        self.entries.iter_mut().find(|e| e.id == id)
281    }
282
283    /// Reports `e`, noting created, modified and removed drawings for sync.
284    fn emit(&mut self, e: ChartEvent) {
285        match e {
286            ChartEvent::DrawingCreated(id) => self.log(LocalChange::Added(id)),
287            ChartEvent::DrawingModified(id) => self.log(LocalChange::Modified(id)),
288            ChartEvent::DrawingRemoved(id) => self.log(LocalChange::Removed(id)),
289            _ => {}
290        }
291        self.events.push(e);
292    }
293
294    fn log(&mut self, c: LocalChange) {
295        if self.sync_log_on && !self.sync_mute {
296            self.sync_log.push(c);
297        }
298    }
299
300    /// Adds a received drawing on top (not undoable).
301    pub(crate) fn add_synced(
302        &mut self,
303        pane: PaneId,
304        data: &DrawingData,
305        visible: bool,
306        locked: bool,
307    ) -> Result<DrawingId> {
308        if !self.panes.contains(&pane) {
309            return Err(Error::UnknownId);
310        }
311        let tool = self.build(data)?;
312        let id = DrawingId(self.next_id);
313        self.next_id += 1;
314        let z = self.entries.len();
315        self.insert(id, pane, z, tool);
316        if let Some(e) = self.entries.get_mut(z) {
317            e.visible = visible;
318            e.locked = locked;
319        }
320        self.emit(ChartEvent::DrawingCreated(id));
321        Ok(id)
322    }
323
324    /// Replaces a drawing with received data (not undoable).
325    pub(crate) fn update_synced(&mut self, id: DrawingId, data: &DrawingData) -> Result<()> {
326        if self.data(id).ok_or(Error::UnknownId)? == *data {
327            return Ok(());
328        }
329        self.replace(id, data)?;
330        self.emit(ChartEvent::DrawingModified(id));
331        Ok(())
332    }
333
334    /// Removes a drawing removed elsewhere (not undoable).
335    pub(crate) fn remove_synced(&mut self, id: DrawingId) -> Result<()> {
336        let z = self.position(id)?;
337        if self.creating.is_some_and(|c| c.id == id) {
338            self.cancel_creation();
339            return Ok(());
340        }
341        self.entries.remove(z);
342        self.after_removal(id);
343        Ok(())
344    }
345
346    fn record(&mut self, cmd: Command) {
347        if self.undo.len() >= MAX_HISTORY {
348            self.undo.remove(0);
349        }
350        self.undo.push(cmd);
351        self.redo.clear();
352    }
353
354    fn insert(&mut self, id: DrawingId, pane: PaneId, z: usize, tool: Box<dyn DrawingTool>) {
355        let z = z.min(self.entries.len());
356        self.entries.insert(
357            z,
358            Entry {
359                id,
360                pane,
361                tool,
362                visible: true,
363                locked: false,
364                bbox: RectPx::default(),
365            },
366        );
367        self.dirty = true;
368    }
369
370    fn after_removal(&mut self, id: DrawingId) {
371        if self.selected == Some(id) {
372            self.selected = None;
373            self.events.push(ChartEvent::DrawingSelected(None));
374        }
375        self.emit(ChartEvent::DrawingRemoved(id));
376        self.dirty = true;
377    }
378
379    /// Adds a drawing on `pane` (on top of the others).
380    ///
381    /// # Errors
382    ///
383    /// - [`Error::UnknownId`] for an unknown pane;
384    /// - [`Error::InvalidArgument`] for an unregistered kind, non-finite
385    ///   prices, too few anchors, or parameters the factory refuses.
386    pub fn add(&mut self, pane: PaneId, data: &DrawingData) -> Result<DrawingId> {
387        if !self.panes.contains(&pane) {
388            return Err(Error::UnknownId);
389        }
390        let tool = self.build(data)?;
391        let id = DrawingId(self.next_id);
392        self.next_id += 1;
393        let z = self.entries.len();
394        let data = tool.save();
395        self.insert(id, pane, z, tool);
396        self.record(Command::Add { id, pane, z, data });
397        self.emit(ChartEvent::DrawingCreated(id));
398        Ok(id)
399    }
400
401    /// Removes a drawing.
402    ///
403    /// # Errors
404    ///
405    /// [`Error::UnknownId`] for an unknown drawing.
406    pub fn remove(&mut self, id: DrawingId) -> Result<()> {
407        let z = self.position(id)?;
408        if self.creating.is_some_and(|c| c.id == id) {
409            self.cancel_creation();
410            return Ok(());
411        }
412        let e = self.entries.remove(z);
413        self.record(Command::Remove {
414            id,
415            pane: e.pane,
416            z,
417            data: e.tool.save(),
418            visible: e.visible,
419            locked: e.locked,
420        });
421        self.after_removal(id);
422        Ok(())
423    }
424
425    /// Ids of all drawings, bottom to top.
426    pub fn ids(&self) -> impl Iterator<Item = DrawingId> + '_ {
427        self.entries.iter().map(|e| e.id)
428    }
429
430    /// A drawing.
431    pub fn get(&self, id: DrawingId) -> Option<&dyn DrawingTool> {
432        self.entry(id).map(|e| e.tool.as_ref())
433    }
434
435    /// The saved form of a drawing.
436    pub fn data(&self, id: DrawingId) -> Option<DrawingData> {
437        self.get(id).map(DrawingTool::save)
438    }
439
440    /// The pane of a drawing.
441    pub fn pane_of(&self, id: DrawingId) -> Option<PaneId> {
442        self.entry(id).map(|e| e.pane)
443    }
444
445    /// Moves a drawing's anchors (undoable).
446    ///
447    /// # Errors
448    ///
449    /// - [`Error::UnknownId`] for an unknown drawing;
450    /// - [`Error::InvalidArgument`] if the number of anchors differs or a
451    ///   price is not finite.
452    pub fn set_anchors(&mut self, id: DrawingId, anchors: &[Anchor]) -> Result<()> {
453        let e = self.entry_mut(id).ok_or(Error::UnknownId)?;
454        if anchors.len() != e.tool.anchors().len() || anchors.iter().any(|a| !a.price.is_finite()) {
455            return Err(Error::InvalidArgument("anchors do not fit the drawing"));
456        }
457        let before = e.tool.anchors().to_vec();
458        e.tool.anchors_mut().copy_from_slice(anchors);
459        self.moved(id, before);
460        Ok(())
461    }
462
463    /// Records a finished move of `id` from `before` (no-op if unchanged).
464    pub(crate) fn moved(&mut self, id: DrawingId, before: Vec<Anchor>) {
465        let Some(e) = self.entry(id) else {
466            return;
467        };
468        let after = e.tool.anchors().to_vec();
469        if after != before {
470            self.record(Command::Move { id, before, after });
471            self.emit(ChartEvent::DrawingModified(id));
472        }
473        self.dirty = true;
474    }
475
476    fn replace(&mut self, id: DrawingId, data: &DrawingData) -> Result<()> {
477        let z = self.position(id)?;
478        let tool = self.build(data)?;
479        self.entries[z].tool = tool;
480        self.dirty = true;
481        Ok(())
482    }
483
484    fn restyle(&mut self, id: DrawingId, edit: impl FnOnce(&mut DrawingData)) -> Result<()> {
485        let before = self.data(id).ok_or(Error::UnknownId)?;
486        let mut after = before.clone();
487        edit(&mut after);
488        if after == before {
489            return Ok(());
490        }
491        self.replace(id, &after)?;
492        self.record(Command::Restyle { id, before, after });
493        self.emit(ChartEvent::DrawingModified(id));
494        Ok(())
495    }
496
497    /// Changes a drawing's style (undoable).
498    ///
499    /// # Errors
500    ///
501    /// [`Error::UnknownId`] for an unknown drawing.
502    pub fn set_style(&mut self, id: DrawingId, style: DrawingStyle) -> Result<()> {
503        self.restyle(id, |d| d.style = style)
504    }
505
506    /// Sets a tool-specific parameter (undoable), e.g. `"text"` of a text or
507    /// `"levels"` of a Fibonacci retracement.
508    ///
509    /// # Errors
510    ///
511    /// - [`Error::UnknownId`] for an unknown drawing;
512    /// - [`Error::InvalidArgument`] if the tool refuses the value; the
513    ///   drawing is unchanged.
514    pub fn set_param(&mut self, id: DrawingId, key: &str, value: Param) -> Result<()> {
515        self.restyle(id, |d| d.set(key, value))
516    }
517
518    /// Shows or hides a drawing.
519    ///
520    /// # Errors
521    ///
522    /// [`Error::UnknownId`] for an unknown drawing.
523    pub fn set_visible(&mut self, id: DrawingId, visible: bool) -> Result<()> {
524        let e = self.entry_mut(id).ok_or(Error::UnknownId)?;
525        let changed = e.visible != visible;
526        e.visible = visible;
527        if !visible && self.selected == Some(id) {
528            self.select(None)?;
529        }
530        if changed {
531            self.log(LocalChange::Visible(id));
532        }
533        self.dirty = true;
534        Ok(())
535    }
536
537    /// Whether a drawing is visible.
538    pub fn is_visible(&self, id: DrawingId) -> Option<bool> {
539        self.entry(id).map(|e| e.visible)
540    }
541
542    /// Locks a drawing: it can be selected and deleted, but not dragged.
543    ///
544    /// # Errors
545    ///
546    /// [`Error::UnknownId`] for an unknown drawing.
547    pub fn set_locked(&mut self, id: DrawingId, locked: bool) -> Result<()> {
548        let e = self.entry_mut(id).ok_or(Error::UnknownId)?;
549        let changed = e.locked != locked;
550        e.locked = locked;
551        if changed {
552            self.log(LocalChange::Locked(id));
553        }
554        Ok(())
555    }
556
557    /// Whether a drawing is locked.
558    pub fn is_locked(&self, id: DrawingId) -> Option<bool> {
559        self.entry(id).map(|e| e.locked)
560    }
561
562    /// Moves a drawing above all others.
563    ///
564    /// # Errors
565    ///
566    /// [`Error::UnknownId`] for an unknown drawing.
567    pub fn bring_to_front(&mut self, id: DrawingId) -> Result<()> {
568        let z = self.position(id)?;
569        let e = self.entries.remove(z);
570        self.entries.push(e);
571        self.dirty = true;
572        Ok(())
573    }
574
575    /// Moves a drawing below all others.
576    ///
577    /// # Errors
578    ///
579    /// [`Error::UnknownId`] for an unknown drawing.
580    pub fn send_to_back(&mut self, id: DrawingId) -> Result<()> {
581        let z = self.position(id)?;
582        let e = self.entries.remove(z);
583        self.entries.insert(0, e);
584        self.dirty = true;
585        Ok(())
586    }
587
588    /// Selects a drawing (`None` clears the selection).
589    ///
590    /// # Errors
591    ///
592    /// [`Error::UnknownId`] for an unknown drawing.
593    pub fn select(&mut self, id: Option<DrawingId>) -> Result<()> {
594        if let Some(id) = id {
595            self.position(id)?;
596        }
597        if self.selected != id {
598            self.selected = id;
599            self.events.push(ChartEvent::DrawingSelected(id));
600            self.dirty = true;
601        }
602        Ok(())
603    }
604
605    /// The selected drawing.
606    pub fn selected(&self) -> Option<DrawingId> {
607        self.selected
608    }
609
610    /// Arms a tool: the next click on a plot starts creating a drawing of
611    /// `kind`. Escape cancels.
612    ///
613    /// # Errors
614    ///
615    /// [`Error::InvalidArgument`] for an unregistered kind.
616    pub fn start_tool(&mut self, kind: &str) -> Result<()> {
617        let (kind, _) = self.factory(kind)?;
618        self.cancel_creation();
619        self.armed = Some(kind);
620        Ok(())
621    }
622
623    /// Disarms the tool and drops a drawing being created.
624    pub fn cancel_tool(&mut self) {
625        self.cancel_creation();
626        self.armed = None;
627    }
628
629    /// The armed tool, or the kind being created.
630    pub fn active_tool(&self) -> Option<&'static str> {
631        self.armed.or_else(|| {
632            let c = self.creating?;
633            Some(self.entry(c.id)?.tool.kind())
634        })
635    }
636
637    /// Starts creating a drawing of the armed kind at `at` on `pane`; it is
638    /// finished at once if it needs a single click.
639    pub(crate) fn begin_creation(&mut self, pane: PaneId, at: Anchor, down: crate::geom::PointPx) {
640        let Some(kind) = self.armed.take() else {
641            return;
642        };
643        let Ok((_, factory)) = self.factory(kind) else {
644            return;
645        };
646        let Ok(mut tool) = factory(&DrawingData::new(kind, Vec::new())) else {
647            return;
648        };
649        let count = tool.anchor_count();
650        // Fixed: all anchors, the second follows the pointer; Open: the
651        // first and the one following the pointer; Freehand: the first.
652        let n = match count {
653            AnchorCount::Fixed(n) => n.max(1),
654            AnchorCount::Open { .. } => 2,
655            AnchorCount::Freehand => 1,
656        };
657        let anchors = tool.anchors_mut();
658        anchors.clear();
659        anchors.resize(n, at);
660        let id = DrawingId(self.next_id);
661        self.next_id += 1;
662        let z = self.entries.len();
663        self.insert(id, pane, z, tool);
664        self.creating = Some(Creating {
665            id,
666            pane,
667            step: 1,
668            down: Some(down),
669            count,
670            last: down,
671        });
672        if count == AnchorCount::Fixed(n) && n == 1 {
673            self.finish_creation();
674        }
675    }
676
677    /// The creation click of the current step at `at`.
678    pub(crate) fn creation_click(&mut self, at: Anchor, down: Option<crate::geom::PointPx>) {
679        let Some(c) = self.creating else {
680            return;
681        };
682        let Some(e) = self.entry_mut(c.id) else {
683            self.creating = None;
684            return;
685        };
686        let anchors = e.tool.anchors_mut();
687        if let AnchorCount::Open { .. } = c.count {
688            if let Some(a) = anchors.get_mut(c.step) {
689                *a = at;
690            }
691            if anchors.len() >= c.count.max() {
692                self.finish_open();
693                return;
694            }
695            anchors.push(at);
696            self.creating = Some(Creating {
697                step: c.step + 1,
698                down,
699                ..c
700            });
701            self.dirty = true;
702            return;
703        }
704        if c.count == AnchorCount::Freehand {
705            return;
706        }
707        let n = c.count.min();
708        if let Some(a) = anchors.get_mut(c.step) {
709            *a = at;
710        }
711        if c.step + 1 >= n {
712            self.finish_creation();
713        } else {
714            if let Some(a) = anchors.get_mut(c.step + 1) {
715                *a = at;
716            }
717            self.creating = Some(Creating {
718                step: c.step + 1,
719                down,
720                ..c
721            });
722        }
723        self.dirty = true;
724    }
725
726    /// Freehand: adds `at` (at screen point `p`) while the button is down,
727    /// once the pointer moved `step` px from the last anchor.
728    pub(crate) fn freehand_move(&mut self, at: Anchor, p: crate::geom::PointPx, step: f32) {
729        let Some(c) = self.creating.filter(|c| c.count == AnchorCount::Freehand) else {
730            return;
731        };
732        if c.down.is_none() || (p.x - c.last.x).hypot(p.y - c.last.y) < step {
733            return;
734        }
735        let Some(e) = self.entry_mut(c.id) else {
736            return;
737        };
738        let anchors = e.tool.anchors_mut();
739        if anchors.len() < MAX_ANCHORS {
740            anchors.push(at);
741            self.creating = Some(Creating { last: p, ..c });
742            self.dirty = true;
743        }
744    }
745
746    /// Freehand: the button was released; finishes the drawing (or drops it
747    /// with fewer than 2 anchors).
748    pub(crate) fn freehand_release(&mut self) {
749        let Some(c) = self.creating.filter(|c| c.count == AnchorCount::Freehand) else {
750            return;
751        };
752        let n = self.entry(c.id).map_or(0, |e| e.tool.anchors().len());
753        if n >= c.count.min() {
754            self.finish_creation();
755        } else {
756            self.cancel_creation();
757        }
758    }
759
760    /// Whether the drawing being created is `Open` or `Freehand`.
761    pub(crate) fn creating_count(&self) -> Option<AnchorCount> {
762        self.creating.map(|c| c.count)
763    }
764
765    /// Open: finishes the drawing (double click, Enter), without the anchor
766    /// following the pointer and repeated last anchors (the second click of
767    /// a double click). Returns `false`, changing nothing, with fewer anchors
768    /// than the minimum.
769    pub(crate) fn finish_open(&mut self) -> bool {
770        let Some(c) = self
771            .creating
772            .filter(|c| matches!(c.count, AnchorCount::Open { .. }))
773        else {
774            return false;
775        };
776        let Some(e) = self.entry_mut(c.id) else {
777            return false;
778        };
779        let anchors = e.tool.anchors_mut();
780        let follower = (anchors.len() > c.step).then(|| anchors.pop()).flatten();
781        let mut keep = anchors.len();
782        while keep >= 2 && anchors[keep - 1] == anchors[keep - 2] {
783            keep -= 1;
784        }
785        if keep < c.count.min() {
786            if let Some(a) = follower {
787                anchors.push(a);
788            }
789            return false;
790        }
791        anchors.truncate(keep);
792        self.finish_creation();
793        true
794    }
795
796    /// Escape while creating: an `Open` drawing with enough anchors is
797    /// finished, anything else is dropped.
798    pub(crate) fn escape_creation(&mut self) {
799        if !self.finish_open() {
800            self.cancel_tool();
801        }
802    }
803
804    /// Moves the anchor that follows the pointer.
805    pub(crate) fn creation_move(&mut self, at: Anchor) {
806        let Some(c) = self.creating.filter(|c| c.count != AnchorCount::Freehand) else {
807            return;
808        };
809        if let Some(a) = self
810            .entry_mut(c.id)
811            .and_then(|e| e.tool.anchors_mut().get_mut(c.step))
812        {
813            *a = at;
814            self.dirty = true;
815        }
816    }
817
818    fn finish_creation(&mut self) {
819        let Some(c) = self.creating.take() else {
820            return;
821        };
822        let Ok(z) = self.position(c.id) else {
823            return;
824        };
825        self.entries[z].tool.finish();
826        let data = self.entries[z].tool.save();
827        self.record(Command::Add {
828            id: c.id,
829            pane: c.pane,
830            z,
831            data,
832        });
833        self.emit(ChartEvent::DrawingCreated(c.id));
834        let _ = self.select(Some(c.id));
835        self.dirty = true;
836    }
837
838    fn cancel_creation(&mut self) {
839        if let Some(c) = self.creating.take() {
840            self.entries.retain(|e| e.id != c.id);
841            self.dirty = true;
842        }
843    }
844
845    /// Whether there is something to undo.
846    pub fn can_undo(&self) -> bool {
847        !self.undo.is_empty()
848    }
849
850    /// Whether there is something to redo.
851    pub fn can_redo(&self) -> bool {
852        !self.redo.is_empty()
853    }
854
855    /// Clears the undo/redo history.
856    pub fn clear_history(&mut self) {
857        self.undo.clear();
858        self.redo.clear();
859    }
860
861    /// Undoes the last change; `false` if there was none.
862    pub fn undo(&mut self) -> bool {
863        self.cancel_creation();
864        let Some(cmd) = self.undo.pop() else {
865            return false;
866        };
867        let inverse = self.apply(cmd, true);
868        if let Some(c) = inverse {
869            self.redo.push(c);
870        }
871        true
872    }
873
874    /// Redoes the last undone change; `false` if there was none.
875    pub fn redo(&mut self) -> bool {
876        self.cancel_creation();
877        let Some(cmd) = self.redo.pop() else {
878            return false;
879        };
880        if let Some(c) = self.apply(cmd, false) {
881            self.undo.push(c);
882        }
883        true
884    }
885
886    /// Applies `cmd` backwards (`undo`) or forwards and returns it for the
887    /// other stack; `None` if it no longer applies.
888    fn apply(&mut self, cmd: Command, undo: bool) -> Option<Command> {
889        match cmd {
890            Command::Add { id, pane, z, data } if undo => {
891                let pos = self.position(id).ok()?;
892                self.entries.remove(pos);
893                self.after_removal(id);
894                Some(Command::Add { id, pane, z, data })
895            }
896            Command::Add { id, pane, z, data } => {
897                self.restore(id, pane, z, &data, true, false)?;
898                Some(Command::Add { id, pane, z, data })
899            }
900            Command::Remove {
901                id,
902                pane,
903                z,
904                data,
905                visible,
906                locked,
907            } => {
908                if undo {
909                    self.restore(id, pane, z, &data, visible, locked)?;
910                } else {
911                    let pos = self.position(id).ok()?;
912                    self.entries.remove(pos);
913                    self.after_removal(id);
914                }
915                Some(Command::Remove {
916                    id,
917                    pane,
918                    z,
919                    data,
920                    visible,
921                    locked,
922                })
923            }
924            Command::Move { id, before, after } => {
925                let target = if undo { &before } else { &after };
926                let e = self.entry_mut(id)?;
927                let anchors = e.tool.anchors_mut();
928                anchors.clear();
929                anchors.extend_from_slice(target);
930                self.emit(ChartEvent::DrawingModified(id));
931                self.dirty = true;
932                Some(Command::Move { id, before, after })
933            }
934            Command::Restyle { id, before, after } => {
935                let target = if undo { &before } else { &after };
936                self.replace(id, target).ok()?;
937                self.emit(ChartEvent::DrawingModified(id));
938                Some(Command::Restyle { id, before, after })
939            }
940        }
941    }
942
943    fn restore(
944        &mut self,
945        id: DrawingId,
946        pane: PaneId,
947        z: usize,
948        data: &DrawingData,
949        visible: bool,
950        locked: bool,
951    ) -> Option<()> {
952        if !self.panes.contains(&pane) {
953            return None;
954        }
955        let tool = self.build(data).ok()?;
956        self.insert(id, pane, z, tool);
957        if let Some(e) = self.entry_mut(id) {
958            e.visible = visible;
959            e.locked = locked;
960        }
961        self.emit(ChartEvent::DrawingCreated(id));
962        Some(())
963    }
964}