1use crate::ids::NodeId;
42use crate::layout::{GraphPayload, LayoutConfig, LayoutSim, LayoutSnapshot};
43use std::sync::atomic::{AtomicBool, Ordering};
44use std::sync::mpsc::{self, Receiver, Sender};
45use std::sync::{Arc, Mutex};
46use std::thread::JoinHandle;
47
48#[derive(Clone, Debug)]
50pub enum LayoutCommand<P: Copy> {
51 Rebuild(Arc<GraphPayload>),
53 Incremental(Arc<GraphPayload>),
55 SetPinned(NodeId, bool),
57 MoveNode(NodeId, P),
59 Cancel,
61 Wake,
63}
64
65#[derive(Clone, Debug)]
67pub enum LayoutMessage<P: Copy> {
68 Frame(LayoutSnapshot<P>),
69 Poisoned,
70}
71
72type Mailbox<P> = Mutex<Option<LayoutMessage<P>>>;
74
75enum Flow {
76 Running,
77 Paused,
78}
79
80fn post<P: Copy>(mailbox: &Arc<Mailbox<P>>, msg: LayoutMessage<P>) {
81 if let Ok(mut slot) = mailbox.lock() {
82 *slot = Some(msg); }
84}
85
86pub struct LayoutWorker<S: LayoutSim> {
89 cmd_tx: Option<Sender<LayoutCommand<S::Pos>>>,
90 mailbox: Arc<Mailbox<S::Pos>>,
91 poisoned: Arc<AtomicBool>,
92 handle: Option<JoinHandle<()>>,
93 initial: Option<Arc<GraphPayload>>,
94 config: LayoutConfig,
95}
96
97impl<S: LayoutSim> LayoutWorker<S> {
98 pub fn spawn(config: LayoutConfig, payload: GraphPayload) -> Self {
100 let initial = Arc::new(payload);
101 let (cmd_tx, cmd_rx) = mpsc::channel::<LayoutCommand<S::Pos>>();
102 let mailbox: Arc<Mailbox<S::Pos>> = Arc::new(Mutex::new(None));
103 let poisoned = Arc::new(AtomicBool::new(false));
104 let thread_config = config.clone();
105 let handle = {
106 let initial = initial.clone();
107 let mailbox = mailbox.clone();
108 let poisoned = poisoned.clone();
109 std::thread::Builder::new()
110 .name("arc-graph-layout".into())
111 .spawn(move || {
112 let run_mailbox = mailbox.clone();
114 let result =
115 std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
116 Self::run(cmd_rx, &run_mailbox, thread_config, &initial);
117 }));
118 if result.is_err() {
119 poisoned.store(true, Ordering::SeqCst);
120 post(&mailbox, LayoutMessage::Poisoned);
121 }
122 })
123 .expect("spawn layout thread")
124 };
125 Self {
126 cmd_tx: Some(cmd_tx),
127 mailbox,
128 poisoned,
129 handle: Some(handle),
130 initial: Some(initial),
131 config,
132 }
133 }
134
135 fn run(
136 cmd_rx: Receiver<LayoutCommand<S::Pos>>,
137 mailbox: &Arc<Mailbox<S::Pos>>,
138 config: LayoutConfig,
139 initial: &Arc<GraphPayload>,
140 ) {
141 let mut sim = S::new(config);
142 sim.rebuild(initial);
143 let mut flow = Flow::Running;
144 loop {
146 match flow {
147 Flow::Running => {
148 while let Ok(cmd) = cmd_rx.try_recv() {
149 match cmd {
150 LayoutCommand::Rebuild(p) => sim.rebuild(&p),
151 LayoutCommand::Incremental(p) => sim.incremental(&p),
152 LayoutCommand::SetPinned(id, pinned) => sim.set_pinned(id, pinned),
153 LayoutCommand::MoveNode(id, pos) => sim.move_node(id, pos),
154 LayoutCommand::Cancel => flow = Flow::Paused,
155 LayoutCommand::Wake => flow = Flow::Running,
156 }
157 }
158 if matches!(flow, Flow::Paused) {
160 continue;
161 }
162 if sim.is_cooled() {
163 post(mailbox, LayoutMessage::Frame(sim.snapshot()));
164 flow = Flow::Paused;
165 continue;
166 }
167 sim.step();
168 post(mailbox, LayoutMessage::Frame(sim.snapshot()));
169 }
170 Flow::Paused => {
171 match cmd_rx.recv() {
173 Ok(LayoutCommand::Rebuild(p)) => {
174 sim.rebuild(&p);
175 flow = Flow::Running;
176 }
177 Ok(LayoutCommand::Incremental(p)) => {
178 sim.incremental(&p);
179 flow = Flow::Running;
180 }
181 Ok(LayoutCommand::SetPinned(id, pinned)) => {
182 sim.set_pinned(id, pinned);
183 post(mailbox, LayoutMessage::Frame(sim.snapshot()));
184 }
185 Ok(LayoutCommand::MoveNode(id, pos)) => {
186 sim.move_node(id, pos);
188 flow = Flow::Running;
189 }
190 Ok(LayoutCommand::Cancel) => {}
191 Ok(LayoutCommand::Wake) => flow = Flow::Running,
192 Err(_) => return, }
194 }
195 }
196 }
197 }
198
199 pub fn send(&self, cmd: LayoutCommand<S::Pos>) {
201 if let Some(tx) = &self.cmd_tx {
202 let _ = tx.send(cmd);
203 }
204 }
205
206 pub fn try_message(&mut self) -> Option<LayoutMessage<S::Pos>> {
209 self.mailbox.lock().ok()?.take()
210 }
211
212 pub fn try_snapshot(&mut self) -> Option<LayoutSnapshot<S::Pos>> {
214 match self.try_message()? {
215 LayoutMessage::Frame(s) => Some(s),
216 LayoutMessage::Poisoned => None,
217 }
218 }
219
220 pub fn is_poisoned(&self) -> bool {
222 self.poisoned.load(Ordering::SeqCst)
223 }
224
225 pub fn restart(&mut self) {
227 self.join_thread();
228 let payload = self.initial.clone().unwrap_or_default();
229 let worker = Self::spawn(self.config.clone(), (*payload).clone());
230 *self = worker;
231 }
232
233 pub fn rerun(&mut self, config: LayoutConfig, payload: GraphPayload) {
235 self.join_thread();
236 let worker = Self::spawn(config, payload);
237 *self = worker;
238 }
239
240 fn join_thread(&mut self) {
241 self.cmd_tx = None;
242 if let Some(h) = self.handle.take() {
243 let _ = h.join();
244 }
245 }
246}
247
248impl<S: LayoutSim> Drop for LayoutWorker<S> {
249 fn drop(&mut self) {
250 if let Some(tx) = &self.cmd_tx {
253 let _ = tx.send(LayoutCommand::Cancel);
254 }
255 self.cmd_tx = None;
256 }
257}
258
259pub type LayoutWorker2D = LayoutWorker<crate::layout::ForceLayout2D>;
261pub type LayoutWorker3D = LayoutWorker<crate::layout::ForceLayout3D>;
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 struct PanicSim;
270
271 impl LayoutSim for PanicSim {
272 type Pos = arc_flow_core::geometry::Vec2;
273 fn new(_config: LayoutConfig) -> Self {
274 Self
275 }
276 fn rebuild(&mut self, _p: &GraphPayload) {}
277 fn incremental(&mut self, _p: &GraphPayload) {}
278 fn set_pinned(&mut self, _id: NodeId, _p: bool) {}
279 fn move_node(&mut self, _id: NodeId, _pos: Self::Pos) {}
280 fn step(&mut self) {
281 panic!("layout thread explodes");
282 }
283 fn is_cooled(&self) -> bool {
284 false
285 }
286 fn snapshot(&self) -> LayoutSnapshot<Self::Pos> {
287 LayoutSnapshot {
288 positions: Arc::new(Vec::new()),
289 iteration: 0,
290 alpha: 1.0,
291 cooled: false,
292 }
293 }
294 }
295
296 #[test]
297 fn panic_in_layout_thread_poisons_but_not_kills_ui() {
298 let mut worker =
299 LayoutWorker::<PanicSim>::spawn(LayoutConfig::default(), GraphPayload::default());
300 let mut poisoned = false;
301 for _ in 0..500 {
302 if matches!(worker.try_message(), Some(LayoutMessage::Poisoned)) {
303 poisoned = true;
304 }
305 if poisoned {
306 break;
307 }
308 std::thread::sleep(std::time::Duration::from_millis(2));
309 }
310 assert!(poisoned, "UI 应收到 Poisoned 而不是崩掉");
311 assert!(worker.is_poisoned());
312 worker.restart();
314 assert!(!worker.is_poisoned());
315 }
316
317 #[test]
318 fn cancel_then_wake_resumes() {
319 let mut g = crate::model::KnowledgeGraph::new();
320 let a = g.add_node("a", None);
321 let b = g.add_node("b", None);
322 g.add_edge(a, b, 1.0, None).unwrap();
323 let mut worker = LayoutWorker2D::spawn(
324 LayoutConfig {
325 max_iterations: 5,
326 ..LayoutConfig::default()
327 },
328 GraphPayload::from_graph(&g),
329 );
330 worker.send(LayoutCommand::Cancel);
331 worker.send(LayoutCommand::Wake);
332 let mut got = false;
333 for _ in 0..1000 {
334 if let Some(s) = worker.try_snapshot()
335 && s.cooled
336 {
337 got = true;
338 break;
339 }
340 std::thread::sleep(std::time::Duration::from_millis(2));
341 }
342 assert!(got, "取消后唤醒应能继续跑到冷却");
343 }
344}