use crate::motion::{Appear, DIM_STRENGTH, GraphMotion};
use arc_flow_core::Viewport;
use arc_flow_core::geometry::{Rect, Size2, Vec2};
use arc_flow_core::spatial::SpatialGrid;
use arc_graph_core::{
GraphPayload, KnowledgeGraph, LayoutCommand, LayoutConfig, LayoutWorker2D, NodeId, NodeKind,
};
use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
use gpui_kit::{
App, Bounds, Context, Corners, Edges, ElementId, FocusHandle, Focusable, InteractiveElement,
IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement,
PathBuilder, Pixels, Render, ScrollDelta, ScrollEvent, SharedString,
StatefulInteractiveElement, Styled, TestSupportExt as _, Window, canvas, div, px, quad, size,
};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
const NODE_WORLD_SIZE: f32 = 36.0;
const NODE_MARKER_WORLD_SIZE: f32 = 12.0;
fn node_label_origin(center: Vec2, diameter: f32, width: f32, height: f32) -> Vec2 {
Vec2::new(
center.x - width / 2.0,
center.y - diameter / 2.0 - f32::from(Spacing::S1) - height,
)
}
const EDGE_WIDTH: f32 = 1.5;
const LOD_DOT_PX: f32 = 4.0;
const LOD_SHELL_PX: f32 = 14.0;
const LOD_MIN_NODES: usize = 500;
const LOD_GLOBAL_ZOOM: f32 = 0.25;
const DOT_MIN_PX: f32 = 2.5;
const MAX_LABELS: usize = 200;
const MAX_FULL_CARDS: usize = 160;
const CULL_MARGIN: f32 = 40.0;
const WHEEL_ZOOM_SPEED: f32 = 0.01;
const KG_MIN_ZOOM: f32 = 0.02;
const KG_MAX_ZOOM: f32 = 4.0;
const LINE_HEIGHT: f32 = 20.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lod {
Full,
Shell,
Dot,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct RenderCounts {
pub full: usize,
pub shell: usize,
pub dot: usize,
pub edges: usize,
pub labels: usize,
}
pub struct Graph2D {
id: SharedString,
label: SharedString,
focus: FocusHandle,
graph: KnowledgeGraph,
payload: GraphPayload,
degrees: Vec<u32>,
worker: Option<LayoutWorker2D>,
layout_active: bool,
layout_paused: bool,
positions: Arc<Vec<Vec2>>,
positions_rev: u64,
viewport: Viewport,
view_size: Option<Size2>,
fit_pending: bool,
spatial: Option<SpatialGrid<u32>>,
spatial_rev: u64,
visible_cache: Option<Arc<VisibleCache>>,
pan_drag: Option<(Vec2, Vec2)>,
rendered: RenderCounts,
bounds_cell: Arc<std::sync::Mutex<Option<Bounds<Pixels>>>>,
motion: GraphMotion,
hover: Option<u32>,
selection: Vec<NodeId>,
rubber: Option<(Vec2, Vec2)>,
node_drag: Option<(u32, Vec2)>,
drag_moved: bool,
revealed: HashSet<NodeId>,
kind_filter: Option<arc_graph_core::KindId>,
hidden: Option<HashSet<u32>>,
slot_index: std::collections::HashMap<NodeId, u32>,
text_width_cache: HashMap<(SharedString, u32), f32>,
}
struct VisibleCache {
key: ([u32; 3], u64),
slots: Vec<u32>,
edges: Vec<(u32, u32)>,
}
impl Graph2D {
pub fn new(id: impl Into<SharedString>, graph: KnowledgeGraph, cx: &mut Context<Self>) -> Self {
let payload = GraphPayload::from_graph(&graph);
let worker = LayoutWorker2D::spawn(LayoutConfig::default(), payload.clone());
Self::build(id, graph, payload, Some(worker), cx)
}
pub fn new_static(
id: impl Into<SharedString>,
graph: KnowledgeGraph,
positions: Vec<Vec2>,
cx: &mut Context<Self>,
) -> Self {
let payload = GraphPayload::from_graph(&graph);
let mut view = Self::build(id, graph, payload, None, cx);
view.positions = Arc::new(positions);
view.positions_rev = 1;
view.fit_pending = true;
view
}
fn build(
id: impl Into<SharedString>,
graph: KnowledgeGraph,
payload: GraphPayload,
worker: Option<LayoutWorker2D>,
_cx: &mut Context<Self>,
) -> Self {
let degrees = {
let mut d = vec![0u32; payload.node_ids.len()];
for &(s, t, _) in &payload.edges {
if s != t {
d[s as usize] += 1;
d[t as usize] += 1;
}
}
d
};
let viewport = Viewport {
min_zoom: KG_MIN_ZOOM,
max_zoom: KG_MAX_ZOOM,
..Viewport::default()
};
let focus = _cx.focus_handle();
let slot_index: std::collections::HashMap<NodeId, u32> = payload
.node_ids
.iter()
.enumerate()
.map(|(i, id)| (*id, i as u32))
.collect();
Self {
id: id.into(),
label: "Knowledge graph".into(),
focus,
graph,
degrees,
layout_active: worker.is_some(),
layout_paused: false,
worker,
payload,
positions: Arc::new(Vec::new()),
positions_rev: 0,
viewport,
view_size: None,
fit_pending: false,
spatial: None,
spatial_rev: 0,
visible_cache: None,
pan_drag: None,
rendered: RenderCounts::default(),
bounds_cell: Arc::new(std::sync::Mutex::new(None)),
motion: GraphMotion::default(),
hover: None,
selection: Vec::new(),
rubber: None,
node_drag: None,
drag_moved: false,
revealed: HashSet::new(),
kind_filter: None,
hidden: None,
slot_index,
text_width_cache: HashMap::new(),
}
}
fn label_width(&mut self, window: &mut Window, label: &str, font_px: f32) -> f32 {
const TEXT_CACHE_CAP: usize = 4_096;
if self.text_width_cache.len() > TEXT_CACHE_CAP {
self.text_width_cache.clear();
}
let key = (SharedString::from(label), (font_px * 4.0).round() as u32);
if let Some(&w) = self.text_width_cache.get(&key) {
return w;
}
let w = f32::from(
window
.text_system()
.layout_line(key.0.clone(), px(font_px), &[], None)
.width,
);
self.text_width_cache.insert(key, w);
w
}
pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn fit_on_mount(mut self) -> Self {
self.fit_pending = true;
self
}
pub fn viewport(&self) -> Viewport {
self.viewport
}
pub fn set_layout_paused(&mut self, paused: bool, cx: &mut Context<Self>) {
if self.layout_paused == paused {
return;
}
self.layout_paused = paused;
if !paused && self.worker.is_some() {
self.layout_active = true;
}
if let Some(worker) = &self.worker {
worker.send(if paused {
LayoutCommand::Cancel
} else {
LayoutCommand::Wake
});
}
cx.notify();
}
pub fn rendered_counts(&self) -> RenderCounts {
self.rendered
}
pub fn positions(&self) -> &Arc<Vec<Vec2>> {
&self.positions
}
pub fn fit_view(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
self.motion.cancel_view();
cx.notify();
if let Some(world) = self.world_bounds() {
let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
self.viewport.fit(&world, view, 60.0);
}
}
pub fn zoom_by(&mut self, factor: f32, _window: &mut Window, cx: &mut Context<Self>) {
self.motion.cancel_view();
cx.notify();
let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
let anchor = Vec2::new(view.w / 2.0, view.h / 2.0);
self.viewport.zoom_by_at(factor, anchor);
}
pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
self.graph.kinds()
}
pub fn kind_filter(&self) -> Option<arc_graph_core::KindId> {
self.kind_filter
}
pub fn set_kind_filter(
&mut self,
kind: Option<arc_graph_core::KindId>,
cx: &mut Context<Self>,
) {
let previous: Vec<bool> = (0..self.payload.node_ids.len())
.map(|s| self.is_slot_hidden(s as u32))
.collect();
self.kind_filter = kind;
self.revealed.clear();
self.selection.clear();
self.hidden = kind.map(|k| {
let mut set = HashSet::new();
for (i, &id) in self.payload.node_ids.iter().enumerate() {
let matches = self.graph.node(id).is_some_and(|n| n.kind == Some(k));
if !matches {
set.insert(i as u32);
}
}
set
});
let now = motion_now(cx);
self.motion.set_reduced(is_reduced_motion(cx));
for (slot, was_hidden) in previous.into_iter().enumerate() {
let hidden = self.is_slot_hidden(slot as u32);
let id = self.payload.node_ids[slot];
if hidden && !was_hidden {
self.motion.node_exited(id, now);
}
if !hidden && was_hidden {
self.motion.node_entered(id, now);
}
}
self.hover = None;
self.motion.set_dim(false, now);
cx.notify();
}
pub fn set_pinned(&mut self, id: NodeId, pinned: bool, cx: &mut Context<Self>) {
let Some(&slot) = self.slot_index.get(&id) else {
return;
};
self.payload.pinned[slot as usize] = pinned;
if let Some(worker) = &self.worker {
worker.send(LayoutCommand::SetPinned(id, pinned));
if let Some(&position) = self.positions.get(slot as usize) {
worker.send(LayoutCommand::MoveNode(id, position));
self.layout_active = true;
}
}
cx.notify();
}
pub fn is_pinned(&self, id: NodeId) -> bool {
self.slot_index
.get(&id)
.is_some_and(|&s| self.payload.pinned[s as usize])
}
pub fn node_label(&self, id: NodeId) -> Option<&str> {
self.graph.node(id).map(|node| node.label.as_str())
}
pub fn selection(&self) -> &[NodeId] {
&self.selection
}
pub fn hover(&self) -> Option<NodeId> {
self.hover.map(|s| self.payload.node_ids[s as usize])
}
pub fn search(&self, query: &str) -> Vec<NodeId> {
let q = query.trim().to_lowercase();
if q.is_empty() {
return Vec::new();
}
let mut hits: Vec<(u32, u32)> = self
.payload
.node_ids
.iter()
.enumerate()
.filter(|(i, _)| !self.is_slot_hidden(*i as u32))
.filter_map(|(i, id)| {
let n = self.graph.node(*id)?;
n.label
.to_lowercase()
.contains(&q)
.then(|| (i as u32, self.degrees[i]))
})
.collect();
hits.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
hits.into_iter()
.take(20)
.map(|(s, _)| self.payload.node_ids[s as usize])
.collect()
}
pub fn fly_to(&mut self, id: NodeId, cx: &mut Context<Self>) {
let Some(&slot) = self.slot_index.get(&id) else {
return;
};
if self.is_slot_hidden(slot) {
return;
}
let Some(p) = self.positions.get(slot as usize).copied() else {
return;
};
if !self.selection.contains(&id) {
self.selection.push(id);
}
let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
let center = Vec2::new(view.w / 2.0, view.h / 2.0);
let mut target = self.viewport;
target.zoom = target.zoom.clamp(1.0, KG_MAX_ZOOM);
target.offset = center.minus(p.scale(target.zoom));
let now = motion_now(cx);
self.motion.set_reduced(is_reduced_motion(cx));
if self
.motion
.animate_view(&self.viewport, &target, center, now)
{
cx.notify();
} else {
self.viewport = target;
cx.notify();
}
}
pub fn expand(&mut self, id: NodeId, cx: &mut Context<Self>) -> usize {
self.motion.set_reduced(is_reduced_motion(cx));
let Some(filter) = self.hidden.as_mut() else {
return 0;
};
let neighbors = self.graph.adjacency().neighbors(id);
let mut revealed_count = 0;
let now = motion_now(cx);
for n in neighbors {
let Some(&slot) = self.slot_index.get(&n) else {
continue;
};
if filter.remove(&slot) {
self.revealed.insert(n);
self.motion.node_entered(n, now);
revealed_count += 1;
}
}
if revealed_count > 0 {
cx.notify();
}
revealed_count
}
pub fn hidden_count(&self) -> usize {
self.hidden.as_ref().map_or(0, |h| h.len())
}
fn is_slot_hidden(&self, slot: u32) -> bool {
self.hidden
.as_ref()
.is_some_and(|h| h.contains(&slot) && !self.revealed_overrides(slot))
}
fn drawn(&self, slot: u32, now: f64) -> bool {
!self.is_slot_hidden(slot)
|| self
.motion
.is_exiting(self.payload.node_ids[slot as usize], now)
}
fn appearance(&self, slot: u32, now: f64) -> Appear {
let id = self.payload.node_ids[slot as usize];
if self.is_slot_hidden(slot) {
self.motion.exit_sample(id, now)
} else {
self.motion.enter_sample(id, now)
}
}
fn emphasis(slot: u32, focus: Option<&HashSet<u32>>, dim: f32) -> f32 {
if focus.is_none_or(|f| f.contains(&slot)) {
1.0
} else {
1.0 - dim * DIM_STRENGTH
}
}
fn revealed_overrides(&self, slot: u32) -> bool {
let Some(&id) = self.payload.node_ids.get(slot as usize) else {
return false;
};
self.revealed.contains(&id)
}
fn world_bounds(&self) -> Option<Rect> {
let p = self.positions.as_ref();
if p.is_empty() {
return None;
}
let r = NODE_WORLD_SIZE / 2.0;
let mut lo = p[0].minus(Vec2::new(r, r));
let mut hi = p[0].plus(Vec2::new(r, r));
for v in p.iter().skip(1) {
lo = Vec2::new(lo.x.min(v.x - r), lo.y.min(v.y - r));
hi = Vec2::new(hi.x.max(v.x + r), hi.y.max(v.y + r));
}
Some(Rect { min: lo, max: hi })
}
fn poll_layout(&mut self) {
let held = self.node_drag.and_then(|(slot, _)| {
self.positions
.get(slot as usize)
.copied()
.map(|p| (slot, p))
});
if let Some(worker) = &mut self.worker {
if let Some(snap) = worker.try_snapshot() {
self.layout_active = !snap.cooled;
self.positions = snap.positions;
self.positions_rev += 1;
}
if worker.is_poisoned() {
self.layout_active = false;
}
}
if let Some((slot, p)) = held
&& let Some(current) = Arc::make_mut(&mut self.positions).get_mut(slot as usize)
{
*current = p;
}
if self.fit_pending && self.view_size.is_some() && !self.positions.is_empty() {
self.fit_pending = false;
if let Some(world) = self.world_bounds() {
let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
self.viewport.fit(&world, view, 60.0);
}
}
}
fn refresh_spatial(&mut self) {
if self.spatial_rev == self.positions_rev && self.spatial.is_some() {
return;
}
let mut grid = SpatialGrid::new(NODE_WORLD_SIZE * 3.0);
let r = NODE_WORLD_SIZE / 2.0;
for (i, p) in self.positions.iter().enumerate() {
let rect = Rect {
min: Vec2::new(p.x - r, p.y - r),
max: Vec2::new(p.x + r, p.y + r),
};
grid.insert(i as u32, rect);
}
self.spatial = Some(grid);
self.spatial_rev = self.positions_rev;
}
fn visible_world(&self) -> Rect {
let view = self.view_size.unwrap_or(Size2::new(4096.0, 4096.0));
self.viewport
.visible_world_rect(view)
.inflate(CULL_MARGIN / self.viewport.zoom.max(0.02))
}
fn refresh_visible(&mut self) {
let key = (
[
self.viewport.offset.x.to_bits(),
self.viewport.offset.y.to_bits(),
self.viewport.zoom.to_bits(),
],
self.positions_rev,
);
if let Some(c) = &self.visible_cache
&& c.key == key
{
return;
}
let visible = self.visible_world();
let mut slots = self
.spatial
.as_ref()
.map(|g| g.query(&visible))
.unwrap_or_default();
slots.sort_unstable();
let r = NODE_WORLD_SIZE / 2.0;
let mut edges = Vec::new();
for &(s, t, _) in &self.payload.edges {
let (Some(a), Some(b)) = (
self.positions.get(s as usize),
self.positions.get(t as usize),
) else {
continue;
};
let seg = Rect {
min: Vec2::new(a.x.min(b.x) - r, a.y.min(b.y) - r),
max: Vec2::new(a.x.max(b.x) + r, a.y.max(b.y) + r),
};
if seg.intersects(&visible) {
edges.push((s, t));
}
}
edges.sort_unstable();
self.visible_cache = Some(Arc::new(VisibleCache { key, slots, edges }));
}
fn local(&self, position: gpui_kit::Point<Pixels>) -> Vec2 {
let b = self.bounds_cell.lock().ok().and_then(|g| *g);
match b {
Some(bounds) => Vec2::new(
f32::from(position.x - bounds.origin.x),
f32::from(position.y - bounds.origin.y),
),
None => Vec2::ZERO,
}
}
fn on_scroll(&mut self, ev: &ScrollEvent, _window: &mut Window, cx: &mut Context<Self>) {
let delta = ev.delta.pixel_delta(px(LINE_HEIGHT));
let (dx, dy) = (f32::from(delta.x), f32::from(delta.y));
self.motion.cancel_view();
if ev.modifiers.secondary(cx) || ev.modifiers.control {
let anchor = self.local(ev.position);
let dy = if matches!(ev.delta, ScrollDelta::Lines(_)) {
dy * 2.0
} else {
dy
};
self.viewport
.zoom_by_at((dy * WHEEL_ZOOM_SPEED).exp(), anchor);
} else {
self.viewport.pan_by(Vec2::new(dx, dy));
}
cx.notify();
cx.stop_propagation();
}
fn hit_slot(&self, world: Vec2) -> Option<u32> {
let grid = self.spatial.as_ref()?;
let r = NODE_WORLD_SIZE / 2.0 + 4.0 / self.viewport.zoom.max(0.02);
let probe = Rect {
min: Vec2::new(world.x - r, world.y - r),
max: Vec2::new(world.x + r, world.y + r),
};
grid.query(&probe)
.into_iter()
.filter(|&s| !self.is_slot_hidden(s))
.filter(|&s| {
self.positions
.get(s as usize)
.is_some_and(|p| (p.x - world.x).abs() <= r && (p.y - world.y).abs() <= r)
})
.min_by(|&a, &b| {
self.positions[a as usize]
.distance(world)
.total_cmp(&self.positions[b as usize].distance(world))
.then(a.cmp(&b))
})
}
fn focus_slots(&self) -> HashSet<u32> {
let mut focus = HashSet::new();
if let Some(h) = self.hover {
focus.insert(h);
}
for &id in &self.selection {
if let Some(&s) = self.slot_index.get(&id) {
focus.insert(s);
}
}
let mut out = focus.clone();
for &s in &focus {
let Some(&id) = self.payload.node_ids.get(s as usize) else {
continue;
};
for n in self.graph.adjacency().neighbors(id) {
if let Some(&ns) = self.slot_index.get(&n) {
out.insert(ns);
}
}
}
out
}
fn on_left_down(&mut self, ev: &MouseDownEvent, _w: &mut Window, cx: &mut Context<Self>) {
self.motion.cancel_view();
self.refresh_spatial();
self.drag_moved = false;
let local = self.local(ev.position);
let world = self.viewport.screen_to_world(local);
if ev.click_count >= 2 {
if let Some(slot) = self.hit_slot(world) {
let id = self.payload.node_ids[slot as usize];
let _ = self.expand(id, cx);
if !self.selection.contains(&id) {
self.selection = vec![id];
}
cx.notify();
cx.stop_propagation();
}
return;
}
if let Some(slot) = self.hit_slot(world) {
let node_pos = self.positions.get(slot as usize).copied().unwrap_or(world);
self.node_drag = Some((slot, world.minus(node_pos)));
self.drag_moved = false;
cx.stop_propagation();
return;
}
if ev.modifiers.shift {
self.rubber = Some((local, local));
} else {
self.pan_drag = Some((local, self.viewport.offset));
}
cx.stop_propagation();
}
fn on_mouse_move(&mut self, ev: &MouseMoveEvent, _w: &mut Window, cx: &mut Context<Self>) {
let local = self.local(ev.position);
let world = self.viewport.screen_to_world(local);
if let Some((slot, grab)) = self.node_drag {
let target = world.minus(grab);
if self
.positions
.get(slot as usize)
.is_some_and(|p| p.distance(target) < 0.01)
{
return;
}
self.drag_moved = true;
self.payload.pinned[slot as usize] = true;
if let Some(worker) = &self.worker {
let id = self.payload.node_ids[slot as usize];
worker.send(LayoutCommand::SetPinned(id, true));
worker.send(LayoutCommand::MoveNode(id, target));
self.layout_active = true;
}
Arc::make_mut(&mut self.positions)[slot as usize] = target;
self.positions_rev += 1;
cx.notify();
return;
}
if let Some((start, _)) = self.rubber {
self.rubber = Some((start, local));
cx.notify();
return;
}
if let Some((start, base)) = self.pan_drag {
self.drag_moved |= local.distance(start) > 4.0;
self.viewport.offset = base.plus(local.minus(start));
cx.notify();
return;
}
let hit = self.hit_slot(world);
if hit != self.hover {
self.hover = hit;
let now = motion_now(cx);
self.motion.set_reduced(is_reduced_motion(cx));
self.motion.set_dim(hit.is_some(), now);
cx.notify();
}
}
fn on_mouse_up(&mut self, ev: &MouseUpEvent, _w: &mut Window, cx: &mut Context<Self>) {
if let Some((slot, _)) = self.node_drag.take() {
if !self.drag_moved {
let id = self.payload.node_ids[slot as usize];
if ev.modifiers.shift {
if let Some(i) = self.selection.iter().position(|&s| s == id) {
self.selection.remove(i);
} else {
self.selection.push(id);
}
} else {
self.selection = vec![id];
}
}
cx.notify();
return;
}
if let Some((start, end)) = self.rubber.take() {
let (lo, hi) = (
Vec2::new(start.x.min(end.x), start.y.min(end.y)),
Vec2::new(start.x.max(end.x), start.y.max(end.y)),
);
let mut picked = Vec::new();
if hi.x - lo.x > 4.0 || hi.y - lo.y > 4.0 {
for (i, p) in self.positions.iter().enumerate() {
let slot = i as u32;
if self.is_slot_hidden(slot) {
continue;
}
let c = self.viewport.world_to_screen(*p);
if c.x >= lo.x && c.x <= hi.x && c.y >= lo.y && c.y <= hi.y {
picked.push(self.payload.node_ids[slot as usize]);
}
}
}
self.selection = picked;
cx.notify();
return;
}
if self.pan_drag.take().is_some() {
if !self.drag_moved {
self.selection.clear();
}
cx.notify();
}
}
fn on_pinch(&mut self, ev: &gpui_kit::PinchEvent, _w: &mut Window, _cx: &mut Context<Self>) {
self.motion.cancel_view();
let anchor = self.local(ev.position);
self.viewport.zoom_by_at(1.0 + ev.delta, anchor);
}
}
impl Focusable for Graph2D {
fn focus_handle(&self, _cx: &App) -> FocusHandle {
self.focus.clone()
}
}
impl Render for Graph2D {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let measured = self
.bounds_cell
.lock()
.ok()
.and_then(|g| *g)
.map(|b| Size2::new(f32::from(b.size.width), f32::from(b.size.height)));
if let Some(measured) = measured
&& self.view_size != Some(measured)
{
self.view_size = Some(measured);
self.visible_cache = None;
}
self.poll_layout();
let now = motion_now(cx);
self.motion.set_reduced(is_reduced_motion(cx));
if self.motion.view_animating() {
let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
let center = Vec2::new(view.w / 2.0, view.h / 2.0);
if let Some((vp, done)) = self.motion.view_sample(&self.viewport, center, now) {
self.viewport = vp;
if done {
self.motion.cancel_view();
}
cx.notify();
}
}
self.motion.prune(now);
if !self.layout_paused
&& (self.motion.animating(now)
|| self.layout_active
|| (self.fit_pending && self.graph.node_count() > 0))
{
window.request_animation_frame();
cx.notify();
}
self.refresh_spatial();
self.refresh_visible();
let colors = cx.arc_theme().colors;
let vp = self.viewport;
let dim = self.motion.dim_factor(now);
let focus = if dim > 0.01 {
Some(self.focus_slots())
} else {
None
};
let visible = self.visible_cache.clone().expect("可见集已刷新");
let slots = &visible.slots;
let edge_pairs = &visible.edges;
let global_dots = self.graph.node_count() >= LOD_MIN_NODES && vp.zoom <= LOD_GLOBAL_ZOOM;
let show_labels =
!(self.drag_moved && (self.pan_drag.is_some() || self.node_drag.is_some()));
let mut full_slots: Vec<u32> = Vec::new();
let mut shells: Vec<(Vec2, f32, f32)> = Vec::new();
let mut dots: Vec<(Vec2, f32, f32)> = Vec::new();
let mut full_pool: Vec<(u32, u32)> = Vec::new(); let mut label_pool: Vec<(u32, u32)> = Vec::new(); for &slot in slots {
if !self.drawn(slot, now) {
continue;
}
let Some(p) = self.positions.get(slot as usize) else {
continue;
};
let appear = self.appearance(slot, now);
let opacity = appear.opacity * Self::emphasis(slot, focus.as_ref(), dim);
let center = vp.world_to_screen(*p);
let screen_h = NODE_WORLD_SIZE * vp.zoom * appear.scale;
let marker_h = (NODE_MARKER_WORLD_SIZE * vp.zoom * appear.scale).max(DOT_MIN_PX);
let lod = if screen_h < LOD_DOT_PX || (global_dots && screen_h < LOD_SHELL_PX) {
Lod::Dot
} else if screen_h < LOD_SHELL_PX {
Lod::Shell
} else {
Lod::Full
};
match lod {
Lod::Full => full_pool.push((slot, self.degrees[slot as usize])),
Lod::Shell => {
shells.push((center, marker_h, opacity));
if show_labels {
label_pool.push((slot, self.degrees[slot as usize]));
}
}
Lod::Dot => {
dots.push((center, marker_h, opacity));
if show_labels {
label_pool.push((slot, self.degrees[slot as usize]));
}
}
}
}
if full_pool.len() > MAX_FULL_CARDS {
full_pool.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
for &(slot, _) in &full_pool[MAX_FULL_CARDS..] {
let p = self.positions[slot as usize];
let center = vp.world_to_screen(p);
let appear = self.appearance(slot, now);
let marker_h = (NODE_MARKER_WORLD_SIZE * vp.zoom * appear.scale).max(DOT_MIN_PX);
let opacity = appear.opacity * Self::emphasis(slot, focus.as_ref(), dim);
shells.push((center, marker_h, opacity));
if show_labels {
label_pool.push((slot, self.degrees[slot as usize]));
}
}
full_pool.truncate(MAX_FULL_CARDS);
}
full_pool.sort_unstable_by_key(|&(s, _)| s);
full_slots.extend(full_pool.into_iter().map(|(s, _)| s));
label_pool.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let label_font = f32::from(Typography::TEXT_XS).max(10.0);
let mut label_cells: std::collections::HashSet<(i32, i32)> =
std::collections::HashSet::new();
let mut labels: Vec<(Vec2, SharedString, f32)> = Vec::new();
'pool: for &(slot, _) in &label_pool {
if labels.len() >= MAX_LABELS {
break;
}
let Some(node) = self.graph.node(self.payload.node_ids[slot as usize]) else {
continue;
};
let Some(center) = self
.positions
.get(slot as usize)
.map(|p| vp.world_to_screen(*p))
else {
continue;
};
let text = SharedString::from(node.label.clone());
let approx_w = self.label_width(window, &text, label_font);
let cell_w = 24.0f32.max(approx_w * 0.5);
let cx0 = (center.x / cell_w).floor() as i32;
let cy0 = (center.y / 18.0).floor() as i32;
for dx in 0..=1 {
for dy in 0..=1 {
if !label_cells.insert((cx0 + dx, cy0 + dy)) {
continue 'pool;
}
}
}
let opacity =
self.appearance(slot, now).opacity * Self::emphasis(slot, focus.as_ref(), dim);
labels.push((
node_label_origin(
center,
(NODE_MARKER_WORLD_SIZE * vp.zoom * self.appearance(slot, now).scale)
.max(DOT_MIN_PX),
approx_w,
label_font * 1.5,
),
text,
opacity,
));
}
let half = (EDGE_WIDTH * vp.zoom).max(0.5) / 2.0;
let positions = self.positions.clone();
let edge_color = colors.border_strong;
let dot_color = colors.accent;
let shell_fill = colors.accent;
let shell_border = colors.accent;
let bounds_for_edges = self.bounds_cell.clone();
let mut edge_groups = [Vec::new(), Vec::new()];
for &(s, t) in edge_pairs {
if self.is_slot_hidden(s) || self.is_slot_hidden(t) {
continue;
}
let focused = focus
.as_ref()
.is_none_or(|f| f.contains(&s) && f.contains(&t));
edge_groups[usize::from(!focused)].push((s, t));
}
let dot_list = dots;
let shell_list = shells;
self.rendered = RenderCounts {
full: full_slots.len(),
shell: shell_list.len(),
dot: dot_list.len(),
edges: edge_groups.iter().map(Vec::len).sum(),
labels: labels.len(),
};
let back_layer = canvas(
{
let bounds_cell = bounds_for_edges.clone();
move |b: Bounds<Pixels>, _window, _| {
if let Ok(mut g) = bounds_cell.lock() {
*g = Some(b);
}
}
},
move |b: Bounds<Pixels>, _, window: &mut Window, _| {
for (group, edge_list) in edge_groups.iter().enumerate() {
if edge_list.is_empty() {
continue;
}
let mut fill = PathBuilder::fill().with_style(gpui_kit::PathStyle::Fill(
gpui_kit::FillOptions {
fill_rule: gpui_kit::FillRule::NonZero,
},
));
for &(s, t) in edge_list {
let (Some(a), Some(bw)) =
(positions.get(s as usize), positions.get(t as usize))
else {
continue;
};
let a = vp.world_to_screen(*a);
let b2 = vp.world_to_screen(*bw);
let d = b2.minus(a);
let len = d.length();
if len < 1.0 {
continue;
}
let n = Vec2::new(-d.y / len * half, d.x / len * half);
let to = |v: Vec2| {
gpui_kit::point(
px(f32::from(b.origin.x)) + px(v.x),
px(f32::from(b.origin.y)) + px(v.y),
)
};
fill.move_to(to(a.plus(n)));
fill.line_to(to(b2.plus(n)));
fill.line_to(to(b2.minus(n)));
fill.line_to(to(a.minus(n)));
fill.close();
}
if let Ok(path) = fill.build() {
let alpha = if group == 0 {
1.0
} else {
1.0 - dim * DIM_STRENGTH
};
window.paint_path(path, edge_color.opacity(alpha));
}
}
for (c, d, fade) in &dot_list {
let color = dot_color.opacity(*fade);
window.paint_quad(quad(
Bounds {
origin: gpui_kit::point(
b.origin.x + px(c.x - d / 2.0),
b.origin.y + px(c.y - d / 2.0),
),
size: size(px(*d), px(*d)),
},
Corners::all(px(*d / 2.0)),
color,
Edges::all(px(0.0)),
color,
gpui_kit::BorderStyle::Solid,
));
}
for (c, s, fade) in &shell_list {
let half_s = s / 2.0;
let (fill, border) = (shell_fill.opacity(*fade), shell_border.opacity(*fade));
window.paint_quad(quad(
Bounds {
origin: gpui_kit::point(
b.origin.x + px(c.x - half_s),
b.origin.y + px(c.y - half_s),
),
size: size(px(*s), px(*s)),
},
Corners::all(px(half_s)),
fill,
Edges::all(px(1.0)),
border,
gpui_kit::BorderStyle::Solid,
));
}
},
)
.absolute()
.size_full();
let label_els: Vec<_> = labels
.into_iter()
.map(|(p, text, opacity)| {
div()
.absolute()
.left(px(p.x))
.top(px(p.y))
.text_size(px(label_font))
.line_height(px(label_font * 1.5))
.text_color(colors.text_secondary.opacity(opacity))
.whitespace_nowrap()
.child(text)
})
.collect();
let node_font = (f32::from(Typography::TEXT_SM) * vp.zoom).clamp(9.0, 24.0);
let label_height = node_font * 1.5;
let world = (NODE_MARKER_WORLD_SIZE * vp.zoom).max(DOT_MIN_PX);
let selected: HashSet<NodeId> = self.selection.iter().copied().collect();
let text_ws: HashMap<u32, f32> = full_slots
.iter()
.filter(|_| show_labels)
.filter_map(|&slot| {
let label = self
.graph
.node(self.payload.node_ids[slot as usize])?
.label
.clone();
Some((slot, self.label_width(window, &label, node_font)))
})
.collect();
let card_els: Vec<_> = full_slots
.iter()
.filter_map(|&slot| {
let node = self.graph.node(self.payload.node_ids[slot as usize])?;
if !self.drawn(slot, now) {
return None;
}
let c = vp.world_to_screen(*self.positions.get(slot as usize)?);
let node_id = node.id;
let appear = self.appearance(slot, now);
let is_sel = selected.contains(&node_id);
let is_hover = self.hover == Some(slot);
let fade = Self::emphasis(slot, focus.as_ref(), dim);
let opacity = (appear.opacity * fade).clamp(0.0, 1.0);
let world = world * appear.scale;
let text_w = text_ws.get(&slot).copied().unwrap_or(world);
let label_pos = node_label_origin(c, world, text_w, label_height);
Some(
div()
.absolute()
.left(px(c.x - world / 2.0))
.top(px(c.y - world / 2.0))
.w(px(world))
.h(px(world))
.opacity(opacity)
.child(
div()
.id(ElementId::NamedInteger(
format!("{}-node", self.id).into(),
node.id.0,
))
.test_support()
.size_full()
.rounded(px(world / 2.0))
.bg(colors.accent)
.border_2()
.border_color(if is_sel || is_hover {
colors.foreground
} else {
colors.accent
}),
)
.children(show_labels.then(|| {
div()
.id(ElementId::NamedInteger(
format!("{}-label", self.id).into(),
node.id.0,
))
.test_support()
.absolute()
.left(px(label_pos.x - (c.x - world / 2.0)))
.top(px(label_pos.y - (c.y - world / 2.0)))
.w(px(text_w))
.h(px(label_height))
.text_size(px(node_font))
.line_height(px(label_height))
.text_color(if is_sel || is_hover {
colors.accent
} else {
colors.foreground
})
.whitespace_nowrap()
.child(node.label.clone())
})),
)
})
.collect();
let id = self.id.clone();
let rubber_rect = self.rubber.map(|(a, b)| {
let lo = Vec2::new(a.x.min(b.x), a.y.min(b.y));
let hi = Vec2::new(a.x.max(b.x), a.y.max(b.y));
(px(lo.x), px(lo.y), px(hi.x - lo.x), px(hi.y - lo.y))
});
div()
.id(ElementId::Name(id))
.test_support()
.track_focus(&self.focus)
.relative()
.size_full()
.overflow_hidden()
.bg(colors.background)
.on_scroll(cx.listener(Self::on_scroll))
.on_pinch(cx.listener(Self::on_pinch))
.on_mouse_down(MouseButton::Left, cx.listener(Self::on_left_down))
.on_mouse_move(cx.listener(Self::on_mouse_move))
.on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
.on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
.on_hover(cx.listener(|this, hovered: &bool, _, cx| {
if !hovered {
this.hover = None;
this.motion.set_dim(false, motion_now(cx));
cx.notify();
}
}))
.child(back_layer)
.children(label_els)
.children(card_els)
.children(rubber_rect.map(|(x, y, w, h)| {
div()
.absolute()
.left(x)
.top(y)
.w(w)
.h(h)
.border_1()
.border_color(colors.accent)
.bg(colors.accent_subtle.opacity(0.15))
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
AppContext as _, Entity, Modifiers, PlatformInput, TestAppContext, VisualTestContext,
point, px, test::TestWindowExt as _,
};
struct Host {
canvas: Entity<Graph2D>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.canvas.clone())
}
}
fn chain_graph(n: usize) -> KnowledgeGraph {
let mut g = KnowledgeGraph::new();
let kind = g.add_kind("概念");
let mut prev = g.add_node("n0", Some(kind));
for i in 1..n {
let cur = g.add_node(format!("n{i}"), Some(kind));
g.add_edge(prev, cur, 1.0, None).unwrap();
prev = cur;
}
g
}
fn grid_positions(n: usize, cols: usize) -> Vec<Vec2> {
(0..n)
.map(|i| Vec2::new((i % cols) as f32 * 120.0, (i / cols) as f32 * 120.0))
.collect()
}
fn large_graph() -> KnowledgeGraph {
let mut g = KnowledgeGraph::new();
let ids: Vec<_> = (0..5_000)
.map(|i| g.add_node(format!("n{i}"), None))
.collect();
for i in 0..10_000u64 {
let s = ids[(i * 7919 % 5_000) as usize];
let t = ids[(i * 104_729 % 5_000) as usize];
let _ = g.add_edge(s, t, 1.0, None);
}
g
}
fn setup(cx: &mut TestAppContext) -> (Entity<Graph2D>, &mut VisualTestContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
});
let mut canvas = None;
let (_, vcx) = cx.add_window_view(|_, cx| {
let c = cx.new(|cx| {
Graph2D::new_static("graph", chain_graph(8), grid_positions(8, 4), cx)
.aria_label("测试图谱")
.fit_on_mount()
});
canvas = Some(c.clone());
Host { canvas: c }
});
vcx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
(canvas.unwrap(), vcx)
}
fn p(x: f32, y: f32) -> gpui_kit::Point<Pixels> {
point(px(x), px(y))
}
#[gpui_kit::test]
fn renders_round_nodes_with_labels_above_and_culls_offscreen(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
assert_eq!(counts.full, 8, "{counts:?}");
assert_eq!(counts.edges, 7);
assert_eq!(counts.shell + counts.dot, 0);
vcx.update(|window, _| {
let root = window.find("graph");
assert!(f32::from(root.bounds().size.width) > 0.0);
let node = window.find(ElementId::NamedInteger("graph-node".into(), 1));
let marker = node.bounds();
assert!(!marker.is_empty());
assert_eq!(marker.size.width, marker.size.height, "圆点必须保持等宽高");
let label = window.find(ElementId::NamedInteger("graph-label".into(), 1));
let label = label.bounds();
assert!(
label.origin.y + label.size.height < marker.origin.y,
"标签应位于圆点上方"
);
let marker_cx = f32::from(marker.origin.x + marker.size.width / 2.0);
let label_cx = f32::from(label.origin.x + label.size.width / 2.0);
assert!((marker_cx - label_cx).abs() < 1.0, "标签应水平居中");
});
canvas.update(vcx, |c, _| {
let b = c.world_bounds().unwrap();
c.viewport.offset.x = -(b.max.x + 5000.0);
c.viewport.offset.y = -(b.max.y + 5000.0);
});
vcx.update(|window, cx| window.render_frame(cx));
let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
assert_eq!((counts.full, counts.edges), (0, 0), "{counts:?}");
}
#[gpui_kit::test]
fn zoom_out_switches_to_dots_and_capped_labels(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
canvas.update(vcx, |c, _| {
let b = c.world_bounds().unwrap();
let view = c.view_size.unwrap_or(Size2::new(800.0, 600.0));
c.viewport.fit(&b, view, 60.0);
c.viewport.zoom = 0.06; });
vcx.update(|window, cx| window.render_frame(cx));
let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
assert!(counts.full == 0, "{counts:?}");
assert!(counts.dot + counts.shell >= 8, "{counts:?}");
assert!(
counts.labels > 0 && counts.labels <= MAX_LABELS,
"{counts:?}"
);
let big = chain_graph(600);
let big_positions = grid_positions(600, 30);
let mut big_view = None;
cx_update_big(vcx, big, big_positions, &mut big_view);
let counts = big_view.unwrap().read_with(vcx, |c, _| c.rendered_counts());
assert!(counts.labels <= MAX_LABELS, "{counts:?}");
}
fn cx_update_big(
vcx: &mut VisualTestContext,
big: KnowledgeGraph,
positions: Vec<Vec2>,
out: &mut Option<Entity<Graph2D>>,
) {
vcx.update(|window, cx| {
let c =
cx.new(|cx| Graph2D::new_static("graph-big", big, positions, cx).fit_on_mount());
window.render_frame(cx);
window.render_frame(cx);
*out = Some(c);
});
}
#[gpui_kit::test]
fn drag_pans_and_ctrl_wheel_zooms_about_cursor(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
let before = canvas.read_with(vcx, |c, _| c.viewport());
vcx.update(|window, cx| window.drag(p(700.0, 500.0), p(760.0, 470.0), cx));
let after = canvas.read_with(vcx, |c, _| c.viewport());
assert!(
(after.offset.x - before.offset.x - 60.0).abs() < 0.5,
"{after:?}"
);
assert!(
(after.offset.y - before.offset.y + 30.0).abs() < 0.5,
"{after:?}"
);
let vp = canvas.read_with(vcx, |c, _| c.viewport());
let world_before = vp.screen_to_world(Vec2::new(300.0, 200.0));
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::Scroll(ScrollEvent {
position: p(300.0, 200.0),
delta: ScrollDelta::Pixels(point(px(0.0), px(80.0))),
modifiers: Modifiers {
control: true,
..Default::default()
},
..Default::default()
}),
cx,
);
});
let vp = canvas.read_with(vcx, |c, _| c.viewport());
assert!(vp.zoom > 1.0, "{vp:?}");
assert!(
vp.world_to_screen(world_before)
.distance(Vec2::new(300.0, 200.0))
< 0.01,
"缩放必须以光标为锚"
);
}
#[gpui_kit::test]
fn pan_hides_all_lod_labels_until_release_outside(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
for zoom in [1.0, 0.3, 0.06] {
canvas.update(vcx, |c, _| {
c.viewport.zoom = zoom;
c.viewport.offset = Vec2::new(120.0, 120.0);
});
vcx.update(|window, cx| window.render_frame(cx));
let before = canvas.read_with(vcx, |c, _| c.rendered_counts());
assert!(before.full > 0 || before.labels > 0, "{before:?}");
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: p(700.0, 500.0),
click_count: 1,
..Default::default()
}),
cx,
);
window.render_frame(cx);
});
assert_eq!(canvas.read_with(vcx, |c, _| c.rendered_counts()), before);
canvas.update(vcx, |c, _| c.text_width_cache.clear());
for position in [p(720.0, 520.0), p(720.0, 520.0), p(700.0, 500.0)] {
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseMove(MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
..Default::default()
}),
cx,
);
window.render_frame(cx);
assert!(
window
.try_find(ElementId::NamedInteger("graph-label".into(), 1))
.is_none()
);
});
canvas.read_with(vcx, |c, _| {
let counts = c.rendered_counts();
assert_eq!(counts.labels, 0, "{counts:?}");
assert_eq!(counts.full + counts.shell + counts.dot, 8, "圆点应保留");
assert_eq!(counts.edges, 7, "连线应保留");
assert!(c.text_width_cache.is_empty(), "拖动期间不应测量文字");
});
}
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: p(-10.0, -10.0),
..Default::default()
}),
cx,
);
window.render_frame(cx);
});
canvas.read_with(vcx, |c, _| {
assert!(c.pan_drag.is_none());
assert_eq!(c.rendered_counts(), before);
assert!(!c.text_width_cache.is_empty(), "松手后应恢复文字");
});
}
}
#[gpui_kit::test]
fn node_drag_hides_labels_but_click_does_not(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
let center = canvas.read_with(vcx, |c, _| c.viewport.world_to_screen(c.positions[0]));
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: p(center.x, center.y),
click_count: 1,
..Default::default()
}),
cx,
);
window.render_frame(cx);
assert!(
window
.try_find(ElementId::NamedInteger("graph-label".into(), 1))
.is_some()
);
});
canvas.update(vcx, |c, _| c.text_width_cache.clear());
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseMove(MouseMoveEvent {
position: p(center.x + 30.0, center.y + 20.0),
pressed_button: Some(MouseButton::Left),
..Default::default()
}),
cx,
);
window.render_frame(cx);
for id in 1..=8 {
assert!(
window
.try_find(ElementId::NamedInteger("graph-label".into(), id))
.is_none()
);
assert!(
window
.try_find(ElementId::NamedInteger("graph-node".into(), id))
.is_some()
);
}
});
canvas.read_with(vcx, |c, _| assert!(c.text_width_cache.is_empty()));
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: p(center.x + 30.0, center.y + 20.0),
..Default::default()
}),
cx,
);
window.render_frame(cx);
for id in 1..=8 {
assert!(
window
.try_find(ElementId::NamedInteger("graph-label".into(), id))
.is_some()
);
}
});
canvas.read_with(vcx, |c, _| {
assert!(c.node_drag.is_none());
assert!(c.is_pinned(NodeId(1)), "拖动固定行为应保留");
});
}
#[gpui_kit::test]
fn click_drag_and_shift_box_select(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
let center = canvas.read_with(vcx, |c, _| c.viewport.world_to_screen(c.positions[0]));
vcx.update(|window, cx| {
window.dispatch_event(
PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: p(center.x, center.y),
click_count: 1,
..Default::default()
}),
cx,
);
window.dispatch_event(
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: p(center.x, center.y),
..Default::default()
}),
cx,
);
});
assert_eq!(
canvas.read_with(vcx, |c, _| c.selection.clone()),
vec![NodeId(1)]
);
vcx.update(|window, cx| {
window.drag(
p(center.x, center.y),
p(center.x + 60.0, center.y + 30.0),
cx,
)
});
canvas.read_with(vcx, |c, _| {
assert!(c.is_pinned(NodeId(1)));
let after = c.viewport.world_to_screen(c.positions[0]);
assert!(after.distance(center.plus(Vec2::new(60.0, 30.0))) < 0.1);
});
canvas.update(vcx, |c, cx| c.set_pinned(NodeId(1), false, cx));
assert!(!canvas.read_with(vcx, |c, _| c.is_pinned(NodeId(1))));
vcx.update(|window, cx| {
canvas.update(cx, |c, cx| {
c.on_left_down(
&MouseDownEvent {
position: p(1.0, 1.0),
modifiers: Modifiers {
shift: true,
..Default::default()
},
..Default::default()
},
window,
cx,
);
c.on_mouse_move(
&MouseMoveEvent {
position: p(1900.0, 1000.0),
..Default::default()
},
window,
cx,
);
c.on_mouse_up(&MouseUpEvent::default(), window, cx);
});
});
assert_eq!(canvas.read_with(vcx, |c, _| c.selection.len()), 8);
}
#[gpui_kit::test]
fn hover_neighbors_and_precise_hit(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
canvas.read_with(vcx, |c, _| {
assert_eq!(c.hit_slot(Vec2::new(30.0, 0.0)), None);
});
vcx.update(|window, cx| {
canvas.update(cx, |c, cx| {
let pos = c.viewport.world_to_screen(c.positions[1]);
c.on_mouse_move(
&MouseMoveEvent {
position: p(pos.x, pos.y),
..Default::default()
},
window,
cx,
);
assert_eq!(c.hover(), Some(NodeId(2)));
let focus = c.focus_slots();
assert!(focus.contains(&0) && focus.contains(&1) && focus.contains(&2));
assert!(!focus.contains(&7));
assert_eq!(Graph2D::emphasis(0, Some(&focus), 1.0), 1.0);
assert!(Graph2D::emphasis(7, Some(&focus), 1.0) < 1.0);
});
});
}
#[gpui_kit::test]
fn filter_expand_search_and_interrupt_flight(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
vcx.update(|window, cx| {
canvas.update(cx, |c, cx| {
let kind = c.graph.add_kind("其他");
c.set_kind_filter(Some(kind), cx);
assert_eq!(c.hidden_count(), 8);
assert!(c.search("n").is_empty());
assert_eq!(c.expand(NodeId(2), cx), 2);
assert_eq!(c.hidden_count(), 6);
assert_eq!(c.search("N0"), vec![NodeId(1)]);
c.set_kind_filter(None, cx);
assert_eq!(c.hidden_count(), 0);
assert_eq!(c.search("n").len(), 8);
c.fly_to(NodeId(4), cx);
assert!(c.motion.view_animating());
c.on_scroll(
&ScrollEvent {
position: p(500.0, 300.0),
..Default::default()
},
window,
cx,
);
assert!(!c.motion.view_animating());
assert!(c.selection.contains(&NodeId(4)));
});
});
}
#[test]
#[ignore]
fn bench_edge_path_batches() {
let graph = large_graph();
let payload = GraphPayload::from_graph(&graph);
let positions: Vec<_> = grid_positions(5_000, 100)
.into_iter()
.map(|p| Vec2::new(p.x * 0.2, p.y * 0.2))
.collect();
let mask = gpui_kit::ContentMask {
bounds: Bounds {
origin: point(px(0.0), px(0.0)),
size: size(px(4096.0), px(4096.0)),
},
};
for batch in [1, 32, 128, 512, 10_000] {
let mut samples = Vec::new();
for iteration in 0..12 {
let started = std::time::Instant::now();
let mut build_ms = 0.0;
let mut bin_ms = 0.0;
for edges in payload.edges.chunks(batch) {
let t = std::time::Instant::now();
let mut fill = PathBuilder::fill().with_style(gpui_kit::PathStyle::Fill(
gpui_kit::FillOptions {
fill_rule: gpui_kit::FillRule::NonZero,
},
));
for &(s, t, _) in edges {
let (a, b) = (positions[s as usize], positions[t as usize]);
let d = b.minus(a);
let len = d.length();
if len < 1.0 {
continue;
}
let n = Vec2::new(-d.y / len * 0.75, d.x / len * 0.75);
let to = |v: Vec2| point(px(v.x + iteration as f32 % 2.0), px(v.y));
fill.move_to(to(a.plus(n)));
fill.line_to(to(b.plus(n)));
fill.line_to(to(b.minus(n)));
fill.line_to(to(a.minus(n)));
fill.close();
}
let path = fill.build().unwrap();
build_ms += t.elapsed().as_secs_f64() * 1000.0;
let t = std::time::Instant::now();
std::hint::black_box(gpui_kit::PaintedPath::new(
path,
2.0,
mask,
gpui_kit::rgba(0x000000ff).into(),
));
bin_ms += t.elapsed().as_secs_f64() * 1000.0;
}
if iteration > 1 {
samples.push((started.elapsed().as_secs_f64() * 1000.0, build_ms, bin_ms));
}
}
let n = samples.len() as f64;
println!(
"BENCH edges batch={batch}: total {:.2} ms, build {:.2} ms, bin {:.2} ms (CPU only)",
samples.iter().map(|s| s.0).sum::<f64>() / n,
samples.iter().map(|s| s.1).sum::<f64>() / n,
samples.iter().map(|s| s.2).sum::<f64>() / n
);
}
}
#[gpui_kit::test]
#[ignore]
fn bench_graph_frame_times(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
});
let graph = large_graph();
let positions = grid_positions(5_000, 100)
.into_iter()
.map(|p| Vec2::new(p.x * 0.2, p.y * 0.2))
.collect();
let mut canvas = None;
let (_, vcx) = cx.add_window_view(|_, cx| {
let c = cx.new(|cx| Graph2D::new_static("graph-bench", graph, positions, cx));
canvas = Some(c.clone());
Host { canvas: c }
});
vcx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
let canvas = canvas.unwrap();
let mut times = Vec::with_capacity(30);
for i in 0usize..30 {
canvas.update(vcx, |c, _| {
c.viewport.offset.x += if i.is_multiple_of(2) { 1.0 } else { -1.0 };
});
let started = std::time::Instant::now();
vcx.update(|window, cx| window.render_frame(cx));
times.push(started.elapsed().as_secs_f64() * 1000.0);
}
times.sort_by(f64::total_cmp);
let avg = times.iter().sum::<f64>() / times.len() as f64;
let p95 = times[(times.len() * 95 / 100).min(times.len() - 1)];
let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
println!(
"BENCH graph 5,000/10,000 dense pan: avg {avg:.2} ms, p95 {p95:.2} ms, drawn {counts:?}"
);
}
#[gpui_kit::test]
fn light_dark_light_keeps_graph_renderable(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
vcx.update(|window, cx| {
install_arc_theme(mode, Accent::Blue, cx);
window.render_frame(cx);
});
assert_eq!(canvas.read_with(vcx, |c, _| c.rendered_counts().full), 8);
}
}
#[gpui_kit::test]
fn visible_set_is_shared_until_view_changes_and_pause_is_idempotent(cx: &mut TestAppContext) {
let (canvas, vcx) = setup(cx);
let first = canvas.read_with(vcx, |c, _| c.visible_cache.clone().unwrap());
vcx.update(|window, cx| window.render_frame(cx));
canvas.read_with(vcx, |c, _| {
assert!(Arc::ptr_eq(&first, c.visible_cache.as_ref().unwrap()));
});
canvas.update(vcx, |c, cx| {
c.set_layout_paused(true, cx);
c.set_layout_paused(true, cx);
assert!(c.layout_paused);
c.set_layout_paused(false, cx);
assert!(!c.layout_paused);
c.viewport.offset.x += 1.0;
});
vcx.update(|window, cx| window.render_frame(cx));
canvas.read_with(vcx, |c, _| {
assert!(!Arc::ptr_eq(&first, c.visible_cache.as_ref().unwrap()));
});
}
#[gpui_kit::test]
fn static_positions_skip_layout_worker(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
});
let mut canvas = None;
let (_, vcx) = cx.add_window_view(|_, cx| {
let c = cx.new(|cx| {
Graph2D::new_static("graph-static", chain_graph(4), grid_positions(4, 2), cx)
});
canvas = Some(c.clone());
Host { canvas: c }
});
vcx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
let counts = canvas.unwrap().read_with(vcx, |c, _| c.rendered_counts());
assert!(counts.full + counts.dot + counts.shell > 0, "{counts:?}");
assert_eq!(counts.edges, 3);
}
}