1use crate::motion::{Appear, DIM_STRENGTH, GraphMotion};
9
10use arc_flow_core::Viewport;
11use arc_flow_core::geometry::{Rect, Size2, Vec2};
12use arc_flow_core::spatial::SpatialGrid;
13use arc_graph_core::{
14 GraphPayload, KnowledgeGraph, LayoutCommand, LayoutConfig, LayoutWorker2D, NodeId, NodeKind,
15};
16use arc_motion::{is_reduced_motion, motion_now};
17use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
18use gpui_kit::{
19 App, Bounds, Context, Corners, Edges, ElementId, FocusHandle, Focusable, InteractiveElement,
20 IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement,
21 PathBuilder, Pixels, Render, ScrollDelta, ScrollEvent, SharedString,
22 StatefulInteractiveElement, Styled, TestSupportExt as _, Window, canvas, div, px, quad, size,
23};
24
25use std::collections::{HashMap, HashSet};
26use std::sync::Arc;
27
28const NODE_WORLD_SIZE: f32 = 36.0;
32const NODE_MARKER_WORLD_SIZE: f32 = 12.0;
34
35fn node_label_origin(center: Vec2, diameter: f32, width: f32, height: f32) -> Vec2 {
37 Vec2::new(
38 center.x - width / 2.0,
39 center.y - diameter / 2.0 - f32::from(Spacing::S1) - height,
40 )
41}
42
43const EDGE_WIDTH: f32 = 1.5;
45const LOD_DOT_PX: f32 = 4.0;
47const LOD_SHELL_PX: f32 = 14.0;
49const LOD_MIN_NODES: usize = 500;
51const LOD_GLOBAL_ZOOM: f32 = 0.25;
52const DOT_MIN_PX: f32 = 2.5;
54const MAX_LABELS: usize = 200;
56const MAX_FULL_CARDS: usize = 160;
60const CULL_MARGIN: f32 = 40.0;
62const WHEEL_ZOOM_SPEED: f32 = 0.01;
64const KG_MIN_ZOOM: f32 = 0.02;
66const KG_MAX_ZOOM: f32 = 4.0;
67const LINE_HEIGHT: f32 = 20.0;
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Lod {
73 Full,
74 Shell,
75 Dot,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
80pub struct RenderCounts {
81 pub full: usize,
83 pub shell: usize,
85 pub dot: usize,
87 pub edges: usize,
89 pub labels: usize,
91}
92
93pub struct Graph2D {
95 id: SharedString,
96 label: SharedString,
97 focus: FocusHandle,
98 graph: KnowledgeGraph,
99 payload: GraphPayload,
101 degrees: Vec<u32>,
103 worker: Option<LayoutWorker2D>,
105 layout_active: bool,
107 positions: Arc<Vec<Vec2>>,
109 positions_rev: u64,
110 viewport: Viewport,
111 view_size: Option<Size2>,
112 fit_pending: bool,
113 spatial: Option<SpatialGrid<u32>>,
115 spatial_rev: u64,
116 visible_cache: Option<VisibleCache>,
118 pan_drag: Option<(Vec2, Vec2)>,
120 rendered: RenderCounts,
121 bounds_cell: Arc<std::sync::Mutex<Option<Bounds<Pixels>>>>,
122
123 motion: GraphMotion,
126 hover: Option<u32>,
128 selection: Vec<NodeId>,
130 rubber: Option<(Vec2, Vec2)>,
132 node_drag: Option<(u32, Vec2)>,
134 drag_moved: bool,
136 revealed: HashSet<NodeId>,
138 kind_filter: Option<arc_graph_core::KindId>,
140 hidden: Option<HashSet<u32>>,
142 slot_index: std::collections::HashMap<NodeId, u32>,
144 text_width_cache: HashMap<(SharedString, u32), f32>,
148}
149
150struct VisibleCache {
151 key: ([u32; 3], u64),
153 slots: Vec<u32>,
154 edges: Vec<(u32, u32)>,
155}
156
157impl Graph2D {
158 pub fn new(id: impl Into<SharedString>, graph: KnowledgeGraph, cx: &mut Context<Self>) -> Self {
160 let payload = GraphPayload::from_graph(&graph);
161 let worker = LayoutWorker2D::spawn(LayoutConfig::default(), payload.clone());
162 Self::build(id, graph, payload, Some(worker), cx)
163 }
164
165 pub fn new_static(
167 id: impl Into<SharedString>,
168 graph: KnowledgeGraph,
169 positions: Vec<Vec2>,
170 cx: &mut Context<Self>,
171 ) -> Self {
172 let payload = GraphPayload::from_graph(&graph);
173 let mut view = Self::build(id, graph, payload, None, cx);
174 view.positions = Arc::new(positions);
175 view.positions_rev = 1;
176 view.fit_pending = true;
177 view
178 }
179
180 fn build(
181 id: impl Into<SharedString>,
182 graph: KnowledgeGraph,
183 payload: GraphPayload,
184 worker: Option<LayoutWorker2D>,
185 _cx: &mut Context<Self>,
186 ) -> Self {
187 let degrees = {
188 let mut d = vec![0u32; payload.node_ids.len()];
189 for &(s, t, _) in &payload.edges {
190 if s != t {
191 d[s as usize] += 1;
192 d[t as usize] += 1;
193 }
194 }
195 d
196 };
197 let viewport = Viewport {
198 min_zoom: KG_MIN_ZOOM,
199 max_zoom: KG_MAX_ZOOM,
200 ..Viewport::default()
201 };
202 let focus = _cx.focus_handle();
203 let slot_index: std::collections::HashMap<NodeId, u32> = payload
204 .node_ids
205 .iter()
206 .enumerate()
207 .map(|(i, id)| (*id, i as u32))
208 .collect();
209 Self {
210 id: id.into(),
211 label: "Knowledge graph".into(),
212 focus,
213 graph,
214 degrees,
215 layout_active: worker.is_some(),
216 worker,
217 payload,
218 positions: Arc::new(Vec::new()),
219 positions_rev: 0,
220 viewport,
221 view_size: None,
222 fit_pending: false,
223 spatial: None,
224 spatial_rev: 0,
225 visible_cache: None,
226 pan_drag: None,
227 rendered: RenderCounts::default(),
228 bounds_cell: Arc::new(std::sync::Mutex::new(None)),
229 motion: GraphMotion::default(),
230 hover: None,
231 selection: Vec::new(),
232 rubber: None,
233 node_drag: None,
234 drag_moved: false,
235 revealed: HashSet::new(),
236 kind_filter: None,
237 hidden: None,
238 slot_index,
239 text_width_cache: HashMap::new(),
240 }
241 }
242
243 fn label_width(&mut self, window: &mut Window, label: &str, font_px: f32) -> f32 {
246 const TEXT_CACHE_CAP: usize = 4_096;
247 if self.text_width_cache.len() > TEXT_CACHE_CAP {
248 self.text_width_cache.clear();
249 }
250 let key = (SharedString::from(label), (font_px * 4.0).round() as u32);
251 if let Some(&w) = self.text_width_cache.get(&key) {
252 return w;
253 }
254 let w = f32::from(
255 window
256 .text_system()
257 .layout_line(key.0.clone(), px(font_px), &[], None)
258 .width,
259 );
260 self.text_width_cache.insert(key, w);
261 w
262 }
263
264 pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
266 self.label = label.into();
267 self
268 }
269
270 pub fn fit_on_mount(mut self) -> Self {
272 self.fit_pending = true;
273 self
274 }
275
276 pub fn viewport(&self) -> Viewport {
278 self.viewport
279 }
280
281 pub fn rendered_counts(&self) -> RenderCounts {
283 self.rendered
284 }
285
286 pub fn positions(&self) -> &Arc<Vec<Vec2>> {
288 &self.positions
289 }
290
291 pub fn fit_view(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
293 self.motion.cancel_view();
294 cx.notify();
295 if let Some(world) = self.world_bounds() {
296 let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
297 self.viewport.fit(&world, view, 60.0);
298 }
299 }
300
301 pub fn zoom_by(&mut self, factor: f32, _window: &mut Window, cx: &mut Context<Self>) {
303 self.motion.cancel_view();
304 cx.notify();
305 let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
306 let anchor = Vec2::new(view.w / 2.0, view.h / 2.0);
307 self.viewport.zoom_by_at(factor, anchor);
308 }
309
310 pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
314 self.graph.kinds()
315 }
316
317 pub fn kind_filter(&self) -> Option<arc_graph_core::KindId> {
319 self.kind_filter
320 }
321
322 pub fn set_kind_filter(
325 &mut self,
326 kind: Option<arc_graph_core::KindId>,
327 cx: &mut Context<Self>,
328 ) {
329 let previous: Vec<bool> = (0..self.payload.node_ids.len())
330 .map(|s| self.is_slot_hidden(s as u32))
331 .collect();
332 self.kind_filter = kind;
333 self.revealed.clear();
334 self.selection.clear();
335 self.hidden = kind.map(|k| {
336 let mut set = HashSet::new();
337 for (i, &id) in self.payload.node_ids.iter().enumerate() {
338 let matches = self.graph.node(id).is_some_and(|n| n.kind == Some(k));
339 if !matches {
340 set.insert(i as u32);
341 }
342 }
343 set
344 });
345 let now = motion_now(cx);
346 self.motion.set_reduced(is_reduced_motion(cx));
347 for (slot, was_hidden) in previous.into_iter().enumerate() {
348 let hidden = self.is_slot_hidden(slot as u32);
349 let id = self.payload.node_ids[slot];
350 if hidden && !was_hidden {
351 self.motion.node_exited(id, now);
352 }
353 if !hidden && was_hidden {
354 self.motion.node_entered(id, now);
355 }
356 }
357 self.hover = None;
358 self.motion.set_dim(false, now);
359 cx.notify();
360 }
361
362 pub fn set_pinned(&mut self, id: NodeId, pinned: bool, cx: &mut Context<Self>) {
364 let Some(&slot) = self.slot_index.get(&id) else {
365 return;
366 };
367 self.payload.pinned[slot as usize] = pinned;
368 if let Some(worker) = &self.worker {
369 worker.send(LayoutCommand::SetPinned(id, pinned));
370 if let Some(&position) = self.positions.get(slot as usize) {
371 worker.send(LayoutCommand::MoveNode(id, position));
372 self.layout_active = true;
373 }
374 }
375 cx.notify();
376 }
377
378 pub fn is_pinned(&self, id: NodeId) -> bool {
379 self.slot_index
380 .get(&id)
381 .is_some_and(|&s| self.payload.pinned[s as usize])
382 }
383
384 pub fn node_label(&self, id: NodeId) -> Option<&str> {
386 self.graph.node(id).map(|node| node.label.as_str())
387 }
388
389 pub fn selection(&self) -> &[NodeId] {
391 &self.selection
392 }
393
394 pub fn hover(&self) -> Option<NodeId> {
396 self.hover.map(|s| self.payload.node_ids[s as usize])
397 }
398
399 pub fn search(&self, query: &str) -> Vec<NodeId> {
401 let q = query.trim().to_lowercase();
402 if q.is_empty() {
403 return Vec::new();
404 }
405 let mut hits: Vec<(u32, u32)> = self
406 .payload
407 .node_ids
408 .iter()
409 .enumerate()
410 .filter(|(i, _)| !self.is_slot_hidden(*i as u32))
411 .filter_map(|(i, id)| {
412 let n = self.graph.node(*id)?;
413 n.label
414 .to_lowercase()
415 .contains(&q)
416 .then(|| (i as u32, self.degrees[i]))
417 })
418 .collect();
419 hits.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
420 hits.into_iter()
421 .take(20)
422 .map(|(s, _)| self.payload.node_ids[s as usize])
423 .collect()
424 }
425
426 pub fn fly_to(&mut self, id: NodeId, cx: &mut Context<Self>) {
428 let Some(&slot) = self.slot_index.get(&id) else {
429 return;
430 };
431 if self.is_slot_hidden(slot) {
432 return;
433 }
434 let Some(p) = self.positions.get(slot as usize).copied() else {
435 return;
436 };
437 if !self.selection.contains(&id) {
438 self.selection.push(id);
439 }
440 let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
441 let center = Vec2::new(view.w / 2.0, view.h / 2.0);
442 let mut target = self.viewport;
443 target.zoom = target.zoom.clamp(1.0, KG_MAX_ZOOM);
444 target.offset = center.minus(p.scale(target.zoom));
445 let now = motion_now(cx);
446 self.motion.set_reduced(is_reduced_motion(cx));
447 if self
448 .motion
449 .animate_view(&self.viewport, &target, center, now)
450 {
451 cx.notify();
452 } else {
453 self.viewport = target;
454 cx.notify();
455 }
456 }
457
458 pub fn expand(&mut self, id: NodeId, cx: &mut Context<Self>) -> usize {
461 self.motion.set_reduced(is_reduced_motion(cx));
462 let Some(filter) = self.hidden.as_mut() else {
463 return 0;
464 };
465 let neighbors = self.graph.adjacency().neighbors(id);
466 let mut revealed_count = 0;
467 let now = motion_now(cx);
468 for n in neighbors {
469 let Some(&slot) = self.slot_index.get(&n) else {
470 continue;
471 };
472 if filter.remove(&slot) {
473 self.revealed.insert(n);
474 self.motion.node_entered(n, now);
475 revealed_count += 1;
476 }
477 }
478 if revealed_count > 0 {
479 cx.notify();
480 }
481 revealed_count
482 }
483
484 pub fn hidden_count(&self) -> usize {
486 self.hidden.as_ref().map_or(0, |h| h.len())
487 }
488
489 fn is_slot_hidden(&self, slot: u32) -> bool {
490 self.hidden
491 .as_ref()
492 .is_some_and(|h| h.contains(&slot) && !self.revealed_overrides(slot))
493 }
494
495 fn drawn(&self, slot: u32, now: f64) -> bool {
496 !self.is_slot_hidden(slot)
497 || self
498 .motion
499 .is_exiting(self.payload.node_ids[slot as usize], now)
500 }
501
502 fn appearance(&self, slot: u32, now: f64) -> Appear {
503 let id = self.payload.node_ids[slot as usize];
504 if self.is_slot_hidden(slot) {
505 self.motion.exit_sample(id, now)
506 } else {
507 self.motion.enter_sample(id, now)
508 }
509 }
510
511 fn emphasis(slot: u32, focus: Option<&HashSet<u32>>, dim: f32) -> f32 {
512 if focus.is_none_or(|f| f.contains(&slot)) {
513 1.0
514 } else {
515 1.0 - dim * DIM_STRENGTH
516 }
517 }
518
519 fn revealed_overrides(&self, slot: u32) -> bool {
521 let Some(&id) = self.payload.node_ids.get(slot as usize) else {
522 return false;
523 };
524 self.revealed.contains(&id)
525 }
526
527 fn world_bounds(&self) -> Option<Rect> {
528 let p = self.positions.as_ref();
529 if p.is_empty() {
530 return None;
531 }
532 let r = NODE_WORLD_SIZE / 2.0;
533 let mut lo = p[0].minus(Vec2::new(r, r));
534 let mut hi = p[0].plus(Vec2::new(r, r));
535 for v in p.iter().skip(1) {
536 lo = Vec2::new(lo.x.min(v.x - r), lo.y.min(v.y - r));
537 hi = Vec2::new(hi.x.max(v.x + r), hi.y.max(v.y + r));
538 }
539 Some(Rect { min: lo, max: hi })
540 }
541
542 fn poll_layout(&mut self) {
543 let held = self.node_drag.and_then(|(slot, _)| {
544 self.positions
545 .get(slot as usize)
546 .copied()
547 .map(|p| (slot, p))
548 });
549 if let Some(worker) = &mut self.worker {
550 if let Some(snap) = worker.try_snapshot() {
551 self.layout_active = !snap.cooled;
552 self.positions = snap.positions;
553 self.positions_rev += 1;
554 }
555 if worker.is_poisoned() {
556 self.layout_active = false;
557 }
558 }
559 if let Some((slot, p)) = held
561 && let Some(current) = Arc::make_mut(&mut self.positions).get_mut(slot as usize)
562 {
563 *current = p;
564 }
565 if self.fit_pending && self.view_size.is_some() && !self.positions.is_empty() {
566 self.fit_pending = false;
567 if let Some(world) = self.world_bounds() {
568 let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
569 self.viewport.fit(&world, view, 60.0);
570 }
571 }
572 }
573
574 fn refresh_spatial(&mut self) {
575 if self.spatial_rev == self.positions_rev && self.spatial.is_some() {
576 return;
577 }
578 let mut grid = SpatialGrid::new(NODE_WORLD_SIZE * 3.0);
579 let r = NODE_WORLD_SIZE / 2.0;
580 for (i, p) in self.positions.iter().enumerate() {
581 let rect = Rect {
582 min: Vec2::new(p.x - r, p.y - r),
583 max: Vec2::new(p.x + r, p.y + r),
584 };
585 grid.insert(i as u32, rect);
586 }
587 self.spatial = Some(grid);
588 self.spatial_rev = self.positions_rev;
589 }
590
591 fn visible_world(&self) -> Rect {
592 let view = self.view_size.unwrap_or(Size2::new(4096.0, 4096.0));
593 self.viewport
594 .visible_world_rect(view)
595 .inflate(CULL_MARGIN / self.viewport.zoom.max(0.02))
596 }
597
598 fn refresh_visible(&mut self) {
599 let key = (
600 [
601 self.viewport.offset.x.to_bits(),
602 self.viewport.offset.y.to_bits(),
603 self.viewport.zoom.to_bits(),
604 ],
605 self.positions_rev,
606 );
607 if let Some(c) = &self.visible_cache
608 && c.key == key
609 {
610 return;
611 }
612 let visible = self.visible_world();
613 let mut slots = self
614 .spatial
615 .as_ref()
616 .map(|g| g.query(&visible))
617 .unwrap_or_default();
618 slots.sort_unstable();
619 let r = NODE_WORLD_SIZE / 2.0;
620 let mut edges = Vec::new();
621 for &(s, t, _) in &self.payload.edges {
622 let (Some(a), Some(b)) = (
624 self.positions.get(s as usize),
625 self.positions.get(t as usize),
626 ) else {
627 continue;
628 };
629 let seg = Rect {
630 min: Vec2::new(a.x.min(b.x) - r, a.y.min(b.y) - r),
631 max: Vec2::new(a.x.max(b.x) + r, a.y.max(b.y) + r),
632 };
633 if seg.intersects(&visible) {
634 edges.push((s, t));
635 }
636 }
637 edges.sort_unstable();
638 self.visible_cache = Some(VisibleCache { key, slots, edges });
639 }
640
641 fn local(&self, position: gpui_kit::Point<Pixels>) -> Vec2 {
642 let b = self.bounds_cell.lock().ok().and_then(|g| *g);
643 match b {
644 Some(bounds) => Vec2::new(
645 f32::from(position.x - bounds.origin.x),
646 f32::from(position.y - bounds.origin.y),
647 ),
648 None => Vec2::ZERO,
649 }
650 }
651
652 fn on_scroll(&mut self, ev: &ScrollEvent, _window: &mut Window, cx: &mut Context<Self>) {
653 let delta = ev.delta.pixel_delta(px(LINE_HEIGHT));
654 let (dx, dy) = (f32::from(delta.x), f32::from(delta.y));
655 self.motion.cancel_view();
656 if ev.modifiers.secondary(cx) || ev.modifiers.control {
657 let anchor = self.local(ev.position);
658 let dy = if matches!(ev.delta, ScrollDelta::Lines(_)) {
659 dy * 2.0
660 } else {
661 dy
662 };
663 self.viewport
664 .zoom_by_at((dy * WHEEL_ZOOM_SPEED).exp(), anchor);
665 } else {
666 self.viewport.pan_by(Vec2::new(dx, dy));
667 }
668 cx.notify();
669 cx.stop_propagation();
670 }
671
672 fn hit_slot(&self, world: Vec2) -> Option<u32> {
674 let grid = self.spatial.as_ref()?;
675 let r = NODE_WORLD_SIZE / 2.0 + 4.0 / self.viewport.zoom.max(0.02);
676 let probe = Rect {
677 min: Vec2::new(world.x - r, world.y - r),
678 max: Vec2::new(world.x + r, world.y + r),
679 };
680 grid.query(&probe)
681 .into_iter()
682 .filter(|&s| !self.is_slot_hidden(s))
683 .filter(|&s| {
684 self.positions
685 .get(s as usize)
686 .is_some_and(|p| (p.x - world.x).abs() <= r && (p.y - world.y).abs() <= r)
687 })
688 .min_by(|&a, &b| {
689 self.positions[a as usize]
690 .distance(world)
691 .total_cmp(&self.positions[b as usize].distance(world))
692 .then(a.cmp(&b))
693 })
694 }
695
696 fn focus_slots(&self) -> HashSet<u32> {
698 let mut focus = HashSet::new();
699 if let Some(h) = self.hover {
700 focus.insert(h);
701 }
702 for &id in &self.selection {
703 if let Some(&s) = self.slot_index.get(&id) {
704 focus.insert(s);
705 }
706 }
707 let mut out = focus.clone();
708 for &s in &focus {
709 let Some(&id) = self.payload.node_ids.get(s as usize) else {
710 continue;
711 };
712 for n in self.graph.adjacency().neighbors(id) {
713 if let Some(&ns) = self.slot_index.get(&n) {
714 out.insert(ns);
715 }
716 }
717 }
718 out
719 }
720
721 fn on_left_down(&mut self, ev: &MouseDownEvent, _w: &mut Window, cx: &mut Context<Self>) {
722 self.motion.cancel_view();
723 self.refresh_spatial();
724 self.drag_moved = false;
725 let local = self.local(ev.position);
726 let world = self.viewport.screen_to_world(local);
727 if ev.click_count >= 2 {
729 if let Some(slot) = self.hit_slot(world) {
730 let id = self.payload.node_ids[slot as usize];
731 let _ = self.expand(id, cx);
732 if !self.selection.contains(&id) {
733 self.selection = vec![id];
734 }
735 cx.notify();
736 cx.stop_propagation();
737 }
738 return;
739 }
740 if let Some(slot) = self.hit_slot(world) {
741 let node_pos = self.positions.get(slot as usize).copied().unwrap_or(world);
743 self.node_drag = Some((slot, world.minus(node_pos)));
744 self.drag_moved = false;
745 cx.stop_propagation();
746 return;
747 }
748 if ev.modifiers.shift {
749 self.rubber = Some((local, local));
751 } else {
752 self.pan_drag = Some((local, self.viewport.offset));
753 }
754 cx.stop_propagation();
755 }
756
757 fn on_mouse_move(&mut self, ev: &MouseMoveEvent, _w: &mut Window, cx: &mut Context<Self>) {
758 let local = self.local(ev.position);
759 let world = self.viewport.screen_to_world(local);
760
761 if let Some((slot, grab)) = self.node_drag {
762 let target = world.minus(grab);
764 if self
765 .positions
766 .get(slot as usize)
767 .is_some_and(|p| p.distance(target) < 0.01)
768 {
769 return;
770 }
771 self.drag_moved = true;
772 self.payload.pinned[slot as usize] = true;
773 if let Some(worker) = &self.worker {
774 let id = self.payload.node_ids[slot as usize];
775 worker.send(LayoutCommand::SetPinned(id, true));
776 worker.send(LayoutCommand::MoveNode(id, target));
777 self.layout_active = true;
778 }
779 Arc::make_mut(&mut self.positions)[slot as usize] = target;
780 self.positions_rev += 1;
781 cx.notify();
782 return;
783 }
784
785 if let Some((start, _)) = self.rubber {
786 self.rubber = Some((start, local));
787 cx.notify();
788 return;
789 }
790
791 if let Some((start, base)) = self.pan_drag {
792 self.drag_moved |= local.distance(start) > 4.0;
793 self.viewport.offset = base.plus(local.minus(start));
794 cx.notify();
795 return;
796 }
797
798 let hit = self.hit_slot(world);
800 if hit != self.hover {
801 self.hover = hit;
802 let now = motion_now(cx);
803 self.motion.set_reduced(is_reduced_motion(cx));
804 self.motion.set_dim(hit.is_some(), now);
805 cx.notify();
806 }
807 }
808
809 fn on_mouse_up(&mut self, ev: &MouseUpEvent, _w: &mut Window, cx: &mut Context<Self>) {
810 if let Some((slot, _)) = self.node_drag.take() {
812 if !self.drag_moved {
813 let id = self.payload.node_ids[slot as usize];
814 if ev.modifiers.shift {
815 if let Some(i) = self.selection.iter().position(|&s| s == id) {
816 self.selection.remove(i);
817 } else {
818 self.selection.push(id);
819 }
820 } else {
821 self.selection = vec![id];
822 }
823 }
824 cx.notify();
825 return;
826 }
827 if let Some((start, end)) = self.rubber.take() {
828 let (lo, hi) = (
830 Vec2::new(start.x.min(end.x), start.y.min(end.y)),
831 Vec2::new(start.x.max(end.x), start.y.max(end.y)),
832 );
833 let mut picked = Vec::new();
834 if hi.x - lo.x > 4.0 || hi.y - lo.y > 4.0 {
835 for (i, p) in self.positions.iter().enumerate() {
836 let slot = i as u32;
837 if self.is_slot_hidden(slot) {
838 continue;
839 }
840 let c = self.viewport.world_to_screen(*p);
841 if c.x >= lo.x && c.x <= hi.x && c.y >= lo.y && c.y <= hi.y {
842 picked.push(self.payload.node_ids[slot as usize]);
843 }
844 }
845 }
846 self.selection = picked;
847 cx.notify();
848 return;
849 }
850 if self.pan_drag.take().is_some() {
851 if !self.drag_moved {
853 self.selection.clear();
854 }
855 cx.notify();
856 }
857 }
858
859 fn on_pinch(&mut self, ev: &gpui_kit::PinchEvent, _w: &mut Window, _cx: &mut Context<Self>) {
860 self.motion.cancel_view();
861 let anchor = self.local(ev.position);
862 self.viewport.zoom_by_at(1.0 + ev.delta, anchor);
863 }
864}
865
866impl Focusable for Graph2D {
867 fn focus_handle(&self, _cx: &App) -> FocusHandle {
868 self.focus.clone()
869 }
870}
871
872impl Render for Graph2D {
873 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
874 let measured = self
875 .bounds_cell
876 .lock()
877 .ok()
878 .and_then(|g| *g)
879 .map(|b| Size2::new(f32::from(b.size.width), f32::from(b.size.height)));
880 if let Some(measured) = measured
881 && self.view_size != Some(measured)
882 {
883 self.view_size = Some(measured);
884 self.visible_cache = None;
885 }
886 self.poll_layout();
887
888 let now = motion_now(cx);
889 self.motion.set_reduced(is_reduced_motion(cx));
890 if self.motion.view_animating() {
892 let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
893 let center = Vec2::new(view.w / 2.0, view.h / 2.0);
894 if let Some((vp, done)) = self.motion.view_sample(&self.viewport, center, now) {
895 self.viewport = vp;
896 if done {
897 self.motion.cancel_view();
898 }
899 cx.notify();
900 }
901 }
902
903 self.motion.prune(now);
904 if self.motion.animating(now)
905 || self.layout_active
906 || (self.fit_pending && self.graph.node_count() > 0)
907 {
908 window.request_animation_frame();
909 cx.notify();
910 }
911 self.refresh_spatial();
912 self.refresh_visible();
913 let colors = cx.arc_theme().colors;
914 let vp = self.viewport;
915 let dim = self.motion.dim_factor(now);
916 let focus = if dim > 0.01 {
917 Some(self.focus_slots())
918 } else {
919 None
920 };
921
922 let (slots, edge_pairs) = {
923 match &self.visible_cache {
924 Some(c) => (c.slots.clone(), c.edges.clone()),
925 None => (Vec::new(), Vec::new()),
926 }
927 };
928 let global_dots = self.graph.node_count() >= LOD_MIN_NODES && vp.zoom <= LOD_GLOBAL_ZOOM;
929 let show_labels =
932 !(self.drag_moved && (self.pan_drag.is_some() || self.node_drag.is_some()));
933
934 let mut full_slots: Vec<u32> = Vec::new();
936 let mut shells: Vec<(Vec2, f32, f32)> = Vec::new();
937 let mut dots: Vec<(Vec2, f32, f32)> = Vec::new();
938 let mut full_pool: Vec<(u32, u32)> = Vec::new(); let mut label_pool: Vec<(u32, u32)> = Vec::new(); for &slot in &slots {
941 if !self.drawn(slot, now) {
942 continue;
943 }
944 let Some(p) = self.positions.get(slot as usize) else {
945 continue;
946 };
947 let appear = self.appearance(slot, now);
948 let opacity = appear.opacity * Self::emphasis(slot, focus.as_ref(), dim);
949 let center = vp.world_to_screen(*p);
950 let screen_h = NODE_WORLD_SIZE * vp.zoom * appear.scale;
951 let marker_h = (NODE_MARKER_WORLD_SIZE * vp.zoom * appear.scale).max(DOT_MIN_PX);
952 let lod = if screen_h < LOD_DOT_PX || (global_dots && screen_h < LOD_SHELL_PX) {
953 Lod::Dot
954 } else if screen_h < LOD_SHELL_PX {
955 Lod::Shell
956 } else {
957 Lod::Full
958 };
959 match lod {
960 Lod::Full => full_pool.push((slot, self.degrees[slot as usize])),
962 Lod::Shell => {
963 shells.push((center, marker_h, opacity));
964 if show_labels {
965 label_pool.push((slot, self.degrees[slot as usize]));
966 }
967 }
968 Lod::Dot => {
969 dots.push((center, marker_h, opacity));
970 if show_labels {
971 label_pool.push((slot, self.degrees[slot as usize]));
972 }
973 }
974 }
975 }
976 if full_pool.len() > MAX_FULL_CARDS {
977 full_pool.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
979 for &(slot, _) in &full_pool[MAX_FULL_CARDS..] {
980 let p = self.positions[slot as usize];
981 let center = vp.world_to_screen(p);
982 let appear = self.appearance(slot, now);
983 let marker_h = (NODE_MARKER_WORLD_SIZE * vp.zoom * appear.scale).max(DOT_MIN_PX);
984 let opacity = appear.opacity * Self::emphasis(slot, focus.as_ref(), dim);
985 shells.push((center, marker_h, opacity));
986 if show_labels {
987 label_pool.push((slot, self.degrees[slot as usize]));
988 }
989 }
990 full_pool.truncate(MAX_FULL_CARDS);
991 }
992 full_pool.sort_unstable_by_key(|&(s, _)| s);
994 full_slots.extend(full_pool.into_iter().map(|(s, _)| s));
995 label_pool.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
997 let label_font = f32::from(Typography::TEXT_XS).max(10.0);
998 let mut label_cells: std::collections::HashSet<(i32, i32)> =
999 std::collections::HashSet::new();
1000 let mut labels: Vec<(Vec2, SharedString, f32)> = Vec::new();
1001 'pool: for &(slot, _) in &label_pool {
1002 if labels.len() >= MAX_LABELS {
1003 break;
1004 }
1005 let Some(node) = self.graph.node(self.payload.node_ids[slot as usize]) else {
1006 continue;
1007 };
1008 let Some(center) = self
1009 .positions
1010 .get(slot as usize)
1011 .map(|p| vp.world_to_screen(*p))
1012 else {
1013 continue;
1014 };
1015 let text = SharedString::from(node.label.clone());
1016 let approx_w = self.label_width(window, &text, label_font);
1017 let cell_w = 24.0f32.max(approx_w * 0.5);
1018 let cx0 = (center.x / cell_w).floor() as i32;
1019 let cy0 = (center.y / 18.0).floor() as i32;
1020 for dx in 0..=1 {
1022 for dy in 0..=1 {
1023 if !label_cells.insert((cx0 + dx, cy0 + dy)) {
1024 continue 'pool;
1025 }
1026 }
1027 }
1028 let opacity =
1029 self.appearance(slot, now).opacity * Self::emphasis(slot, focus.as_ref(), dim);
1030 labels.push((
1031 node_label_origin(
1032 center,
1033 (NODE_MARKER_WORLD_SIZE * vp.zoom * self.appearance(slot, now).scale)
1034 .max(DOT_MIN_PX),
1035 approx_w,
1036 label_font * 1.5,
1037 ),
1038 text,
1039 opacity,
1040 ));
1041 }
1042 let half = (EDGE_WIDTH * vp.zoom).max(0.5) / 2.0;
1044 let positions = self.positions.clone();
1045 let edge_color = colors.border_strong;
1046 let dot_color = colors.accent;
1047 let shell_fill = colors.accent;
1048 let shell_border = colors.accent;
1049 let bounds_for_edges = self.bounds_cell.clone();
1050 let mut edge_groups = [Vec::new(), Vec::new()];
1052 for &(s, t) in &edge_pairs {
1053 if self.is_slot_hidden(s) || self.is_slot_hidden(t) {
1054 continue;
1055 }
1056 let focused = focus
1057 .as_ref()
1058 .is_none_or(|f| f.contains(&s) && f.contains(&t));
1059 edge_groups[usize::from(!focused)].push((s, t));
1060 }
1061 let dot_list = dots;
1062 let shell_list = shells;
1063 self.rendered = RenderCounts {
1064 full: full_slots.len(),
1065 shell: shell_list.len(),
1066 dot: dot_list.len(),
1067 edges: edge_groups.iter().map(Vec::len).sum(),
1068 labels: labels.len(),
1069 };
1070 let back_layer = canvas(
1071 {
1072 let bounds_cell = bounds_for_edges.clone();
1073 move |b: Bounds<Pixels>, _window, _| {
1074 if let Ok(mut g) = bounds_cell.lock() {
1075 *g = Some(b);
1076 }
1077 }
1078 },
1079 move |b: Bounds<Pixels>, _, window: &mut Window, _| {
1080 for (group, edge_list) in edge_groups.iter().enumerate() {
1082 if edge_list.is_empty() {
1083 continue;
1084 }
1085 let mut fill = PathBuilder::fill().with_style(gpui_kit::PathStyle::Fill(
1088 gpui_kit::FillOptions {
1089 fill_rule: gpui_kit::FillRule::NonZero,
1090 },
1091 ));
1092 for &(s, t) in edge_list {
1093 let (Some(a), Some(bw)) =
1094 (positions.get(s as usize), positions.get(t as usize))
1095 else {
1096 continue;
1097 };
1098 let a = vp.world_to_screen(*a);
1099 let b2 = vp.world_to_screen(*bw);
1100 let d = b2.minus(a);
1101 let len = d.length();
1102 if len < 1.0 {
1103 continue;
1104 }
1105 let n = Vec2::new(-d.y / len * half, d.x / len * half);
1106 let to = |v: Vec2| {
1107 gpui_kit::point(
1108 px(f32::from(b.origin.x)) + px(v.x),
1109 px(f32::from(b.origin.y)) + px(v.y),
1110 )
1111 };
1112 fill.move_to(to(a.plus(n)));
1113 fill.line_to(to(b2.plus(n)));
1114 fill.line_to(to(b2.minus(n)));
1115 fill.line_to(to(a.minus(n)));
1116 fill.close();
1117 }
1118 if let Ok(path) = fill.build() {
1119 let alpha = if group == 0 {
1120 1.0
1121 } else {
1122 1.0 - dim * DIM_STRENGTH
1123 };
1124 window.paint_path(path, edge_color.opacity(alpha));
1125 }
1126 }
1127 for (c, d, fade) in &dot_list {
1129 let color = dot_color.opacity(*fade);
1130 window.paint_quad(quad(
1131 Bounds {
1132 origin: gpui_kit::point(
1133 b.origin.x + px(c.x - d / 2.0),
1134 b.origin.y + px(c.y - d / 2.0),
1135 ),
1136 size: size(px(*d), px(*d)),
1137 },
1138 Corners::all(px(*d / 2.0)),
1139 color,
1140 Edges::all(px(0.0)),
1141 color,
1142 gpui_kit::BorderStyle::Solid,
1143 ));
1144 }
1145 for (c, s, fade) in &shell_list {
1147 let half_s = s / 2.0;
1148 let (fill, border) = (shell_fill.opacity(*fade), shell_border.opacity(*fade));
1149 window.paint_quad(quad(
1150 Bounds {
1151 origin: gpui_kit::point(
1152 b.origin.x + px(c.x - half_s),
1153 b.origin.y + px(c.y - half_s),
1154 ),
1155 size: size(px(*s), px(*s)),
1156 },
1157 Corners::all(px(half_s)),
1158 fill,
1159 Edges::all(px(1.0)),
1160 border,
1161 gpui_kit::BorderStyle::Solid,
1162 ));
1163 }
1164 },
1165 )
1166 .absolute()
1167 .size_full();
1168
1169 let label_els: Vec<_> = labels
1171 .into_iter()
1172 .map(|(p, text, opacity)| {
1173 div()
1174 .absolute()
1175 .left(px(p.x))
1176 .top(px(p.y))
1177 .text_size(px(label_font))
1178 .line_height(px(label_font * 1.5))
1179 .text_color(colors.text_secondary.opacity(opacity))
1180 .whitespace_nowrap()
1181 .child(text)
1182 })
1183 .collect();
1184
1185 let node_font = (f32::from(Typography::TEXT_SM) * vp.zoom).clamp(9.0, 24.0);
1187 let label_height = node_font * 1.5;
1188 let world = (NODE_MARKER_WORLD_SIZE * vp.zoom).max(DOT_MIN_PX);
1189 let selected: HashSet<NodeId> = self.selection.iter().copied().collect();
1190 let text_ws: HashMap<u32, f32> = full_slots
1192 .iter()
1193 .filter(|_| show_labels)
1194 .filter_map(|&slot| {
1195 let label = self
1196 .graph
1197 .node(self.payload.node_ids[slot as usize])?
1198 .label
1199 .clone();
1200 Some((slot, self.label_width(window, &label, node_font)))
1201 })
1202 .collect();
1203 let card_els: Vec<_> = full_slots
1204 .iter()
1205 .filter_map(|&slot| {
1206 let node = self.graph.node(self.payload.node_ids[slot as usize])?;
1207 if !self.drawn(slot, now) {
1208 return None;
1209 }
1210 let c = vp.world_to_screen(*self.positions.get(slot as usize)?);
1211 let node_id = node.id;
1212 let appear = self.appearance(slot, now);
1213 let is_sel = selected.contains(&node_id);
1214 let is_hover = self.hover == Some(slot);
1215 let fade = Self::emphasis(slot, focus.as_ref(), dim);
1216 let opacity = (appear.opacity * fade).clamp(0.0, 1.0);
1217 let world = world * appear.scale;
1218 let text_w = text_ws.get(&slot).copied().unwrap_or(world);
1219 let label_pos = node_label_origin(c, world, text_w, label_height);
1220 Some(
1221 div()
1222 .absolute()
1223 .left(px(c.x - world / 2.0))
1224 .top(px(c.y - world / 2.0))
1225 .w(px(world))
1226 .h(px(world))
1227 .opacity(opacity)
1228 .child(
1229 div()
1230 .id(ElementId::NamedInteger(
1231 format!("{}-node", self.id).into(),
1232 node.id.0,
1233 ))
1234 .test_support()
1235 .size_full()
1236 .rounded(px(world / 2.0))
1237 .bg(colors.accent)
1238 .border_2()
1239 .border_color(if is_sel || is_hover {
1240 colors.foreground
1241 } else {
1242 colors.accent
1243 }),
1244 )
1245 .children(show_labels.then(|| {
1246 div()
1247 .id(ElementId::NamedInteger(
1248 format!("{}-label", self.id).into(),
1249 node.id.0,
1250 ))
1251 .test_support()
1252 .absolute()
1253 .left(px(label_pos.x - (c.x - world / 2.0)))
1254 .top(px(label_pos.y - (c.y - world / 2.0)))
1255 .w(px(text_w))
1256 .h(px(label_height))
1257 .text_size(px(node_font))
1258 .line_height(px(label_height))
1259 .text_color(if is_sel || is_hover {
1260 colors.accent
1261 } else {
1262 colors.foreground
1263 })
1264 .whitespace_nowrap()
1265 .child(node.label.clone())
1266 })),
1267 )
1268 })
1269 .collect();
1270
1271 let id = self.id.clone();
1273 let rubber_rect = self.rubber.map(|(a, b)| {
1274 let lo = Vec2::new(a.x.min(b.x), a.y.min(b.y));
1275 let hi = Vec2::new(a.x.max(b.x), a.y.max(b.y));
1276 (px(lo.x), px(lo.y), px(hi.x - lo.x), px(hi.y - lo.y))
1277 });
1278 div()
1279 .id(ElementId::Name(id))
1280 .test_support()
1281 .track_focus(&self.focus)
1282 .relative()
1283 .size_full()
1284 .overflow_hidden()
1285 .bg(colors.background)
1286 .on_scroll(cx.listener(Self::on_scroll))
1287 .on_pinch(cx.listener(Self::on_pinch))
1288 .on_mouse_down(MouseButton::Left, cx.listener(Self::on_left_down))
1289 .on_mouse_move(cx.listener(Self::on_mouse_move))
1290 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
1291 .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
1292 .on_hover(cx.listener(|this, hovered: &bool, _, cx| {
1293 if !hovered {
1294 this.hover = None;
1295 this.motion.set_dim(false, motion_now(cx));
1296 cx.notify();
1297 }
1298 }))
1299 .child(back_layer)
1300 .children(label_els)
1301 .children(card_els)
1302 .children(rubber_rect.map(|(x, y, w, h)| {
1303 div()
1304 .absolute()
1305 .left(x)
1306 .top(y)
1307 .w(w)
1308 .h(h)
1309 .border_1()
1310 .border_color(colors.accent)
1311 .bg(colors.accent_subtle.opacity(0.15))
1312 }))
1313 }
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318 use super::*;
1319 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1320 use gpui_kit::{
1321 AppContext as _, Entity, Modifiers, PlatformInput, TestAppContext, VisualTestContext,
1322 point, px, test::TestWindowExt as _,
1323 };
1324
1325 struct Host {
1326 canvas: Entity<Graph2D>,
1327 }
1328
1329 impl Render for Host {
1330 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1331 div().size_full().child(self.canvas.clone())
1332 }
1333 }
1334
1335 fn chain_graph(n: usize) -> KnowledgeGraph {
1336 let mut g = KnowledgeGraph::new();
1337 let kind = g.add_kind("概念");
1338 let mut prev = g.add_node("n0", Some(kind));
1339 for i in 1..n {
1340 let cur = g.add_node(format!("n{i}"), Some(kind));
1341 g.add_edge(prev, cur, 1.0, None).unwrap();
1342 prev = cur;
1343 }
1344 g
1345 }
1346
1347 fn grid_positions(n: usize, cols: usize) -> Vec<Vec2> {
1349 (0..n)
1350 .map(|i| Vec2::new((i % cols) as f32 * 120.0, (i / cols) as f32 * 120.0))
1351 .collect()
1352 }
1353
1354 fn large_graph() -> KnowledgeGraph {
1355 let mut g = KnowledgeGraph::new();
1356 let ids: Vec<_> = (0..5_000)
1357 .map(|i| g.add_node(format!("n{i}"), None))
1358 .collect();
1359 for i in 0..10_000u64 {
1360 let s = ids[(i * 7919 % 5_000) as usize];
1361 let t = ids[(i * 104_729 % 5_000) as usize];
1362 let _ = g.add_edge(s, t, 1.0, None);
1363 }
1364 g
1365 }
1366
1367 fn setup(cx: &mut TestAppContext) -> (Entity<Graph2D>, &mut VisualTestContext) {
1368 cx.update(|cx| {
1369 gpui_kit::init(cx);
1370 install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1371 });
1372 let mut canvas = None;
1373 let (_, vcx) = cx.add_window_view(|_, cx| {
1374 let c = cx.new(|cx| {
1375 Graph2D::new_static("graph", chain_graph(8), grid_positions(8, 4), cx)
1376 .aria_label("测试图谱")
1377 .fit_on_mount()
1378 });
1379 canvas = Some(c.clone());
1380 Host { canvas: c }
1381 });
1382 vcx.update(|window, cx| {
1383 window.render_frame(cx);
1384 window.render_frame(cx);
1385 });
1386 (canvas.unwrap(), vcx)
1387 }
1388
1389 fn p(x: f32, y: f32) -> gpui_kit::Point<Pixels> {
1390 point(px(x), px(y))
1391 }
1392
1393 #[gpui_kit::test]
1394 fn renders_round_nodes_with_labels_above_and_culls_offscreen(cx: &mut TestAppContext) {
1395 let (canvas, vcx) = setup(cx);
1396 let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1398 assert_eq!(counts.full, 8, "{counts:?}");
1399 assert_eq!(counts.edges, 7);
1400 assert_eq!(counts.shell + counts.dot, 0);
1401 vcx.update(|window, _| {
1403 let root = window.find("graph");
1404 assert!(f32::from(root.bounds().size.width) > 0.0);
1405 let node = window.find(ElementId::NamedInteger("graph-node".into(), 1));
1406 let marker = node.bounds();
1407 assert!(!marker.is_empty());
1408 assert_eq!(marker.size.width, marker.size.height, "圆点必须保持等宽高");
1409 let label = window.find(ElementId::NamedInteger("graph-label".into(), 1));
1410 let label = label.bounds();
1411 assert!(
1412 label.origin.y + label.size.height < marker.origin.y,
1413 "标签应位于圆点上方"
1414 );
1415 let marker_cx = f32::from(marker.origin.x + marker.size.width / 2.0);
1416 let label_cx = f32::from(label.origin.x + label.size.width / 2.0);
1417 assert!((marker_cx - label_cx).abs() < 1.0, "标签应水平居中");
1418 });
1419 canvas.update(vcx, |c, _| {
1421 let b = c.world_bounds().unwrap();
1422 c.viewport.offset.x = -(b.max.x + 5000.0);
1423 c.viewport.offset.y = -(b.max.y + 5000.0);
1424 });
1425 vcx.update(|window, cx| window.render_frame(cx));
1426 let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1427 assert_eq!((counts.full, counts.edges), (0, 0), "{counts:?}");
1428 }
1429
1430 #[gpui_kit::test]
1431 fn zoom_out_switches_to_dots_and_capped_labels(cx: &mut TestAppContext) {
1432 let (canvas, vcx) = setup(cx);
1433 canvas.update(vcx, |c, _| {
1435 let b = c.world_bounds().unwrap();
1436 let view = c.view_size.unwrap_or(Size2::new(800.0, 600.0));
1437 c.viewport.fit(&b, view, 60.0);
1438 c.viewport.zoom = 0.06; });
1440 vcx.update(|window, cx| window.render_frame(cx));
1441 let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1442 assert!(counts.full == 0, "{counts:?}");
1443 assert!(counts.dot + counts.shell >= 8, "{counts:?}");
1444 assert!(
1445 counts.labels > 0 && counts.labels <= MAX_LABELS,
1446 "{counts:?}"
1447 );
1448 let big = chain_graph(600);
1450 let big_positions = grid_positions(600, 30);
1451 let mut big_view = None;
1452 cx_update_big(vcx, big, big_positions, &mut big_view);
1453 let counts = big_view.unwrap().read_with(vcx, |c, _| c.rendered_counts());
1454 assert!(counts.labels <= MAX_LABELS, "{counts:?}");
1455 }
1456
1457 fn cx_update_big(
1458 vcx: &mut VisualTestContext,
1459 big: KnowledgeGraph,
1460 positions: Vec<Vec2>,
1461 out: &mut Option<Entity<Graph2D>>,
1462 ) {
1463 vcx.update(|window, cx| {
1464 let c =
1465 cx.new(|cx| Graph2D::new_static("graph-big", big, positions, cx).fit_on_mount());
1466 window.render_frame(cx);
1467 window.render_frame(cx);
1468 *out = Some(c);
1469 });
1470 }
1471
1472 #[gpui_kit::test]
1473 fn drag_pans_and_ctrl_wheel_zooms_about_cursor(cx: &mut TestAppContext) {
1474 let (canvas, vcx) = setup(cx);
1475 let before = canvas.read_with(vcx, |c, _| c.viewport());
1476 vcx.update(|window, cx| window.drag(p(700.0, 500.0), p(760.0, 470.0), cx));
1477 let after = canvas.read_with(vcx, |c, _| c.viewport());
1478 assert!(
1479 (after.offset.x - before.offset.x - 60.0).abs() < 0.5,
1480 "{after:?}"
1481 );
1482 assert!(
1483 (after.offset.y - before.offset.y + 30.0).abs() < 0.5,
1484 "{after:?}"
1485 );
1486
1487 let vp = canvas.read_with(vcx, |c, _| c.viewport());
1489 let world_before = vp.screen_to_world(Vec2::new(300.0, 200.0));
1490 vcx.update(|window, cx| {
1491 window.dispatch_event(
1492 PlatformInput::Scroll(ScrollEvent {
1493 position: p(300.0, 200.0),
1494 delta: ScrollDelta::Pixels(point(px(0.0), px(80.0))),
1495 modifiers: Modifiers {
1496 control: true,
1497 ..Default::default()
1498 },
1499 ..Default::default()
1500 }),
1501 cx,
1502 );
1503 });
1504 let vp = canvas.read_with(vcx, |c, _| c.viewport());
1505 assert!(vp.zoom > 1.0, "{vp:?}");
1506 assert!(
1507 vp.world_to_screen(world_before)
1508 .distance(Vec2::new(300.0, 200.0))
1509 < 0.01,
1510 "缩放必须以光标为锚"
1511 );
1512 }
1513
1514 #[gpui_kit::test]
1515 fn pan_hides_all_lod_labels_until_release_outside(cx: &mut TestAppContext) {
1516 let (canvas, vcx) = setup(cx);
1517 for zoom in [1.0, 0.3, 0.06] {
1518 canvas.update(vcx, |c, _| {
1519 c.viewport.zoom = zoom;
1520 c.viewport.offset = Vec2::new(120.0, 120.0);
1521 });
1522 vcx.update(|window, cx| window.render_frame(cx));
1523 let before = canvas.read_with(vcx, |c, _| c.rendered_counts());
1524 assert!(before.full > 0 || before.labels > 0, "{before:?}");
1525 vcx.update(|window, cx| {
1526 window.dispatch_event(
1527 PlatformInput::MouseDown(MouseDownEvent {
1528 button: MouseButton::Left,
1529 position: p(700.0, 500.0),
1530 click_count: 1,
1531 ..Default::default()
1532 }),
1533 cx,
1534 );
1535 window.render_frame(cx);
1536 });
1537 assert_eq!(canvas.read_with(vcx, |c, _| c.rendered_counts()), before);
1539 canvas.update(vcx, |c, _| c.text_width_cache.clear());
1540 for position in [p(720.0, 520.0), p(720.0, 520.0), p(700.0, 500.0)] {
1542 vcx.update(|window, cx| {
1543 window.dispatch_event(
1544 PlatformInput::MouseMove(MouseMoveEvent {
1545 position,
1546 pressed_button: Some(MouseButton::Left),
1547 ..Default::default()
1548 }),
1549 cx,
1550 );
1551 window.render_frame(cx);
1552 assert!(
1553 window
1554 .try_find(ElementId::NamedInteger("graph-label".into(), 1))
1555 .is_none()
1556 );
1557 });
1558 canvas.read_with(vcx, |c, _| {
1559 let counts = c.rendered_counts();
1560 assert_eq!(counts.labels, 0, "{counts:?}");
1561 assert_eq!(counts.full + counts.shell + counts.dot, 8, "圆点应保留");
1562 assert_eq!(counts.edges, 7, "连线应保留");
1563 assert!(c.text_width_cache.is_empty(), "拖动期间不应测量文字");
1564 });
1565 }
1566 vcx.update(|window, cx| {
1568 window.dispatch_event(
1569 PlatformInput::MouseUp(MouseUpEvent {
1570 button: MouseButton::Left,
1571 position: p(-10.0, -10.0),
1572 ..Default::default()
1573 }),
1574 cx,
1575 );
1576 window.render_frame(cx);
1577 });
1578 canvas.read_with(vcx, |c, _| {
1579 assert!(c.pan_drag.is_none());
1580 assert_eq!(c.rendered_counts(), before);
1581 assert!(!c.text_width_cache.is_empty(), "松手后应恢复文字");
1582 });
1583 }
1584 }
1585
1586 #[gpui_kit::test]
1587 fn node_drag_hides_labels_but_click_does_not(cx: &mut TestAppContext) {
1588 let (canvas, vcx) = setup(cx);
1589 let center = canvas.read_with(vcx, |c, _| c.viewport.world_to_screen(c.positions[0]));
1590 vcx.update(|window, cx| {
1591 window.dispatch_event(
1592 PlatformInput::MouseDown(MouseDownEvent {
1593 button: MouseButton::Left,
1594 position: p(center.x, center.y),
1595 click_count: 1,
1596 ..Default::default()
1597 }),
1598 cx,
1599 );
1600 window.render_frame(cx);
1601 assert!(
1602 window
1603 .try_find(ElementId::NamedInteger("graph-label".into(), 1))
1604 .is_some()
1605 );
1606 });
1607 canvas.update(vcx, |c, _| c.text_width_cache.clear());
1608 vcx.update(|window, cx| {
1609 window.dispatch_event(
1610 PlatformInput::MouseMove(MouseMoveEvent {
1611 position: p(center.x + 30.0, center.y + 20.0),
1612 pressed_button: Some(MouseButton::Left),
1613 ..Default::default()
1614 }),
1615 cx,
1616 );
1617 window.render_frame(cx);
1618 for id in 1..=8 {
1619 assert!(
1620 window
1621 .try_find(ElementId::NamedInteger("graph-label".into(), id))
1622 .is_none()
1623 );
1624 assert!(
1625 window
1626 .try_find(ElementId::NamedInteger("graph-node".into(), id))
1627 .is_some()
1628 );
1629 }
1630 });
1631 canvas.read_with(vcx, |c, _| assert!(c.text_width_cache.is_empty()));
1632 vcx.update(|window, cx| {
1633 window.dispatch_event(
1634 PlatformInput::MouseUp(MouseUpEvent {
1635 button: MouseButton::Left,
1636 position: p(center.x + 30.0, center.y + 20.0),
1637 ..Default::default()
1638 }),
1639 cx,
1640 );
1641 window.render_frame(cx);
1642 for id in 1..=8 {
1643 assert!(
1644 window
1645 .try_find(ElementId::NamedInteger("graph-label".into(), id))
1646 .is_some()
1647 );
1648 }
1649 });
1650 canvas.read_with(vcx, |c, _| {
1651 assert!(c.node_drag.is_none());
1652 assert!(c.is_pinned(NodeId(1)), "拖动固定行为应保留");
1653 });
1654 }
1655
1656 #[gpui_kit::test]
1657 fn click_drag_and_shift_box_select(cx: &mut TestAppContext) {
1658 let (canvas, vcx) = setup(cx);
1659 let center = canvas.read_with(vcx, |c, _| c.viewport.world_to_screen(c.positions[0]));
1660 vcx.update(|window, cx| {
1661 window.dispatch_event(
1662 PlatformInput::MouseDown(MouseDownEvent {
1663 button: MouseButton::Left,
1664 position: p(center.x, center.y),
1665 click_count: 1,
1666 ..Default::default()
1667 }),
1668 cx,
1669 );
1670 window.dispatch_event(
1671 PlatformInput::MouseUp(MouseUpEvent {
1672 button: MouseButton::Left,
1673 position: p(center.x, center.y),
1674 ..Default::default()
1675 }),
1676 cx,
1677 );
1678 });
1679 assert_eq!(
1680 canvas.read_with(vcx, |c, _| c.selection.clone()),
1681 vec![NodeId(1)]
1682 );
1683 vcx.update(|window, cx| {
1684 window.drag(
1685 p(center.x, center.y),
1686 p(center.x + 60.0, center.y + 30.0),
1687 cx,
1688 )
1689 });
1690 canvas.read_with(vcx, |c, _| {
1691 assert!(c.is_pinned(NodeId(1)));
1692 let after = c.viewport.world_to_screen(c.positions[0]);
1693 assert!(after.distance(center.plus(Vec2::new(60.0, 30.0))) < 0.1);
1694 });
1695 canvas.update(vcx, |c, cx| c.set_pinned(NodeId(1), false, cx));
1696 assert!(!canvas.read_with(vcx, |c, _| c.is_pinned(NodeId(1))));
1697 vcx.update(|window, cx| {
1699 canvas.update(cx, |c, cx| {
1700 c.on_left_down(
1701 &MouseDownEvent {
1702 position: p(1.0, 1.0),
1703 modifiers: Modifiers {
1704 shift: true,
1705 ..Default::default()
1706 },
1707 ..Default::default()
1708 },
1709 window,
1710 cx,
1711 );
1712 c.on_mouse_move(
1713 &MouseMoveEvent {
1714 position: p(1900.0, 1000.0),
1715 ..Default::default()
1716 },
1717 window,
1718 cx,
1719 );
1720 c.on_mouse_up(&MouseUpEvent::default(), window, cx);
1721 });
1722 });
1723 assert_eq!(canvas.read_with(vcx, |c, _| c.selection.len()), 8);
1724 }
1725
1726 #[gpui_kit::test]
1727 fn hover_neighbors_and_precise_hit(cx: &mut TestAppContext) {
1728 let (canvas, vcx) = setup(cx);
1729 canvas.read_with(vcx, |c, _| {
1730 assert_eq!(c.hit_slot(Vec2::new(30.0, 0.0)), None);
1732 });
1733 vcx.update(|window, cx| {
1734 canvas.update(cx, |c, cx| {
1735 let pos = c.viewport.world_to_screen(c.positions[1]);
1736 c.on_mouse_move(
1737 &MouseMoveEvent {
1738 position: p(pos.x, pos.y),
1739 ..Default::default()
1740 },
1741 window,
1742 cx,
1743 );
1744 assert_eq!(c.hover(), Some(NodeId(2)));
1745 let focus = c.focus_slots();
1746 assert!(focus.contains(&0) && focus.contains(&1) && focus.contains(&2));
1747 assert!(!focus.contains(&7));
1748 assert_eq!(Graph2D::emphasis(0, Some(&focus), 1.0), 1.0);
1749 assert!(Graph2D::emphasis(7, Some(&focus), 1.0) < 1.0);
1750 });
1751 });
1752 }
1753
1754 #[gpui_kit::test]
1755 fn filter_expand_search_and_interrupt_flight(cx: &mut TestAppContext) {
1756 let (canvas, vcx) = setup(cx);
1757 vcx.update(|window, cx| {
1758 canvas.update(cx, |c, cx| {
1759 let kind = c.graph.add_kind("其他");
1760 c.set_kind_filter(Some(kind), cx);
1762 assert_eq!(c.hidden_count(), 8);
1763 assert!(c.search("n").is_empty());
1764 assert_eq!(c.expand(NodeId(2), cx), 2);
1765 assert_eq!(c.hidden_count(), 6);
1766 assert_eq!(c.search("N0"), vec![NodeId(1)]);
1767 c.set_kind_filter(None, cx);
1768 assert_eq!(c.hidden_count(), 0);
1769 assert_eq!(c.search("n").len(), 8);
1770 c.fly_to(NodeId(4), cx);
1771 assert!(c.motion.view_animating());
1772 c.on_scroll(
1773 &ScrollEvent {
1774 position: p(500.0, 300.0),
1775 ..Default::default()
1776 },
1777 window,
1778 cx,
1779 );
1780 assert!(!c.motion.view_animating());
1781 assert!(c.selection.contains(&NodeId(4)));
1782 });
1783 });
1784 }
1785
1786 #[test]
1789 #[ignore]
1790 fn bench_edge_path_batches() {
1791 let graph = large_graph();
1792 let payload = GraphPayload::from_graph(&graph);
1793 let positions: Vec<_> = grid_positions(5_000, 100)
1794 .into_iter()
1795 .map(|p| Vec2::new(p.x * 0.2, p.y * 0.2))
1796 .collect();
1797 let mask = gpui_kit::ContentMask {
1798 bounds: Bounds {
1799 origin: point(px(0.0), px(0.0)),
1800 size: size(px(4096.0), px(4096.0)),
1801 },
1802 };
1803 for batch in [1, 32, 128, 512, 10_000] {
1804 let mut samples = Vec::new();
1805 for iteration in 0..12 {
1806 let started = std::time::Instant::now();
1807 let mut build_ms = 0.0;
1808 let mut bin_ms = 0.0;
1809 for edges in payload.edges.chunks(batch) {
1810 let t = std::time::Instant::now();
1811 let mut fill = PathBuilder::fill().with_style(gpui_kit::PathStyle::Fill(
1812 gpui_kit::FillOptions {
1813 fill_rule: gpui_kit::FillRule::NonZero,
1814 },
1815 ));
1816 for &(s, t, _) in edges {
1817 let (a, b) = (positions[s as usize], positions[t as usize]);
1818 let d = b.minus(a);
1819 let len = d.length();
1820 if len < 1.0 {
1821 continue;
1822 }
1823 let n = Vec2::new(-d.y / len * 0.75, d.x / len * 0.75);
1824 let to = |v: Vec2| point(px(v.x + iteration as f32 % 2.0), px(v.y));
1825 fill.move_to(to(a.plus(n)));
1826 fill.line_to(to(b.plus(n)));
1827 fill.line_to(to(b.minus(n)));
1828 fill.line_to(to(a.minus(n)));
1829 fill.close();
1830 }
1831 let path = fill.build().unwrap();
1832 build_ms += t.elapsed().as_secs_f64() * 1000.0;
1833 let t = std::time::Instant::now();
1834 std::hint::black_box(gpui_kit::PaintedPath::new(
1835 path,
1836 2.0,
1837 mask,
1838 gpui_kit::rgba(0x000000ff).into(),
1839 ));
1840 bin_ms += t.elapsed().as_secs_f64() * 1000.0;
1841 }
1842 if iteration > 1 {
1843 samples.push((started.elapsed().as_secs_f64() * 1000.0, build_ms, bin_ms));
1844 }
1845 }
1846 let n = samples.len() as f64;
1847 println!(
1848 "BENCH edges batch={batch}: total {:.2} ms, build {:.2} ms, bin {:.2} ms (CPU only)",
1849 samples.iter().map(|s| s.0).sum::<f64>() / n,
1850 samples.iter().map(|s| s.1).sum::<f64>() / n,
1851 samples.iter().map(|s| s.2).sum::<f64>() / n
1852 );
1853 }
1854 }
1855
1856 #[gpui_kit::test]
1864 #[ignore]
1865 fn bench_graph_frame_times(cx: &mut TestAppContext) {
1866 cx.update(|cx| {
1867 gpui_kit::init(cx);
1868 install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1869 });
1870 let graph = large_graph();
1871 let positions = grid_positions(5_000, 100)
1872 .into_iter()
1873 .map(|p| Vec2::new(p.x * 0.2, p.y * 0.2))
1874 .collect();
1875 let mut canvas = None;
1876 let (_, vcx) = cx.add_window_view(|_, cx| {
1877 let c = cx.new(|cx| Graph2D::new_static("graph-bench", graph, positions, cx));
1878 canvas = Some(c.clone());
1879 Host { canvas: c }
1880 });
1881
1882 vcx.update(|window, cx| {
1884 window.render_frame(cx);
1885 window.render_frame(cx);
1886 });
1887 let canvas = canvas.unwrap();
1888 let mut times = Vec::with_capacity(30);
1889 for i in 0usize..30 {
1890 canvas.update(vcx, |c, _| {
1891 c.viewport.offset.x += if i.is_multiple_of(2) { 1.0 } else { -1.0 };
1892 });
1893 let started = std::time::Instant::now();
1894 vcx.update(|window, cx| window.render_frame(cx));
1895 times.push(started.elapsed().as_secs_f64() * 1000.0);
1896 }
1897 times.sort_by(f64::total_cmp);
1898 let avg = times.iter().sum::<f64>() / times.len() as f64;
1899 let p95 = times[(times.len() * 95 / 100).min(times.len() - 1)];
1900 let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1901 println!(
1902 "BENCH graph 5,000/10,000 dense pan: avg {avg:.2} ms, p95 {p95:.2} ms, drawn {counts:?}"
1903 );
1904 }
1905
1906 #[gpui_kit::test]
1907 fn light_dark_light_keeps_graph_renderable(cx: &mut TestAppContext) {
1908 let (canvas, vcx) = setup(cx);
1909 for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
1910 vcx.update(|window, cx| {
1911 install_arc_theme(mode, Accent::Blue, cx);
1912 window.render_frame(cx);
1913 });
1914 assert_eq!(canvas.read_with(vcx, |c, _| c.rendered_counts().full), 8);
1915 }
1916 }
1917
1918 #[gpui_kit::test]
1919 fn static_positions_skip_layout_worker(cx: &mut TestAppContext) {
1920 cx.update(|cx| {
1922 gpui_kit::init(cx);
1923 install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1924 });
1925 let mut canvas = None;
1926 let (_, vcx) = cx.add_window_view(|_, cx| {
1927 let c = cx.new(|cx| {
1928 Graph2D::new_static("graph-static", chain_graph(4), grid_positions(4, 2), cx)
1929 });
1930 canvas = Some(c.clone());
1931 Host { canvas: c }
1932 });
1933 vcx.update(|window, cx| {
1934 window.render_frame(cx);
1935 window.render_frame(cx);
1936 });
1937 let counts = canvas.unwrap().read_with(vcx, |c, _| c.rendered_counts());
1939 assert!(counts.full + counts.dot + counts.shell > 0, "{counts:?}");
1940 assert_eq!(counts.edges, 3);
1941 }
1942}