Skip to main content

arc_graph/
view.rs

1//! 知识图谱 2D 画布。数据来自 [`arc_graph_core`],渲染走 arc-tokens。
2//!
3//! 渲染分层(与 arc-flow 同套路):
4//! 1. 背景 canvas:批量边(直线退化为细长 quad 填充,同色一条路径)+ 节点点 / 外壳 quad;
5//! 2. 浮动标签层(缩小模式):按度数优先级 + 屏幕网格碰撞剔除,≤ 200 个;
6//! 3. 详细节点层(放大模式):圆点 + 居中置于上方的文字。
7
8use 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
28// ---------- 常量(几何值,非样式;样式一律走 arc-tokens) ----------
29
30/// 节点世界直径(布局坐标下)。
31const NODE_WORLD_SIZE: f32 = 36.0;
32/// 可见圆点直径;交互仍保留较大的世界命中区域,方便抓取。
33const NODE_MARKER_WORLD_SIZE: f32 = 12.0;
34
35/// 标签居中置于圆点上方,间距取共享令牌。
36fn 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
43/// 边基线宽(屏幕 px,随 zoom 缩放)。
44const EDGE_WIDTH: f32 = 1.5;
45/// 节点在屏幕上小于该高时画点(px)。
46const LOD_DOT_PX: f32 = 4.0;
47/// 节点在屏幕上小于该高时画外壳(px)。
48const LOD_SHELL_PX: f32 = 14.0;
49/// 全局点模式:节点数达到该值且缩放不超过该值时,全部按点 / 外壳画。
50const LOD_MIN_NODES: usize = 500;
51const LOD_GLOBAL_ZOOM: f32 = 0.25;
52/// 点 / 外壳最小绘制尺寸(px),避免缩没了看不见。
53const DOT_MIN_PX: f32 = 2.5;
54/// 浮动标签同屏上限(方案 §5)。
55const MAX_LABELS: usize = 200;
56/// Full 卡片同屏上限:div 卡片 + 逐个文本测量是最贵的渲染路径,
57/// 超限的节点降级为 Shell 外壳(canvas 批量 quad),浮动标签照常兜底。
58/// 上限取标签上限同量级,保证「看得清的细节」与「帧耗时」同时可控。
59const MAX_FULL_CARDS: usize = 160;
60/// 视口裁剪外扩余量(px)。
61const CULL_MARGIN: f32 = 40.0;
62/// 滚轮缩放速度。
63const WHEEL_ZOOM_SPEED: f32 = 0.01;
64/// 知识图谱缩放范围(大图要能缩到很小的全景)。
65const KG_MIN_ZOOM: f32 = 0.02;
66const KG_MAX_ZOOM: f32 = 4.0;
67/// 行高(滚轮一格的像素)。
68const LINE_HEIGHT: f32 = 20.0;
69
70/// LOD 层级。
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Lod {
73    Full,
74    Shell,
75    Dot,
76}
77
78/// 渲染统计(窗口测试与 story 状态栏用)。
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
80pub struct RenderCounts {
81    /// Full 卡片数。
82    pub full: usize,
83    /// Shell 外壳数。
84    pub shell: usize,
85    /// Dot 点数。
86    pub dot: usize,
87    /// 边数。
88    pub edges: usize,
89    /// 浮动标签数。
90    pub labels: usize,
91}
92
93/// 2D 知识图谱画布。
94pub struct Graph2D {
95    id: SharedString,
96    label: SharedString,
97    focus: FocusHandle,
98    graph: KnowledgeGraph,
99    /// 槽位快照(node_ids 升序),边的槽位对从这里取。
100    payload: GraphPayload,
101    /// 每槽位度数(浮动标签优先级)。
102    degrees: Vec<u32>,
103    /// 后台布局线程;`new_static` 时为 None。
104    worker: Option<LayoutWorker2D>,
105    /// 只在布局活动期间请求下一帧;冷却后停止空转。
106    layout_active: bool,
107    /// 宿主隐藏页面时暂停后台布局并停止自动重绘。
108    layout_paused: bool,
109    /// 最新坐标快照(槽位对齐)。
110    positions: Arc<Vec<Vec2>>,
111    positions_rev: u64,
112    viewport: Viewport,
113    view_size: Option<Size2>,
114    fit_pending: bool,
115    /// 节点空间索引(按 positions_rev 失效)。
116    spatial: Option<SpatialGrid<u32>>,
117    spatial_rev: u64,
118    /// 可见集缓存(视口 / 布局版本失效)。
119    visible_cache: Option<Arc<VisibleCache>>,
120    /// 背景拖拽平移状态(起点 + 起始 offset)。
121    pan_drag: Option<(Vec2, Vec2)>,
122    rendered: RenderCounts,
123    bounds_cell: Arc<std::sync::Mutex<Option<Bounds<Pixels>>>>,
124
125    // ---------- G4 交互与动效 ----------
126    /// 动效状态机(进场 / 悬停淡出 / 视口弹簧)。
127    motion: GraphMotion,
128    /// 悬停节点槽位(None = 无悬停)。
129    hover: Option<u32>,
130    /// 点选 / 框选结果(保序)。
131    selection: Vec<NodeId>,
132    /// 框选拖拽(屏幕起点, 当前点)。
133    rubber: Option<(Vec2, Vec2)>,
134    /// 节点拖动:(槽位, 抓取点相对节点中心的偏移)。
135    node_drag: Option<(u32, Vec2)>,
136    /// 本次按下后是否发生过大位移(区分「点击」与「拖动」)。
137    drag_moved: bool,
138    /// 双击展开临时揭示的节点(筛选期间)。
139    revealed: HashSet<NodeId>,
140    /// 类型筛选(None = 全部)。
141    kind_filter: Option<arc_graph_core::KindId>,
142    /// 筛选后的隐藏槽位集(None = 无筛选,渲染走快路径)。
143    hidden: Option<HashSet<u32>>,
144    /// NodeId → 槽位反查表(payload 构建时生成)。
145    slot_index: std::collections::HashMap<NodeId, u32>,
146    /// 文本测量缓存:(标签, 字号) → 宽度 px。Full 卡片每帧都要锚定宽度,
147    /// shaping 结果只取决于这两个输入,跨帧复用(容量由播放集大小自然限制,
148    /// 超过阈值整体重建,避免长期膨胀)。
149    text_width_cache: HashMap<(SharedString, u32), f32>,
150}
151
152struct VisibleCache {
153    /// (视口位模式, positions_rev) 缓存键。
154    key: ([u32; 3], u64),
155    slots: Vec<u32>,
156    edges: Vec<(u32, u32)>,
157}
158
159impl Graph2D {
160    /// 带后台力导向布局创建(推荐入口)。
161    pub fn new(id: impl Into<SharedString>, graph: KnowledgeGraph, cx: &mut Context<Self>) -> Self {
162        let payload = GraphPayload::from_graph(&graph);
163        let worker = LayoutWorker2D::spawn(LayoutConfig::default(), payload.clone());
164        Self::build(id, graph, payload, Some(worker), cx)
165    }
166
167    /// 使用预先算好的坐标创建(跳过后台布局;坐标按 `NodeId` 升序对齐)。
168    pub fn new_static(
169        id: impl Into<SharedString>,
170        graph: KnowledgeGraph,
171        positions: Vec<Vec2>,
172        cx: &mut Context<Self>,
173    ) -> Self {
174        let payload = GraphPayload::from_graph(&graph);
175        let mut view = Self::build(id, graph, payload, None, cx);
176        view.positions = Arc::new(positions);
177        view.positions_rev = 1;
178        view.fit_pending = true;
179        view
180    }
181
182    fn build(
183        id: impl Into<SharedString>,
184        graph: KnowledgeGraph,
185        payload: GraphPayload,
186        worker: Option<LayoutWorker2D>,
187        _cx: &mut Context<Self>,
188    ) -> Self {
189        let degrees = {
190            let mut d = vec![0u32; payload.node_ids.len()];
191            for &(s, t, _) in &payload.edges {
192                if s != t {
193                    d[s as usize] += 1;
194                    d[t as usize] += 1;
195                }
196            }
197            d
198        };
199        let viewport = Viewport {
200            min_zoom: KG_MIN_ZOOM,
201            max_zoom: KG_MAX_ZOOM,
202            ..Viewport::default()
203        };
204        let focus = _cx.focus_handle();
205        let slot_index: std::collections::HashMap<NodeId, u32> = payload
206            .node_ids
207            .iter()
208            .enumerate()
209            .map(|(i, id)| (*id, i as u32))
210            .collect();
211        Self {
212            id: id.into(),
213            label: "Knowledge graph".into(),
214            focus,
215            graph,
216            degrees,
217            layout_active: worker.is_some(),
218            layout_paused: false,
219            worker,
220            payload,
221            positions: Arc::new(Vec::new()),
222            positions_rev: 0,
223            viewport,
224            view_size: None,
225            fit_pending: false,
226            spatial: None,
227            spatial_rev: 0,
228            visible_cache: None,
229            pan_drag: None,
230            rendered: RenderCounts::default(),
231            bounds_cell: Arc::new(std::sync::Mutex::new(None)),
232            motion: GraphMotion::default(),
233            hover: None,
234            selection: Vec::new(),
235            rubber: None,
236            node_drag: None,
237            drag_moved: false,
238            revealed: HashSet::new(),
239            kind_filter: None,
240            hidden: None,
241            slot_index,
242            text_width_cache: HashMap::new(),
243        }
244    }
245
246    /// 标签精确宽度(px,含 shaping):按 (标签, 字号) 缓存,跨帧复用。
247    /// 缓存过大时整体重建——全量重建成本 = 一帧的测量数,可接受。
248    fn label_width(&mut self, window: &mut Window, label: &str, font_px: f32) -> f32 {
249        const TEXT_CACHE_CAP: usize = 4_096;
250        if self.text_width_cache.len() > TEXT_CACHE_CAP {
251            self.text_width_cache.clear();
252        }
253        let key = (SharedString::from(label), (font_px * 4.0).round() as u32);
254        if let Some(&w) = self.text_width_cache.get(&key) {
255            return w;
256        }
257        let w = f32::from(
258            window
259                .text_system()
260                .layout_line(key.0.clone(), px(font_px), &[], None)
261                .width,
262        );
263        self.text_width_cache.insert(key, w);
264        w
265    }
266
267    /// 无障碍名称。
268    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
269        self.label = label.into();
270        self
271    }
272
273    /// 首个布局快照到达后自动适配视图。
274    pub fn fit_on_mount(mut self) -> Self {
275        self.fit_pending = true;
276        self
277    }
278
279    /// 当前视口。
280    pub fn viewport(&self) -> Viewport {
281        self.viewport
282    }
283
284    /// 宿主页面隐藏/恢复时调用;保留坐标和交互状态,不销毁模型。
285    pub fn set_layout_paused(&mut self, paused: bool, cx: &mut Context<Self>) {
286        if self.layout_paused == paused {
287            return;
288        }
289        self.layout_paused = paused;
290        if !paused && self.worker.is_some() {
291            self.layout_active = true;
292        }
293        if let Some(worker) = &self.worker {
294            worker.send(if paused {
295                LayoutCommand::Cancel
296            } else {
297                LayoutCommand::Wake
298            });
299        }
300        cx.notify();
301    }
302
303    /// 最近一次渲染统计。
304    pub fn rendered_counts(&self) -> RenderCounts {
305        self.rendered
306    }
307
308    /// 槽位坐标(与 `GraphPayload.node_ids` 对齐),测试与 story 状态栏用。
309    pub fn positions(&self) -> &Arc<Vec<Vec2>> {
310        &self.positions
311    }
312
313    /// 适配视图(包含全部节点与半径)。
314    pub fn fit_view(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
315        self.motion.cancel_view();
316        cx.notify();
317        if let Some(world) = self.world_bounds() {
318            let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
319            self.viewport.fit(&world, view, 60.0);
320        }
321    }
322
323    /// 以画布中心为锚缩放。
324    pub fn zoom_by(&mut self, factor: f32, _window: &mut Window, cx: &mut Context<Self>) {
325        self.motion.cancel_view();
326        cx.notify();
327        let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
328        let anchor = Vec2::new(view.w / 2.0, view.h / 2.0);
329        self.viewport.zoom_by_at(factor, anchor);
330    }
331
332    // ---------- G4 交互 API ----------
333
334    /// 图中的全部类型(story 筛选按钮用)。
335    pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
336        self.graph.kinds()
337    }
338
339    /// 当前类型筛选。
340    pub fn kind_filter(&self) -> Option<arc_graph_core::KindId> {
341        self.kind_filter
342    }
343
344    /// 按类型筛选视图:只保留该类型节点(及两端都可见的边)。
345    /// `None` 取消筛选。双击可见节点可临时展开其一度邻居([`Self::expand`])。
346    pub fn set_kind_filter(
347        &mut self,
348        kind: Option<arc_graph_core::KindId>,
349        cx: &mut Context<Self>,
350    ) {
351        let previous: Vec<bool> = (0..self.payload.node_ids.len())
352            .map(|s| self.is_slot_hidden(s as u32))
353            .collect();
354        self.kind_filter = kind;
355        self.revealed.clear();
356        self.selection.clear();
357        self.hidden = kind.map(|k| {
358            let mut set = HashSet::new();
359            for (i, &id) in self.payload.node_ids.iter().enumerate() {
360                let matches = self.graph.node(id).is_some_and(|n| n.kind == Some(k));
361                if !matches {
362                    set.insert(i as u32);
363                }
364            }
365            set
366        });
367        let now = motion_now(cx);
368        self.motion.set_reduced(is_reduced_motion(cx));
369        for (slot, was_hidden) in previous.into_iter().enumerate() {
370            let hidden = self.is_slot_hidden(slot as u32);
371            let id = self.payload.node_ids[slot];
372            if hidden && !was_hidden {
373                self.motion.node_exited(id, now);
374            }
375            if !hidden && was_hidden {
376                self.motion.node_entered(id, now);
377            }
378        }
379        self.hover = None;
380        self.motion.set_dim(false, now);
381        cx.notify();
382    }
383
384    /// 固定或解除固定。拖动后保持固定;调用此方法传 false 可恢复力导向布局。
385    pub fn set_pinned(&mut self, id: NodeId, pinned: bool, cx: &mut Context<Self>) {
386        let Some(&slot) = self.slot_index.get(&id) else {
387            return;
388        };
389        self.payload.pinned[slot as usize] = pinned;
390        if let Some(worker) = &self.worker {
391            worker.send(LayoutCommand::SetPinned(id, pinned));
392            if let Some(&position) = self.positions.get(slot as usize) {
393                worker.send(LayoutCommand::MoveNode(id, position));
394                self.layout_active = true;
395            }
396        }
397        cx.notify();
398    }
399
400    pub fn is_pinned(&self, id: NodeId) -> bool {
401        self.slot_index
402            .get(&id)
403            .is_some_and(|&s| self.payload.pinned[s as usize])
404    }
405
406    /// 节点显示名称(组合搜索结果列表时使用)。
407    pub fn node_label(&self, id: NodeId) -> Option<&str> {
408        self.graph.node(id).map(|node| node.label.as_str())
409    }
410
411    /// 当前选中节点(保序)。
412    pub fn selection(&self) -> &[NodeId] {
413        &self.selection
414    }
415
416    /// 当前悬停节点。
417    pub fn hover(&self) -> Option<NodeId> {
418        self.hover.map(|s| self.payload.node_ids[s as usize])
419    }
420
421    /// 搜索节点(大小写不敏感包含匹配,按度数降序,最多 20 个)。
422    pub fn search(&self, query: &str) -> Vec<NodeId> {
423        let q = query.trim().to_lowercase();
424        if q.is_empty() {
425            return Vec::new();
426        }
427        let mut hits: Vec<(u32, u32)> = self
428            .payload
429            .node_ids
430            .iter()
431            .enumerate()
432            .filter(|(i, _)| !self.is_slot_hidden(*i as u32))
433            .filter_map(|(i, id)| {
434                let n = self.graph.node(*id)?;
435                n.label
436                    .to_lowercase()
437                    .contains(&q)
438                    .then(|| (i as u32, self.degrees[i]))
439            })
440            .collect();
441        hits.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
442        hits.into_iter()
443            .take(20)
444            .map(|(s, _)| self.payload.node_ids[s as usize])
445            .collect()
446    }
447
448    /// 平滑飞到节点(相机弹簧;reduced motion 立即跳转)并选中它。
449    pub fn fly_to(&mut self, id: NodeId, cx: &mut Context<Self>) {
450        let Some(&slot) = self.slot_index.get(&id) else {
451            return;
452        };
453        if self.is_slot_hidden(slot) {
454            return;
455        }
456        let Some(p) = self.positions.get(slot as usize).copied() else {
457            return;
458        };
459        if !self.selection.contains(&id) {
460            self.selection.push(id);
461        }
462        let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
463        let center = Vec2::new(view.w / 2.0, view.h / 2.0);
464        let mut target = self.viewport;
465        target.zoom = target.zoom.clamp(1.0, KG_MAX_ZOOM);
466        target.offset = center.minus(p.scale(target.zoom));
467        let now = motion_now(cx);
468        self.motion.set_reduced(is_reduced_motion(cx));
469        if self
470            .motion
471            .animate_view(&self.viewport, &target, center, now)
472        {
473            cx.notify();
474        } else {
475            self.viewport = target;
476            cx.notify();
477        }
478    }
479
480    /// 双击展开:把节点的一度邻居中当前被筛选隐藏的节点临时揭示出来(带进场动效)。
481    /// 返回本次揭示的数量。
482    pub fn expand(&mut self, id: NodeId, cx: &mut Context<Self>) -> usize {
483        self.motion.set_reduced(is_reduced_motion(cx));
484        let Some(filter) = self.hidden.as_mut() else {
485            return 0;
486        };
487        let neighbors = self.graph.adjacency().neighbors(id);
488        let mut revealed_count = 0;
489        let now = motion_now(cx);
490        for n in neighbors {
491            let Some(&slot) = self.slot_index.get(&n) else {
492                continue;
493            };
494            if filter.remove(&slot) {
495                self.revealed.insert(n);
496                self.motion.node_entered(n, now);
497                revealed_count += 1;
498            }
499        }
500        if revealed_count > 0 {
501            cx.notify();
502        }
503        revealed_count
504    }
505
506    /// 因筛选被隐藏的节点数。
507    pub fn hidden_count(&self) -> usize {
508        self.hidden.as_ref().map_or(0, |h| h.len())
509    }
510
511    fn is_slot_hidden(&self, slot: u32) -> bool {
512        self.hidden
513            .as_ref()
514            .is_some_and(|h| h.contains(&slot) && !self.revealed_overrides(slot))
515    }
516
517    fn drawn(&self, slot: u32, now: f64) -> bool {
518        !self.is_slot_hidden(slot)
519            || self
520                .motion
521                .is_exiting(self.payload.node_ids[slot as usize], now)
522    }
523
524    fn appearance(&self, slot: u32, now: f64) -> Appear {
525        let id = self.payload.node_ids[slot as usize];
526        if self.is_slot_hidden(slot) {
527            self.motion.exit_sample(id, now)
528        } else {
529            self.motion.enter_sample(id, now)
530        }
531    }
532
533    fn emphasis(slot: u32, focus: Option<&HashSet<u32>>, dim: f32) -> f32 {
534        if focus.is_none_or(|f| f.contains(&slot)) {
535            1.0
536        } else {
537            1.0 - dim * DIM_STRENGTH
538        }
539    }
540
541    /// 已揭示节点覆盖隐藏集:槽位属于揭示节点的返回 true。
542    fn revealed_overrides(&self, slot: u32) -> bool {
543        let Some(&id) = self.payload.node_ids.get(slot as usize) else {
544            return false;
545        };
546        self.revealed.contains(&id)
547    }
548
549    fn world_bounds(&self) -> Option<Rect> {
550        let p = self.positions.as_ref();
551        if p.is_empty() {
552            return None;
553        }
554        let r = NODE_WORLD_SIZE / 2.0;
555        let mut lo = p[0].minus(Vec2::new(r, r));
556        let mut hi = p[0].plus(Vec2::new(r, r));
557        for v in p.iter().skip(1) {
558            lo = Vec2::new(lo.x.min(v.x - r), lo.y.min(v.y - r));
559            hi = Vec2::new(hi.x.max(v.x + r), hi.y.max(v.y + r));
560        }
561        Some(Rect { min: lo, max: hi })
562    }
563
564    fn poll_layout(&mut self) {
565        let held = self.node_drag.and_then(|(slot, _)| {
566            self.positions
567                .get(slot as usize)
568                .copied()
569                .map(|p| (slot, p))
570        });
571        if let Some(worker) = &mut self.worker {
572            if let Some(snap) = worker.try_snapshot() {
573                self.layout_active = !snap.cooled;
574                self.positions = snap.positions;
575                self.positions_rev += 1;
576            }
577            if worker.is_poisoned() {
578                self.layout_active = false;
579            }
580        }
581        // 防止尚未消费的旧快照把正在拖动的节点拉回。
582        if let Some((slot, p)) = held
583            && let Some(current) = Arc::make_mut(&mut self.positions).get_mut(slot as usize)
584        {
585            *current = p;
586        }
587        if self.fit_pending && self.view_size.is_some() && !self.positions.is_empty() {
588            self.fit_pending = false;
589            if let Some(world) = self.world_bounds() {
590                let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
591                self.viewport.fit(&world, view, 60.0);
592            }
593        }
594    }
595
596    fn refresh_spatial(&mut self) {
597        if self.spatial_rev == self.positions_rev && self.spatial.is_some() {
598            return;
599        }
600        let mut grid = SpatialGrid::new(NODE_WORLD_SIZE * 3.0);
601        let r = NODE_WORLD_SIZE / 2.0;
602        for (i, p) in self.positions.iter().enumerate() {
603            let rect = Rect {
604                min: Vec2::new(p.x - r, p.y - r),
605                max: Vec2::new(p.x + r, p.y + r),
606            };
607            grid.insert(i as u32, rect);
608        }
609        self.spatial = Some(grid);
610        self.spatial_rev = self.positions_rev;
611    }
612
613    fn visible_world(&self) -> Rect {
614        let view = self.view_size.unwrap_or(Size2::new(4096.0, 4096.0));
615        self.viewport
616            .visible_world_rect(view)
617            .inflate(CULL_MARGIN / self.viewport.zoom.max(0.02))
618    }
619
620    fn refresh_visible(&mut self) {
621        let key = (
622            [
623                self.viewport.offset.x.to_bits(),
624                self.viewport.offset.y.to_bits(),
625                self.viewport.zoom.to_bits(),
626            ],
627            self.positions_rev,
628        );
629        if let Some(c) = &self.visible_cache
630            && c.key == key
631        {
632            return;
633        }
634        let visible = self.visible_world();
635        let mut slots = self
636            .spatial
637            .as_ref()
638            .map(|g| g.query(&visible))
639            .unwrap_or_default();
640        slots.sort_unstable();
641        let r = NODE_WORLD_SIZE / 2.0;
642        let mut edges = Vec::new();
643        for &(s, t, _) in &self.payload.edges {
644            // 线段包围盒与视口相交即视为可见(直线边足够准确)。
645            let (Some(a), Some(b)) = (
646                self.positions.get(s as usize),
647                self.positions.get(t as usize),
648            ) else {
649                continue;
650            };
651            let seg = Rect {
652                min: Vec2::new(a.x.min(b.x) - r, a.y.min(b.y) - r),
653                max: Vec2::new(a.x.max(b.x) + r, a.y.max(b.y) + r),
654            };
655            if seg.intersects(&visible) {
656                edges.push((s, t));
657            }
658        }
659        edges.sort_unstable();
660        self.visible_cache = Some(Arc::new(VisibleCache { key, slots, edges }));
661    }
662
663    fn local(&self, position: gpui_kit::Point<Pixels>) -> Vec2 {
664        let b = self.bounds_cell.lock().ok().and_then(|g| *g);
665        match b {
666            Some(bounds) => Vec2::new(
667                f32::from(position.x - bounds.origin.x),
668                f32::from(position.y - bounds.origin.y),
669            ),
670            None => Vec2::ZERO,
671        }
672    }
673
674    fn on_scroll(&mut self, ev: &ScrollEvent, _window: &mut Window, cx: &mut Context<Self>) {
675        let delta = ev.delta.pixel_delta(px(LINE_HEIGHT));
676        let (dx, dy) = (f32::from(delta.x), f32::from(delta.y));
677        self.motion.cancel_view();
678        if ev.modifiers.secondary(cx) || ev.modifiers.control {
679            let anchor = self.local(ev.position);
680            let dy = if matches!(ev.delta, ScrollDelta::Lines(_)) {
681                dy * 2.0
682            } else {
683                dy
684            };
685            self.viewport
686                .zoom_by_at((dy * WHEEL_ZOOM_SPEED).exp(), anchor);
687        } else {
688            self.viewport.pan_by(Vec2::new(dx, dy));
689        }
690        cx.notify();
691        cx.stop_propagation();
692    }
693
694    /// 世界坐标命中测试:返回节点槽位(跳过隐藏节点)。
695    fn hit_slot(&self, world: Vec2) -> Option<u32> {
696        let grid = self.spatial.as_ref()?;
697        let r = NODE_WORLD_SIZE / 2.0 + 4.0 / self.viewport.zoom.max(0.02);
698        let probe = Rect {
699            min: Vec2::new(world.x - r, world.y - r),
700            max: Vec2::new(world.x + r, world.y + r),
701        };
702        grid.query(&probe)
703            .into_iter()
704            .filter(|&s| !self.is_slot_hidden(s))
705            .filter(|&s| {
706                self.positions
707                    .get(s as usize)
708                    .is_some_and(|p| (p.x - world.x).abs() <= r && (p.y - world.y).abs() <= r)
709            })
710            .min_by(|&a, &b| {
711                self.positions[a as usize]
712                    .distance(world)
713                    .total_cmp(&self.positions[b as usize].distance(world))
714                    .then(a.cmp(&b))
715            })
716    }
717
718    /// 焦点节点(悬停 + 选中)与其一度邻居的槽位集。
719    fn focus_slots(&self) -> HashSet<u32> {
720        let mut focus = HashSet::new();
721        if let Some(h) = self.hover {
722            focus.insert(h);
723        }
724        for &id in &self.selection {
725            if let Some(&s) = self.slot_index.get(&id) {
726                focus.insert(s);
727            }
728        }
729        let mut out = focus.clone();
730        for &s in &focus {
731            let Some(&id) = self.payload.node_ids.get(s as usize) else {
732                continue;
733            };
734            for n in self.graph.adjacency().neighbors(id) {
735                if let Some(&ns) = self.slot_index.get(&n) {
736                    out.insert(ns);
737                }
738            }
739        }
740        out
741    }
742
743    fn on_left_down(&mut self, ev: &MouseDownEvent, _w: &mut Window, cx: &mut Context<Self>) {
744        self.motion.cancel_view();
745        self.refresh_spatial();
746        self.drag_moved = false;
747        let local = self.local(ev.position);
748        let world = self.viewport.screen_to_world(local);
749        // 双击节点:展开一度邻居(筛选期间)。
750        if ev.click_count >= 2 {
751            if let Some(slot) = self.hit_slot(world) {
752                let id = self.payload.node_ids[slot as usize];
753                let _ = self.expand(id, cx);
754                if !self.selection.contains(&id) {
755                    self.selection = vec![id];
756                }
757                cx.notify();
758                cx.stop_propagation();
759            }
760            return;
761        }
762        if let Some(slot) = self.hit_slot(world) {
763            // 节点按下:准备拖动(区分点击在松手时判定)。
764            let node_pos = self.positions.get(slot as usize).copied().unwrap_or(world);
765            self.node_drag = Some((slot, world.minus(node_pos)));
766            self.drag_moved = false;
767            cx.stop_propagation();
768            return;
769        }
770        if ev.modifiers.shift {
771            // Shift + 背景:框选。
772            self.rubber = Some((local, local));
773        } else {
774            self.pan_drag = Some((local, self.viewport.offset));
775        }
776        cx.stop_propagation();
777    }
778
779    fn on_mouse_move(&mut self, ev: &MouseMoveEvent, _w: &mut Window, cx: &mut Context<Self>) {
780        let local = self.local(ev.position);
781        let world = self.viewport.screen_to_world(local);
782
783        if let Some((slot, grab)) = self.node_drag {
784            // 拖动节点:本地立即落位(反馈跟手),worker 同步 SetPinned + MoveNode。
785            let target = world.minus(grab);
786            if self
787                .positions
788                .get(slot as usize)
789                .is_some_and(|p| p.distance(target) < 0.01)
790            {
791                return;
792            }
793            self.drag_moved = true;
794            self.payload.pinned[slot as usize] = true;
795            if let Some(worker) = &self.worker {
796                let id = self.payload.node_ids[slot as usize];
797                worker.send(LayoutCommand::SetPinned(id, true));
798                worker.send(LayoutCommand::MoveNode(id, target));
799                self.layout_active = true;
800            }
801            Arc::make_mut(&mut self.positions)[slot as usize] = target;
802            self.positions_rev += 1;
803            cx.notify();
804            return;
805        }
806
807        if let Some((start, _)) = self.rubber {
808            self.rubber = Some((start, local));
809            cx.notify();
810            return;
811        }
812
813        if let Some((start, base)) = self.pan_drag {
814            self.drag_moved |= local.distance(start) > 4.0;
815            self.viewport.offset = base.plus(local.minus(start));
816            cx.notify();
817            return;
818        }
819
820        // 悬停:命中变化才重绘(淡出渐变随动)。
821        let hit = self.hit_slot(world);
822        if hit != self.hover {
823            self.hover = hit;
824            let now = motion_now(cx);
825            self.motion.set_reduced(is_reduced_motion(cx));
826            self.motion.set_dim(hit.is_some(), now);
827            cx.notify();
828        }
829    }
830
831    fn on_mouse_up(&mut self, ev: &MouseUpEvent, _w: &mut Window, cx: &mut Context<Self>) {
832        // 节点松手:没位移就是点选。
833        if let Some((slot, _)) = self.node_drag.take() {
834            if !self.drag_moved {
835                let id = self.payload.node_ids[slot as usize];
836                if ev.modifiers.shift {
837                    if let Some(i) = self.selection.iter().position(|&s| s == id) {
838                        self.selection.remove(i);
839                    } else {
840                        self.selection.push(id);
841                    }
842                } else {
843                    self.selection = vec![id];
844                }
845            }
846            cx.notify();
847            return;
848        }
849        if let Some((start, end)) = self.rubber.take() {
850            // 框选:屏幕矩形与节点中心相交。
851            let (lo, hi) = (
852                Vec2::new(start.x.min(end.x), start.y.min(end.y)),
853                Vec2::new(start.x.max(end.x), start.y.max(end.y)),
854            );
855            let mut picked = Vec::new();
856            if hi.x - lo.x > 4.0 || hi.y - lo.y > 4.0 {
857                for (i, p) in self.positions.iter().enumerate() {
858                    let slot = i as u32;
859                    if self.is_slot_hidden(slot) {
860                        continue;
861                    }
862                    let c = self.viewport.world_to_screen(*p);
863                    if c.x >= lo.x && c.x <= hi.x && c.y >= lo.y && c.y <= hi.y {
864                        picked.push(self.payload.node_ids[slot as usize]);
865                    }
866                }
867            }
868            self.selection = picked;
869            cx.notify();
870            return;
871        }
872        if self.pan_drag.take().is_some() {
873            // 背景单击清除选择;平移保留已有选择。
874            if !self.drag_moved {
875                self.selection.clear();
876            }
877            cx.notify();
878        }
879    }
880
881    fn on_pinch(&mut self, ev: &gpui_kit::PinchEvent, _w: &mut Window, _cx: &mut Context<Self>) {
882        self.motion.cancel_view();
883        let anchor = self.local(ev.position);
884        self.viewport.zoom_by_at(1.0 + ev.delta, anchor);
885    }
886}
887
888impl Focusable for Graph2D {
889    fn focus_handle(&self, _cx: &App) -> FocusHandle {
890        self.focus.clone()
891    }
892}
893
894impl Render for Graph2D {
895    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
896        let measured = self
897            .bounds_cell
898            .lock()
899            .ok()
900            .and_then(|g| *g)
901            .map(|b| Size2::new(f32::from(b.size.width), f32::from(b.size.height)));
902        if let Some(measured) = measured
903            && self.view_size != Some(measured)
904        {
905            self.view_size = Some(measured);
906            self.visible_cache = None;
907        }
908        self.poll_layout();
909
910        let now = motion_now(cx);
911        self.motion.set_reduced(is_reduced_motion(cx));
912        // 视口弹簧取样:动画中每帧替换视口并请求下一帧。
913        if self.motion.view_animating() {
914            let view = self.view_size.unwrap_or(Size2::new(800.0, 600.0));
915            let center = Vec2::new(view.w / 2.0, view.h / 2.0);
916            if let Some((vp, done)) = self.motion.view_sample(&self.viewport, center, now) {
917                self.viewport = vp;
918                if done {
919                    self.motion.cancel_view();
920                }
921                cx.notify();
922            }
923        }
924
925        self.motion.prune(now);
926        if !self.layout_paused
927            && (self.motion.animating(now)
928                || self.layout_active
929                || (self.fit_pending && self.graph.node_count() > 0))
930        {
931            window.request_animation_frame();
932            cx.notify();
933        }
934        self.refresh_spatial();
935        self.refresh_visible();
936        let colors = cx.arc_theme().colors;
937        let vp = self.viewport;
938        let dim = self.motion.dim_factor(now);
939        let focus = if dim > 0.01 {
940            Some(self.focus_slots())
941        } else {
942            None
943        };
944
945        // 仅克隆共享句柄;悬停/淡出时不复制数千槽位与边的可见集。
946        let visible = self.visible_cache.clone().expect("可见集已刷新");
947        let slots = &visible.slots;
948        let edge_pairs = &visible.edges;
949        let global_dots = self.graph.node_count() >= LOD_MIN_NODES && vp.zoom <= LOD_GLOBAL_ZOOM;
950        // 实际拖动后锁定隐藏,直到松手;停住或拖回起点都不提前恢复,避免文字闪烁。
951        // 不用透明度隐藏:直接跳过标签筛选、测宽和元素构建。
952        let show_labels =
953            !(self.drag_moved && (self.pan_drag.is_some() || self.node_drag.is_some()));
954
955        // ---------- LOD 判定 ----------
956        let mut full_slots: Vec<u32> = Vec::new();
957        let mut shells: Vec<(Vec2, f32, f32)> = Vec::new();
958        let mut dots: Vec<(Vec2, f32, f32)> = Vec::new();
959        let mut full_pool: Vec<(u32, u32)> = Vec::new(); // (槽位, 度数):Full 候选按度数截断
960        let mut label_pool: Vec<(u32, u32)> = Vec::new(); // (槽位, 度数)
961        for &slot in slots {
962            if !self.drawn(slot, now) {
963                continue;
964            }
965            let Some(p) = self.positions.get(slot as usize) else {
966                continue;
967            };
968            let appear = self.appearance(slot, now);
969            let opacity = appear.opacity * Self::emphasis(slot, focus.as_ref(), dim);
970            let center = vp.world_to_screen(*p);
971            let screen_h = NODE_WORLD_SIZE * vp.zoom * appear.scale;
972            let marker_h = (NODE_MARKER_WORLD_SIZE * vp.zoom * appear.scale).max(DOT_MIN_PX);
973            let lod = if screen_h < LOD_DOT_PX || (global_dots && screen_h < LOD_SHELL_PX) {
974                Lod::Dot
975            } else if screen_h < LOD_SHELL_PX {
976                Lod::Shell
977            } else {
978                Lod::Full
979            };
980            match lod {
981                // Full 候选先入池,按度数截到 MAX_FULL_CARDS;溢出的转外壳。
982                Lod::Full => full_pool.push((slot, self.degrees[slot as usize])),
983                Lod::Shell => {
984                    shells.push((center, marker_h, opacity));
985                    if show_labels {
986                        label_pool.push((slot, self.degrees[slot as usize]));
987                    }
988                }
989                Lod::Dot => {
990                    dots.push((center, marker_h, opacity));
991                    if show_labels {
992                        label_pool.push((slot, self.degrees[slot as usize]));
993                    }
994                }
995            }
996        }
997        if full_pool.len() > MAX_FULL_CARDS {
998            // 度数高者优先保留 Full 卡片(信息量大的节点最值得放大细节)。
999            full_pool.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
1000            for &(slot, _) in &full_pool[MAX_FULL_CARDS..] {
1001                let p = self.positions[slot as usize];
1002                let center = vp.world_to_screen(p);
1003                let appear = self.appearance(slot, now);
1004                let marker_h = (NODE_MARKER_WORLD_SIZE * vp.zoom * appear.scale).max(DOT_MIN_PX);
1005                let opacity = appear.opacity * Self::emphasis(slot, focus.as_ref(), dim);
1006                shells.push((center, marker_h, opacity));
1007                if show_labels {
1008                    label_pool.push((slot, self.degrees[slot as usize]));
1009                }
1010            }
1011            full_pool.truncate(MAX_FULL_CARDS);
1012        }
1013        // 恢复槽位升序:卡片层按槽位序渲染,保持与事件命中、测试断言一致。
1014        full_pool.sort_unstable_by_key(|&(s, _)| s);
1015        full_slots.extend(full_pool.into_iter().map(|(s, _)| s));
1016        // 浮动标签:度数优先 + 屏幕网格碰撞剔除 + 上限 200。
1017        label_pool.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
1018        let label_font = f32::from(Typography::TEXT_XS).max(10.0);
1019        let mut label_cells: std::collections::HashSet<(i32, i32)> =
1020            std::collections::HashSet::new();
1021        let mut labels: Vec<(Vec2, SharedString, f32)> = Vec::new();
1022        'pool: for &(slot, _) in &label_pool {
1023            if labels.len() >= MAX_LABELS {
1024                break;
1025            }
1026            let Some(node) = self.graph.node(self.payload.node_ids[slot as usize]) else {
1027                continue;
1028            };
1029            let Some(center) = self
1030                .positions
1031                .get(slot as usize)
1032                .map(|p| vp.world_to_screen(*p))
1033            else {
1034                continue;
1035            };
1036            let text = SharedString::from(node.label.clone());
1037            let approx_w = self.label_width(window, &text, label_font);
1038            let cell_w = 24.0f32.max(approx_w * 0.5);
1039            let cx0 = (center.x / cell_w).floor() as i32;
1040            let cy0 = (center.y / 18.0).floor() as i32;
1041            // 2×2 邻域去重(近似碰撞即可)。
1042            for dx in 0..=1 {
1043                for dy in 0..=1 {
1044                    if !label_cells.insert((cx0 + dx, cy0 + dy)) {
1045                        continue 'pool;
1046                    }
1047                }
1048            }
1049            let opacity =
1050                self.appearance(slot, now).opacity * Self::emphasis(slot, focus.as_ref(), dim);
1051            labels.push((
1052                node_label_origin(
1053                    center,
1054                    (NODE_MARKER_WORLD_SIZE * vp.zoom * self.appearance(slot, now).scale)
1055                        .max(DOT_MIN_PX),
1056                    approx_w,
1057                    label_font * 1.5,
1058                ),
1059                text,
1060                opacity,
1061            ));
1062        }
1063        // ---------- 第 1 层:边 + 点 / 外壳(一个 canvas 批量画) ----------
1064        let half = (EDGE_WIDTH * vp.zoom).max(0.5) / 2.0;
1065        let positions = self.positions.clone();
1066        let edge_color = colors.border_strong;
1067        let dot_color = colors.accent;
1068        let shell_fill = colors.accent;
1069        let shell_border = colors.accent;
1070        let bounds_for_edges = self.bounds_cell.clone();
1071        // 两个批次:焦点邻接边保持清晰,其余边淡出,不退化成逐边 path。
1072        let mut edge_groups = [Vec::new(), Vec::new()];
1073        for &(s, t) in edge_pairs {
1074            if self.is_slot_hidden(s) || self.is_slot_hidden(t) {
1075                continue;
1076            }
1077            let focused = focus
1078                .as_ref()
1079                .is_none_or(|f| f.contains(&s) && f.contains(&t));
1080            edge_groups[usize::from(!focused)].push((s, t));
1081        }
1082        let dot_list = dots;
1083        let shell_list = shells;
1084        self.rendered = RenderCounts {
1085            full: full_slots.len(),
1086            shell: shell_list.len(),
1087            dot: dot_list.len(),
1088            edges: edge_groups.iter().map(Vec::len).sum(),
1089            labels: labels.len(),
1090        };
1091        let back_layer = canvas(
1092            {
1093                let bounds_cell = bounds_for_edges.clone();
1094                move |b: Bounds<Pixels>, _window, _| {
1095                    if let Ok(mut g) = bounds_cell.lock() {
1096                        *g = Some(b);
1097                    }
1098                }
1099            },
1100            move |b: Bounds<Pixels>, _, window: &mut Window, _| {
1101                // 边:同色直线合并成一条路径(细长四边形填充,省 stroke 展开)。
1102                for (group, edge_list) in edge_groups.iter().enumerate() {
1103                    if edge_list.is_empty() {
1104                        continue;
1105                    }
1106                    // 所有边轮廓绕向一致;NonZero 让交叉区取并集,不能用默认
1107                    // EvenOdd,否则重叠两次的边会互相挖空。
1108                    let mut fill = PathBuilder::fill().with_style(gpui_kit::PathStyle::Fill(
1109                        gpui_kit::FillOptions {
1110                            fill_rule: gpui_kit::FillRule::NonZero,
1111                        },
1112                    ));
1113                    for &(s, t) in edge_list {
1114                        let (Some(a), Some(bw)) =
1115                            (positions.get(s as usize), positions.get(t as usize))
1116                        else {
1117                            continue;
1118                        };
1119                        let a = vp.world_to_screen(*a);
1120                        let b2 = vp.world_to_screen(*bw);
1121                        let d = b2.minus(a);
1122                        let len = d.length();
1123                        if len < 1.0 {
1124                            continue;
1125                        }
1126                        let n = Vec2::new(-d.y / len * half, d.x / len * half);
1127                        let to = |v: Vec2| {
1128                            gpui_kit::point(
1129                                px(f32::from(b.origin.x)) + px(v.x),
1130                                px(f32::from(b.origin.y)) + px(v.y),
1131                            )
1132                        };
1133                        fill.move_to(to(a.plus(n)));
1134                        fill.line_to(to(b2.plus(n)));
1135                        fill.line_to(to(b2.minus(n)));
1136                        fill.line_to(to(a.minus(n)));
1137                        fill.close();
1138                    }
1139                    if let Ok(path) = fill.build() {
1140                        let alpha = if group == 0 {
1141                            1.0
1142                        } else {
1143                            1.0 - dim * DIM_STRENGTH
1144                        };
1145                        window.paint_path(path, edge_color.opacity(alpha));
1146                    }
1147                }
1148                // 节点点。
1149                for (c, d, fade) in &dot_list {
1150                    let color = dot_color.opacity(*fade);
1151                    window.paint_quad(quad(
1152                        Bounds {
1153                            origin: gpui_kit::point(
1154                                b.origin.x + px(c.x - d / 2.0),
1155                                b.origin.y + px(c.y - d / 2.0),
1156                            ),
1157                            size: size(px(*d), px(*d)),
1158                        },
1159                        Corners::all(px(*d / 2.0)),
1160                        color,
1161                        Edges::all(px(0.0)),
1162                        color,
1163                        gpui_kit::BorderStyle::Solid,
1164                    ));
1165                }
1166                // 外壳同样绘制为圆点。
1167                for (c, s, fade) in &shell_list {
1168                    let half_s = s / 2.0;
1169                    let (fill, border) = (shell_fill.opacity(*fade), shell_border.opacity(*fade));
1170                    window.paint_quad(quad(
1171                        Bounds {
1172                            origin: gpui_kit::point(
1173                                b.origin.x + px(c.x - half_s),
1174                                b.origin.y + px(c.y - half_s),
1175                            ),
1176                            size: size(px(*s), px(*s)),
1177                        },
1178                        Corners::all(px(half_s)),
1179                        fill,
1180                        Edges::all(px(1.0)),
1181                        border,
1182                        gpui_kit::BorderStyle::Solid,
1183                    ));
1184                }
1185            },
1186        )
1187        .absolute()
1188        .size_full();
1189
1190        // ---------- 第 2 层:浮动标签 ----------
1191        let label_els: Vec<_> = labels
1192            .into_iter()
1193            .map(|(p, text, opacity)| {
1194                div()
1195                    .absolute()
1196                    .left(px(p.x))
1197                    .top(px(p.y))
1198                    .text_size(px(label_font))
1199                    .line_height(px(label_font * 1.5))
1200                    .text_color(colors.text_secondary.opacity(opacity))
1201                    .whitespace_nowrap()
1202                    .child(text)
1203            })
1204            .collect();
1205
1206        // ---------- 第 3 层:详细圆点 + 上方标签 ----------
1207        let node_font = (f32::from(Typography::TEXT_SM) * vp.zoom).clamp(9.0, 24.0);
1208        let label_height = node_font * 1.5;
1209        let world = (NODE_MARKER_WORLD_SIZE * vp.zoom).max(DOT_MIN_PX);
1210        let selected: HashSet<NodeId> = self.selection.iter().copied().collect();
1211        // 先集中测量标签宽度(&mut self),再构建元素(&self),避免闭包双重借用。
1212        let text_ws: HashMap<u32, f32> = full_slots
1213            .iter()
1214            .filter(|_| show_labels)
1215            .filter_map(|&slot| {
1216                let label = self
1217                    .graph
1218                    .node(self.payload.node_ids[slot as usize])?
1219                    .label
1220                    .clone();
1221                Some((slot, self.label_width(window, &label, node_font)))
1222            })
1223            .collect();
1224        let card_els: Vec<_> = full_slots
1225            .iter()
1226            .filter_map(|&slot| {
1227                let node = self.graph.node(self.payload.node_ids[slot as usize])?;
1228                if !self.drawn(slot, now) {
1229                    return None;
1230                }
1231                let c = vp.world_to_screen(*self.positions.get(slot as usize)?);
1232                let node_id = node.id;
1233                let appear = self.appearance(slot, now);
1234                let is_sel = selected.contains(&node_id);
1235                let is_hover = self.hover == Some(slot);
1236                let fade = Self::emphasis(slot, focus.as_ref(), dim);
1237                let opacity = (appear.opacity * fade).clamp(0.0, 1.0);
1238                let world = world * appear.scale;
1239                let text_w = text_ws.get(&slot).copied().unwrap_or(world);
1240                let label_pos = node_label_origin(c, world, text_w, label_height);
1241                Some(
1242                    div()
1243                        .absolute()
1244                        .left(px(c.x - world / 2.0))
1245                        .top(px(c.y - world / 2.0))
1246                        .w(px(world))
1247                        .h(px(world))
1248                        .opacity(opacity)
1249                        .child(
1250                            div()
1251                                .id(ElementId::NamedInteger(
1252                                    format!("{}-node", self.id).into(),
1253                                    node.id.0,
1254                                ))
1255                                .test_support()
1256                                .size_full()
1257                                .rounded(px(world / 2.0))
1258                                .bg(colors.accent)
1259                                .border_2()
1260                                .border_color(if is_sel || is_hover {
1261                                    colors.foreground
1262                                } else {
1263                                    colors.accent
1264                                }),
1265                        )
1266                        .children(show_labels.then(|| {
1267                            div()
1268                                .id(ElementId::NamedInteger(
1269                                    format!("{}-label", self.id).into(),
1270                                    node.id.0,
1271                                ))
1272                                .test_support()
1273                                .absolute()
1274                                .left(px(label_pos.x - (c.x - world / 2.0)))
1275                                .top(px(label_pos.y - (c.y - world / 2.0)))
1276                                .w(px(text_w))
1277                                .h(px(label_height))
1278                                .text_size(px(node_font))
1279                                .line_height(px(label_height))
1280                                .text_color(if is_sel || is_hover {
1281                                    colors.accent
1282                                } else {
1283                                    colors.foreground
1284                                })
1285                                .whitespace_nowrap()
1286                                .child(node.label.clone())
1287                        })),
1288                )
1289            })
1290            .collect();
1291
1292        // ---------- 组装 ----------
1293        let id = self.id.clone();
1294        let rubber_rect = self.rubber.map(|(a, b)| {
1295            let lo = Vec2::new(a.x.min(b.x), a.y.min(b.y));
1296            let hi = Vec2::new(a.x.max(b.x), a.y.max(b.y));
1297            (px(lo.x), px(lo.y), px(hi.x - lo.x), px(hi.y - lo.y))
1298        });
1299        div()
1300            .id(ElementId::Name(id))
1301            .test_support()
1302            .track_focus(&self.focus)
1303            .relative()
1304            .size_full()
1305            .overflow_hidden()
1306            .bg(colors.background)
1307            .on_scroll(cx.listener(Self::on_scroll))
1308            .on_pinch(cx.listener(Self::on_pinch))
1309            .on_mouse_down(MouseButton::Left, cx.listener(Self::on_left_down))
1310            .on_mouse_move(cx.listener(Self::on_mouse_move))
1311            .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
1312            .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
1313            .on_hover(cx.listener(|this, hovered: &bool, _, cx| {
1314                if !hovered {
1315                    this.hover = None;
1316                    this.motion.set_dim(false, motion_now(cx));
1317                    cx.notify();
1318                }
1319            }))
1320            .child(back_layer)
1321            .children(label_els)
1322            .children(card_els)
1323            .children(rubber_rect.map(|(x, y, w, h)| {
1324                div()
1325                    .absolute()
1326                    .left(x)
1327                    .top(y)
1328                    .w(w)
1329                    .h(h)
1330                    .border_1()
1331                    .border_color(colors.accent)
1332                    .bg(colors.accent_subtle.opacity(0.15))
1333            }))
1334    }
1335}
1336
1337#[cfg(test)]
1338mod tests {
1339    use super::*;
1340    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1341    use gpui_kit::{
1342        AppContext as _, Entity, Modifiers, PlatformInput, TestAppContext, VisualTestContext,
1343        point, px, test::TestWindowExt as _,
1344    };
1345
1346    struct Host {
1347        canvas: Entity<Graph2D>,
1348    }
1349
1350    impl Render for Host {
1351        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1352            div().size_full().child(self.canvas.clone())
1353        }
1354    }
1355
1356    fn chain_graph(n: usize) -> KnowledgeGraph {
1357        let mut g = KnowledgeGraph::new();
1358        let kind = g.add_kind("概念");
1359        let mut prev = g.add_node("n0", Some(kind));
1360        for i in 1..n {
1361            let cur = g.add_node(format!("n{i}"), Some(kind));
1362            g.add_edge(prev, cur, 1.0, None).unwrap();
1363            prev = cur;
1364        }
1365        g
1366    }
1367
1368    /// 网格静态坐标(世界间距 120,节点直径 36)。
1369    fn grid_positions(n: usize, cols: usize) -> Vec<Vec2> {
1370        (0..n)
1371            .map(|i| Vec2::new((i % cols) as f32 * 120.0, (i / cols) as f32 * 120.0))
1372            .collect()
1373    }
1374
1375    fn large_graph() -> KnowledgeGraph {
1376        let mut g = KnowledgeGraph::new();
1377        let ids: Vec<_> = (0..5_000)
1378            .map(|i| g.add_node(format!("n{i}"), None))
1379            .collect();
1380        for i in 0..10_000u64 {
1381            let s = ids[(i * 7919 % 5_000) as usize];
1382            let t = ids[(i * 104_729 % 5_000) as usize];
1383            let _ = g.add_edge(s, t, 1.0, None);
1384        }
1385        g
1386    }
1387
1388    fn setup(cx: &mut TestAppContext) -> (Entity<Graph2D>, &mut VisualTestContext) {
1389        cx.update(|cx| {
1390            gpui_kit::init(cx);
1391            install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1392        });
1393        let mut canvas = None;
1394        let (_, vcx) = cx.add_window_view(|_, cx| {
1395            let c = cx.new(|cx| {
1396                Graph2D::new_static("graph", chain_graph(8), grid_positions(8, 4), cx)
1397                    .aria_label("测试图谱")
1398                    .fit_on_mount()
1399            });
1400            canvas = Some(c.clone());
1401            Host { canvas: c }
1402        });
1403        vcx.update(|window, cx| {
1404            window.render_frame(cx);
1405            window.render_frame(cx);
1406        });
1407        (canvas.unwrap(), vcx)
1408    }
1409
1410    fn p(x: f32, y: f32) -> gpui_kit::Point<Pixels> {
1411        point(px(x), px(y))
1412    }
1413
1414    #[gpui_kit::test]
1415    fn renders_round_nodes_with_labels_above_and_culls_offscreen(cx: &mut TestAppContext) {
1416        let (canvas, vcx) = setup(cx);
1417        // fit_on_mount 已适配:8 节点全部可见,7 条边,Full 卡片。
1418        let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1419        assert_eq!(counts.full, 8, "{counts:?}");
1420        assert_eq!(counts.edges, 7);
1421        assert_eq!(counts.shell + counts.dot, 0);
1422        // 节点卡片是可发现的元素(供测试与读屏)。
1423        vcx.update(|window, _| {
1424            let root = window.find("graph");
1425            assert!(f32::from(root.bounds().size.width) > 0.0);
1426            let node = window.find(ElementId::NamedInteger("graph-node".into(), 1));
1427            let marker = node.bounds();
1428            assert!(!marker.is_empty());
1429            assert_eq!(marker.size.width, marker.size.height, "圆点必须保持等宽高");
1430            let label = window.find(ElementId::NamedInteger("graph-label".into(), 1));
1431            let label = label.bounds();
1432            assert!(
1433                label.origin.y + label.size.height < marker.origin.y,
1434                "标签应位于圆点上方"
1435            );
1436            let marker_cx = f32::from(marker.origin.x + marker.size.width / 2.0);
1437            let label_cx = f32::from(label.origin.x + label.size.width / 2.0);
1438            assert!((marker_cx - label_cx).abs() < 1.0, "标签应水平居中");
1439        });
1440        // 平移到远离图的位置:全部被裁剪。
1441        canvas.update(vcx, |c, _| {
1442            let b = c.world_bounds().unwrap();
1443            c.viewport.offset.x = -(b.max.x + 5000.0);
1444            c.viewport.offset.y = -(b.max.y + 5000.0);
1445        });
1446        vcx.update(|window, cx| window.render_frame(cx));
1447        let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1448        assert_eq!((counts.full, counts.edges), (0, 0), "{counts:?}");
1449    }
1450
1451    #[gpui_kit::test]
1452    fn zoom_out_switches_to_dots_and_capped_labels(cx: &mut TestAppContext) {
1453        let (canvas, vcx) = setup(cx);
1454        // 缩小到全景点模式:Full 卡片消失,出现点 + 浮动标签。
1455        canvas.update(vcx, |c, _| {
1456            let b = c.world_bounds().unwrap();
1457            let view = c.view_size.unwrap_or(Size2::new(800.0, 600.0));
1458            c.viewport.fit(&b, view, 60.0);
1459            c.viewport.zoom = 0.06; // 36 * 0.06 ≈ 2.2 px → 点模式
1460        });
1461        vcx.update(|window, cx| window.render_frame(cx));
1462        let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1463        assert!(counts.full == 0, "{counts:?}");
1464        assert!(counts.dot + counts.shell >= 8, "{counts:?}");
1465        assert!(
1466            counts.labels > 0 && counts.labels <= MAX_LABELS,
1467            "{counts:?}"
1468        );
1469        // 大图上限:200 节点以上时标签数不超过 200。
1470        let big = chain_graph(600);
1471        let big_positions = grid_positions(600, 30);
1472        let mut big_view = None;
1473        cx_update_big(vcx, big, big_positions, &mut big_view);
1474        let counts = big_view.unwrap().read_with(vcx, |c, _| c.rendered_counts());
1475        assert!(counts.labels <= MAX_LABELS, "{counts:?}");
1476    }
1477
1478    fn cx_update_big(
1479        vcx: &mut VisualTestContext,
1480        big: KnowledgeGraph,
1481        positions: Vec<Vec2>,
1482        out: &mut Option<Entity<Graph2D>>,
1483    ) {
1484        vcx.update(|window, cx| {
1485            let c =
1486                cx.new(|cx| Graph2D::new_static("graph-big", big, positions, cx).fit_on_mount());
1487            window.render_frame(cx);
1488            window.render_frame(cx);
1489            *out = Some(c);
1490        });
1491    }
1492
1493    #[gpui_kit::test]
1494    fn drag_pans_and_ctrl_wheel_zooms_about_cursor(cx: &mut TestAppContext) {
1495        let (canvas, vcx) = setup(cx);
1496        let before = canvas.read_with(vcx, |c, _| c.viewport());
1497        vcx.update(|window, cx| window.drag(p(700.0, 500.0), p(760.0, 470.0), cx));
1498        let after = canvas.read_with(vcx, |c, _| c.viewport());
1499        assert!(
1500            (after.offset.x - before.offset.x - 60.0).abs() < 0.5,
1501            "{after:?}"
1502        );
1503        assert!(
1504            (after.offset.y - before.offset.y + 30.0).abs() < 0.5,
1505            "{after:?}"
1506        );
1507
1508        // Ctrl+滚轮以光标为锚缩放:锚点的世界坐标不动。
1509        let vp = canvas.read_with(vcx, |c, _| c.viewport());
1510        let world_before = vp.screen_to_world(Vec2::new(300.0, 200.0));
1511        vcx.update(|window, cx| {
1512            window.dispatch_event(
1513                PlatformInput::Scroll(ScrollEvent {
1514                    position: p(300.0, 200.0),
1515                    delta: ScrollDelta::Pixels(point(px(0.0), px(80.0))),
1516                    modifiers: Modifiers {
1517                        control: true,
1518                        ..Default::default()
1519                    },
1520                    ..Default::default()
1521                }),
1522                cx,
1523            );
1524        });
1525        let vp = canvas.read_with(vcx, |c, _| c.viewport());
1526        assert!(vp.zoom > 1.0, "{vp:?}");
1527        assert!(
1528            vp.world_to_screen(world_before)
1529                .distance(Vec2::new(300.0, 200.0))
1530                < 0.01,
1531            "缩放必须以光标为锚"
1532        );
1533    }
1534
1535    #[gpui_kit::test]
1536    fn pan_hides_all_lod_labels_until_release_outside(cx: &mut TestAppContext) {
1537        let (canvas, vcx) = setup(cx);
1538        for zoom in [1.0, 0.3, 0.06] {
1539            canvas.update(vcx, |c, _| {
1540                c.viewport.zoom = zoom;
1541                c.viewport.offset = Vec2::new(120.0, 120.0);
1542            });
1543            vcx.update(|window, cx| window.render_frame(cx));
1544            let before = canvas.read_with(vcx, |c, _| c.rendered_counts());
1545            assert!(before.full > 0 || before.labels > 0, "{before:?}");
1546            vcx.update(|window, cx| {
1547                window.dispatch_event(
1548                    PlatformInput::MouseDown(MouseDownEvent {
1549                        button: MouseButton::Left,
1550                        position: p(700.0, 500.0),
1551                        click_count: 1,
1552                        ..Default::default()
1553                    }),
1554                    cx,
1555                );
1556                window.render_frame(cx);
1557            });
1558            // 仅按下不隐藏,避免单击造成文字闪一下。
1559            assert_eq!(canvas.read_with(vcx, |c, _| c.rendered_counts()), before);
1560            canvas.update(vcx, |c, _| c.text_width_cache.clear());
1561            // 位移、停住、拖回起点:都必须维持隐藏直到松手。
1562            for position in [p(720.0, 520.0), p(720.0, 520.0), p(700.0, 500.0)] {
1563                vcx.update(|window, cx| {
1564                    window.dispatch_event(
1565                        PlatformInput::MouseMove(MouseMoveEvent {
1566                            position,
1567                            pressed_button: Some(MouseButton::Left),
1568                            ..Default::default()
1569                        }),
1570                        cx,
1571                    );
1572                    window.render_frame(cx);
1573                    assert!(
1574                        window
1575                            .try_find(ElementId::NamedInteger("graph-label".into(), 1))
1576                            .is_none()
1577                    );
1578                });
1579                canvas.read_with(vcx, |c, _| {
1580                    let counts = c.rendered_counts();
1581                    assert_eq!(counts.labels, 0, "{counts:?}");
1582                    assert_eq!(counts.full + counts.shell + counts.dot, 8, "圆点应保留");
1583                    assert_eq!(counts.edges, 7, "连线应保留");
1584                    assert!(c.text_width_cache.is_empty(), "拖动期间不应测量文字");
1585                });
1586            }
1587            // 画布外松手仍须清除拖拽状态并恢复文字。
1588            vcx.update(|window, cx| {
1589                window.dispatch_event(
1590                    PlatformInput::MouseUp(MouseUpEvent {
1591                        button: MouseButton::Left,
1592                        position: p(-10.0, -10.0),
1593                        ..Default::default()
1594                    }),
1595                    cx,
1596                );
1597                window.render_frame(cx);
1598            });
1599            canvas.read_with(vcx, |c, _| {
1600                assert!(c.pan_drag.is_none());
1601                assert_eq!(c.rendered_counts(), before);
1602                assert!(!c.text_width_cache.is_empty(), "松手后应恢复文字");
1603            });
1604        }
1605    }
1606
1607    #[gpui_kit::test]
1608    fn node_drag_hides_labels_but_click_does_not(cx: &mut TestAppContext) {
1609        let (canvas, vcx) = setup(cx);
1610        let center = canvas.read_with(vcx, |c, _| c.viewport.world_to_screen(c.positions[0]));
1611        vcx.update(|window, cx| {
1612            window.dispatch_event(
1613                PlatformInput::MouseDown(MouseDownEvent {
1614                    button: MouseButton::Left,
1615                    position: p(center.x, center.y),
1616                    click_count: 1,
1617                    ..Default::default()
1618                }),
1619                cx,
1620            );
1621            window.render_frame(cx);
1622            assert!(
1623                window
1624                    .try_find(ElementId::NamedInteger("graph-label".into(), 1))
1625                    .is_some()
1626            );
1627        });
1628        canvas.update(vcx, |c, _| c.text_width_cache.clear());
1629        vcx.update(|window, cx| {
1630            window.dispatch_event(
1631                PlatformInput::MouseMove(MouseMoveEvent {
1632                    position: p(center.x + 30.0, center.y + 20.0),
1633                    pressed_button: Some(MouseButton::Left),
1634                    ..Default::default()
1635                }),
1636                cx,
1637            );
1638            window.render_frame(cx);
1639            for id in 1..=8 {
1640                assert!(
1641                    window
1642                        .try_find(ElementId::NamedInteger("graph-label".into(), id))
1643                        .is_none()
1644                );
1645                assert!(
1646                    window
1647                        .try_find(ElementId::NamedInteger("graph-node".into(), id))
1648                        .is_some()
1649                );
1650            }
1651        });
1652        canvas.read_with(vcx, |c, _| assert!(c.text_width_cache.is_empty()));
1653        vcx.update(|window, cx| {
1654            window.dispatch_event(
1655                PlatformInput::MouseUp(MouseUpEvent {
1656                    button: MouseButton::Left,
1657                    position: p(center.x + 30.0, center.y + 20.0),
1658                    ..Default::default()
1659                }),
1660                cx,
1661            );
1662            window.render_frame(cx);
1663            for id in 1..=8 {
1664                assert!(
1665                    window
1666                        .try_find(ElementId::NamedInteger("graph-label".into(), id))
1667                        .is_some()
1668                );
1669            }
1670        });
1671        canvas.read_with(vcx, |c, _| {
1672            assert!(c.node_drag.is_none());
1673            assert!(c.is_pinned(NodeId(1)), "拖动固定行为应保留");
1674        });
1675    }
1676
1677    #[gpui_kit::test]
1678    fn click_drag_and_shift_box_select(cx: &mut TestAppContext) {
1679        let (canvas, vcx) = setup(cx);
1680        let center = canvas.read_with(vcx, |c, _| c.viewport.world_to_screen(c.positions[0]));
1681        vcx.update(|window, cx| {
1682            window.dispatch_event(
1683                PlatformInput::MouseDown(MouseDownEvent {
1684                    button: MouseButton::Left,
1685                    position: p(center.x, center.y),
1686                    click_count: 1,
1687                    ..Default::default()
1688                }),
1689                cx,
1690            );
1691            window.dispatch_event(
1692                PlatformInput::MouseUp(MouseUpEvent {
1693                    button: MouseButton::Left,
1694                    position: p(center.x, center.y),
1695                    ..Default::default()
1696                }),
1697                cx,
1698            );
1699        });
1700        assert_eq!(
1701            canvas.read_with(vcx, |c, _| c.selection.clone()),
1702            vec![NodeId(1)]
1703        );
1704        vcx.update(|window, cx| {
1705            window.drag(
1706                p(center.x, center.y),
1707                p(center.x + 60.0, center.y + 30.0),
1708                cx,
1709            )
1710        });
1711        canvas.read_with(vcx, |c, _| {
1712            assert!(c.is_pinned(NodeId(1)));
1713            let after = c.viewport.world_to_screen(c.positions[0]);
1714            assert!(after.distance(center.plus(Vec2::new(60.0, 30.0))) < 0.1);
1715        });
1716        canvas.update(vcx, |c, cx| c.set_pinned(NodeId(1), false, cx));
1717        assert!(!canvas.read_with(vcx, |c, _| c.is_pinned(NodeId(1))));
1718        // 框选用真实事件处理器,屏幕范围包住整张图。
1719        vcx.update(|window, cx| {
1720            canvas.update(cx, |c, cx| {
1721                c.on_left_down(
1722                    &MouseDownEvent {
1723                        position: p(1.0, 1.0),
1724                        modifiers: Modifiers {
1725                            shift: true,
1726                            ..Default::default()
1727                        },
1728                        ..Default::default()
1729                    },
1730                    window,
1731                    cx,
1732                );
1733                c.on_mouse_move(
1734                    &MouseMoveEvent {
1735                        position: p(1900.0, 1000.0),
1736                        ..Default::default()
1737                    },
1738                    window,
1739                    cx,
1740                );
1741                c.on_mouse_up(&MouseUpEvent::default(), window, cx);
1742            });
1743        });
1744        assert_eq!(canvas.read_with(vcx, |c, _| c.selection.len()), 8);
1745    }
1746
1747    #[gpui_kit::test]
1748    fn hover_neighbors_and_precise_hit(cx: &mut TestAppContext) {
1749        let (canvas, vcx) = setup(cx);
1750        canvas.read_with(vcx, |c, _| {
1751            // 旧实现只测相交包围盒,离节点 30 世界单位的空白也会误命中。
1752            assert_eq!(c.hit_slot(Vec2::new(30.0, 0.0)), None);
1753        });
1754        vcx.update(|window, cx| {
1755            canvas.update(cx, |c, cx| {
1756                let pos = c.viewport.world_to_screen(c.positions[1]);
1757                c.on_mouse_move(
1758                    &MouseMoveEvent {
1759                        position: p(pos.x, pos.y),
1760                        ..Default::default()
1761                    },
1762                    window,
1763                    cx,
1764                );
1765                assert_eq!(c.hover(), Some(NodeId(2)));
1766                let focus = c.focus_slots();
1767                assert!(focus.contains(&0) && focus.contains(&1) && focus.contains(&2));
1768                assert!(!focus.contains(&7));
1769                assert_eq!(Graph2D::emphasis(0, Some(&focus), 1.0), 1.0);
1770                assert!(Graph2D::emphasis(7, Some(&focus), 1.0) < 1.0);
1771            });
1772        });
1773    }
1774
1775    #[gpui_kit::test]
1776    fn filter_expand_search_and_interrupt_flight(cx: &mut TestAppContext) {
1777        let (canvas, vcx) = setup(cx);
1778        vcx.update(|window, cx| {
1779            canvas.update(cx, |c, cx| {
1780                let kind = c.graph.add_kind("其他");
1781                // 无匹配类型时全部隐藏,搜索也不得返回隐藏节点。
1782                c.set_kind_filter(Some(kind), cx);
1783                assert_eq!(c.hidden_count(), 8);
1784                assert!(c.search("n").is_empty());
1785                assert_eq!(c.expand(NodeId(2), cx), 2);
1786                assert_eq!(c.hidden_count(), 6);
1787                assert_eq!(c.search("N0"), vec![NodeId(1)]);
1788                c.set_kind_filter(None, cx);
1789                assert_eq!(c.hidden_count(), 0);
1790                assert_eq!(c.search("n").len(), 8);
1791                c.fly_to(NodeId(4), cx);
1792                assert!(c.motion.view_animating());
1793                c.on_scroll(
1794                    &ScrollEvent {
1795                        position: p(500.0, 300.0),
1796                        ..Default::default()
1797                    },
1798                    window,
1799                    cx,
1800                );
1801                assert!(!c.motion.view_animating());
1802                assert!(c.selection.contains(&NodeId(4)));
1803            });
1804        });
1805    }
1806
1807    /// 单独测量边几何构建与 GPUI CPU 分箱,不包含 GPU 绘制或显示器 present。
1808    /// 对照不同批大小,避免将 Canvas 的合并经验直接套到 GPUI 的 winding 路径上。
1809    #[test]
1810    #[ignore]
1811    fn bench_edge_path_batches() {
1812        let graph = large_graph();
1813        let payload = GraphPayload::from_graph(&graph);
1814        let positions: Vec<_> = grid_positions(5_000, 100)
1815            .into_iter()
1816            .map(|p| Vec2::new(p.x * 0.2, p.y * 0.2))
1817            .collect();
1818        let mask = gpui_kit::ContentMask {
1819            bounds: Bounds {
1820                origin: point(px(0.0), px(0.0)),
1821                size: size(px(4096.0), px(4096.0)),
1822            },
1823        };
1824        for batch in [1, 32, 128, 512, 10_000] {
1825            let mut samples = Vec::new();
1826            for iteration in 0..12 {
1827                let started = std::time::Instant::now();
1828                let mut build_ms = 0.0;
1829                let mut bin_ms = 0.0;
1830                for edges in payload.edges.chunks(batch) {
1831                    let t = std::time::Instant::now();
1832                    let mut fill = PathBuilder::fill().with_style(gpui_kit::PathStyle::Fill(
1833                        gpui_kit::FillOptions {
1834                            fill_rule: gpui_kit::FillRule::NonZero,
1835                        },
1836                    ));
1837                    for &(s, t, _) in edges {
1838                        let (a, b) = (positions[s as usize], positions[t as usize]);
1839                        let d = b.minus(a);
1840                        let len = d.length();
1841                        if len < 1.0 {
1842                            continue;
1843                        }
1844                        let n = Vec2::new(-d.y / len * 0.75, d.x / len * 0.75);
1845                        let to = |v: Vec2| point(px(v.x + iteration as f32 % 2.0), px(v.y));
1846                        fill.move_to(to(a.plus(n)));
1847                        fill.line_to(to(b.plus(n)));
1848                        fill.line_to(to(b.minus(n)));
1849                        fill.line_to(to(a.minus(n)));
1850                        fill.close();
1851                    }
1852                    let path = fill.build().unwrap();
1853                    build_ms += t.elapsed().as_secs_f64() * 1000.0;
1854                    let t = std::time::Instant::now();
1855                    std::hint::black_box(gpui_kit::PaintedPath::new(
1856                        path,
1857                        2.0,
1858                        mask,
1859                        gpui_kit::rgba(0x000000ff).into(),
1860                    ));
1861                    bin_ms += t.elapsed().as_secs_f64() * 1000.0;
1862                }
1863                if iteration > 1 {
1864                    samples.push((started.elapsed().as_secs_f64() * 1000.0, build_ms, bin_ms));
1865                }
1866            }
1867            let n = samples.len() as f64;
1868            println!(
1869                "BENCH edges batch={batch}: total {:.2} ms, build {:.2} ms, bin {:.2} ms (CPU only)",
1870                samples.iter().map(|s| s.0).sum::<f64>() / n,
1871                samples.iter().map(|s| s.1).sum::<f64>() / n,
1872                samples.iter().map(|s| s.2).sum::<f64>() / n
1873            );
1874        }
1875    }
1876
1877    /// 视图 CPU 帧耗时基准:覆盖方案 G7 的 5,000 节点 / 10,000 边规模。
1878    ///
1879    /// 运行:`cargo test -p arc-graph --release --lib bench_graph_frame_times -- --ignored --nocapture`
1880    ///
1881    /// 普通 TestAppContext 不安装真实渲染器:这里测场景树、布局、路径分箱,
1882    /// 不包含 GPU 执行、合成或显示器 present,不能把耗时倒数当成实机 FPS。
1883    /// 此测试不设通过阈值;test ok 仅表示执行成功,不表示满足 16ms 性能预算。
1884    #[gpui_kit::test]
1885    #[ignore]
1886    fn bench_graph_frame_times(cx: &mut TestAppContext) {
1887        cx.update(|cx| {
1888            gpui_kit::init(cx);
1889            install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1890        });
1891        let graph = large_graph();
1892        let positions = grid_positions(5_000, 100)
1893            .into_iter()
1894            .map(|p| Vec2::new(p.x * 0.2, p.y * 0.2))
1895            .collect();
1896        let mut canvas = None;
1897        let (_, vcx) = cx.add_window_view(|_, cx| {
1898            let c = cx.new(|cx| Graph2D::new_static("graph-bench", graph, positions, cx));
1899            canvas = Some(c.clone());
1900            Host { canvas: c }
1901        });
1902
1903        // 预热:第一次布局包含字体与元素缓存初始化,单独排除。
1904        vcx.update(|window, cx| {
1905            window.render_frame(cx);
1906            window.render_frame(cx);
1907        });
1908        let canvas = canvas.unwrap();
1909        let mut times = Vec::with_capacity(30);
1910        for i in 0usize..30 {
1911            canvas.update(vcx, |c, _| {
1912                c.viewport.offset.x += if i.is_multiple_of(2) { 1.0 } else { -1.0 };
1913            });
1914            let started = std::time::Instant::now();
1915            vcx.update(|window, cx| window.render_frame(cx));
1916            times.push(started.elapsed().as_secs_f64() * 1000.0);
1917        }
1918        times.sort_by(f64::total_cmp);
1919        let avg = times.iter().sum::<f64>() / times.len() as f64;
1920        let p95 = times[(times.len() * 95 / 100).min(times.len() - 1)];
1921        let counts = canvas.read_with(vcx, |c, _| c.rendered_counts());
1922        println!(
1923            "BENCH graph 5,000/10,000 dense pan: avg {avg:.2} ms, p95 {p95:.2} ms, drawn {counts:?}"
1924        );
1925    }
1926
1927    #[gpui_kit::test]
1928    fn light_dark_light_keeps_graph_renderable(cx: &mut TestAppContext) {
1929        let (canvas, vcx) = setup(cx);
1930        for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
1931            vcx.update(|window, cx| {
1932                install_arc_theme(mode, Accent::Blue, cx);
1933                window.render_frame(cx);
1934            });
1935            assert_eq!(canvas.read_with(vcx, |c, _| c.rendered_counts().full), 8);
1936        }
1937    }
1938
1939    #[gpui_kit::test]
1940    fn visible_set_is_shared_until_view_changes_and_pause_is_idempotent(cx: &mut TestAppContext) {
1941        let (canvas, vcx) = setup(cx);
1942        let first = canvas.read_with(vcx, |c, _| c.visible_cache.clone().unwrap());
1943        vcx.update(|window, cx| window.render_frame(cx));
1944        canvas.read_with(vcx, |c, _| {
1945            assert!(Arc::ptr_eq(&first, c.visible_cache.as_ref().unwrap()));
1946        });
1947        canvas.update(vcx, |c, cx| {
1948            c.set_layout_paused(true, cx);
1949            c.set_layout_paused(true, cx);
1950            assert!(c.layout_paused);
1951            c.set_layout_paused(false, cx);
1952            assert!(!c.layout_paused);
1953            c.viewport.offset.x += 1.0;
1954        });
1955        vcx.update(|window, cx| window.render_frame(cx));
1956        canvas.read_with(vcx, |c, _| {
1957            assert!(!Arc::ptr_eq(&first, c.visible_cache.as_ref().unwrap()));
1958        });
1959    }
1960
1961    #[gpui_kit::test]
1962    fn static_positions_skip_layout_worker(cx: &mut TestAppContext) {
1963        // 静态构造:无后台线程,坐标立即生效(离线布局结果直接渲染的入口)。
1964        cx.update(|cx| {
1965            gpui_kit::init(cx);
1966            install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1967        });
1968        let mut canvas = None;
1969        let (_, vcx) = cx.add_window_view(|_, cx| {
1970            let c = cx.new(|cx| {
1971                Graph2D::new_static("graph-static", chain_graph(4), grid_positions(4, 2), cx)
1972            });
1973            canvas = Some(c.clone());
1974            Host { canvas: c }
1975        });
1976        vcx.update(|window, cx| {
1977            window.render_frame(cx);
1978            window.render_frame(cx);
1979        });
1980        // 静态坐标立即可渲染(无布局线程)。
1981        let counts = canvas.unwrap().read_with(vcx, |c, _| c.rendered_counts());
1982        assert!(counts.full + counts.dot + counts.shell > 0, "{counts:?}");
1983        assert_eq!(counts.edges, 3);
1984    }
1985}