ferrochart_core/sync/mod.rs
1//! Multi-chart sync: crosshair time, visible time range and drawings.
2//!
3//! A [`SyncGroup`] is a small shared bus (`Arc<Mutex<_>>`) with one slot per
4//! kind of message, holding the latest message and who sent it. A chart that
5//! joined a group posts the changes the user (or the host's API calls) made to
6//! it, and picks up the other members' messages when it builds a frame;
7//! [`Chart::needs_redraw`] reports pending messages, so hosts drive synced
8//! charts exactly like single ones. Each posted message is also reported as
9//! [`ChartEvent::Sync`] for hosts that forward messages themselves (charts in
10//! different workers or processes) with [`Chart::apply_sync`].
11//!
12//! Messages are anchored by time, not logical index, so charts of different
13//! symbols or intervals stay aligned. Applying a message never posts it again,
14//! so messages cannot bounce between charts.
15//!
16//! Drawings (opt-in, [`SyncOptions::drawings`]) travel as [`DrawingSyncOp`]s
17//! through a bounded queue on the bus; see [`drawings`].
18
19use std::sync::{Arc, Mutex, PoisonError};
20
21use crate::chart::{Chart, ChartEvent};
22use crate::data::Timestamp;
23use crate::drawing::{index_of_time, time_of_index};
24use crate::frame::Invalidation;
25
26pub mod drawings;
27use drawings::{DrawingBus, DrawingSyncState};
28pub use drawings::{DrawingSyncOp, SyncKey};
29
30/// A message between synced charts.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum SyncMessage {
34 /// The crosshair is at `time` (extrapolated past the data), or was
35 /// removed (`None`).
36 Crosshair {
37 /// Time under the crosshair.
38 time: Option<Timestamp>,
39 },
40 /// The plot shows times `from..to` (left and right edges, interpolated
41 /// between bars and extrapolated past the data).
42 VisibleRange {
43 /// Time at the left edge.
44 from: Timestamp,
45 /// Time at the right edge.
46 to: Timestamp,
47 },
48}
49
50impl SyncMessage {
51 /// Slot of the message in the bus.
52 fn slot(self) -> usize {
53 match self {
54 Self::Crosshair { .. } => 0,
55 Self::VisibleRange { .. } => 1,
56 }
57 }
58}
59
60/// What a chart shares with its group.
61///
62/// # Examples
63///
64/// ```
65/// use ferrochart_core::sync::SyncOptions;
66///
67/// let crosshair_only = SyncOptions { visible_range: false, ..SyncOptions::default() };
68/// assert!(crosshair_only.crosshair);
69/// assert!(!crosshair_only.drawings);
70/// ```
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub struct SyncOptions {
73 /// Share the crosshair time.
74 pub crosshair: bool,
75 /// Share the visible time range (pan and zoom).
76 pub visible_range: bool,
77 /// Share the drawings of the main pane (charts of the same symbol);
78 /// off by default.
79 pub drawings: bool,
80}
81
82impl Default for SyncOptions {
83 fn default() -> Self {
84 Self {
85 crosshair: true,
86 visible_range: true,
87 drawings: false,
88 }
89 }
90}
91
92impl SyncOptions {
93 fn allows(self, slot: usize) -> bool {
94 match slot {
95 0 => self.crosshair,
96 _ => self.visible_range,
97 }
98 }
99}
100
101const SLOTS: usize = 2;
102
103#[derive(Clone, Copy, Debug, Default)]
104struct Slot {
105 /// Sequence number of `msg` (0: never posted).
106 seq: u64,
107 /// The member that posted it.
108 from: u32,
109 msg: Option<SyncMessage>,
110}
111
112#[derive(Debug, Default)]
113struct Bus {
114 members: u32,
115 seq: u64,
116 slots: [Slot; SLOTS],
117 drawings: DrawingBus,
118}
119
120/// A group of synced charts. Cloning gives another
121/// handle to the same group.
122///
123/// # Examples
124///
125/// ```
126/// use ferrochart_core::sync::{SyncGroup, SyncOptions};
127/// use ferrochart_core::{Chart, ChartOptions};
128///
129/// let group = SyncGroup::new();
130/// let mut a = Chart::new(ChartOptions::default());
131/// let mut b = Chart::new(ChartOptions::default());
132/// a.join_sync(&group, SyncOptions::default());
133/// b.join_sync(&group, SyncOptions { visible_range: false, ..SyncOptions::default() });
134/// // Moving the crosshair over `a` now shows it on `b` after `b` builds a frame.
135/// ```
136#[derive(Clone, Debug, Default)]
137pub struct SyncGroup {
138 bus: Arc<Mutex<Bus>>,
139}
140
141impl SyncGroup {
142 /// Creates an empty group.
143 pub fn new() -> Self {
144 Self::default()
145 }
146
147 /// Creates an empty group whose drawing [`SyncKey`]s start with
148 /// `origin` (the high 32 bits). Hosts that forward drawing operations
149 /// between groups (charts in different workers) give each group its own
150 /// origin, so that keys do not collide.
151 ///
152 /// # Examples
153 ///
154 /// ```
155 /// use ferrochart_core::sync::SyncGroup;
156 ///
157 /// let worker_a = SyncGroup::with_origin(1);
158 /// let worker_b = SyncGroup::with_origin(2);
159 /// # let _ = (worker_a, worker_b);
160 /// ```
161 pub fn with_origin(origin: u32) -> Self {
162 let group = Self::default();
163 group.with(|bus| bus.drawings.origin = origin);
164 group
165 }
166
167 fn with<R>(&self, f: impl FnOnce(&mut Bus) -> R) -> R {
168 // A panic while holding the lock cannot leave the bus inconsistent
169 // (every update is a plain store), so a poisoned lock is still usable.
170 let mut bus = self.bus.lock().unwrap_or_else(PoisonError::into_inner);
171 f(&mut bus)
172 }
173
174 fn join(&self) -> u32 {
175 self.with(|bus| {
176 bus.members = bus.members.wrapping_add(1);
177 bus.members
178 })
179 }
180
181 /// Posts `msg` from `member`. Removing the crosshair only clears the
182 /// member's own crosshair (another chart may already show one). Returns
183 /// whether the message was posted.
184 fn post(&self, member: u32, msg: SyncMessage) -> bool {
185 self.with(|bus| {
186 let slot = &mut bus.slots[msg.slot()];
187 if msg == (SyncMessage::Crosshair { time: None }) && slot.from != member {
188 return false;
189 }
190 bus.seq += 1;
191 *slot = Slot {
192 seq: bus.seq,
193 from: member,
194 msg: Some(msg),
195 };
196 true
197 })
198 }
199}
200
201/// A chart's membership in a group.
202#[derive(Clone, Debug)]
203pub(crate) struct SyncLink {
204 group: SyncGroup,
205 member: u32,
206 opts: SyncOptions,
207 /// Sequence numbers already seen, per slot.
208 seen: [u64; SLOTS],
209 /// Last drawing operation seen.
210 drawings_seen: u64,
211}
212
213/// Sync state of a chart.
214#[derive(Clone, Debug)]
215pub(crate) struct SyncState {
216 pub(crate) link: Option<SyncLink>,
217 /// Crosshair time received from another chart.
218 pub(crate) remote_crosshair: Option<Timestamp>,
219 /// The crosshair time this chart posted last (`None`: none shown).
220 posted_crosshair: Option<Timestamp>,
221 /// `(bar_spacing, right_offset)` after the last frame or applied message:
222 /// a difference at the next frame is a local pan or zoom.
223 view: (f64, f64),
224 /// The view changed locally: post the range once the frame is laid out.
225 post_view: bool,
226 /// Drawing sync.
227 pub(crate) drawings: DrawingSyncState,
228}
229
230impl Default for SyncState {
231 fn default() -> Self {
232 Self {
233 link: None,
234 remote_crosshair: None,
235 posted_crosshair: None,
236 view: (f64::NAN, f64::NAN),
237 post_view: false,
238 drawings: DrawingSyncState::default(),
239 }
240 }
241}
242
243impl Chart {
244 /// Joins `group` (leaving the current one, if any), sharing what `opts`
245 /// selects. The chart takes over the group's
246 /// current crosshair and range at its next frame. With
247 /// [`SyncOptions::drawings`] it first takes over the group's drawings,
248 /// then shares its own (of the main pane).
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// use ferrochart_core::sync::{SyncGroup, SyncOptions};
254 /// use ferrochart_core::{Chart, ChartOptions};
255 ///
256 /// let group = SyncGroup::new();
257 /// let mut charts: Vec<Chart> = (0..4).map(|_| Chart::new(ChartOptions::default())).collect();
258 /// for chart in &mut charts {
259 /// chart.join_sync(&group, SyncOptions::default());
260 /// }
261 /// assert_eq!(charts[0].sync_options(), Some(SyncOptions::default()));
262 /// ```
263 pub fn join_sync(&mut self, group: &SyncGroup, opts: SyncOptions) {
264 self.leave_sync();
265 self.sync.link = Some(SyncLink {
266 group: group.clone(),
267 member: group.join(),
268 opts,
269 seen: [0; SLOTS],
270 drawings_seen: 0,
271 });
272 self.sync.view = self.view_key();
273 if opts.drawings {
274 self.join_drawing_sync(group);
275 }
276 }
277
278 /// Leaves the group; the chart's crosshair is removed from the others.
279 pub fn leave_sync(&mut self) {
280 if let Some(link) = self.sync.link.take()
281 && self.sync.posted_crosshair.is_some()
282 {
283 link.group
284 .post(link.member, SyncMessage::Crosshair { time: None });
285 }
286 self.sync.posted_crosshair = None;
287 self.drawings.sync_log_on = false;
288 self.drawings.sync_log.clear();
289 if self.sync.remote_crosshair.take().is_some() {
290 self.invalidation = self.invalidation.max(Invalidation::Cursor);
291 }
292 }
293
294 /// What the chart shares, `None` outside a group.
295 pub fn sync_options(&self) -> Option<SyncOptions> {
296 self.sync.link.as_ref().map(|l| l.opts)
297 }
298
299 /// Applies a message from another chart, e.g. one the host forwarded
300 /// from a [`ChartEvent::Sync`] of a chart in another worker. It is not
301 /// posted again. A range is ignored while the chart has no data.
302 ///
303 /// # Examples
304 ///
305 /// ```
306 /// use ferrochart_core::sync::SyncMessage;
307 /// use ferrochart_core::frame::Invalidation;
308 /// use ferrochart_core::{Chart, ChartOptions};
309 ///
310 /// let mut chart = Chart::new(ChartOptions::default());
311 /// # let _ = chart.needs_redraw();
312 /// chart.apply_sync(SyncMessage::Crosshair { time: Some(1_700_000_000_000) });
313 /// assert_ne!(chart.needs_redraw(), Invalidation::None);
314 /// ```
315 pub fn apply_sync(&mut self, msg: SyncMessage) {
316 match msg {
317 SyncMessage::Crosshair { time } => {
318 if time != self.sync.remote_crosshair {
319 self.sync.remote_crosshair = time;
320 self.invalidation = self.invalidation.max(Invalidation::Cursor);
321 }
322 }
323 SyncMessage::VisibleRange { from, to } => self.apply_range(from, to),
324 }
325 }
326
327 /// Shows times `from..to` across the plot, as far as the spacing limits
328 /// allow (the right edge is kept).
329 fn apply_range(&mut self, from: Timestamp, to: Timestamp) {
330 let (Some(a), Some(b)) = (
331 index_of_time(&self.time_index, from),
332 index_of_time(&self.time_index, to),
333 ) else {
334 return;
335 };
336 if b > a {
337 // Re-applied until the layout settles: the plot width may change
338 // with the price axis labels of the new range.
339 self.time_scale.show_span(a, b);
340 } else {
341 let last = (self.time_index.end_index() - 1) as f64;
342 self.time_scale.set_right_offset(b - last - 0.5);
343 }
344 self.sync.view = self.view_key();
345 }
346
347 fn view_key(&self) -> (f64, f64) {
348 (
349 self.time_scale.bar_spacing(),
350 self.time_scale.right_offset(),
351 )
352 }
353
354 /// Pending messages of other members, as an invalidation.
355 pub(crate) fn sync_pending(&self) -> Invalidation {
356 let Some(link) = &self.sync.link else {
357 return Invalidation::None;
358 };
359 link.group.with(|bus| {
360 let mut inv = Invalidation::None;
361 if link.opts.drawings && bus.drawings.pending(link.member, link.drawings_seen) {
362 inv = Invalidation::Light;
363 }
364 for (k, slot) in bus.slots.iter().enumerate() {
365 if slot.seq > link.seen[k] && slot.from != link.member && link.opts.allows(k) {
366 inv = inv.max(if k == 0 {
367 Invalidation::Cursor
368 } else {
369 Invalidation::Light
370 });
371 }
372 }
373 inv
374 })
375 }
376
377 /// Start of a frame: notes a local pan or zoom, then applies the other
378 /// members' new messages (a local pan or zoom wins over a received range).
379 pub(crate) fn pull_sync(&mut self) {
380 self.flush_drawing_sync();
381 self.pull_drawing_sync();
382 let local = !same_bits(self.view_key(), self.sync.view);
383 self.sync.post_view |= local;
384 let Some(link) = &mut self.sync.link else {
385 return;
386 };
387 let mut msgs = [None; SLOTS];
388 link.group.with(|bus| {
389 for (k, slot) in bus.slots.iter().enumerate() {
390 if slot.seq > link.seen[k] {
391 link.seen[k] = slot.seq;
392 if slot.from != link.member && link.opts.allows(k) {
393 msgs[k] = slot.msg;
394 }
395 }
396 }
397 });
398 for msg in msgs.into_iter().flatten() {
399 if matches!(msg, SyncMessage::VisibleRange { .. }) && local {
400 continue;
401 }
402 self.apply_sync(msg);
403 }
404 }
405
406 /// Posts `msg` to the group (if it shares that kind) and reports it.
407 fn post_sync(&mut self, msg: SyncMessage) {
408 let Some(link) = &self.sync.link else {
409 return;
410 };
411 if link.opts.allows(msg.slot()) && link.group.post(link.member, msg) {
412 self.push_event(ChartEvent::Sync(msg));
413 }
414 }
415
416 /// End of a frame: posts the local crosshair time (`None` when the
417 /// pointer is not over a plot) and the range after a local pan or zoom.
418 pub(crate) fn push_sync(&mut self, local_crosshair: Option<f64>) {
419 self.flush_drawing_sync();
420 if self.sync.link.is_none() {
421 self.sync.post_view = false;
422 self.sync.view = self.view_key();
423 return;
424 }
425 let time = local_crosshair.and_then(|i| time_of_index(&self.time_index, i));
426 if time != self.sync.posted_crosshair {
427 self.sync.posted_crosshair = time;
428 self.post_sync(SyncMessage::Crosshair { time });
429 }
430 if self.sync.post_view {
431 let (from, to) = self.time_scale.visible_range();
432 if let (Some(from), Some(to)) = (
433 time_of_index(&self.time_index, from),
434 time_of_index(&self.time_index, to),
435 ) {
436 self.post_sync(SyncMessage::VisibleRange { from, to });
437 }
438 }
439 self.sync.post_view = false;
440 self.sync.view = self.view_key();
441 }
442
443 /// Logical index of the bar a received crosshair time falls in: the last
444 /// bar at or before it, extrapolated past the data.
445 pub(crate) fn remote_crosshair_index(&self) -> Option<i64> {
446 let t = self.sync.remote_crosshair?;
447 let index = &self.time_index;
448 let last = index.end_index() - 1;
449 if index.is_empty() || t > index.time_at(last)? || t < index.time_at(index.first_index())? {
450 return index_of_time(index, t).map(|i| i.round() as i64);
451 }
452 let j = index.lower_bound(t);
453 Some(if index.time_at(j) == Some(t) {
454 j
455 } else {
456 j - 1
457 })
458 }
459}
460
461fn same_bits(a: (f64, f64), b: (f64, f64)) -> bool {
462 a.0.to_bits() == b.0.to_bits() && a.1.to_bits() == b.1.to_bits()
463}