1use 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
28pub const MAX_OPS: usize = 1024;
30
31#[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#[derive(Clone, Debug, PartialEq)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39#[non_exhaustive]
40pub enum DrawingSyncOp {
41 Add {
43 key: SyncKey,
45 data: DrawingData,
47 visible: bool,
49 locked: bool,
51 },
52 Update {
54 key: SyncKey,
56 data: DrawingData,
58 },
59 SetVisible {
61 key: SyncKey,
63 visible: bool,
65 },
66 SetLocked {
68 key: SyncKey,
70 locked: bool,
72 },
73 Remove {
75 key: SyncKey,
77 },
78}
79
80impl DrawingSyncOp {
81 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#[derive(Clone, Debug)]
95struct TableEntry {
96 key: SyncKey,
97 data: DrawingData,
98 visible: bool,
99 locked: bool,
100}
101
102#[derive(Debug, Default)]
104pub(super) struct DrawingBus {
105 pub(super) origin: u32,
107 next_key: u32,
108 seq: u64,
110 ops: VecDeque<(u64, u32, DrawingSyncOp)>,
112 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 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 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#[derive(Clone, Debug, Default)]
184pub(crate) struct DrawingSyncState {
185 keys: Vec<(SyncKey, DrawingId)>,
187 key_group: Option<SyncGroup>,
190 outbox: VecDeque<DrawingSyncOp>,
192 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 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 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 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 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 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 let _ = self.apply_drawing_sync(op);
386 }
387 }
388
389 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 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 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 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}