Skip to main content

ferrochart_core/sync/
drawings.rs

1//! Drawing sync between charts of the same symbol.
2//!
3//! Drawing operations are not `Copy`, so they do not use the bus' slots:
4//! they go through a bounded queue ([`MAX_OPS`] operations, the oldest are
5//! dropped), and the bus keeps the current state of the group's drawings, a
6//! table `SyncKey → (DrawingData, visible, locked)`. A member that fell
7//! further behind than the queue reaches is rebuilt from the table.
8//!
9//! Each chart maps [`SyncKey`]s to its own [`DrawingId`]s. Only drawings of
10//! the main pane are shared (other panes may show different indicators in
11//! each chart), and received drawings go to the main pane. Received
12//! operations bypass the undo stack; local undo and redo send their effect
13//! like any other change, so the charts converge. Selection and the tool in
14//! progress are not shared.
15//!
16//! Local changes are sent at the start and end of the chart's next frame
17//! (and by [`Chart::take_drawing_sync_ops`]).
18
19use std::collections::VecDeque;
20use std::sync::Arc;
21
22use super::SyncGroup;
23use crate::chart::{Chart, ChartEvent};
24use crate::data::DrawingId;
25use crate::drawing::{DrawingData, LocalChange};
26use crate::error::{Error, Result};
27
28/// Length of the bus' operation queue and of a chart's outbox.
29pub const MAX_OPS: usize = 1024;
30
31/// Identity of a drawing within a sync group, assigned by the group's bus.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34pub struct SyncKey(pub u64);
35
36/// A change of a synced drawing.
37#[derive(Clone, Debug, PartialEq)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39#[non_exhaustive]
40pub enum DrawingSyncOp {
41    /// A drawing was added (or is part of a full state).
42    Add {
43        /// Its key.
44        key: SyncKey,
45        /// Its saved form.
46        data: DrawingData,
47        /// Whether it is shown.
48        visible: bool,
49        /// Whether it is locked.
50        locked: bool,
51    },
52    /// A drawing was moved, restyled or given new parameters.
53    Update {
54        /// Its key.
55        key: SyncKey,
56        /// Its new saved form.
57        data: DrawingData,
58    },
59    /// A drawing was shown or hidden.
60    SetVisible {
61        /// Its key.
62        key: SyncKey,
63        /// Whether it is shown.
64        visible: bool,
65    },
66    /// A drawing was locked or unlocked.
67    SetLocked {
68        /// Its key.
69        key: SyncKey,
70        /// Whether it is locked.
71        locked: bool,
72    },
73    /// A drawing was removed.
74    Remove {
75        /// Its key.
76        key: SyncKey,
77    },
78}
79
80impl DrawingSyncOp {
81    /// The drawing the operation applies to.
82    pub fn key(&self) -> SyncKey {
83        match self {
84            Self::Add { key, .. }
85            | Self::Update { key, .. }
86            | Self::SetVisible { key, .. }
87            | Self::SetLocked { key, .. }
88            | Self::Remove { key } => *key,
89        }
90    }
91}
92
93/// A drawing of the bus' state table.
94#[derive(Clone, Debug)]
95struct TableEntry {
96    key: SyncKey,
97    data: DrawingData,
98    visible: bool,
99    locked: bool,
100}
101
102/// Drawing part of the bus.
103#[derive(Debug, Default)]
104pub(super) struct DrawingBus {
105    /// High 32 bits of the keys.
106    pub(super) origin: u32,
107    next_key: u32,
108    /// Sequence number of the last operation (0: none).
109    seq: u64,
110    /// `(seq, sender, op)`, oldest first.
111    ops: VecDeque<(u64, u32, DrawingSyncOp)>,
112    /// Current drawings, in the order they were added.
113    table: Vec<TableEntry>,
114}
115
116impl DrawingBus {
117    fn key(&mut self) -> SyncKey {
118        self.next_key = self.next_key.wrapping_add(1);
119        SyncKey(u64::from(self.origin) << 32 | u64::from(self.next_key))
120    }
121
122    /// Whether a member that saw operations up to `seen` must apply some.
123    pub(super) fn pending(&self, member: u32, seen: u64) -> bool {
124        if self.seq <= seen {
125            return false;
126        }
127        self.behind(seen)
128            || self
129                .ops
130                .iter()
131                .rev()
132                .take_while(|(s, ..)| *s > seen)
133                .any(|(_, from, _)| *from != member)
134    }
135
136    /// Whether operations after `seen` were dropped from the queue.
137    fn behind(&self, seen: u64) -> bool {
138        self.ops.front().is_some_and(|(s, ..)| *s > seen + 1)
139    }
140
141    fn post(&mut self, member: u32, op: DrawingSyncOp) {
142        let pos = self.table.iter().position(|e| e.key == op.key());
143        match (&op, pos) {
144            (
145                DrawingSyncOp::Add {
146                    key,
147                    data,
148                    visible,
149                    locked,
150                },
151                _,
152            ) => {
153                let entry = TableEntry {
154                    key: *key,
155                    data: data.clone(),
156                    visible: *visible,
157                    locked: *locked,
158                };
159                match pos {
160                    Some(i) => self.table[i] = entry,
161                    None => self.table.push(entry),
162                }
163            }
164            (DrawingSyncOp::Update { data, .. }, Some(i)) => self.table[i].data = data.clone(),
165            (DrawingSyncOp::SetVisible { visible, .. }, Some(i)) => {
166                self.table[i].visible = *visible;
167            }
168            (DrawingSyncOp::SetLocked { locked, .. }, Some(i)) => self.table[i].locked = *locked,
169            (DrawingSyncOp::Remove { .. }, Some(i)) => {
170                self.table.remove(i);
171            }
172            _ => {}
173        }
174        self.seq += 1;
175        if self.ops.len() >= MAX_OPS {
176            self.ops.pop_front();
177        }
178        self.ops.push_back((self.seq, member, op));
179    }
180}
181
182/// Drawing sync state of a chart.
183#[derive(Clone, Debug, Default)]
184pub(crate) struct DrawingSyncState {
185    /// Synced drawings of this chart.
186    keys: Vec<(SyncKey, DrawingId)>,
187    /// The group `keys` came from: kept when the chart leaves and joins the
188    /// same group again, dropped for another group.
189    key_group: Option<SyncGroup>,
190    /// Operations this chart sent, not yet taken by the host.
191    outbox: VecDeque<DrawingSyncOp>,
192    /// `ChartEvent::DrawingSync` was reported and the outbox not taken since.
193    reported: bool,
194}
195
196impl DrawingSyncState {
197    fn id_of(&self, key: SyncKey) -> Option<DrawingId> {
198        self.keys.iter().find(|(k, _)| *k == key).map(|&(_, id)| id)
199    }
200
201    fn key_of(&self, id: DrawingId) -> Option<SyncKey> {
202        self.keys.iter().find(|(_, d)| *d == id).map(|&(k, _)| k)
203    }
204
205    fn forget(&mut self, key: SyncKey) {
206        self.keys.retain(|(k, _)| *k != key);
207    }
208}
209
210impl Chart {
211    /// Joining with drawings: takes over the group's drawings, then shares
212    /// the chart's own drawings of the main pane.
213    pub(super) fn join_drawing_sync(&mut self, group: &SyncGroup) {
214        let state = &mut self.sync.drawings;
215        if !state
216            .key_group
217            .as_ref()
218            .is_some_and(|g| Arc::ptr_eq(&g.bus, &group.bus))
219        {
220            state.keys.clear();
221            state.key_group = Some(group.clone());
222        }
223        let (table, seq) = group.with(|bus| (bus.drawings.table.clone(), bus.drawings.seq));
224        if let Some(link) = &mut self.sync.link {
225            link.drawings_seen = seq;
226        }
227        self.resync_drawings(&table);
228        self.drawings.sync_log_on = true;
229        let main = self.main_pane();
230        let creating = self.drawings.creating.map(|c| c.id);
231        let local: Vec<_> = self
232            .drawings
233            .entries
234            .iter()
235            .filter(|e| e.pane == main && Some(e.id) != creating)
236            .map(|e| e.id)
237            .filter(|&id| self.sync.drawings.key_of(id).is_none())
238            .collect();
239        self.drawings
240            .sync_log
241            .extend(local.into_iter().map(LocalChange::Added));
242        self.flush_drawing_sync();
243    }
244
245    /// Makes the synced drawings match `table`: drawings no longer in it are
246    /// removed, the others added or updated. Received changes are not sent
247    /// again.
248    fn resync_drawings(&mut self, table: &[TableEntry]) {
249        let drawings = &self.drawings;
250        self.sync
251            .drawings
252            .keys
253            .retain(|&(_, id)| drawings.entry(id).is_some());
254        let gone: Vec<_> = self
255            .sync
256            .drawings
257            .keys
258            .iter()
259            .filter(|(k, _)| !table.iter().any(|e| e.key == *k))
260            .map(|&(k, _)| k)
261            .collect();
262        for key in gone {
263            let _ = self.apply_drawing_sync(DrawingSyncOp::Remove { key });
264        }
265        for e in table {
266            // A kind this chart does not know is skipped.
267            let _ = self.apply_drawing_sync(DrawingSyncOp::Add {
268                key: e.key,
269                data: e.data.clone(),
270                visible: e.visible,
271                locked: e.locked,
272            });
273        }
274    }
275
276    /// Turns the local changes into operations: posts them to the group and
277    /// keeps them for [`Chart::take_drawing_sync_ops`].
278    pub(super) fn flush_drawing_sync(&mut self) {
279        if self.drawings.sync_log.is_empty() {
280            return;
281        }
282        let mut log = core::mem::take(&mut self.drawings.sync_log);
283        let main = self.main_pane();
284        for &change in &log {
285            if let Some(op) = self.local_op(change, main) {
286                self.send_drawing_op(op);
287            }
288        }
289        log.clear();
290        self.drawings.sync_log = log;
291    }
292
293    fn local_op(
294        &mut self,
295        change: LocalChange,
296        main: crate::data::PaneId,
297    ) -> Option<DrawingSyncOp> {
298        let state = &mut self.sync.drawings;
299        match change {
300            LocalChange::Added(id) => {
301                let e = self.drawings.entry(id).filter(|e| e.pane == main)?;
302                if state.key_of(id).is_some() {
303                    return None;
304                }
305                let link = self.sync.link.as_ref()?;
306                let key = link.group.with(|bus| bus.drawings.key());
307                state.keys.push((key, id));
308                Some(DrawingSyncOp::Add {
309                    key,
310                    data: e.tool.save(),
311                    visible: e.visible,
312                    locked: e.locked,
313                })
314            }
315            LocalChange::Modified(id) => Some(DrawingSyncOp::Update {
316                key: state.key_of(id)?,
317                data: self.drawings.entry(id)?.tool.save(),
318            }),
319            LocalChange::Visible(id) => Some(DrawingSyncOp::SetVisible {
320                key: state.key_of(id)?,
321                visible: self.drawings.entry(id)?.visible,
322            }),
323            LocalChange::Locked(id) => Some(DrawingSyncOp::SetLocked {
324                key: state.key_of(id)?,
325                locked: self.drawings.entry(id)?.locked,
326            }),
327            LocalChange::Removed(id) => {
328                let key = state.key_of(id)?;
329                state.forget(key);
330                Some(DrawingSyncOp::Remove { key })
331            }
332        }
333    }
334
335    fn send_drawing_op(&mut self, op: DrawingSyncOp) {
336        if let Some(link) = &self.sync.link {
337            let member = link.member;
338            link.group.with(|bus| bus.drawings.post(member, op.clone()));
339        }
340        let state = &mut self.sync.drawings;
341        if state.outbox.len() >= MAX_OPS {
342            state.outbox.pop_front();
343        }
344        state.outbox.push_back(op);
345        if !state.reported {
346            state.reported = true;
347            self.push_event(ChartEvent::DrawingSync);
348        }
349    }
350
351    /// Start of a frame: applies the drawing operations of the other members
352    /// (or rebuilds from the group's table after falling behind).
353    pub(super) fn pull_drawing_sync(&mut self) {
354        let Some(link) = &mut self.sync.link else {
355            return;
356        };
357        if !link.opts.drawings {
358            return;
359        }
360        let (member, seen) = (link.member, link.drawings_seen);
361        let mut ops = Vec::new();
362        let mut table = None;
363        let seq = link.group.with(|bus| {
364            let d = &bus.drawings;
365            if d.seq > seen {
366                if d.behind(seen) {
367                    table = Some(d.table.clone());
368                } else {
369                    ops.extend(
370                        d.ops
371                            .iter()
372                            .filter(|(s, from, _)| *s > seen && *from != member)
373                            .map(|(.., op)| op.clone()),
374                    );
375                }
376            }
377            d.seq
378        });
379        link.drawings_seen = seq;
380        if let Some(table) = table {
381            self.resync_drawings(&table);
382        }
383        for op in ops {
384            // An operation on a drawing this chart cannot build is skipped.
385            let _ = self.apply_drawing_sync(op);
386        }
387    }
388
389    /// Takes the drawing operations this chart sent and the host has not
390    /// taken yet (oldest first, at most [`MAX_OPS`]), e.g. to forward them to
391    /// charts in other workers with [`Chart::apply_drawing_sync`]. A new
392    /// [`ChartEvent::DrawingSync`] is reported for the next operation.
393    ///
394    /// # Examples
395    ///
396    /// ```
397    /// use ferrochart_core::drawing::{Anchor, DrawingData};
398    /// use ferrochart_core::sync::{DrawingSyncOp, SyncGroup, SyncOptions};
399    /// use ferrochart_core::{Chart, ChartOptions};
400    ///
401    /// let group = SyncGroup::new();
402    /// let mut a = Chart::new(ChartOptions::default());
403    /// a.join_sync(&group, SyncOptions { drawings: true, ..SyncOptions::default() });
404    /// let line = DrawingData::new("horizontal_line", vec![Anchor { time: 0, price: 100.0 }]);
405    /// let pane = a.main_pane();
406    /// a.drawings().add(pane, &line)?;
407    /// let mut ops = Vec::new();
408    /// a.take_drawing_sync_ops(&mut ops);
409    /// assert!(matches!(ops[..], [DrawingSyncOp::Add { .. }]));
410    ///
411    /// // A chart in another worker (here: not in the group) applies them.
412    /// let mut b = Chart::new(ChartOptions::default());
413    /// for op in ops {
414    ///     b.apply_drawing_sync(op)?;
415    /// }
416    /// assert_eq!(b.drawings().ids().count(), 1);
417    /// # Ok::<(), ferrochart_core::Error>(())
418    /// ```
419    pub fn take_drawing_sync_ops(&mut self, out: &mut Vec<DrawingSyncOp>) {
420        self.flush_drawing_sync();
421        let state = &mut self.sync.drawings;
422        out.extend(state.outbox.drain(..));
423        state.reported = false;
424    }
425
426    /// Applies a drawing operation of another chart, e.g. one the host
427    /// forwarded from another worker. Received drawings go to the main pane;
428    /// the change is not undoable and is not sent again. An `Add` of a key
429    /// the chart already has updates that drawing.
430    ///
431    /// # Errors
432    ///
433    /// - [`Error::UnknownId`] for a key the chart does not have (except for
434    ///   `Add`);
435    /// - [`Error::InvalidArgument`] for a drawing the chart cannot build
436    ///   (unregistered kind, bad anchors or parameters).
437    pub fn apply_drawing_sync(&mut self, op: DrawingSyncOp) -> Result<()> {
438        self.drawings.sync_mute = true;
439        let result = self.apply_drawing_op(op);
440        self.drawings.sync_mute = false;
441        result
442    }
443
444    fn apply_drawing_op(&mut self, op: DrawingSyncOp) -> Result<()> {
445        let main = self.main_pane();
446        let state = &mut self.sync.drawings;
447        let id = state
448            .id_of(op.key())
449            .filter(|&id| self.drawings.entry(id).is_some());
450        match op {
451            DrawingSyncOp::Add {
452                key,
453                data,
454                visible,
455                locked,
456            } => {
457                if let Some(id) = id {
458                    self.drawings.update_synced(id, &data)?;
459                    self.drawings.set_visible(id, visible)?;
460                    return self.drawings.set_locked(id, locked);
461                }
462                state.forget(key);
463                let id = self.drawings.add_synced(main, &data, visible, locked)?;
464                self.sync.drawings.keys.push((key, id));
465                Ok(())
466            }
467            DrawingSyncOp::Update { data, .. } => self
468                .drawings
469                .update_synced(id.ok_or(Error::UnknownId)?, &data),
470            DrawingSyncOp::SetVisible { visible, .. } => self
471                .drawings
472                .set_visible(id.ok_or(Error::UnknownId)?, visible),
473            DrawingSyncOp::SetLocked { locked, .. } => self
474                .drawings
475                .set_locked(id.ok_or(Error::UnknownId)?, locked),
476            DrawingSyncOp::Remove { key } => {
477                state.forget(key);
478                self.drawings.remove_synced(id.ok_or(Error::UnknownId)?)
479            }
480        }
481    }
482
483    /// The synced drawings of this chart as `Add` operations, bottom to top:
484    /// the full state for [`Chart::load_drawing_sync_state`] on a chart that
485    /// joins from another worker.
486    pub fn drawing_sync_state(&self) -> Vec<DrawingSyncOp> {
487        let state = &self.sync.drawings;
488        self.drawings
489            .entries
490            .iter()
491            .filter_map(|e| {
492                Some(DrawingSyncOp::Add {
493                    key: state.key_of(e.id)?,
494                    data: e.tool.save(),
495                    visible: e.visible,
496                    locked: e.locked,
497                })
498            })
499            .collect()
500    }
501
502    /// Makes the synced drawings match `state` (from
503    /// [`Chart::drawing_sync_state`]): synced drawings not in it are removed,
504    /// the others added or updated. Not undoable, not sent again.
505    ///
506    /// # Errors
507    ///
508    /// [`Error::InvalidArgument`] if an operation is not an `Add`, a key
509    /// repeats, or a drawing cannot be built; the chart is unchanged.
510    pub fn load_drawing_sync_state(&mut self, state: &[DrawingSyncOp]) -> Result<()> {
511        let mut table = Vec::with_capacity(state.len());
512        for op in state {
513            let DrawingSyncOp::Add {
514                key,
515                data,
516                visible,
517                locked,
518            } = op
519            else {
520                return Err(Error::InvalidArgument(
521                    "a drawing sync state holds only Add",
522                ));
523            };
524            if table.iter().any(|e: &TableEntry| e.key == *key) {
525                return Err(Error::InvalidArgument("repeated sync key"));
526            }
527            self.drawings.build_saved(data)?;
528            table.push(TableEntry {
529                key: *key,
530                data: data.clone(),
531                visible: *visible,
532                locked: *locked,
533            });
534        }
535        self.resync_drawings(&table);
536        Ok(())
537    }
538}