arc-graph 0.4.0

GPUI knowledge-graph canvas (2D) built on arc-graph-core: force layout in a background thread, LOD, label culling and viewport culling.
Documentation
//! 本地设计:真实离屏渲染验收,不将软件渲染或虚拟时钟当作物理屏 120Hz 证据。
//! Linux/macOS:ARC_GRAPH_RENDER_DIR=/output cargo test -p arc-graph --test rendering

fn main() {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    rendering::run();
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    println!(
        "SKIP: this platform has no GPUI headless pixel renderer; desktop capture is required"
    );
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
mod rendering {
    use arc_flow_core::geometry::Vec2;
    use arc_graph::{Graph2D, KnowledgeGraph, NodeId};
    use arc_motion::{ReducedMotionChoice, set_reduced_motion};
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        AppContext as _, HeadlessAppContext, MouseButton, point, px, size,
        test::{TestEventExt as _, TestWindowExt as _},
    };
    use std::{path::PathBuf, sync::Arc, time::Duration};

    pub fn run() {
        let output = std::env::var_os("ARC_GRAPH_RENDER_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("target/graph-rendering"));
        std::fs::create_dir_all(&output).expect("create screenshot directory");
        let mut cx = HeadlessAppContext::with_platform(
            gpui_kit::platform::current_platform(true).text_system(),
            Arc::new(gpui_kit::assets::AllAssets),
            gpui_kit::platform::current_headless_renderer,
        );
        cx.update(|cx| {
            gpui_kit::init(cx);
            // 与 gallery 相同:把 kit 组件字体指到平台真实家族,避免静默回退缺字。
            cx.global_mut::<gpui_kit::component::Theme>().font_family =
                arc_tokens::Typography::body_family().into();
            install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
            set_reduced_motion(ReducedMotionChoice::Reduce, cx);
        });
        let mut graph = KnowledgeGraph::new();
        let people = graph.add_kind("人物");
        let concept = graph.add_kind("概念");
        let ids: Vec<_> = ["张三", "李四", "知识图谱", "Barnes–Hut", "GPUI", "孤立节点"]
            .into_iter()
            .enumerate()
            .map(|(i, label)| graph.add_node(label, Some(if i < 2 { people } else { concept })))
            .collect();
        for (a, b) in [(0, 1), (0, 2), (2, 3), (2, 4)] {
            graph.add_edge(ids[a], ids[b], 1.0, None).unwrap();
        }
        let positions = vec![
            Vec2::new(0.0, 0.0),
            Vec2::new(180.0, 0.0),
            Vec2::new(0.0, 150.0),
            Vec2::new(180.0, 150.0),
            Vec2::new(360.0, 150.0),
            Vec2::new(360.0, 0.0),
        ];
        let (handle, canvas) = cx.update(|cx| {
            gpui_kit::open_window(
                gpui_kit::WindowOptions {
                    window_bounds: Some(gpui_kit::WindowBounds::Windowed(gpui_kit::Bounds {
                        origin: Default::default(),
                        size: size(px(960.0), px(600.0)),
                    })),
                    focus: false,
                    show: false,
                    ..Default::default()
                },
                cx,
                |_, cx| cx.new(|cx| Graph2D::new_static("graph-pixels", graph, positions, cx)),
            )
            .expect("open real-renderer window")
        });
        let window_handle = handle.into();
        // 两帧:先测量真实容器,再按容器适配。
        let draw = |cx: &mut HeadlessAppContext| {
            cx.update_window(window_handle, |_, window, cx| window.render_frame(cx))
                .unwrap();
        };
        draw(&mut cx);
        draw(&mut cx);
        let mut light_pixels = None;
        for (name, mode) in [
            ("light", ThemeMode::Light),
            ("dark", ThemeMode::Dark),
            ("light-again", ThemeMode::Light),
        ] {
            cx.update(|cx| install_arc_theme(mode, Accent::Blue, cx));
            draw(&mut cx);
            let image = cx
                .capture_screenshot(window_handle)
                .expect("real offscreen pixels required");
            // 逻辑尺寸 960×600;hidpi 缩放下像素缓冲按 scale 放大。
            let scale = image.width() as f32 / 960.0;
            assert!(
                (scale - (scale as u32) as f32).abs() < f32::EPSILON
                    && image.height() == 600 * scale as u32
                    && scale >= 1.0,
                "unexpected buffer {}x{} for 960x600 logical",
                image.width(),
                image.height()
            );
            let background = image.get_pixel(0, 0);
            assert!(
                image.pixels().filter(|p| *p != background).count() > 1000,
                "graph must not be blank"
            );
            if name == "light" {
                light_pixels = Some(image.as_raw().clone());
            }
            if name == "light-again" {
                assert_eq!(
                    Some(image.as_raw()),
                    light_pixels.as_ref(),
                    "theme roundtrip must restore pixels"
                );
            }
            image.save(output.join(format!("{name}.png"))).unwrap();
        }
        cx.update_window(window_handle, |_, window, cx| {
            let pos = canvas
                .read(cx)
                .viewport()
                .world_to_screen(Vec2::new(0.0, 0.0));
            window.pointer_move(point(px(pos.x), px(pos.y)), None, cx);
            window.pointer_down(point(px(pos.x), px(pos.y)), MouseButton::Left, cx);
            window.pointer_up(point(px(pos.x), px(pos.y)), MouseButton::Left, cx);
            assert_eq!(canvas.read(cx).selection(), &[NodeId(1)]);
            window.render_frame(cx);
        })
        .unwrap();
        cx.advance_clock(Duration::from_millis(500));
        draw(&mut cx);
        cx.capture_screenshot(window_handle)
            .unwrap()
            .save(output.join("selected-hover.png"))
            .unwrap();
        cx.update(|cx| canvas.update(cx, |view, cx| view.set_kind_filter(Some(people), cx)));
        cx.advance_clock(Duration::from_millis(500));
        draw(&mut cx);
        cx.update(|cx| assert_eq!(canvas.read(cx).hidden_count(), 4));
        cx.capture_screenshot(window_handle)
            .unwrap()
            .save(output.join("filtered.png"))
            .unwrap();
        cx.update(|cx| {
            canvas.update(cx, |view, cx| {
                assert_eq!(view.expand(NodeId(1), cx), 1);
                view.set_kind_filter(None, cx);
            })
        });
        cx.advance_clock(Duration::from_millis(500));
        draw(&mut cx);
        cx.update_window(window_handle, |_, window, cx| {
            canvas.update(cx, |view, cx| view.zoom_by(0.05, window, cx))
        })
        .unwrap();
        draw(&mut cx);
        cx.capture_screenshot(window_handle)
            .unwrap()
            .save(output.join("lod-dots.png"))
            .unwrap();
        // 两条对角边交叉:同一填充路径必须取并集,中心不能被 EvenOdd 挖空。
        let mut crossing = KnowledgeGraph::new();
        let ids: Vec<_> = (0..4)
            .map(|i| crossing.add_node(format!("c{i}"), None))
            .collect();
        crossing.add_edge(ids[0], ids[1], 1.0, None).unwrap();
        crossing.add_edge(ids[2], ids[3], 1.0, None).unwrap();
        let (cross_handle, cross_view) = cx.update(|cx| {
            gpui_kit::open_window(
                gpui_kit::WindowOptions {
                    window_bounds: Some(gpui_kit::WindowBounds::Windowed(gpui_kit::Bounds {
                        origin: Default::default(),
                        size: size(px(960.0), px(600.0)),
                    })),
                    focus: false,
                    show: false,
                    ..Default::default()
                },
                cx,
                |_, cx| {
                    cx.new(|cx| {
                        Graph2D::new_static(
                            "crossing",
                            crossing,
                            vec![
                                Vec2::new(-120.0, -120.0),
                                Vec2::new(120.0, 120.0),
                                Vec2::new(-120.0, 120.0),
                                Vec2::new(120.0, -120.0),
                            ],
                            cx,
                        )
                    })
                },
            )
            .unwrap()
        });
        let cross_handle = cross_handle.into();
        for _ in 0..2 {
            cx.update_window(cross_handle, |_, window, cx| window.render_frame(cx))
                .unwrap();
        }
        let center = cx.update(|cx| cross_view.read(cx).viewport().world_to_screen(Vec2::ZERO));
        let image = cx.capture_screenshot(cross_handle).unwrap();
        let scale = image.width() as f32 / 960.0;
        assert_ne!(
            image.get_pixel((center.x * scale) as u32, (center.y * scale) as u32),
            image.get_pixel(0, 0),
            "crossing edges must not cancel their fill"
        );
        image.save(output.join("crossing-edges.png")).unwrap();
        println!(
            "PASS: real pixels, crossing edge union, light-dark-light identity, pointer selection, filtering, expansion, LOD; output={}",
            output.display()
        );
        println!(
            "NOT TESTED: native desktop presentation, physical refresh rate, 120fps, reference pixel/curve error"
        );
    }
}