use std::sync::{Arc, Mutex, PoisonError};
use crate::chart::{Chart, ChartEvent};
use crate::data::Timestamp;
use crate::drawing::{index_of_time, time_of_index};
use crate::frame::Invalidation;
pub mod drawings;
use drawings::{DrawingBus, DrawingSyncState};
pub use drawings::{DrawingSyncOp, SyncKey};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SyncMessage {
Crosshair {
time: Option<Timestamp>,
},
VisibleRange {
from: Timestamp,
to: Timestamp,
},
}
impl SyncMessage {
fn slot(self) -> usize {
match self {
Self::Crosshair { .. } => 0,
Self::VisibleRange { .. } => 1,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SyncOptions {
pub crosshair: bool,
pub visible_range: bool,
pub drawings: bool,
}
impl Default for SyncOptions {
fn default() -> Self {
Self {
crosshair: true,
visible_range: true,
drawings: false,
}
}
}
impl SyncOptions {
fn allows(self, slot: usize) -> bool {
match slot {
0 => self.crosshair,
_ => self.visible_range,
}
}
}
const SLOTS: usize = 2;
#[derive(Clone, Copy, Debug, Default)]
struct Slot {
seq: u64,
from: u32,
msg: Option<SyncMessage>,
}
#[derive(Debug, Default)]
struct Bus {
members: u32,
seq: u64,
slots: [Slot; SLOTS],
drawings: DrawingBus,
}
#[derive(Clone, Debug, Default)]
pub struct SyncGroup {
bus: Arc<Mutex<Bus>>,
}
impl SyncGroup {
pub fn new() -> Self {
Self::default()
}
pub fn with_origin(origin: u32) -> Self {
let group = Self::default();
group.with(|bus| bus.drawings.origin = origin);
group
}
fn with<R>(&self, f: impl FnOnce(&mut Bus) -> R) -> R {
let mut bus = self.bus.lock().unwrap_or_else(PoisonError::into_inner);
f(&mut bus)
}
fn join(&self) -> u32 {
self.with(|bus| {
bus.members = bus.members.wrapping_add(1);
bus.members
})
}
fn post(&self, member: u32, msg: SyncMessage) -> bool {
self.with(|bus| {
let slot = &mut bus.slots[msg.slot()];
if msg == (SyncMessage::Crosshair { time: None }) && slot.from != member {
return false;
}
bus.seq += 1;
*slot = Slot {
seq: bus.seq,
from: member,
msg: Some(msg),
};
true
})
}
}
#[derive(Clone, Debug)]
pub(crate) struct SyncLink {
group: SyncGroup,
member: u32,
opts: SyncOptions,
seen: [u64; SLOTS],
drawings_seen: u64,
}
#[derive(Clone, Debug)]
pub(crate) struct SyncState {
pub(crate) link: Option<SyncLink>,
pub(crate) remote_crosshair: Option<Timestamp>,
posted_crosshair: Option<Timestamp>,
view: (f64, f64),
post_view: bool,
pub(crate) drawings: DrawingSyncState,
}
impl Default for SyncState {
fn default() -> Self {
Self {
link: None,
remote_crosshair: None,
posted_crosshair: None,
view: (f64::NAN, f64::NAN),
post_view: false,
drawings: DrawingSyncState::default(),
}
}
}
impl Chart {
pub fn join_sync(&mut self, group: &SyncGroup, opts: SyncOptions) {
self.leave_sync();
self.sync.link = Some(SyncLink {
group: group.clone(),
member: group.join(),
opts,
seen: [0; SLOTS],
drawings_seen: 0,
});
self.sync.view = self.view_key();
if opts.drawings {
self.join_drawing_sync(group);
}
}
pub fn leave_sync(&mut self) {
if let Some(link) = self.sync.link.take()
&& self.sync.posted_crosshair.is_some()
{
link.group
.post(link.member, SyncMessage::Crosshair { time: None });
}
self.sync.posted_crosshair = None;
self.drawings.sync_log_on = false;
self.drawings.sync_log.clear();
if self.sync.remote_crosshair.take().is_some() {
self.invalidation = self.invalidation.max(Invalidation::Cursor);
}
}
pub fn sync_options(&self) -> Option<SyncOptions> {
self.sync.link.as_ref().map(|l| l.opts)
}
pub fn apply_sync(&mut self, msg: SyncMessage) {
match msg {
SyncMessage::Crosshair { time } => {
if time != self.sync.remote_crosshair {
self.sync.remote_crosshair = time;
self.invalidation = self.invalidation.max(Invalidation::Cursor);
}
}
SyncMessage::VisibleRange { from, to } => self.apply_range(from, to),
}
}
fn apply_range(&mut self, from: Timestamp, to: Timestamp) {
let (Some(a), Some(b)) = (
index_of_time(&self.time_index, from),
index_of_time(&self.time_index, to),
) else {
return;
};
if b > a {
self.time_scale.show_span(a, b);
} else {
let last = (self.time_index.end_index() - 1) as f64;
self.time_scale.set_right_offset(b - last - 0.5);
}
self.sync.view = self.view_key();
}
fn view_key(&self) -> (f64, f64) {
(
self.time_scale.bar_spacing(),
self.time_scale.right_offset(),
)
}
pub(crate) fn sync_pending(&self) -> Invalidation {
let Some(link) = &self.sync.link else {
return Invalidation::None;
};
link.group.with(|bus| {
let mut inv = Invalidation::None;
if link.opts.drawings && bus.drawings.pending(link.member, link.drawings_seen) {
inv = Invalidation::Light;
}
for (k, slot) in bus.slots.iter().enumerate() {
if slot.seq > link.seen[k] && slot.from != link.member && link.opts.allows(k) {
inv = inv.max(if k == 0 {
Invalidation::Cursor
} else {
Invalidation::Light
});
}
}
inv
})
}
pub(crate) fn pull_sync(&mut self) {
self.flush_drawing_sync();
self.pull_drawing_sync();
let local = !same_bits(self.view_key(), self.sync.view);
self.sync.post_view |= local;
let Some(link) = &mut self.sync.link else {
return;
};
let mut msgs = [None; SLOTS];
link.group.with(|bus| {
for (k, slot) in bus.slots.iter().enumerate() {
if slot.seq > link.seen[k] {
link.seen[k] = slot.seq;
if slot.from != link.member && link.opts.allows(k) {
msgs[k] = slot.msg;
}
}
}
});
for msg in msgs.into_iter().flatten() {
if matches!(msg, SyncMessage::VisibleRange { .. }) && local {
continue;
}
self.apply_sync(msg);
}
}
fn post_sync(&mut self, msg: SyncMessage) {
let Some(link) = &self.sync.link else {
return;
};
if link.opts.allows(msg.slot()) && link.group.post(link.member, msg) {
self.push_event(ChartEvent::Sync(msg));
}
}
pub(crate) fn push_sync(&mut self, local_crosshair: Option<f64>) {
self.flush_drawing_sync();
if self.sync.link.is_none() {
self.sync.post_view = false;
self.sync.view = self.view_key();
return;
}
let time = local_crosshair.and_then(|i| time_of_index(&self.time_index, i));
if time != self.sync.posted_crosshair {
self.sync.posted_crosshair = time;
self.post_sync(SyncMessage::Crosshair { time });
}
if self.sync.post_view {
let (from, to) = self.time_scale.visible_range();
if let (Some(from), Some(to)) = (
time_of_index(&self.time_index, from),
time_of_index(&self.time_index, to),
) {
self.post_sync(SyncMessage::VisibleRange { from, to });
}
}
self.sync.post_view = false;
self.sync.view = self.view_key();
}
pub(crate) fn remote_crosshair_index(&self) -> Option<i64> {
let t = self.sync.remote_crosshair?;
let index = &self.time_index;
let last = index.end_index() - 1;
if index.is_empty() || t > index.time_at(last)? || t < index.time_at(index.first_index())? {
return index_of_time(index, t).map(|i| i.round() as i64);
}
let j = index.lower_bound(t);
Some(if index.time_at(j) == Some(t) {
j
} else {
j - 1
})
}
}
fn same_bits(a: (f64, f64), b: (f64, f64)) -> bool {
a.0.to_bits() == b.0.to_bits() && a.1.to_bits() == b.1.to_bits()
}